diff --git a/.gitattributes b/.gitattributes index d530ed421..87c9db929 100644 --- a/.gitattributes +++ b/.gitattributes @@ -51,11 +51,12 @@ *.dylib filter=lfs diff=lfs merge=lfs -text *.bundle filter=lfs diff=lfs merge=lfs -text *.engine filter=lfs diff=lfs merge=lfs -text -*.sbsar filter=lfs diff=lfs merge=lfs -text *.msgpack filter=lfs diff=lfs merge=lfs -text GameData/*.cc filter=lfs diff=lfs merge=lfs -text GameData/Mods/**/*.cc filter=lfs diff=lfs merge=lfs -text GameData/Mods/**/*.glb filter=lfs diff=lfs merge=lfs -text +tests/fixtures/mods/**/*.cc filter=lfs diff=lfs merge=lfs -text +tests/fixtures/mods/**/*.glb filter=lfs diff=lfs merge=lfs -text tools/blender/tests/fixtures/*.glb filter=lfs diff=lfs merge=lfs -text *.a filter=lfs diff=lfs merge=lfs -text *AkSoundEngine filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore index ac9c49142..8f15133d1 100644 --- a/.gitignore +++ b/.gitignore @@ -113,3 +113,4 @@ tests/_scratch_* # Stryker.NET mutation reports (regenerated per run) StrykerOutput/ +native/aetherlight/target/ diff --git a/Assets/Content/Prefabs/Turrets/Turret.prefab b/Assets/Content/Prefabs/Turrets/Turret.prefab index 748ca8a29..2df968941 100644 --- a/Assets/Content/Prefabs/Turrets/Turret.prefab +++ b/Assets/Content/Prefabs/Turrets/Turret.prefab @@ -998,8 +998,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: 3720744386649352057, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} + - {fileID: 2100000, guid: 38f8ba6b169127249b6532be2b3926ee, type: 2} + - {fileID: 2100000, guid: 5e43f48908cce2949a41677ec48affe5, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt b/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt new file mode 100644 index 000000000..d2fcdf3eb --- /dev/null +++ b/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt @@ -0,0 +1,93 @@ +Copyright(c) 2014 by Julieta Ulanovsky + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/Assets/Materials/Substance.meta b/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt.meta similarity index 57% rename from Assets/Materials/Substance.meta rename to Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt.meta index c6926c786..c2ea6a451 100644 --- a/Assets/Materials/Substance.meta +++ b/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt.meta @@ -1,7 +1,6 @@ fileFormatVersion: 2 -guid: 7de1c11cf7591ec48bdb53e9818172f5 -folderAsset: yes -DefaultImporter: +guid: dc84a6b2454445f9be69af26e86eb90c +TextScriptImporter: externalObjects: {} userData: assetBundleName: diff --git a/Assets/Fonts/Ubuntu/UFL-1.0.txt b/Assets/Fonts/Ubuntu/UFL-1.0.txt new file mode 100644 index 000000000..ae78a8f94 --- /dev/null +++ b/Assets/Fonts/Ubuntu/UFL-1.0.txt @@ -0,0 +1,96 @@ +------------------------------- +UBUNTU FONT LICENCE Version 1.0 +------------------------------- + +PREAMBLE +This licence allows the licensed fonts to be used, studied, modified and +redistributed freely. The fonts, including any derivative works, can be +bundled, embedded, and redistributed provided the terms of this licence +are met. The fonts and derivatives, however, cannot be released under +any other licence. The requirement for fonts to remain under this +licence does not require any document created using the fonts or their +derivatives to be published under this licence, as long as the primary +purpose of the document is not to be a vehicle for the distribution of +the fonts. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this licence and clearly marked as such. This may +include source files, build scripts and documentation. + +"Original Version" refers to the collection of Font Software components +as received under this licence. + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to +a new environment. + +"Copyright Holder(s)" refers to all individuals and companies who have a +copyright ownership of the Font Software. + +"Substantially Changed" refers to Modified Versions which can be easily +identified as dissimilar to the Font Software by users of the Font +Software comparing the Original Version with the Modified Version. + +To "Propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification and with or without charging +a redistribution fee), making available to the public, and in some +countries other activities as well. + +PERMISSION & CONDITIONS +This licence does not grant any rights under trademark law and all such +rights are reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of the Font Software, to propagate the Font Software, subject to +the below conditions: + +1) Each copy of the Font Software must contain the above copyright +notice and this licence. These can be included either as stand-alone +text files, human-readable headers or in the appropriate machine- +readable metadata fields within text or binary files as long as those +fields can be easily viewed by the user. + +2) The font name complies with the following: +(a) The Original Version must retain its name, unmodified. +(b) Modified Versions which are Substantially Changed must be renamed to +avoid use of the name of the Original Version or similar names entirely. +(c) Modified Versions which are not Substantially Changed must be +renamed to both (i) retain the name of the Original Version and (ii) add +additional naming elements to distinguish the Modified Version from the +Original Version. The name of such Modified Versions must be the name of +the Original Version, with "derivative X" where X represents the name of +the new work, appended to that name. + +3) The name(s) of the Copyright Holder(s) and any contributor to the +Font Software shall not be used to promote, endorse or advertise any +Modified Version, except (i) as required by this licence, (ii) to +acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with +their explicit written permission. + +4) The Font Software, modified or unmodified, in part or in whole, must +be distributed entirely under this licence, and must not be distributed +under any other licence. The requirement for fonts to remain under this +licence does not affect any document created using the Font Software, +except any version of the Font Software extracted from a document +created using the Font Software may only be distributed under this +licence. + +TERMINATION +This licence becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER +DEALINGS IN THE FONT SOFTWARE. diff --git a/Assets/Materials/Substance/Metal.meta b/Assets/Fonts/Ubuntu/UFL-1.0.txt.meta similarity index 57% rename from Assets/Materials/Substance/Metal.meta rename to Assets/Fonts/Ubuntu/UFL-1.0.txt.meta index e8c0226e7..33790c1ab 100644 --- a/Assets/Materials/Substance/Metal.meta +++ b/Assets/Fonts/Ubuntu/UFL-1.0.txt.meta @@ -1,7 +1,6 @@ fileFormatVersion: 2 -guid: 09aee558716a08d4c9806b9b4273a209 -folderAsset: yes -DefaultImporter: +guid: 331370618a0a473fb6a6837985b38a35 +TextScriptImporter: externalObjects: {} userData: assetBundleName: diff --git a/Assets/Materials/Aluminium brushed.mat b/Assets/Materials/Aluminium brushed.mat index b8ade999f..a624f95e1 100644 --- a/Assets/Materials/Aluminium brushed.mat +++ b/Assets/Materials/Aluminium brushed.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 4730978449518085612, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 2800000, guid: c3ef09438e3e46d18a4c267810aeb285, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -45,23 +44,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 7556082237344091230, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 2800000, guid: f70b6df0395b4752b4ec80cb7bfd8f42, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6373266012617290493, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 2800000, guid: 40f5e915d2734d43bc01f984772e9d29, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: 342959783478273704, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: -9132138291289375396, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: @@ -85,7 +80,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.951, g: 0.951, b: 0.951, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint Magenta.mat b/Assets/Materials/Car Paint Magenta.mat index dbe95bd62..bff25331a 100644 --- a/Assets/Materials/Car Paint Magenta.mat +++ b/Assets/Materials/Car Paint Magenta.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _FadeTex: @@ -35,18 +34,15 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -59,6 +55,6 @@ Material: - _Metallic: 1 - _OcclusionStrength: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.5, g: 0, b: 0.228113, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint Red.mat b/Assets/Materials/Car Paint Red.mat index 8a7ffa46f..063e9367c 100644 --- a/Assets/Materials/Car Paint Red.mat +++ b/Assets/Materials/Car Paint Red.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -45,23 +44,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: -1652887728991447519, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: @@ -85,7 +80,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 1, g: 0.15685, b: 0, a: 1} - _EdgeColor: {r: 6.0235295, g: 6.0235295, b: 24.094118, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint White Small.mat b/Assets/Materials/Car Paint White Small.mat index aab8a3663..cca6010f3 100644 --- a/Assets/Materials/Car Paint White Small.mat +++ b/Assets/Materials/Car Paint White Small.mat @@ -29,8 +29,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -54,23 +53,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 16, y: 16} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: -1652887728991447519, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -95,7 +90,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 1, g: 0.891509, b: 0.946396, a: 1} - _EdgeColor: {r: 6.0235295, g: 6.0235295, b: 24.094118, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint White.mat b/Assets/Materials/Car Paint White.mat index ba32280af..ad0af17d2 100644 --- a/Assets/Materials/Car Paint White.mat +++ b/Assets/Materials/Car Paint White.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _FadeTex: @@ -35,18 +34,15 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -59,6 +55,6 @@ Material: - _Metallic: 1 - _OcclusionStrength: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 1, g: 0.891509, b: 0.946396, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Cockpit.mat b/Assets/Materials/Cockpit.mat index 543d0d608..fb19e541a 100644 --- a/Assets/Materials/Cockpit.mat +++ b/Assets/Materials/Cockpit.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -3419035557588562233, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 2800000, guid: 3a10044baac4438f9fc0930783eccdf7, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -51,23 +50,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 2800000, guid: 5a9cee903a2d48718aaf6b224126f279, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 2800000, guid: 8b24d7ea11c341408a146fa39f59b7b0, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -3436886866959827803, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 7009887839391554354, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -92,7 +87,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.85, g: 0.65, b: 0.30, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Metal 003.mat b/Assets/Materials/Metal 003.mat index 4d07d4c1a..09330e338 100644 --- a/Assets/Materials/Metal 003.mat +++ b/Assets/Materials/Metal 003.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -2508943184622041221, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 2800000, guid: 3a10044baac4438f9fc0930783eccdf7, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -41,23 +40,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1236254257114565538, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 2800000, guid: 5a9cee903a2d48718aaf6b224126f279, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 4019402794555593307, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 2800000, guid: 8b24d7ea11c341408a146fa39f59b7b0, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1475328947160444094, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 7523010977671448217, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: diff --git a/Assets/Materials/Mine Glow.mat b/Assets/Materials/Mine Glow.mat index e1627f2d9..7d6d630e7 100644 --- a/Assets/Materials/Mine Glow.mat +++ b/Assets/Materials/Mine Glow.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} + m_Texture: {fileID: 2800000, guid: 8bc10cfce8a64defaf9f67d156003f09, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -41,13 +40,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: 2195885db9e846999fd10aa7f5c629b1, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: d91bff887b764847a484d0a9bedce9e9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: diff --git a/Assets/Models/Discobolus/Discobolus Bronze.mat b/Assets/Materials/Pickup Trim.mat similarity index 64% rename from Assets/Models/Discobolus/Discobolus Bronze.mat rename to Assets/Materials/Pickup Trim.mat index 30697d42a..0cea43f4f 100644 --- a/Assets/Models/Discobolus/Discobolus Bronze.mat +++ b/Assets/Materials/Pickup Trim.mat @@ -2,25 +2,34 @@ %TAG !u! tag:unity3d.com,2011: --- !u!21 &2100000 Material: - serializedVersion: 6 + serializedVersion: 8 m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} - m_Name: Discobolus Bronze - m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: _METALLICGLOSSMAP _NORMALMAP + m_Name: Pickup Trim + m_Shader: {fileID: 4800000, guid: ddff0b48b92c991499817d2a0f5d5059, type: 3} + m_Parent: {fileID: 0} + m_ModifiedSerializedProperties: 0 + m_ValidKeywords: [] + m_InvalidKeywords: + - _MAINTEX + - _METALLICGLOSSMAP + - _NORMALMAP + - _OCCLUSIONMAP + - _PARALLAXMAP m_LightmapFlags: 4 m_EnableInstancingVariants: 0 m_DoubleSidedGI: 0 m_CustomRenderQueue: -1 stringTagMap: {} disabledShaderPasses: [] + m_LockedProperties: m_SavedProperties: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 2800000, guid: 9863db663524d9a4eab030a666b1f2da, type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -37,35 +46,41 @@ Material: m_Offset: {x: 0, y: 0} - _EmissionMap: m_Texture: {fileID: 0} + m_Scale: {x: 16, y: 16} + m_Offset: {x: 0, y: 0} + - _FadeTex: + m_Texture: {fileID: 2800000, guid: df0632a08c5f1a1498fa325c755dc459, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - m_Scale: {x: 1, y: 1} + m_Texture: {fileID: 0} + m_Scale: {x: 16, y: 16} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: 2800000, guid: d60207b632e464d4b884dded41db5b9b, type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} + m_Ints: [] m_Floats: - _BumpScale: 1 - _Cutoff: 0.5 - _DetailNormalMapScale: 1 - _DstBlend: 0 + - _Fade: 1 + - _FadeEdge: 0.1 + - _FadeSharpness: 16 - _GlossMapScale: 1 - - _Glossiness: 0.5 + - _Glossiness: 0.7 - _GlossyReflections: 1 - - _Metallic: 0 + - _Metallic: 0.6 - _Mode: 0 - _OcclusionStrength: 1 - _Parallax: 0.005 @@ -75,6 +90,8 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0, g: 0.605881, b: 1, a: 1} + - _EdgeColor: {r: 6.0235295, g: 6.0235295, b: 24.094118, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] + m_AllowLocking: 1 diff --git a/Assets/Steel.mat.meta b/Assets/Materials/Pickup Trim.mat.meta similarity index 79% rename from Assets/Steel.mat.meta rename to Assets/Materials/Pickup Trim.mat.meta index d645ba6a4..d57d829c2 100644 --- a/Assets/Steel.mat.meta +++ b/Assets/Materials/Pickup Trim.mat.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4c998decce894b4458e1bc667975aeea +guid: bebc82079e5d4e578a73c3ab48d2c2da NativeFormatImporter: externalObjects: {} mainObjectFileID: 2100000 diff --git a/Assets/Materials/Radiators 1.mat b/Assets/Materials/Radiators 1.mat deleted file mode 100644 index a6219fe9d..000000000 --- a/Assets/Materials/Radiators 1.mat +++ /dev/null @@ -1,87 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Radiators 1 - m_Shader: {fileID: 4800000, guid: d69ef48273708ef4680762f5cdcfc860, type: 3} - m_ShaderKeywords: - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpPower: 2 - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _Emission: 15 - - _EmissionFresnel: 4 - - _EmissionRoughnessFresnelPower: 0.5 - - _GlossMapScale: 1 - - _Glossiness: 1 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _ReverseRim: 0 - - _Rotation: 0 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 1, g: 0.40135294, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Materials/Radiators 1.mat.meta b/Assets/Materials/Radiators 1.mat.meta deleted file mode 100644 index c562a84de..000000000 --- a/Assets/Materials/Radiators 1.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: f396635dc77c59c44ac85ae278a2e909 -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Materials/Radiators.mat b/Assets/Materials/Radiators.mat index aa7eaf0fb..1e5c52a54 100644 --- a/Assets/Materials/Radiators.mat +++ b/Assets/Materials/Radiators.mat @@ -21,8 +21,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} + m_Texture: {fileID: 2800000, guid: 8bc10cfce8a64defaf9f67d156003f09, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -46,13 +45,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: 2195885db9e846999fd10aa7f5c629b1, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: d91bff887b764847a484d0a9bedce9e9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: diff --git a/Assets/Materials/Silver.mat b/Assets/Materials/Silver.mat index e02d24f97..0bb79d6a1 100644 --- a/Assets/Materials/Silver.mat +++ b/Assets/Materials/Silver.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 8947980237086559854, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 2800000, guid: c3ef09438e3e46d18a4c267810aeb285, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -51,23 +50,19 @@ Material: m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1383037052668628532, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 2800000, guid: f70b6df0395b4752b4ec80cb7bfd8f42, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6429125567479694453, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 2800000, guid: 40f5e915d2734d43bc01f984772e9d29, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -9097439929179392311, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 425190381137097012, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] diff --git a/Assets/Materials/Station Lights.mat b/Assets/Materials/Station Lights.mat index f863306a1..2aac54ac7 100644 --- a/Assets/Materials/Station Lights.mat +++ b/Assets/Materials/Station Lights.mat @@ -24,8 +24,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} + m_Texture: {fileID: 2800000, guid: 8bc10cfce8a64defaf9f67d156003f09, type: 3} m_Scale: {x: 8, y: 8} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -49,13 +48,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: 2195885db9e846999fd10aa7f5c629b1, type: 3} m_Scale: {x: 16, y: 16} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: d91bff887b764847a484d0a9bedce9e9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: diff --git a/Assets/Materials/Steel brushed.mat b/Assets/Materials/Steel brushed.mat deleted file mode 100644 index dba1bd074..000000000 --- a/Assets/Materials/Steel brushed.mat +++ /dev/null @@ -1,83 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Steel brushed - m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: _MAINTEX _METALLICGLOSSMAP _NORMALMAP _OCCLUSIONMAP _PARALLAXMAP - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -4471413742775304797, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -4638397344074346932, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: 5049811794194361025, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 1753668427856518731, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: -3498708498072814504, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _GlossMapScale: 1 - - _Glossiness: 0.5 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Materials/Steel brushed.mat.meta b/Assets/Materials/Steel brushed.mat.meta deleted file mode 100644 index 73afa8139..000000000 --- a/Assets/Materials/Steel brushed.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: df3e704fc59794a45b8e14a78d96cca3 -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Materials/Steel parkerized.mat b/Assets/Materials/Steel parkerized.mat index b4194ab66..ba47afb87 100644 --- a/Assets/Materials/Steel parkerized.mat +++ b/Assets/Materials/Steel parkerized.mat @@ -29,8 +29,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 885599758852769373, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 2800000, guid: dc71e34b4a1f4de7aa826d18b67b5852, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -54,23 +53,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -4474525002722929857, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 2800000, guid: 1ed06708491744fe944217d19e450157, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -2334804936223627746, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 2800000, guid: 31e7d642ff8a49a28390c82626c4b6b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -8380876848358870972, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 172713863077875830, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] diff --git a/Assets/Materials/Steel.mat b/Assets/Materials/Steel.mat index 37420bfd4..6eeb29385 100644 --- a/Assets/Materials/Steel.mat +++ b/Assets/Materials/Steel.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 2800000, guid: c3ef09438e3e46d18a4c267810aeb285, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -51,23 +50,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 2800000, guid: f70b6df0395b4752b4ec80cb7bfd8f42, type: 3} m_Scale: {x: 4, y: 4} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 2800000, guid: 40f5e915d2734d43bc01f984772e9d29, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] diff --git a/Assets/Materials/Substance/Metal/Pickup Base.sbsar b/Assets/Materials/Substance/Metal/Pickup Base.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Base.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta b/Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta deleted file mode 100644 index 2966159bc..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta +++ /dev/null @@ -1,382 +0,0 @@ -fileFormatVersion: 2 -guid: 26a894e543f3ed44893b1620707ca62c -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n - \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 1 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 1 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: 3068890721646206586, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: -3552914696322007609, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: -1242281561028671816, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: -1652887728991447519, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} diff --git a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar b/Assets/Materials/Substance/Metal/Pickup Trim.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta b/Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta deleted file mode 100644 index 302e453b5..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta +++ /dev/null @@ -1,381 +0,0 @@ -fileFormatVersion: 2 -guid: c00b5a4f1e4743a4ca59b8030251f900 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.005 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3068890721646206586, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: -3552914696322007609, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: -1242281561028671816, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: -1652887728991447519, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} diff --git a/Assets/Materials/Substance/Metal/galvanized_001.sbsar b/Assets/Materials/Substance/Metal/galvanized_001.sbsar deleted file mode 100644 index 5d6237210..000000000 --- a/Assets/Materials/Substance/Metal/galvanized_001.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:274db26d631b6cd53024c1366c01322d99b6194b5e211d04c5430bb8174ae8f6 -size 8207 diff --git a/Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta b/Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta deleted file mode 100644 index 9815351c0..000000000 --- a/Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 2be0f689f5b01be4aa1032bc86f15eab -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: galvanized_001/galvanized_001 - - first: - 4: 400000 - second: galvanized_001/galvanized_001/Transform - - first: - 21: 2100000 - second: mat.Galvanized_001 - - first: - 23: 2300000 - second: galvanized_001/galvanized_001/MeshRenderer - - first: - 28: 2800000 - second: Galvanized_001_baseColor - - first: - 28: 2800002 - second: Galvanized_001_normal - - first: - 28: 2800004 - second: Galvanized_001_metallic - - first: - 28: 2800006 - second: Galvanized_001_ambientOcclusion - - first: - 28: 2800008 - second: Galvanized_001_height - - first: - 33: 3300000 - second: galvanized_001/galvanized_001/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: galvanized_001/galvanized_001/SphereCollider - - first: - 1001: 100100000 - second: galvanized_001 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Galvanized_001 - prototypeName: Galvanized_001 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2787997366030867252, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 7907137595978400316, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 1034366337303036879, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4470803051826786927, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3422293810953865746, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Galvanized_001_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -231086597109407277, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - generatedTextures: - - {fileID: 7907137595978400316, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: -2787997366030867252, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: 1034366337303036879, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: 4470803051826786927, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: -3422293810953865746, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} diff --git a/Assets/Materials/Substance/Metal/iron_damaged.sbsar b/Assets/Materials/Substance/Metal/iron_damaged.sbsar deleted file mode 100644 index cb09572e5..000000000 --- a/Assets/Materials/Substance/Metal/iron_damaged.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4a12de208077d6dfd8e70dfa8a8976bb9e5b2ca2d258bb34aa50c81a58a6451c -size 30808 diff --git a/Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta b/Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta deleted file mode 100644 index d7a4d07d7..000000000 --- a/Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta +++ /dev/null @@ -1,293 +0,0 @@ -fileFormatVersion: 2 -guid: d15fc45ed0000934d946b5f271f637ef -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Iron Damaged - prototypeName: Iron Damaged - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -1855041196637152199, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -2789335455068261637, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 7922211451800446260, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4424499752615739725, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7474978398744299577, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambientocclusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Iron Damaged - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 1736733470071950104, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - generatedTextures: - - {fileID: -2789335455068261637, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: -1855041196637152199, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: 7922211451800446260, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: 7474978398744299577, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: -4424499752615739725, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} diff --git a/Assets/Materials/Substance/Metal/iron_rugged.sbsar b/Assets/Materials/Substance/Metal/iron_rugged.sbsar deleted file mode 100644 index d211f88ad..000000000 --- a/Assets/Materials/Substance/Metal/iron_rugged.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5f2bc787cbb3f6511050a4faddaa07077bf54814131752687ed3717914d77de5 -size 28930 diff --git a/Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta b/Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta deleted file mode 100644 index 4d3540662..000000000 --- a/Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta +++ /dev/null @@ -1,293 +0,0 @@ -fileFormatVersion: 2 -guid: afbd691d0ea2a5a47b5a43b244593a56 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Iron Rugged - prototypeName: Iron Rugged - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2323688274092838296, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -3909611376798458227, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -1417795912608492100, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -7795300588429949130, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 3868076301887189615, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambientocclusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Iron Rugged - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -7894845242109240131, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - generatedTextures: - - {fileID: -3909611376798458227, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: -2323688274092838296, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: -1417795912608492100, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: 3868076301887189615, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: -7795300588429949130, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_002.sbsar b/Assets/Materials/Substance/Metal/metal_002.sbsar deleted file mode 100644 index 97dcc5ffe..000000000 --- a/Assets/Materials/Substance/Metal/metal_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9282e9326add2015fd2748e98c38062e438b085036eae00825551986e30d002f -size 11670 diff --git a/Assets/Materials/Substance/Metal/metal_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_002.sbsar.meta deleted file mode 100644 index 725363c0a..000000000 --- a/Assets/Materials/Substance/Metal/metal_002.sbsar.meta +++ /dev/null @@ -1,372 +0,0 @@ -fileFormatVersion: 2 -guid: 2b42584452fe0cc4fa4e8a115230b156 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_002/metal_002 - - first: - 4: 400000 - second: metal_002/metal_002/Transform - - first: - 21: 2100000 - second: mat.Metal 002 - - first: - 23: 2300000 - second: metal_002/metal_002/MeshRenderer - - first: - 28: 2800000 - second: Metal 002_baseColor - - first: - 28: 2800002 - second: Metal 002_normal - - first: - 28: 2800004 - second: Metal 002_metallic - - first: - 28: 2800006 - second: Metal 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal 002_height - - first: - 33: 3300000 - second: metal_002/metal_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_002/metal_002/SphereCollider - - first: - 1001: 100100000 - second: metal_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal 002 - prototypeName: Metal 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1550000119726971649, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -6882973941229436791, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 6347190432477724635, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3766318789785789000, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - generatedTextures: - - {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: 1550000119726971649, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: -6882973941229436791, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: 6347190432477724635, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_003.sbsar b/Assets/Materials/Substance/Metal/metal_003.sbsar deleted file mode 100644 index bbc118a2d..000000000 --- a/Assets/Materials/Substance/Metal/metal_003.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4ef8ee0ce61d17b7c84433ea0f780f32609c81f580f2c7d3a9c78303b9051a47 -size 7739 diff --git a/Assets/Materials/Substance/Metal/metal_003.sbsar.meta b/Assets/Materials/Substance/Metal/metal_003.sbsar.meta deleted file mode 100644 index f3ab67932..000000000 --- a/Assets/Materials/Substance/Metal/metal_003.sbsar.meta +++ /dev/null @@ -1,372 +0,0 @@ -fileFormatVersion: 2 -guid: 885e680924fc12c439a842a2142d4b78 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_003/metal_003 - - first: - 4: 400000 - second: metal_003/metal_003/Transform - - first: - 21: 2100000 - second: mat.Metal 003 - - first: - 23: 2300000 - second: metal_003/metal_003/MeshRenderer - - first: - 28: 2800000 - second: Metal 003_baseColor - - first: - 28: 2800002 - second: Metal 003_normal - - first: - 28: 2800004 - second: Metal 003_metallic - - first: - 28: 2800006 - second: Metal 003_height - - first: - 28: 2800008 - second: Metal 003_ambientOcclusion - - first: - 33: 3300000 - second: metal_003/metal_003/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_003/metal_003/SphereCollider - - first: - 1001: 100100000 - second: metal_003 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal 003 - prototypeName: Metal 003 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2508943184622041221, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 8, y: 8} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -1236254257114565538, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 8, y: 8} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 4019402794555593307, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1475328947160444094, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7523010977671448217, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Metal 003_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -741235592913766832, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - generatedTextures: - - {fileID: -1236254257114565538, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: -2508943184622041221, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: 4019402794555593307, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: 7523010977671448217, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: -1475328947160444094, guid: 885e680924fc12c439a842a2142d4b78, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_006.sbsar b/Assets/Materials/Substance/Metal/metal_006.sbsar deleted file mode 100644 index ac614998f..000000000 --- a/Assets/Materials/Substance/Metal/metal_006.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c7cdd662d4c7ee3124366ac316fe6aa5dd247c279bba053a9084916e0510d8df -size 12109 diff --git a/Assets/Materials/Substance/Metal/metal_006.sbsar.meta b/Assets/Materials/Substance/Metal/metal_006.sbsar.meta deleted file mode 100644 index f304dd2c0..000000000 --- a/Assets/Materials/Substance/Metal/metal_006.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 53adf8e53222e6f4791d7bf2110fb70c -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_006/metal_006 - - first: - 4: 400000 - second: metal_006/metal_006/Transform - - first: - 21: 2100000 - second: mat.Metal 006 - - first: - 23: 2300000 - second: metal_006/metal_006/MeshRenderer - - first: - 28: 2800000 - second: Metal 006_baseColor - - first: - 28: 2800002 - second: Metal 006_normal - - first: - 28: 2800004 - second: Metal 006_metallic - - first: - 28: 2800006 - second: Metal 006_height - - first: - 28: 2800008 - second: Metal 006_ambientOcclusion - - first: - 33: 3300000 - second: metal_006/metal_006/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_006/metal_006/SphereCollider - - first: - 1001: 100100000 - second: metal_006 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal 006 - prototypeName: Metal 006 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -9145106948908842110, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 8714526317094329886, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 8283496261199770474, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -247870979206812949, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 4895182546727821380, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Metal 006_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3954565982357225544, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - generatedTextures: - - {fileID: 8714526317094329886, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: -9145106948908842110, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: 8283496261199770474, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: 4895182546727821380, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: -247870979206812949, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar b/Assets/Materials/Substance/Metal/metal_aluminium.sbsar deleted file mode 100644 index 088b73bee..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b19246651deb85c3c0a8d424507e0711ccce8c9eae241da396a36cd210f38f20 -size 10491 diff --git a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta b/Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta deleted file mode 100644 index 95addd8d7..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: 6b2eb94965ca27542b8627d3521f5b5b -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_aluminium/metal_aluminium - - first: - 4: 400000 - second: metal_aluminium/metal_aluminium/Transform - - first: - 21: 2100000 - second: mat.Aluminium - - first: - 23: 2300000 - second: metal_aluminium/metal_aluminium/MeshRenderer - - first: - 28: 2800000 - second: Aluminium_baseColor - - first: - 28: 2800002 - second: Aluminium_normal - - first: - 28: 2800004 - second: Aluminium_metallic - - first: - 28: 2800006 - second: Aluminium_ambientOcclusion - - first: - 28: 2800008 - second: Aluminium_height - - first: - 33: 3300000 - second: metal_aluminium/metal_aluminium/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_aluminium/metal_aluminium/SphereCollider - - first: - 1001: 100100000 - second: metal_aluminium - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Aluminium - prototypeName: Aluminium - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -7227111979962756822, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5122202571912407749, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -5067940305606501900, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 9049458111962441826, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -7751791800289965735, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Aluminium_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 2717629391965333470, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - generatedTextures: - - {fileID: 5122202571912407749, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: -7227111979962756822, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: -5067940305606501900, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: 9049458111962441826, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: -7751791800289965735, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar b/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar deleted file mode 100644 index 7f2ec6e98..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:41bfd12f87e8255f00383022aa8a1d0c83273a8a23e21233db9f8f08eb89738f -size 12223 diff --git a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta b/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta deleted file mode 100644 index cafdf3d25..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: 06d6a565d43fba5409712ce9a10bfbef -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_aluminium_brushed/metal_aluminium_brushed - - first: - 4: 400000 - second: metal_aluminium_brushed/metal_aluminium_brushed/Transform - - first: - 21: 2100000 - second: mat.Aluminium brushed - - first: - 23: 2300000 - second: metal_aluminium_brushed/metal_aluminium_brushed/MeshRenderer - - first: - 28: 2800000 - second: Aluminium brushed_baseColor - - first: - 28: 2800002 - second: Aluminium brushed_normal - - first: - 28: 2800004 - second: Aluminium brushed_metallic - - first: - 28: 2800006 - second: Aluminium brushed_ambientOcclusion - - first: - 28: 2800008 - second: Aluminium brushed_height - - first: - 33: 3300000 - second: metal_aluminium_brushed/metal_aluminium_brushed/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_aluminium_brushed/metal_aluminium_brushed/SphereCollider - - first: - 1001: 100100000 - second: metal_aluminium_brushed - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Aluminium brushed - prototypeName: Aluminium brushed - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n - \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 4730978449518085612, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 7556082237344091230, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 6373266012617290493, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 342959783478273704, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -9132138291289375396, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Aluminium brushed_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -5899741495057040748, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - generatedTextures: - - {fileID: 7556082237344091230, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: 4730978449518085612, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: 6373266012617290493, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: 342959783478273704, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: -9132138291289375396, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_brass.sbsar b/Assets/Materials/Substance/Metal/metal_brass.sbsar deleted file mode 100644 index 8db7e53b4..000000000 --- a/Assets/Materials/Substance/Metal/metal_brass.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:26e440c8cc91202789c408e82dfa3caca98938014aaf63baade897fade94f212 -size 12658 diff --git a/Assets/Materials/Substance/Metal/metal_brass.sbsar.meta b/Assets/Materials/Substance/Metal/metal_brass.sbsar.meta deleted file mode 100644 index dad220291..000000000 --- a/Assets/Materials/Substance/Metal/metal_brass.sbsar.meta +++ /dev/null @@ -1,375 +0,0 @@ -fileFormatVersion: 2 -guid: 9fc901afb8a434e46b9405eaec2df5a4 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_brass/metal_brass - - first: - 4: 400000 - second: metal_brass/metal_brass/Transform - - first: - 21: 2100000 - second: mat.Brass - - first: - 23: 2300000 - second: metal_brass/metal_brass/MeshRenderer - - first: - 28: 2800000 - second: Brass_baseColor - - first: - 28: 2800002 - second: Brass_normal - - first: - 28: 2800004 - second: Brass_metallic - - first: - 28: 2800006 - second: Brass_ambientOcclusion - - first: - 28: 2800008 - second: Brass_height - - first: - 33: 3300000 - second: metal_brass/metal_brass/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_brass/metal_brass/SphereCollider - - first: - 1001: 100100000 - second: metal_brass - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Brass - prototypeName: Brass - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3419035557588562233, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -3436886866959827803, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7009887839391554354, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Brass_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -4907982557009795279, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - generatedTextures: - - {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: -3419035557588562233, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: -3436886866959827803, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: 7009887839391554354, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta deleted file mode 100644 index d6786ba5e..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta +++ /dev/null @@ -1,379 +0,0 @@ -fileFormatVersion: 2 -guid: 1c858fec5b74c7c46b1712494192b6b5 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 16, y: 16} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 16, y: 16} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.005 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: 3068890721646206586, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: -3552914696322007609, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: -1242281561028671816, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: -1652887728991447519, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta deleted file mode 100644 index c839a27b8..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta +++ /dev/null @@ -1,381 +0,0 @@ -fileFormatVersion: 2 -guid: a1d39ea984432bf44b4a0686afe2bf1a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 2, y: 2} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 1 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 1 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: 3068890721646206586, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: -3552914696322007609, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: -1242281561028671816, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: -1652887728991447519, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta deleted file mode 100644 index ded098ca6..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta +++ /dev/null @@ -1,381 +0,0 @@ -fileFormatVersion: 2 -guid: 504c7bfe0d50ff64a88b8eac2ceb46f8 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.005 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: 3068890721646206586, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: -3552914696322007609, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: -1242281561028671816, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: -1652887728991447519, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta deleted file mode 100644 index 98f20f5ea..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta +++ /dev/null @@ -1,382 +0,0 @@ -fileFormatVersion: 2 -guid: b2bec4b400153d745b2915f1c43e5c96 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n \n \n \n - \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 1 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 1 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: 3068890721646206586, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: -3552914696322007609, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: -1242281561028671816, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: -1652887728991447519, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_copper.sbsar b/Assets/Materials/Substance/Metal/metal_copper.sbsar deleted file mode 100644 index b9eaa9f10..000000000 --- a/Assets/Materials/Substance/Metal/metal_copper.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7e0b38479a336f09f0f273488c666a1eb025ddd9a65366da00c80179ca0a64ee -size 7413 diff --git a/Assets/Materials/Substance/Metal/metal_copper.sbsar.meta b/Assets/Materials/Substance/Metal/metal_copper.sbsar.meta deleted file mode 100644 index d1afb9abd..000000000 --- a/Assets/Materials/Substance/Metal/metal_copper.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 8249e9ffcbd97c84d8ce73343e156c82 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_copper/metal_copper - - first: - 4: 400000 - second: metal_copper/metal_copper/Transform - - first: - 21: 2100000 - second: mat.Copper - - first: - 23: 2300000 - second: metal_copper/metal_copper/MeshRenderer - - first: - 28: 2800000 - second: Copper_baseColor - - first: - 28: 2800002 - second: Copper_normal - - first: - 28: 2800004 - second: Copper_metallic - - first: - 28: 2800006 - second: Copper_ambientOcclusion - - first: - 28: 2800008 - second: Copper_height - - first: - 33: 3300000 - second: metal_copper/metal_copper/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_copper/metal_copper/SphereCollider - - first: - 1001: 100100000 - second: metal_copper - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Copper - prototypeName: Copper - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3792452219542522299, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -595311359069952391, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -1397886531756242709, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 2236529815293478155, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1739956823984805281, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Copper_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 9219180724257492359, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - generatedTextures: - - {fileID: -595311359069952391, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: -3792452219542522299, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: -1397886531756242709, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: 2236529815293478155, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: -1739956823984805281, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar b/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar deleted file mode 100644 index 24237719c..000000000 --- a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5b798bdf0e774a7d826b7080b18c91ac8000cf6ac617dc395d8cf105aba8d7da -size 12826 diff --git a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta deleted file mode 100644 index 3de9c9e1e..000000000 --- a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 9d0963470d3545a4e932ed4ea95b9d62 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_corrugated_002/metal_corrugated_002 - - first: - 4: 400000 - second: metal_corrugated_002/metal_corrugated_002/Transform - - first: - 21: 2100000 - second: mat.Metal Corrugated 002 - - first: - 23: 2300000 - second: metal_corrugated_002/metal_corrugated_002/MeshRenderer - - first: - 28: 2800000 - second: Metal Corrugated 002_baseColor - - first: - 28: 2800002 - second: Metal Corrugated 002_normal - - first: - 28: 2800004 - second: Metal Corrugated 002_metallic - - first: - 28: 2800006 - second: Metal Corrugated 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal Corrugated 002_height - - first: - 33: 3300000 - second: metal_corrugated_002/metal_corrugated_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_corrugated_002/metal_corrugated_002/SphereCollider - - first: - 1001: 100100000 - second: metal_corrugated_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Corrugated 002 - prototypeName: Metal Corrugated 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3654691528969531916, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 4818317370781631303, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 5859956115695178477, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -8111981235355854162, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -5667621616349238808, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Corrugated 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1355354389579744761, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - generatedTextures: - - {fileID: 4818317370781631303, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: -3654691528969531916, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: 5859956115695178477, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: -8111981235355854162, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: -5667621616349238808, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar b/Assets/Materials/Substance/Metal/metal_floor_002.sbsar deleted file mode 100644 index af4adc50c..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5815e5257550f8315dd80831c4cab398a3ae7b234b25e716ecca18c9facbd9be -size 11140 diff --git a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta deleted file mode 100644 index c100570af..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: ddc6970cc883b9845bdadc91983130c2 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_floor_002/metal_floor_002 - - first: - 4: 400000 - second: metal_floor_002/metal_floor_002/Transform - - first: - 21: 2100000 - second: mat.Metal Floor 002 - - first: - 23: 2300000 - second: metal_floor_002/metal_floor_002/MeshRenderer - - first: - 28: 2800000 - second: Metal Floor 002_baseColor - - first: - 28: 2800002 - second: Metal Floor 002_normal - - first: - 28: 2800004 - second: Metal Floor 002_metallic - - first: - 28: 2800006 - second: Metal Floor 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal Floor 002_height - - first: - 33: 3300000 - second: metal_floor_002/metal_floor_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_floor_002/metal_floor_002/SphereCollider - - first: - 1001: 100100000 - second: metal_floor_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Floor 002 - prototypeName: Metal Floor 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 351554284034007472, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -7508666898770042810, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -4403901252400104909, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4356325417559842052, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3247329771169464856, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Floor 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3616699503892477274, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - generatedTextures: - - {fileID: -7508666898770042810, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: 351554284034007472, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: -4403901252400104909, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: -4356325417559842052, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: -3247329771169464856, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar b/Assets/Materials/Substance/Metal/metal_floor_004.sbsar deleted file mode 100644 index f7136c15b..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3d30688944fced2d854f8375ebecd8ad7a6a8021cee07e89710b44ad8272addd -size 8634 diff --git a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta b/Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta deleted file mode 100644 index 031cbe6c4..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 50192727b92e0af4cbe5c773bec3537f -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_floor_004/metal_floor_004 - - first: - 4: 400000 - second: metal_floor_004/metal_floor_004/Transform - - first: - 21: 2100000 - second: mat.Metal Floor 004 - - first: - 23: 2300000 - second: metal_floor_004/metal_floor_004/MeshRenderer - - first: - 28: 2800000 - second: Metal Floor 004_baseColor - - first: - 28: 2800002 - second: Metal Floor 004_normal - - first: - 28: 2800004 - second: Metal Floor 004_metallic - - first: - 28: 2800006 - second: Metal Floor 004_ambientOcclusion - - first: - 28: 2800008 - second: Metal Floor 004_height - - first: - 33: 3300000 - second: metal_floor_004/metal_floor_004/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_floor_004/metal_floor_004/SphereCollider - - first: - 1001: 100100000 - second: metal_floor_004 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Floor 004 - prototypeName: Metal Floor 004 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 5886398526092406922, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 1550179426837470591, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 4385304290797446058, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -3130265262045919237, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 4866469902769357514, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Floor 004_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1891697860355797410, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - generatedTextures: - - {fileID: 1550179426837470591, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: 5886398526092406922, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: 4385304290797446058, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: -3130265262045919237, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: 4866469902769357514, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar b/Assets/Materials/Substance/Metal/metal_floor_006.sbsar deleted file mode 100644 index 81ce60800..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9604a8c7814d09f90d8bc64061cdc39c733d9f96de43143717f9a951b1f08a0e -size 10884 diff --git a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta b/Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta deleted file mode 100644 index 91f291c9d..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 06833951ebae4cc45ad88d58cb5571de -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_floor_006/metal_floor_006 - - first: - 4: 400000 - second: metal_floor_006/metal_floor_006/Transform - - first: - 21: 2100000 - second: mat.Metal Floor 006 - - first: - 23: 2300000 - second: metal_floor_006/metal_floor_006/MeshRenderer - - first: - 28: 2800000 - second: Metal Floor 006_baseColor - - first: - 28: 2800002 - second: Metal Floor 006_normal - - first: - 28: 2800004 - second: Metal Floor 006_metallic - - first: - 28: 2800006 - second: Metal Floor 006_ambientOcclusion - - first: - 28: 2800008 - second: Metal Floor 006_height - - first: - 33: 3300000 - second: metal_floor_006/metal_floor_006/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_floor_006/metal_floor_006/SphereCollider - - first: - 1001: 100100000 - second: metal_floor_006 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Floor 006 - prototypeName: Metal Floor 006 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2252411089510067877, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -446378320346000722, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 877764506763962143, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4232129871321120126, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 3318615130639472310, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Floor 006_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -6975397259061671394, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - generatedTextures: - - {fileID: -446378320346000722, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: -2252411089510067877, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: 877764506763962143, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: -4232129871321120126, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: 3318615130639472310, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_gold.sbsar b/Assets/Materials/Substance/Metal/metal_gold.sbsar deleted file mode 100644 index 5aa377680..000000000 --- a/Assets/Materials/Substance/Metal/metal_gold.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:29ef1a459ab7d090b32ee563d729038527c4d031595abef2a49398543d11343c -size 7428 diff --git a/Assets/Materials/Substance/Metal/metal_gold.sbsar.meta b/Assets/Materials/Substance/Metal/metal_gold.sbsar.meta deleted file mode 100644 index c4e7f4644..000000000 --- a/Assets/Materials/Substance/Metal/metal_gold.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: a74970be876d3554ea0f279f39314c9c -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_gold/metal_gold - - first: - 4: 400000 - second: metal_gold/metal_gold/Transform - - first: - 21: 2100000 - second: mat.Gold - - first: - 23: 2300000 - second: metal_gold/metal_gold/MeshRenderer - - first: - 28: 2800000 - second: Gold_baseColor - - first: - 28: 2800002 - second: Gold_normal - - first: - 28: 2800004 - second: Gold_metallic - - first: - 28: 2800006 - second: Gold_ambientOcclusion - - first: - 28: 2800008 - second: Gold_height - - first: - 33: 3300000 - second: metal_gold/metal_gold/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_gold/metal_gold/SphereCollider - - first: - 1001: 100100000 - second: metal_gold - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Gold - prototypeName: Gold - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -6248678595456566848, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 2039085267362074300, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8783136193678078058, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7384525862955468029, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -8934633548313413119, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Gold_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -905690159841262435, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - generatedTextures: - - {fileID: 2039085267362074300, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: -6248678595456566848, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: -8783136193678078058, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: 7384525862955468029, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: -8934633548313413119, guid: a74970be876d3554ea0f279f39314c9c, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_nickel.sbsar b/Assets/Materials/Substance/Metal/metal_nickel.sbsar deleted file mode 100644 index e7cf69c6b..000000000 --- a/Assets/Materials/Substance/Metal/metal_nickel.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a0395691305bc49406088b12b65ea186d65d5101bc230a2e91b4ddbf2c7b65ea -size 8935 diff --git a/Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta b/Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta deleted file mode 100644 index 65531754c..000000000 --- a/Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: c5f2177e1f35daa499f4d7e0b7f3370a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_nickel/metal_nickel - - first: - 4: 400000 - second: metal_nickel/metal_nickel/Transform - - first: - 21: 2100000 - second: mat.Nickel - - first: - 23: 2300000 - second: metal_nickel/metal_nickel/MeshRenderer - - first: - 28: 2800000 - second: Nickel_baseColor - - first: - 28: 2800002 - second: Nickel_normal - - first: - 28: 2800004 - second: Nickel_metallic - - first: - 28: 2800006 - second: Nickel_ambientOcclusion - - first: - 28: 2800008 - second: Nickel_height - - first: - 33: 3300000 - second: metal_nickel/metal_nickel/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_nickel/metal_nickel/SphereCollider - - first: - 1001: 100100000 - second: metal_nickel - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Nickel - prototypeName: Nickel - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1040180909335529060, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -3896990606402278735, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8156577797594723071, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -7935365347593253955, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -4922792887777872198, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Nickel_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -443055228576417237, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - generatedTextures: - - {fileID: -3896990606402278735, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: 1040180909335529060, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: -8156577797594723071, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: -7935365347593253955, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: -4922792887777872198, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar b/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar deleted file mode 100644 index d764cd35f..000000000 --- a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bc8dcd55f0619c028037c7225720acb4eea87b28cc7c120125fa2b38d02f775a -size 13628 diff --git a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta b/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta deleted file mode 100644 index 467fa07bd..000000000 --- a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta +++ /dev/null @@ -1,376 +0,0 @@ -fileFormatVersion: 2 -guid: b7e648471e9dfc44490bd41973711541 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_painted_steel/metal_painted_steel - - first: - 4: 400000 - second: metal_painted_steel/metal_painted_steel/Transform - - first: - 21: 2100000 - second: mat.Painted steel - - first: - 23: 2300000 - second: metal_painted_steel/metal_painted_steel/MeshRenderer - - first: - 28: 2800000 - second: Painted steel_baseColor - - first: - 28: 2800002 - second: Painted steel_normal - - first: - 28: 2800004 - second: Painted steel_metallic - - first: - 28: 2800006 - second: Painted steel_ambientOcclusion - - first: - 28: 2800008 - second: Painted steel_height - - first: - 33: 3300000 - second: metal_painted_steel/metal_painted_steel/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_painted_steel/metal_painted_steel/SphereCollider - - first: - 1001: 100100000 - second: metal_painted_steel - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Painted steel - prototypeName: Painted steel - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 4387638379454744182, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 5280895355680202213, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 1053975553097811288, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -5932748352949090903, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Painted steel_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -4658142721435264040, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - generatedTextures: - - {fileID: 4387638379454744182, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: 5280895355680202213, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: 1053975553097811288, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: -5932748352949090903, guid: b7e648471e9dfc44490bd41973711541, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar b/Assets/Materials/Substance/Metal/metal_panels_001.sbsar deleted file mode 100644 index 2ee3b87ea..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e868f72fde8e3c55a2d8c097ebb39c05157670897d14eeb86932021feec16158 -size 11295 diff --git a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta b/Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta deleted file mode 100644 index a423b3b51..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 7363fcc4a3c41a349b29de7ec34555be -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_panels_001/metal_panels_001 - - first: - 4: 400000 - second: metal_panels_001/metal_panels_001/Transform - - first: - 21: 2100000 - second: mat.Metal Panels 001 - - first: - 23: 2300000 - second: metal_panels_001/metal_panels_001/MeshRenderer - - first: - 28: 2800000 - second: Metal Panels 001_baseColor - - first: - 28: 2800002 - second: Metal Panels 001_normal - - first: - 28: 2800004 - second: Metal Panels 001_metallic - - first: - 28: 2800006 - second: Metal Panels 001_ambientOcclusion - - first: - 28: 2800008 - second: Metal Panels 001_height - - first: - 33: 3300000 - second: metal_panels_001/metal_panels_001/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_panels_001/metal_panels_001/SphereCollider - - first: - 1001: 100100000 - second: metal_panels_001 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Panels 001 - prototypeName: Metal Panels 001 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 2945532018097518028, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 6344665451385196243, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -103584793617860315, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -2941359408041138506, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 1361220934952870948, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Panels 001_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 1523472303362493764, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - generatedTextures: - - {fileID: 6344665451385196243, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: 2945532018097518028, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: -103584793617860315, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: -2941359408041138506, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: 1361220934952870948, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar b/Assets/Materials/Substance/Metal/metal_panels_002.sbsar deleted file mode 100644 index 2cf3cd0b5..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b16e09a1b06ae6b857d9f9478af0838a31ba554a2455b9e65e9db43a125ce633 -size 7592 diff --git a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta deleted file mode 100644 index fe8ecd2b6..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 2e9a9dbacde66a446852af882f33e9e2 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_panels_002/metal_panels_002 - - first: - 4: 400000 - second: metal_panels_002/metal_panels_002/Transform - - first: - 21: 2100000 - second: mat.Metal Panels 002 - - first: - 23: 2300000 - second: metal_panels_002/metal_panels_002/MeshRenderer - - first: - 28: 2800000 - second: Metal Panels 002_baseColor - - first: - 28: 2800002 - second: Metal Panels 002_normal - - first: - 28: 2800004 - second: Metal Panels 002_metallic - - first: - 28: 2800006 - second: Metal Panels 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal Panels 002_height - - first: - 33: 3300000 - second: metal_panels_002/metal_panels_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_panels_002/metal_panels_002/SphereCollider - - first: - 1001: 100100000 - second: metal_panels_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Panels 002 - prototypeName: Metal Panels 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -7157783387845257801, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 6030008930922367719, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -5177487458041023939, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -6221273311826804186, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -2755774738339798629, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Panels 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3282252981698000714, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - generatedTextures: - - {fileID: 6030008930922367719, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -7157783387845257801, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -5177487458041023939, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -6221273311826804186, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -2755774738339798629, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar b/Assets/Materials/Substance/Metal/metal_plate_001.sbsar deleted file mode 100644 index 3d06effb9..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7c9aea022bbc0138be51bb7b89314a569ad359390a0b8d1b6b2c717d317acd8b -size 10171 diff --git a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta b/Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta deleted file mode 100644 index 9a0327632..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 180b85899b4b1f848b348230339ce984 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_plate_001/metal_plate_001 - - first: - 4: 400000 - second: metal_plate_001/metal_plate_001/Transform - - first: - 21: 2100000 - second: mat.Metal plate 001 - - first: - 23: 2300000 - second: metal_plate_001/metal_plate_001/MeshRenderer - - first: - 28: 2800000 - second: Metal plate 001_baseColor - - first: - 28: 2800002 - second: Metal plate 001_normal - - first: - 28: 2800004 - second: Metal plate 001_metallic - - first: - 28: 2800006 - second: Metal plate 001_ambientOcclusion - - first: - 28: 2800008 - second: Metal plate 001_height - - first: - 33: 3300000 - second: metal_plate_001/metal_plate_001/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_plate_001/metal_plate_001/SphereCollider - - first: - 1001: 100100000 - second: metal_plate_001 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal plate 001 - prototypeName: Metal plate 001 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 6805374924820727666, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 443512894100413061, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3656363544911682969, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 6012193567810889268, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 1247009903862830065, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal plate 001_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1468868417959000437, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - generatedTextures: - - {fileID: 443512894100413061, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: 6805374924820727666, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: -3656363544911682969, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: 6012193567810889268, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: 1247009903862830065, guid: 180b85899b4b1f848b348230339ce984, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar b/Assets/Materials/Substance/Metal/metal_plate_004.sbsar deleted file mode 100644 index dc0474e13..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:65295627150c30fc70fe138aee16c2266bffdd0a5b1fbcbe7fe040a3d0309d39 -size 14216 diff --git a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta b/Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta deleted file mode 100644 index fd4373932..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 0b5dfc86c0681a3459a57d197804191b -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_plate_004/metal_plate_004 - - first: - 4: 400000 - second: metal_plate_004/metal_plate_004/Transform - - first: - 21: 2100000 - second: mat.Metal plate 004 - - first: - 23: 2300000 - second: metal_plate_004/metal_plate_004/MeshRenderer - - first: - 28: 2800000 - second: Metal plate 004_baseColor - - first: - 28: 2800002 - second: Metal plate 004_normal - - first: - 28: 2800004 - second: Metal plate 004_metallic - - first: - 28: 2800006 - second: Metal plate 004_ambientOcclusion - - first: - 28: 2800008 - second: Metal plate 004_height - - first: - 33: 3300000 - second: metal_plate_004/metal_plate_004/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_plate_004/metal_plate_004/SphereCollider - - first: - 1001: 100100000 - second: metal_plate_004 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal plate 004 - prototypeName: Metal plate 004 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -7484568915117973449, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 1309396409266656355, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -5781884682247363129, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 5620992320681838871, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 6570316561944570698, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal plate 004_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -5894754650268316995, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - generatedTextures: - - {fileID: 1309396409266656355, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: -7484568915117973449, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: -5781884682247363129, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: 5620992320681838871, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: 6570316561944570698, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar b/Assets/Materials/Substance/Metal/metal_plate_011.sbsar deleted file mode 100644 index c1e0a3922..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:829bc422cbe5b984103972cd7cf36d207fe0a6b561a2619301dec3e684009784 -size 9674 diff --git a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta b/Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta deleted file mode 100644 index 55c1cd50c..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: ca8f080ab60226e4097841eee2bfa8db -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_plate_011/metal_plate_011 - - first: - 4: 400000 - second: metal_plate_011/metal_plate_011/Transform - - first: - 21: 2100000 - second: mat.Metal plate 011 - - first: - 23: 2300000 - second: metal_plate_011/metal_plate_011/MeshRenderer - - first: - 28: 2800000 - second: Metal plate 011_baseColor - - first: - 28: 2800002 - second: Metal plate 011_normal - - first: - 28: 2800004 - second: Metal plate 011_metallic - - first: - 28: 2800006 - second: Metal plate 011_ambientOcclusion - - first: - 28: 2800008 - second: Metal plate 011_height - - first: - 33: 3300000 - second: metal_plate_011/metal_plate_011/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_plate_011/metal_plate_011/SphereCollider - - first: - 1001: 100100000 - second: metal_plate_011 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal plate 011 - prototypeName: Metal plate 011 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1206901763152500494, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -562402163750398719, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8211546087015286653, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7355910353852850503, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -2794334530799708578, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal plate 011_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 5028268363422298589, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - generatedTextures: - - {fileID: -562402163750398719, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: 1206901763152500494, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: -8211546087015286653, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: 7355910353852850503, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: -2794334530799708578, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_platinum.sbsar b/Assets/Materials/Substance/Metal/metal_platinum.sbsar deleted file mode 100644 index ffaec19de..000000000 --- a/Assets/Materials/Substance/Metal/metal_platinum.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b880030baaf5ccc272c780265fc4b1570a55a63a8b804223ccbdc54a576b9be7 -size 5196 diff --git a/Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta b/Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta deleted file mode 100644 index f39efaf0d..000000000 --- a/Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta +++ /dev/null @@ -1,372 +0,0 @@ -fileFormatVersion: 2 -guid: 9458f33b8e7e51a42aa19686b9779d82 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_platinum/metal_platinum - - first: - 4: 400000 - second: metal_platinum/metal_platinum/Transform - - first: - 21: 2100000 - second: mat.Platinum - - first: - 23: 2300000 - second: metal_platinum/metal_platinum/MeshRenderer - - first: - 28: 2800000 - second: Platinum_baseColor - - first: - 28: 2800002 - second: Platinum_normal - - first: - 28: 2800004 - second: Platinum_metallic - - first: - 28: 2800006 - second: Platinum_ambientOcclusion - - first: - 28: 2800008 - second: Platinum_height - - first: - 33: 3300000 - second: metal_platinum/metal_platinum/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_platinum/metal_platinum/SphereCollider - - first: - 1001: 100100000 - second: metal_platinum - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Platinum - prototypeName: Platinum - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3498638986299907941, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -8172963137857357993, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8040379993892829019, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 225164955126363719, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -130007606447889175, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Platinum_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 8636029498071112704, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - generatedTextures: - - {fileID: -8172963137857357993, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: 3498638986299907941, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: -8040379993892829019, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: 225164955126363719, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: -130007606447889175, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar b/Assets/Materials/Substance/Metal/metal_roll_up.sbsar deleted file mode 100644 index db99f183e..000000000 --- a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1a2036e21cdd2d392fdcb755d2faf982335fc4deaa8c7b913110db234fa04f3a -size 11017 diff --git a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta b/Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta deleted file mode 100644 index 3d93351e8..000000000 --- a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 4e39297ae4fe9ee4b803c04eabb69da7 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_roll_up/metal_roll_up - - first: - 4: 400000 - second: metal_roll_up/metal_roll_up/Transform - - first: - 21: 2100000 - second: mat.Metal roll up - - first: - 23: 2300000 - second: metal_roll_up/metal_roll_up/MeshRenderer - - first: - 28: 2800000 - second: Metal roll up_baseColor - - first: - 28: 2800002 - second: Metal roll up_normal - - first: - 28: 2800004 - second: Metal roll up_metallic - - first: - 28: 2800006 - second: Metal roll up_ambientOcclusion - - first: - 28: 2800008 - second: Metal roll up_height - - first: - 33: 3300000 - second: metal_roll_up/metal_roll_up/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_roll_up/metal_roll_up/SphereCollider - - first: - 1001: 100100000 - second: metal_roll_up - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal roll up - prototypeName: Metal roll up - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1258325809611119299, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -5250987364813910665, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -1897870436205287166, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7199963334284863655, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 1153539711168243343, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal roll up_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 7440086527666654772, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - generatedTextures: - - {fileID: -5250987364813910665, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: 1258325809611119299, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: -1897870436205287166, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: 7199963334284863655, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: 1153539711168243343, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_silver.sbsar b/Assets/Materials/Substance/Metal/metal_silver.sbsar deleted file mode 100644 index 08b0ac146..000000000 --- a/Assets/Materials/Substance/Metal/metal_silver.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4b18ce39a69d5e25641d53fcbe04f281c92ca7e01936e6a9b279476be8ff3255 -size 6898 diff --git a/Assets/Materials/Substance/Metal/metal_silver.sbsar.meta b/Assets/Materials/Substance/Metal/metal_silver.sbsar.meta deleted file mode 100644 index 326559316..000000000 --- a/Assets/Materials/Substance/Metal/metal_silver.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 0be5fb1df83ac8e499a3f6a060041e49 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_silver/metal_silver - - first: - 4: 400000 - second: metal_silver/metal_silver/Transform - - first: - 21: 2100000 - second: mat.Silver - - first: - 23: 2300000 - second: metal_silver/metal_silver/MeshRenderer - - first: - 28: 2800000 - second: Silver_baseColor - - first: - 28: 2800002 - second: Silver_normal - - first: - 28: 2800004 - second: Silver_metallic - - first: - 28: 2800006 - second: Silver_ambientOcclusion - - first: - 28: 2800008 - second: Silver_height - - first: - 33: 3300000 - second: metal_silver/metal_silver/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_silver/metal_silver/SphereCollider - - first: - 1001: 100100000 - second: metal_silver - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Silver - prototypeName: Silver - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 8947980237086559854, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -1383037052668628532, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 6429125567479694453, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -9097439929179392311, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 425190381137097012, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Silver_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 7490952440742008943, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - generatedTextures: - - {fileID: -1383037052668628532, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: 8947980237086559854, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: 6429125567479694453, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: -9097439929179392311, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: 425190381137097012, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel.sbsar b/Assets/Materials/Substance/Metal/metal_steel.sbsar deleted file mode 100644 index 31ec34fd3..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d559edac51ad4c529c197d7c9a813fe8c2fa1bcb0963cd0f8bad8ab1403b3821 -size 10697 diff --git a/Assets/Materials/Substance/Metal/metal_steel.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel.sbsar.meta deleted file mode 100644 index 172d4668b..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel.sbsar.meta +++ /dev/null @@ -1,375 +0,0 @@ -fileFormatVersion: 2 -guid: cbc61995a46604441ab9de4f1c68e290 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel/metal_steel - - first: - 4: 400000 - second: metal_steel/metal_steel/Transform - - first: - 21: 2100000 - second: mat.Steel - - first: - 23: 2300000 - second: metal_steel/metal_steel/MeshRenderer - - first: - 28: 2800000 - second: Steel_baseColor - - first: - 28: 2800002 - second: Steel_normal - - first: - 28: 2800004 - second: Steel_metallic - - first: - 28: 2800006 - second: Steel_ambientOcclusion - - first: - 28: 2800008 - second: Steel_height - - first: - 33: 3300000 - second: metal_steel/metal_steel/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel/metal_steel/SphereCollider - - first: - 1001: 100100000 - second: metal_steel - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel - prototypeName: Steel - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -3155047780354543793, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - generatedTextures: - - {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar b/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar deleted file mode 100644 index 45c0b10b3..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bf6b40453b42e050b2ce05478f1c1964d9489cdf02413f12b40f4ce1e49b4432 -size 12832 diff --git a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta deleted file mode 100644 index d08c0d290..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta +++ /dev/null @@ -1,370 +0,0 @@ -fileFormatVersion: 2 -guid: ea7457b9a4f0bcb43becaa33de541cbd -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel_brushed/metal_steel_brushed - - first: - 4: 400000 - second: metal_steel_brushed/metal_steel_brushed/Transform - - first: - 21: 2100000 - second: mat.Steel brushed - - first: - 23: 2300000 - second: metal_steel_brushed/metal_steel_brushed/MeshRenderer - - first: - 28: 2800000 - second: Steel brushed_baseColor - - first: - 28: 2800002 - second: Steel brushed_normal - - first: - 28: 2800004 - second: Steel brushed_metallic - - first: - 28: 2800006 - second: Steel brushed_ambientOcclusion - - first: - 28: 2800008 - second: Steel brushed_height - - first: - 33: 3300000 - second: metal_steel_brushed/metal_steel_brushed/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel_brushed/metal_steel_brushed/SphereCollider - - first: - 1001: 100100000 - second: metal_steel_brushed - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel brushed - prototypeName: Steel brushed - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -4471413742775304797, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -4638397344074346932, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 5049811794194361025, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 1753668427856518731, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3498708498072814504, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel brushed_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 7852708265981260911, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - generatedTextures: - - {fileID: -4638397344074346932, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: -4471413742775304797, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: 5049811794194361025, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: 1753668427856518731, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: -3498708498072814504, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar b/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar deleted file mode 100644 index 6580295bb..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a9ae449451a55abd8466e8af67685a45d86fd39ea2070294dde7f2a07776bea5 -size 17275 diff --git a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta deleted file mode 100644 index 1dd652796..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 092bdd8d243488141aeab5bb0d72429a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel_bumped/metal_steel_bumped - - first: - 4: 400000 - second: metal_steel_bumped/metal_steel_bumped/Transform - - first: - 21: 2100000 - second: mat.Steel bumped - - first: - 23: 2300000 - second: metal_steel_bumped/metal_steel_bumped/MeshRenderer - - first: - 28: 2800000 - second: Steel bumped_baseColor - - first: - 28: 2800002 - second: Steel bumped_normal - - first: - 28: 2800004 - second: Steel bumped_metallic - - first: - 28: 2800006 - second: Steel bumped_ambientOcclusion - - first: - 28: 2800008 - second: Steel bumped_height - - first: - 33: 3300000 - second: metal_steel_bumped/metal_steel_bumped/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel_bumped/metal_steel_bumped/SphereCollider - - first: - 1001: 100100000 - second: metal_steel_bumped - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel bumped - prototypeName: Steel bumped - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3586080781697202320, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 86365302875955127, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 9208498935135840223, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7740971908710523460, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 6493472383464308858, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel bumped_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -864409875390858066, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - generatedTextures: - - {fileID: 86365302875955127, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 3586080781697202320, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 9208498935135840223, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 7740971908710523460, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 6493472383464308858, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar b/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar deleted file mode 100644 index 92bee293c..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:54993a1aae47acf7e1aba24812f215e1787969016dd1f420899ab363342a7b6d -size 9206 diff --git a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta deleted file mode 100644 index a7cabf9ff..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: e7758cad28ae98f478940e55222419a6 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel_parkerized/metal_steel_parkerized - - first: - 4: 400000 - second: metal_steel_parkerized/metal_steel_parkerized/Transform - - first: - 21: 2100000 - second: mat.Steel parkerized - - first: - 23: 2300000 - second: metal_steel_parkerized/metal_steel_parkerized/MeshRenderer - - first: - 28: 2800000 - second: Steel parkerized_baseColor - - first: - 28: 2800002 - second: Steel parkerized_normal - - first: - 28: 2800004 - second: Steel parkerized_metallic - - first: - 28: 2800006 - second: Steel parkerized_ambientOcclusion - - first: - 28: 2800008 - second: Steel parkerized_height - - first: - 33: 3300000 - second: metal_steel_parkerized/metal_steel_parkerized/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel_parkerized/metal_steel_parkerized/SphereCollider - - first: - 1001: 100100000 - second: metal_steel_parkerized - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel parkerized - prototypeName: Steel parkerized - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 885599758852769373, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -4474525002722929857, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -2334804936223627746, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -8380876848358870972, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 172713863077875830, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel parkerized_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -6026401407715332296, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - generatedTextures: - - {fileID: -4474525002722929857, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: 885599758852769373, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: -2334804936223627746, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: -8380876848358870972, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: 172713863077875830, guid: e7758cad28ae98f478940e55222419a6, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_titanium.sbsar b/Assets/Materials/Substance/Metal/metal_titanium.sbsar deleted file mode 100644 index ede9cde4d..000000000 --- a/Assets/Materials/Substance/Metal/metal_titanium.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e3aabfbcb813fef9ef20793d54c93bf5c37255573bb8ad043620f60041acd6d1 -size 5206 diff --git a/Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta b/Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta deleted file mode 100644 index e4ece6915..000000000 --- a/Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 58e16b7dbc1c31f4585e11544cdce127 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_titanium/metal_titanium - - first: - 4: 400000 - second: metal_titanium/metal_titanium/Transform - - first: - 21: 2100000 - second: mat.Titanium - - first: - 23: 2300000 - second: metal_titanium/metal_titanium/MeshRenderer - - first: - 28: 2800000 - second: Titanium_baseColor - - first: - 28: 2800002 - second: Titanium_normal - - first: - 28: 2800004 - second: Titanium_metallic - - first: - 28: 2800006 - second: Titanium_ambientOcclusion - - first: - 28: 2800008 - second: Titanium_height - - first: - 33: 3300000 - second: metal_titanium/metal_titanium/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_titanium/metal_titanium/SphereCollider - - first: - 1001: 100100000 - second: metal_titanium - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Titanium - prototypeName: Titanium - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -5074057273227030627, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 3009319823116150993, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 3613456606582262254, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7558371940554398246, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3774795931012705877, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Titanium_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 9178725544925813344, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - generatedTextures: - - {fileID: 3009319823116150993, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: -5074057273227030627, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: 3613456606582262254, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: 7558371940554398246, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: -3774795931012705877, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_used.sbsar b/Assets/Materials/Substance/Metal/metal_used.sbsar deleted file mode 100644 index 5a8b87d9c..000000000 --- a/Assets/Materials/Substance/Metal/metal_used.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:03b72a9708206dd2c10aba185b507def52bbbcb713666711ed5d67926fbedd68 -size 14332 diff --git a/Assets/Materials/Substance/Metal/metal_used.sbsar.meta b/Assets/Materials/Substance/Metal/metal_used.sbsar.meta deleted file mode 100644 index 37fcc6a20..000000000 --- a/Assets/Materials/Substance/Metal/metal_used.sbsar.meta +++ /dev/null @@ -1,371 +0,0 @@ -fileFormatVersion: 2 -guid: 130f566ffa0b2424fbb47de2194c136a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_used/metal_used - - first: - 4: 400000 - second: metal_used/metal_used/Transform - - first: - 21: 2100000 - second: mat.Metal used - - first: - 23: 2300000 - second: metal_used/metal_used/MeshRenderer - - first: - 28: 2800000 - second: Metal used_baseColor - - first: - 28: 2800002 - second: Metal used_normal - - first: - 28: 2800004 - second: Metal used_metallic - - first: - 28: 2800006 - second: Metal used_ambientOcclusion - - first: - 28: 2800008 - second: Metal used_height - - first: - 33: 3300000 - second: metal_used/metal_used/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_used/metal_used/SphereCollider - - first: - 1001: 100100000 - second: metal_used - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal used - prototypeName: Metal used - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 8398852885706109728, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 8357651109123355072, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -435054815742279573, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 6248133906606842143, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 2780512161145013460, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal used_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -890370705972978167, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - generatedTextures: - - {fileID: 8357651109123355072, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: 8398852885706109728, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: -435054815742279573, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: 6248133906606842143, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: 2780512161145013460, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_weapon.sbsar b/Assets/Materials/Substance/Metal/metal_weapon.sbsar deleted file mode 100644 index d96236940..000000000 --- a/Assets/Materials/Substance/Metal/metal_weapon.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8e9033843201f75f1b86df82b69fd89ee6b9aa317df18f9105d0f8904d56be8f -size 10547 diff --git a/Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta b/Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta deleted file mode 100644 index 05d1fcf4b..000000000 --- a/Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: 07f679eadba9fb14abac26b1e165f7d5 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_weapon/metal_weapon - - first: - 4: 400000 - second: metal_weapon/metal_weapon/Transform - - first: - 21: 2100000 - second: mat.Metal Weapon - - first: - 23: 2300000 - second: metal_weapon/metal_weapon/MeshRenderer - - first: - 28: 2800000 - second: Metal Weapon_baseColor - - first: - 28: 2800002 - second: Metal Weapon_normal - - first: - 28: 2800004 - second: Metal Weapon_metallic - - first: - 28: 2800006 - second: Metal Weapon_ambientOcclusion - - first: - 28: 2800008 - second: Metal Weapon_height - - first: - 33: 3300000 - second: metal_weapon/metal_weapon/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_weapon/metal_weapon/SphereCollider - - first: - 1001: 100100000 - second: metal_weapon - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Weapon - prototypeName: Metal Weapon - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -6635831357954291190, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -6402586014670071135, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 854616604008364032, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4606406952830974004, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -5822151887330517421, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Weapon_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -6659110875122461561, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - generatedTextures: - - {fileID: -6402586014670071135, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: -6635831357954291190, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: 854616604008364032, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: 4606406952830974004, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: -5822151887330517421, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_woven.sbsar b/Assets/Materials/Substance/Metal/metal_woven.sbsar deleted file mode 100644 index 576f8c4a5..000000000 --- a/Assets/Materials/Substance/Metal/metal_woven.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6c50e25516df1c3d2cb879d4e3e78491462296d92f05ac5774b6aa1290a777ee -size 9445 diff --git a/Assets/Materials/Substance/Metal/metal_woven.sbsar.meta b/Assets/Materials/Substance/Metal/metal_woven.sbsar.meta deleted file mode 100644 index 27d8bfafe..000000000 --- a/Assets/Materials/Substance/Metal/metal_woven.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: deb7e15e5f95294498d18869d9f11302 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_woven/metal_woven - - first: - 4: 400000 - second: metal_woven/metal_woven/Transform - - first: - 21: 2100000 - second: mat.Metal woven - - first: - 23: 2300000 - second: metal_woven/metal_woven/MeshRenderer - - first: - 28: 2800000 - second: Metal woven_baseColor - - first: - 28: 2800002 - second: Metal woven_normal - - first: - 28: 2800004 - second: Metal woven_metallic - - first: - 28: 2800006 - second: Metal woven_ambientOcclusion - - first: - 28: 2800008 - second: Metal woven_height - - first: - 33: 3300000 - second: metal_woven/metal_woven/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_woven/metal_woven/SphereCollider - - first: - 1001: 100100000 - second: metal_woven - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal woven - prototypeName: Metal woven - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 549858149917880910, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -5021036940690714266, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -4741193760961545063, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4441773978818050154, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -8782013540898460330, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal woven_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1778075352807424672, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - generatedTextures: - - {fileID: -5021036940690714266, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: 549858149917880910, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: -4741193760961545063, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: 4441773978818050154, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: -8782013540898460330, guid: deb7e15e5f95294498d18869d9f11302, type: 3} diff --git a/Assets/Materials/Substance/Metal/snatched_metal.sbsar b/Assets/Materials/Substance/Metal/snatched_metal.sbsar deleted file mode 100644 index 35980ce5c..000000000 --- a/Assets/Materials/Substance/Metal/snatched_metal.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:556e67022b660530d0afc8296e37706b09e9ef08db46b5421edbd80f0c8993f2 -size 28573 diff --git a/Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta b/Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta deleted file mode 100644 index 3da7ab6e7..000000000 --- a/Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta +++ /dev/null @@ -1,311 +0,0 @@ -fileFormatVersion: 2 -guid: 9aa51bbe4dd46874a906608c34a739e4 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Snatched Metal - prototypeName: Snatched Metal - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 8651868829797956950, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 3043754869544600785, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8730703347107057792, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 8639218750153593357, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 8363912540366899318, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambientocclusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: opacity - identifier: opacity - usageName: opacity - channelStr: opacity - label: Opacity - usage: 2 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: opacity - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: opacity - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: opacity - components: - - sourceName: opacity - from: 0 - to: 3 - textureParameters: - - textureName: Snatched Metal - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - opacity - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -2363654054484809406, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - generatedTextures: - - {fileID: 3043754869544600785, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: 8651868829797956950, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: -8730703347107057792, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: 8363912540366899318, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: 8639218750153593357, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} diff --git a/Assets/Materials/Substance/marble_002.sbsar b/Assets/Materials/Substance/marble_002.sbsar deleted file mode 100644 index 728270967..000000000 --- a/Assets/Materials/Substance/marble_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2859e24557bccbe309d8946052849b828cabd34b8e45b933faee212eeffd462e -size 8113 diff --git a/Assets/Materials/Substance/marble_002.sbsar.meta b/Assets/Materials/Substance/marble_002.sbsar.meta deleted file mode 100644 index 624e0d1a6..000000000 --- a/Assets/Materials/Substance/marble_002.sbsar.meta +++ /dev/null @@ -1,296 +0,0 @@ -fileFormatVersion: 2 -guid: ef9a54b8dacea9f44be70da43472f701 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Marble 002 - prototypeName: Marble 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " \n \n - \n \n \n \n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 5777664804669422655, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -5564000130503291907, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3258750942226492355, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4985089394248351555, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7116303992264550, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Marble 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 4096 - textureHeight: 4096 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -4681939019719023292, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - generatedTextures: - - {fileID: -5564000130503291907, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: 5777664804669422655, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: -3258750942226492355, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: 4985089394248351555, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: 7116303992264550, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} diff --git a/Assets/Materials/Thrusters.mat b/Assets/Materials/Thrusters.mat deleted file mode 100644 index f9b21ae83..000000000 --- a/Assets/Materials/Thrusters.mat +++ /dev/null @@ -1,87 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Thrusters - m_Shader: {fileID: 4800000, guid: d69ef48273708ef4680762f5cdcfc860, type: 3} - m_ShaderKeywords: - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpPower: 2 - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _Emission: 0 - - _EmissionFresnel: 1 - - _EmissionRoughnessFresnelPower: 0.5 - - _GlossMapScale: 1 - - _Glossiness: 1 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _ReverseRim: 0 - - _Rotation: 0 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0.7112653, g: 0.4292453, b: 1, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Materials/Thrusters.mat.meta b/Assets/Materials/Thrusters.mat.meta deleted file mode 100644 index 5fd79a1be..000000000 --- a/Assets/Materials/Thrusters.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 616adaf59c64a444f8249cc7cf13c527 -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Models/Discobolus/Discobolus Bronze.mat.meta b/Assets/Models/Discobolus/Discobolus Bronze.mat.meta deleted file mode 100644 index 4ca3a3b46..000000000 --- a/Assets/Models/Discobolus/Discobolus Bronze.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 45f1ac126982c314a8471da3d264210b -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 2100000 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Models/Discobolus/Discobolus Marble.mat b/Assets/Models/Discobolus/Discobolus Marble.mat index 3c862a22c..f4331ed09 100644 --- a/Assets/Models/Discobolus/Discobolus Marble.mat +++ b/Assets/Models/Discobolus/Discobolus Marble.mat @@ -40,13 +40,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -5564000130503291907, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3258750942226492355, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: @@ -63,7 +61,7 @@ Material: - _DetailNormalMapScale: 1 - _DstBlend: 0 - _GlossMapScale: 1 - - _Glossiness: 0.5 + - _Glossiness: 0.45 - _GlossyReflections: 1 - _Metallic: 0 - _Mode: 0 @@ -75,6 +73,6 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.7, g: 0.654348, b: 0.525, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Models/Zenith_Blender.fbx.meta b/Assets/Models/Zenith_Blender.fbx.meta index 2094752dc..6f719ce83 100644 --- a/Assets/Models/Zenith_Blender.fbx.meta +++ b/Assets/Models/Zenith_Blender.fbx.meta @@ -8,8 +8,7 @@ ModelImporter: type: UnityEngine:Material assembly: UnityEngine.CoreModule name: Black - second: {fileID: 3720744386649352057, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + second: {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} - first: type: UnityEngine:Material assembly: UnityEngine.CoreModule @@ -19,8 +18,7 @@ ModelImporter: type: UnityEngine:Material assembly: UnityEngine.CoreModule name: White - second: {fileID: -741235592913766832, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + second: {fileID: 2100000, guid: 39af4e3978df92f40a55e2a114aa242a, type: 2} materials: materialImportMode: 1 materialName: 0 diff --git a/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc b/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc deleted file mode 100644 index ef6b2e96c..000000000 --- a/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc +++ /dev/null @@ -1,129 +0,0 @@ -// -// Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader -// -// Original work (webgl-noise) Copyright (C) 2011 Stefan Gustavson -// Translation and modification was made by Keijiro Takahashi. -// -// This shader is based on the webgl-noise GLSL shader. For further details -// of the original shader, please see the following description from the -// original source code. -// - -// -// GLSL textureless classic 2D noise "cnoise", -// with an RSL-style periodic variant "pnoise". -// Author: Stefan Gustavson (stefan.gustavson@liu.se) -// Version: 2011-08-22 -// -// Many thanks to Ian McEwan of Ashima Arts for the -// ideas for permutation and gradient selection. -// -// Copyright (c) 2011 Stefan Gustavson. All rights reserved. -// Distributed under the MIT license. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -float4 mod(float4 x, float4 y) -{ - return x - y * floor(x / y); -} - -float4 mod289(float4 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 permute(float4 x) -{ - return mod289(((x*34.0)+1.0)*x); -} - -float4 taylorInvSqrt(float4 r) -{ - return (float4)1.79284291400159 - r * 0.85373472095314; -} - -float2 fade(float2 t) { - return t*t*t*(t*(t*6.0-15.0)+10.0); -} - -// Classic Perlin noise -float cnoise(float2 P) -{ - float4 Pi = floor(P.xyxy) + float4(0.0, 0.0, 1.0, 1.0); - float4 Pf = frac (P.xyxy) - float4(0.0, 0.0, 1.0, 1.0); - Pi = mod289(Pi); // To avoid truncation effects in permutation - float4 ix = Pi.xzxz; - float4 iy = Pi.yyww; - float4 fx = Pf.xzxz; - float4 fy = Pf.yyww; - - float4 i = permute(permute(ix) + iy); - - float4 gx = frac(i / 41.0) * 2.0 - 1.0 ; - float4 gy = abs(gx) - 0.5 ; - float4 tx = floor(gx + 0.5); - gx = gx - tx; - - float2 g00 = float2(gx.x,gy.x); - float2 g10 = float2(gx.y,gy.y); - float2 g01 = float2(gx.z,gy.z); - float2 g11 = float2(gx.w,gy.w); - - float4 norm = taylorInvSqrt(float4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11))); - g00 *= norm.x; - g01 *= norm.y; - g10 *= norm.z; - g11 *= norm.w; - - float n00 = dot(g00, float2(fx.x, fy.x)); - float n10 = dot(g10, float2(fx.y, fy.y)); - float n01 = dot(g01, float2(fx.z, fy.z)); - float n11 = dot(g11, float2(fx.w, fy.w)); - - float2 fade_xy = fade(Pf.xy); - float2 n_x = lerp(float2(n00, n01), float2(n10, n11), fade_xy.x); - float n_xy = lerp(n_x.x, n_x.y, fade_xy.y); - return 2.3 * n_xy; -} - -// Classic Perlin noise, periodic variant -float pnoise(float2 P, float2 rep) -{ - float4 Pi = floor(P.xyxy) + float4(0.0, 0.0, 1.0, 1.0); - float4 Pf = frac (P.xyxy) - float4(0.0, 0.0, 1.0, 1.0); - Pi = mod(Pi, rep.xyxy); // To create noise with explicit period - Pi = mod289(Pi); // To avoid truncation effects in permutation - float4 ix = Pi.xzxz; - float4 iy = Pi.yyww; - float4 fx = Pf.xzxz; - float4 fy = Pf.yyww; - - float4 i = permute(permute(ix) + iy); - - float4 gx = frac(i / 41.0) * 2.0 - 1.0 ; - float4 gy = abs(gx) - 0.5 ; - float4 tx = floor(gx + 0.5); - gx = gx - tx; - - float2 g00 = float2(gx.x,gy.x); - float2 g10 = float2(gx.y,gy.y); - float2 g01 = float2(gx.z,gy.z); - float2 g11 = float2(gx.w,gy.w); - - float4 norm = taylorInvSqrt(float4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11))); - g00 *= norm.x; - g01 *= norm.y; - g10 *= norm.z; - g11 *= norm.w; - - float n00 = dot(g00, float2(fx.x, fy.x)); - float n10 = dot(g10, float2(fx.y, fy.y)); - float n01 = dot(g01, float2(fx.z, fy.z)); - float n11 = dot(g11, float2(fx.w, fy.w)); - - float2 fade_xy = fade(Pf.xy); - float2 n_x = lerp(float2(n00, n01), float2(n10, n11), fade_xy.x); - float n_xy = lerp(n_x.x, n_x.y, fade_xy.y); - return 2.3 * n_xy; -} diff --git a/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc.meta b/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc.meta deleted file mode 100644 index ff437e70a..000000000 --- a/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: e1b0b5fd6a4e44923b40d856017562e1 -ShaderImporter: - defaultTextures: [] - userData: diff --git a/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc b/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc deleted file mode 100644 index 738f6d12a..000000000 --- a/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc +++ /dev/null @@ -1,194 +0,0 @@ -// -// Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader -// -// Original work (webgl-noise) Copyright (C) 2011 Stefan Gustavson -// Translation and modification was made by Keijiro Takahashi. -// -// This shader is based on the webgl-noise GLSL shader. For further details -// of the original shader, please see the following description from the -// original source code. -// - -// -// GLSL textureless classic 3D noise "cnoise", -// with an RSL-style periodic variant "pnoise". -// Author: Stefan Gustavson (stefan.gustavson@liu.se) -// Version: 2011-10-11 -// -// Many thanks to Ian McEwan of Ashima Arts for the -// ideas for permutation and gradient selection. -// -// Copyright (c) 2011 Stefan Gustavson. All rights reserved. -// Distributed under the MIT license. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -float3 mod(float3 x, float3 y) -{ - return x - y * floor(x / y); -} - -float3 mod289(float3 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 mod289(float4 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 permute(float4 x) -{ - return mod289(((x*34.0)+1.0)*x); -} - -float4 taylorInvSqrt(float4 r) -{ - return (float4)1.79284291400159 - r * 0.85373472095314; -} - -float3 fade(float3 t) { - return t*t*t*(t*(t*6.0-15.0)+10.0); -} - -// Classic Perlin noise -float cnoise(float3 P) -{ - float3 Pi0 = floor(P); // Integer part for indexing - float3 Pi1 = Pi0 + (float3)1.0; // Integer part + 1 - Pi0 = mod289(Pi0); - Pi1 = mod289(Pi1); - float3 Pf0 = frac(P); // Fractional part for interpolation - float3 Pf1 = Pf0 - (float3)1.0; // Fractional part - 1.0 - float4 ix = float4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); - float4 iy = float4(Pi0.y, Pi0.y, Pi1.y, Pi1.y); - float4 iz0 = (float4)Pi0.z; - float4 iz1 = (float4)Pi1.z; - - float4 ixy = permute(permute(ix) + iy); - float4 ixy0 = permute(ixy + iz0); - float4 ixy1 = permute(ixy + iz1); - - float4 gx0 = ixy0 / 7.0; - float4 gy0 = frac(floor(gx0) / 7.0) - 0.5; - gx0 = frac(gx0); - float4 gz0 = (float4)0.5 - abs(gx0) - abs(gy0); - float4 sz0 = step(gz0, (float4)0.0); - gx0 -= sz0 * (step((float4)0.0, gx0) - 0.5); - gy0 -= sz0 * (step((float4)0.0, gy0) - 0.5); - - float4 gx1 = ixy1 / 7.0; - float4 gy1 = frac(floor(gx1) / 7.0) - 0.5; - gx1 = frac(gx1); - float4 gz1 = (float4)0.5 - abs(gx1) - abs(gy1); - float4 sz1 = step(gz1, (float4)0.0); - gx1 -= sz1 * (step((float4)0.0, gx1) - 0.5); - gy1 -= sz1 * (step((float4)0.0, gy1) - 0.5); - - float3 g000 = float3(gx0.x,gy0.x,gz0.x); - float3 g100 = float3(gx0.y,gy0.y,gz0.y); - float3 g010 = float3(gx0.z,gy0.z,gz0.z); - float3 g110 = float3(gx0.w,gy0.w,gz0.w); - float3 g001 = float3(gx1.x,gy1.x,gz1.x); - float3 g101 = float3(gx1.y,gy1.y,gz1.y); - float3 g011 = float3(gx1.z,gy1.z,gz1.z); - float3 g111 = float3(gx1.w,gy1.w,gz1.w); - - float4 norm0 = taylorInvSqrt(float4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); - g000 *= norm0.x; - g010 *= norm0.y; - g100 *= norm0.z; - g110 *= norm0.w; - - float4 norm1 = taylorInvSqrt(float4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); - g001 *= norm1.x; - g011 *= norm1.y; - g101 *= norm1.z; - g111 *= norm1.w; - - float n000 = dot(g000, Pf0); - float n100 = dot(g100, float3(Pf1.x, Pf0.y, Pf0.z)); - float n010 = dot(g010, float3(Pf0.x, Pf1.y, Pf0.z)); - float n110 = dot(g110, float3(Pf1.x, Pf1.y, Pf0.z)); - float n001 = dot(g001, float3(Pf0.x, Pf0.y, Pf1.z)); - float n101 = dot(g101, float3(Pf1.x, Pf0.y, Pf1.z)); - float n011 = dot(g011, float3(Pf0.x, Pf1.y, Pf1.z)); - float n111 = dot(g111, Pf1); - - float3 fade_xyz = fade(Pf0); - float4 n_z = lerp(float4(n000, n100, n010, n110), float4(n001, n101, n011, n111), fade_xyz.z); - float2 n_yz = lerp(n_z.xy, n_z.zw, fade_xyz.y); - float n_xyz = lerp(n_yz.x, n_yz.y, fade_xyz.x); - return 2.2 * n_xyz; -} - -// Classic Perlin noise, periodic variant -float pnoise(float3 P, float3 rep) -{ - float3 Pi0 = mod(floor(P), rep); // Integer part, modulo period - float3 Pi1 = mod(Pi0 + (float3)1.0, rep); // Integer part + 1, mod period - Pi0 = mod289(Pi0); - Pi1 = mod289(Pi1); - float3 Pf0 = frac(P); // Fractional part for interpolation - float3 Pf1 = Pf0 - (float3)1.0; // Fractional part - 1.0 - float4 ix = float4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); - float4 iy = float4(Pi0.y, Pi0.y, Pi1.y, Pi1.y); - float4 iz0 = (float4)Pi0.z; - float4 iz1 = (float4)Pi1.z; - - float4 ixy = permute(permute(ix) + iy); - float4 ixy0 = permute(ixy + iz0); - float4 ixy1 = permute(ixy + iz1); - - float4 gx0 = ixy0 / 7.0; - float4 gy0 = frac(floor(gx0) / 7.0) - 0.5; - gx0 = frac(gx0); - float4 gz0 = (float4)0.5 - abs(gx0) - abs(gy0); - float4 sz0 = step(gz0, (float4)0.0); - gx0 -= sz0 * (step((float4)0.0, gx0) - 0.5); - gy0 -= sz0 * (step((float4)0.0, gy0) - 0.5); - - float4 gx1 = ixy1 / 7.0; - float4 gy1 = frac(floor(gx1) / 7.0) - 0.5; - gx1 = frac(gx1); - float4 gz1 = (float4)0.5 - abs(gx1) - abs(gy1); - float4 sz1 = step(gz1, (float4)0.0); - gx1 -= sz1 * (step((float4)0.0, gx1) - 0.5); - gy1 -= sz1 * (step((float4)0.0, gy1) - 0.5); - - float3 g000 = float3(gx0.x,gy0.x,gz0.x); - float3 g100 = float3(gx0.y,gy0.y,gz0.y); - float3 g010 = float3(gx0.z,gy0.z,gz0.z); - float3 g110 = float3(gx0.w,gy0.w,gz0.w); - float3 g001 = float3(gx1.x,gy1.x,gz1.x); - float3 g101 = float3(gx1.y,gy1.y,gz1.y); - float3 g011 = float3(gx1.z,gy1.z,gz1.z); - float3 g111 = float3(gx1.w,gy1.w,gz1.w); - - float4 norm0 = taylorInvSqrt(float4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); - g000 *= norm0.x; - g010 *= norm0.y; - g100 *= norm0.z; - g110 *= norm0.w; - float4 norm1 = taylorInvSqrt(float4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); - g001 *= norm1.x; - g011 *= norm1.y; - g101 *= norm1.z; - g111 *= norm1.w; - - float n000 = dot(g000, Pf0); - float n100 = dot(g100, float3(Pf1.x, Pf0.y, Pf0.z)); - float n010 = dot(g010, float3(Pf0.x, Pf1.y, Pf0.z)); - float n110 = dot(g110, float3(Pf1.x, Pf1.y, Pf0.z)); - float n001 = dot(g001, float3(Pf0.x, Pf0.y, Pf1.z)); - float n101 = dot(g101, float3(Pf1.x, Pf0.y, Pf1.z)); - float n011 = dot(g011, float3(Pf0.x, Pf1.y, Pf1.z)); - float n111 = dot(g111, Pf1); - - float3 fade_xyz = fade(Pf0); - float4 n_z = lerp(float4(n000, n100, n010, n110), float4(n001, n101, n011, n111), fade_xyz.z); - float2 n_yz = lerp(n_z.xy, n_z.zw, fade_xyz.y); - float n_xyz = lerp(n_yz.x, n_yz.y, fade_xyz.x); - return 2.2 * n_xyz; -} diff --git a/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc.meta b/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc.meta deleted file mode 100644 index b4dd551ab..000000000 --- a/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 3ba1abd1cb44c47b68fbb577c6c4ba3e -ShaderImporter: - defaultTextures: [] - userData: diff --git a/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc b/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc deleted file mode 100644 index 0b7add240..000000000 --- a/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc +++ /dev/null @@ -1,114 +0,0 @@ -// -// Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader -// -// Original work (webgl-noise) Copyright (C) 2011 Ashima Arts. -// Translation and modification was made by Keijiro Takahashi. -// -// This shader is based on the webgl-noise GLSL shader. For further details -// of the original shader, please see the following description from the -// original source code. -// - -// -// Description : Array and textureless GLSL 2D/3D/4D simplex -// noise functions. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : ijm -// Lastmod : 20110822 (ijm) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -float3 mod289(float3 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 mod289(float4 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 permute(float4 x) -{ - return mod289((x * 34.0 + 1.0) * x); -} - -float4 taylorInvSqrt(float4 r) -{ - return 1.79284291400159 - r * 0.85373472095314; -} - -float snoise(float3 v) -{ - const float2 C = float2(1.0 / 6.0, 1.0 / 3.0); - - // First corner - float3 i = floor(v + dot(v, C.yyy)); - float3 x0 = v - i + dot(i, C.xxx); - - // Other corners - float3 g = step(x0.yzx, x0.xyz); - float3 l = 1.0 - g; - float3 i1 = min(g.xyz, l.zxy); - float3 i2 = max(g.xyz, l.zxy); - - // x1 = x0 - i1 + 1.0 * C.xxx; - // x2 = x0 - i2 + 2.0 * C.xxx; - // x3 = x0 - 1.0 + 3.0 * C.xxx; - float3 x1 = x0 - i1 + C.xxx; - float3 x2 = x0 - i2 + C.yyy; - float3 x3 = x0 - 0.5; - - // Permutations - i = mod289(i); // Avoid truncation effects in permutation - float4 p = - permute(permute(permute(i.z + float4(0.0, i1.z, i2.z, 1.0)) - + i.y + float4(0.0, i1.y, i2.y, 1.0)) - + i.x + float4(0.0, i1.x, i2.x, 1.0)); - - // Gradients: 7x7 points over a square, mapped onto an octahedron. - // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) - float4 j = p - 49.0 * floor(p / 49.0); // mod(p,7*7) - - float4 x_ = floor(j / 7.0); - float4 y_ = floor(j - 7.0 * x_); // mod(j,N) - - float4 x = (x_ * 2.0 + 0.5) / 7.0 - 1.0; - float4 y = (y_ * 2.0 + 0.5) / 7.0 - 1.0; - - float4 h = 1.0 - abs(x) - abs(y); - - float4 b0 = float4(x.xy, y.xy); - float4 b1 = float4(x.zw, y.zw); - - //float4 s0 = float4(lessThan(b0, 0.0)) * 2.0 - 1.0; - //float4 s1 = float4(lessThan(b1, 0.0)) * 2.0 - 1.0; - float4 s0 = floor(b0) * 2.0 + 1.0; - float4 s1 = floor(b1) * 2.0 + 1.0; - float4 sh = -step(h, 0.0); - - float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; - float4 a1 = b1.xzyw + s1.xzyw * sh.zzww; - - float3 g0 = float3(a0.xy, h.x); - float3 g1 = float3(a0.zw, h.y); - float3 g2 = float3(a1.xy, h.z); - float3 g3 = float3(a1.zw, h.w); - - // Normalise gradients - float4 norm = taylorInvSqrt(float4(dot(g0, g0), dot(g1, g1), dot(g2, g2), dot(g3, g3))); - g0 *= norm.x; - g1 *= norm.y; - g2 *= norm.z; - g3 *= norm.w; - - // Mix final noise value - float4 m = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); - m = m * m; - m = m * m; - - float4 px = float4(dot(x0, g0), dot(x1, g1), dot(x2, g2), dot(x3, g3)); - return 42.0 * dot(m, px); -} diff --git a/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc.meta b/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc.meta deleted file mode 100644 index 612bd9ef0..000000000 --- a/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: b577a94f58a1398409bfcfe9cd5dbf99 -timeCreated: 1448788105 -licenseType: Pro -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc b/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc deleted file mode 100644 index 4cfef835a..000000000 --- a/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc +++ /dev/null @@ -1,118 +0,0 @@ -// -// Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader -// -// Original work (webgl-noise) Copyright (C) 2011 Ashima Arts. -// Translation and modification was made by Keijiro Takahashi. -// -// This shader is based on the webgl-noise GLSL shader. For further details -// of the original shader, please see the following description from the -// original source code. -// - -// -// Description : Array and textureless GLSL 2D/3D/4D simplex -// noise functions. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : ijm -// Lastmod : 20110822 (ijm) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -float3 mod289(float3 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 mod289(float4 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 permute(float4 x) -{ - return mod289((x * 34.0 + 1.0) * x); -} - -float4 taylorInvSqrt(float4 r) -{ - return 1.79284291400159 - r * 0.85373472095314; -} - -float3 snoise_grad(float3 v) -{ - const float2 C = float2(1.0 / 6.0, 1.0 / 3.0); - - // First corner - float3 i = floor(v + dot(v, C.yyy)); - float3 x0 = v - i + dot(i, C.xxx); - - // Other corners - float3 g = step(x0.yzx, x0.xyz); - float3 l = 1.0 - g; - float3 i1 = min(g.xyz, l.zxy); - float3 i2 = max(g.xyz, l.zxy); - - // x1 = x0 - i1 + 1.0 * C.xxx; - // x2 = x0 - i2 + 2.0 * C.xxx; - // x3 = x0 - 1.0 + 3.0 * C.xxx; - float3 x1 = x0 - i1 + C.xxx; - float3 x2 = x0 - i2 + C.yyy; - float3 x3 = x0 - 0.5; - - // Permutations - i = mod289(i); // Avoid truncation effects in permutation - float4 p = - permute(permute(permute(i.z + float4(0.0, i1.z, i2.z, 1.0)) - + i.y + float4(0.0, i1.y, i2.y, 1.0)) - + i.x + float4(0.0, i1.x, i2.x, 1.0)); - - // Gradients: 7x7 points over a square, mapped onto an octahedron. - // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) - float4 j = p - 49.0 * floor(p / 49.0); // mod(p,7*7) - - float4 x_ = floor(j / 7.0); - float4 y_ = floor(j - 7.0 * x_); // mod(j,N) - - float4 x = (x_ * 2.0 + 0.5) / 7.0 - 1.0; - float4 y = (y_ * 2.0 + 0.5) / 7.0 - 1.0; - - float4 h = 1.0 - abs(x) - abs(y); - - float4 b0 = float4(x.xy, y.xy); - float4 b1 = float4(x.zw, y.zw); - - //float4 s0 = float4(lessThan(b0, 0.0)) * 2.0 - 1.0; - //float4 s1 = float4(lessThan(b1, 0.0)) * 2.0 - 1.0; - float4 s0 = floor(b0) * 2.0 + 1.0; - float4 s1 = floor(b1) * 2.0 + 1.0; - float4 sh = -step(h, 0.0); - - float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; - float4 a1 = b1.xzyw + s1.xzyw * sh.zzww; - - float3 g0 = float3(a0.xy, h.x); - float3 g1 = float3(a0.zw, h.y); - float3 g2 = float3(a1.xy, h.z); - float3 g3 = float3(a1.zw, h.w); - - // Normalise gradients - float4 norm = taylorInvSqrt(float4(dot(g0, g0), dot(g1, g1), dot(g2, g2), dot(g3, g3))); - g0 *= norm.x; - g1 *= norm.y; - g2 *= norm.z; - g3 *= norm.w; - - // Compute gradient of noise function at P - float4 m = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); - float4 m2 = m * m; - float4 m3 = m2 * m; - float4 m4 = m2 * m2; - float3 grad = - -6.0 * m3.x * x0 * dot(x0, g0) + m4.x * g0 + - -6.0 * m3.y * x1 * dot(x1, g1) + m4.y * g1 + - -6.0 * m3.z * x2 * dot(x2, g2) + m4.z * g2 + - -6.0 * m3.w * x3 * dot(x3, g3) + m4.w * g3; - return 42.0 * grad; -} diff --git a/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc.meta b/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc.meta deleted file mode 100644 index 250b646fa..000000000 --- a/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: a7111eafc2463224faacf7be3bddb9a4 -timeCreated: 1449292284 -licenseType: Pro -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab b/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab index 7a65a0864..7be70840f 100644 --- a/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab b/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab index f9a477cda..4a8609c7c 100644 --- a/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab b/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab index 4252e74cc..b80967c41 100644 --- a/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Octahedron.prefab b/Assets/Prefabs/RPG/Pickups/Octahedron.prefab index 099083195..9cabd7b79 100644 --- a/Assets/Prefabs/RPG/Pickups/Octahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Octahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab b/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab index 6dad19967..20f8073a7 100644 --- a/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Resources/Settings.asset b/Assets/Resources/Settings.asset index 46bee7272..7d89eea8e 100644 --- a/Assets/Resources/Settings.asset +++ b/Assets/Resources/Settings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7f09c54dfdb87dffd76fa92365d62c53ce333457b89ccf8ead09093ffffedc42 -size 12525 +oid sha256:d9d381e3b25ea04d92768f0633cb89668108229dcc17336b560d0cbbfbaed04f +size 12397 diff --git a/Assets/Resources/Sprites/Attribution.txt b/Assets/Resources/Sprites/Attribution.txt index 666742406..8ca89fb1b 100644 --- a/Assets/Resources/Sprites/Attribution.txt +++ b/Assets/Resources/Sprites/Attribution.txt @@ -2,8 +2,7 @@ Noun Project Tornado by Bart Laubsch Alien Abduction by Bart Laubsch -Hurricane by icon 54 from -Smashicons Space by Ben Davis +Hurricane by icon 54 from Smashicons Space by Ben Davis Space 2 - Solid by Ben Davis Filter by Karthik Aathis Search by il Capitano diff --git a/Assets/Scenes/ARPG.unity b/Assets/Scenes/ARPG.unity index 4d5b15473..f583a38ec 100644 --- a/Assets/Scenes/ARPG.unity +++ b/Assets/Scenes/ARPG.unity @@ -21236,7 +21236,7 @@ GameObject: m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 - m_IsActive: 0 + m_IsActive: 1 --- !u!224 &1396909587 RectTransform: m_ObjectHideFlags: 0 @@ -24703,26 +24703,7 @@ MonoBehaviour: m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_text: "What the fuck did you just fucking type about me, you little bitch? I\u2019ll - have you know I graduated top of my class at MIT, and I\u2019ve been involved - in numerous secret raids with Anonymous, and I have over 300 confirmed DDoSes.\n\nI - am trained in online trolling and I\u2019m the top hacker in the entire world. - You are nothing to me but just another virus host. I will wipe you the fuck out - with precision the likes of which has never been seen before on the Internet, - mark my fucking words. You think you can get away with typing that shit to me - over the Internet? Think again, fucker.\n\nAs we chat over IRC I am tracing your - IP with my damn bare hands so you better prepare for the storm, maggot. The storm - that wipes out the pathetic little thing you call your computer. You\u2019re - fucking dead, kid. I can be anywhere, anytime, and I can hack into your files - in over seven hundred ways, and that\u2019s just with my bare hands.\n\nNot only - am I extensively trained in hacking, but I have access to the entire arsenal - of every piece of malware ever created and I will use it to its full extent to - wipe your miserable ass off the face of the world wide web, you little shit. - If only you could have known what unholy retribution your little \u201Cclever\u201D - comment was about to bring down upon you, maybe you would have held your fucking - fingers. But you couldn\u2019t, you didn\u2019t, and now you\u2019re paying the - price, you goddamn idiot. I will shit code all over you and you will drown in - it.\n\nYou\u2019re fucking dead, kiddo." + m_text: "" m_isRightToLeft: 0 m_fontAsset: {fileID: 11400000, guid: 53555f7a2d5e745428813f1b1118734f, type: 2} m_sharedMaterial: {fileID: -2804126062856497447, guid: 53555f7a2d5e745428813f1b1118734f, diff --git a/Assets/Scripts/Editor/ShipPrefabAuthoring.cs b/Assets/Scripts/Editor/ShipPrefabAuthoring.cs index d2937b79d..45bbc8609 100644 --- a/Assets/Scripts/Editor/ShipPrefabAuthoring.cs +++ b/Assets/Scripts/Editor/ShipPrefabAuthoring.cs @@ -112,6 +112,7 @@ public static class ShipPrefabAuthoring case "Thruster": var emitter = DirectChild(node, "Emitter")?.GetComponent(); if (emitter == null) throw new InvalidOperationException($"{name} needs an Emitter mesh child"); + ShipModShips.Hide(emitter, invisible); AddOrGet(node.gameObject).Emitter = emitter; thrusters.Add(node.GetComponent()); break; diff --git a/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs b/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs index 9f740f557..5342eb352 100644 --- a/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs +++ b/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs @@ -28,6 +28,8 @@ public static class ShipPrefabAuthoringSmoke ShipPrefabAuthoring.Configure(root); var ship = root.GetComponent(); Require(ship != null && ship.ThrusterHardpoints.Length == 1 && ship.ThrusterHardpoints[0].Emitter != null, "thruster emitter"); + Require(Array.TrueForAll(ship.ThrusterHardpoints[0].Emitter.sharedMaterials, material => material == ship.InvisibleMaterial), + "thruster emitter drawn with the invisible material only"); Require(ship.WeaponHardpoints.Length == 1 && ship.WeaponHardpoints[0].FiringPoint.Length == 2, "weapon muzzles"); Require(ship.WeaponHardpoints[0].FiringPoint[0].name == "Muzzle.0", "numeric muzzle order"); Require(ship.RadiatorHardpoints.Length == 1 && ship.RadiatorHardpoints[0].Mesh != null, "radiator mesh"); diff --git a/Assets/Scripts/EventLog.cs b/Assets/Scripts/EventLog.cs index 54db8dd57..967653b1d 100644 --- a/Assets/Scripts/EventLog.cs +++ b/Assets/Scripts/EventLog.cs @@ -13,7 +13,8 @@ public class EventLog : MonoBehaviour private SizedQueue LogMessages; private StringBuilder LogText; - private void Start() + // Awake, not Start: a message can arrive in the frame the parent activates, before Start would run. + private void Awake() { LogMessages = new SizedQueue(LineCount); LogText = new StringBuilder(); diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index a0cf3a4c1..6cfff750e 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -106,6 +106,9 @@ public class ActionGameManager : MonoBehaviour } public static Galaxy CurrentGalaxy; + // Whether a run is live: a failed start and a finished run both clear the galaxy, and the scene's update paths (this + // manager's, the renderer's) step and draw nothing without one. + public static bool RunLive => CurrentGalaxy != null; // The scenario a new run starts from: MainMenu.Launch sets it, and StartGame's new-run branch consumes it once. public static Scenario PendingScenario; @@ -188,9 +191,6 @@ public class ActionGameManager : MonoBehaviour //public PlayerInput Input; - // private CinemachineFramingTransposer _transposer; - // private CinemachineComposer _composer; - private bool _paused; private float _time; private int _zoomLevelIndex; @@ -556,11 +556,7 @@ public class ActionGameManager : MonoBehaviour { FollowCamera.Follow = x.missile.transform; FollowCamera.LookAt = x.target ? x.target : x.missile.transform; - x.missile.OnKill += () => - { - FollowCamera.LookAt = ZoneRenderer.EntityInstances[CurrentEntity].LookAtPoint; - FollowCamera.Follow = ZoneRenderer.EntityInstances[CurrentEntity].transform; - }; + x.missile.OnKill += () => FrameFollow(CurrentEntity); }); } }); @@ -737,8 +733,7 @@ public class ActionGameManager : MonoBehaviour Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, - galaxyZone, - CurrentGalaxy.IsPrelude + galaxyZone ); galaxyZone.Contents = new Zone(ItemManager, Settings.PlanetSettings, galaxyZone.PackedContents, galaxyZone, CurrentGalaxy); } @@ -854,21 +849,12 @@ public class ActionGameManager : MonoBehaviour var scenario = PendingScenario; PendingScenario = null; var failures = new List(); - RunStart.Staged staged = null; - try + var staged = RunStart.Launch(() => RunSave.Replace(CultCache, () => { - staged = RunSave.Replace(CultCache, () => - { - RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); - PopulateLevel(CurrentGalaxy.Entrance); - return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, Settings.TutorialGenerationSettings, failures); - }); - } - catch (Exception exception) - { - Debug.LogException(exception); - failures.Add(exception.Message); - } + RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); + PopulateLevel(CurrentGalaxy.Entrance); + return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, failures); + }), failures, Debug.LogException); if (staged == null) { @@ -1092,9 +1078,14 @@ public class ActionGameManager : MonoBehaviour _shipSubscriptions.Add(CurrentEntity.Zone.ShotResolved .Where(outcome => outcome.Source == CurrentEntity) .Subscribe(outcome => _debugLastShots[outcome.Weapon] = outcome)); + _shipSubscriptions.Add(CurrentEntity.Zone.CargoGained + .Where(gain => gain.Taker == CurrentEntity) + .Subscribe(gain => + { + if (EventLog != null) EventLog.LogMessage(HaulFeed.Line(gain, ItemManager), gain.Adrift > 0 ? Color.yellow : Color.white); + })); - FollowCamera.LookAt = ZoneRenderer.EntityInstances[CurrentEntity].LookAtPoint; - FollowCamera.Follow = ZoneRenderer.EntityInstances[CurrentEntity].transform; + FrameFollow(CurrentEntity); _articulationGroups = CurrentEntity.Equipment .Where(item => item.Behaviors.Any(x => x.Data is WeaponData && !(x.Data is LauncherData))) .GroupBy(item => ZoneRenderer.EntityInstances[CurrentEntity] @@ -1202,6 +1193,20 @@ public class ActionGameManager : MonoBehaviour _incomingLockIndicator = (incoming, incoming.GetComponent()); } + private CinemachineFramingTransposer _framingTransposer; + + // The one writer of the follow camera's Follow, LookAt and distance for an entity: the distance is + // the hull's reach (from its centre of mass, where Follow sits) times the authored ratio. + private void FrameFollow(Entity entity) + { + var instance = ZoneRenderer.EntityInstances[entity]; + FollowCamera.LookAt = instance.LookAtPoint; + FollowCamera.Follow = instance.transform; + if (_framingTransposer == null) + _framingTransposer = FollowCamera.GetCinemachineComponent(); + _framingTransposer.m_CameraDistance = Settings.FollowCameraDistancePerReach * Contacts.Radius(entity); + } + private void UpdatePlayerPanel() { ShipPanel.Display(CurrentEntity, true); @@ -1342,6 +1347,7 @@ public class ActionGameManager : MonoBehaviour void Update() { + if (!RunLive) return; if(!_paused) { _time += Time.deltaTime; diff --git a/Assets/Scripts/Gameplay/GameSettings.cs b/Assets/Scripts/Gameplay/GameSettings.cs index 9d89c5822..77855a148 100644 --- a/Assets/Scripts/Gameplay/GameSettings.cs +++ b/Assets/Scripts/Gameplay/GameSettings.cs @@ -14,6 +14,9 @@ public class GameSettings : ScriptableObject public float HeatstrokePhasingFloor = 0; public float HeatstrokePhasingFrequency = 5; public float WormholeDistanceRatio; + // The follow camera's distance from the hull's centre of mass, as a multiple of the hull's reach + // (Contacts.Radius); 1.5 keeps the Longinus at about 30 m. + public float FollowCameraDistancePerReach = 1.5f; public float DefaultViewDistance; public float[] MinimapZoomLevels; public int DefaultMinimapZoom; @@ -22,8 +25,7 @@ public class GameSettings : ScriptableObject public float MinimapAsteroidSize = 3; public float MinimapIconSize = 1f / 32; public float PlanetRotationSpeed = 1; - public TutorialGenerationSettings TutorialGenerationSettings; - public SectorBackgroundSettings TutorialBackgroundSettings; + public SectorBackgroundSettings CastBackgroundSettings; public SectorBackgroundSettings SectorBackgroundSettings; public SectorGenerationSettings SectorGenerationSettings; public BodySettingsCollection[] BodySettingsCollections; diff --git a/Assets/Scripts/Gameplay/ShipModShips.cs b/Assets/Scripts/Gameplay/ShipModShips.cs index 89106a6b7..33f09f590 100644 --- a/Assets/Scripts/Gameplay/ShipModShips.cs +++ b/Assets/Scripts/Gameplay/ShipModShips.cs @@ -6,9 +6,10 @@ using GameCult.Caching; using UnityEngine; using Object = UnityEngine.Object; -// Mod ships in the running game. Compose decides which mod hulls exist; Preload builds a prototype for each, keyed by the -// hull's record key, into an inactive assembled copy that Instantiate clones synchronously, so LoadEntity never loads async. -// A composed hull Preload cannot build is an import fault: Loading faults with ImportFault, naming every such hull's package. +// Mod ships in the running game. Compose (Bind) is the one verdict on whether a mod hull exists, from the package's files; +// Preload only builds a prototype for each, keyed by the hull's record key, into an inactive assembled copy that Instantiate +// clones synchronously, so LoadEntity never loads async. ImportFault reports what the Unity importer made of a composed hull: +// a composed hull Preload cannot build is an import fault: Loading faults with ImportFault, naming every such hull's package. // The prototypes are cache-only: rebuilt every boot from the catalog, the mod GLBs and the template. public static class ShipModShips { @@ -101,6 +102,7 @@ public static class ShipModShips node.name = id; return node; } + // An importer report, not a verdict: Bind has already judged the file. MeshRenderer Renderer(string id) { var found = Node(id).GetComponentInChildren(true); @@ -130,9 +132,6 @@ public static class ShipModShips var surface = AddOrGet(hullNode.gameObject); var shieldMarker = Node(plan.Shield); - var scale = shieldMarker.localScale; - if (!(scale.x > 0 && scale.y > 0 && scale.z > 0)) - throw new InvalidOperationException($"{ship.Id}: the shield anchor scale must have three positive radii."); var shield = Object.Instantiate(template.Shield.GetComponent(), shieldMarker, false); Reset(shield.transform); AddOrGet(shield.gameObject); diff --git a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs index 6b899ee35..300229d3f 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs @@ -6,6 +6,7 @@ using System; using System.Collections; using System.Collections.Generic; using System.Linq; +using GameCult.Caching; using MessagePack; using Newtonsoft.Json; using CultMath; @@ -212,4 +213,7 @@ public abstract class BehaviorData { return base.ToString().FormatTypeName(); } + + // Element identity: minted by the cache on write; "" means unset. + [Key(37)] [CultElementId] public string Id = ""; } \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs index b90a124da..8e44075ed 100644 --- a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs @@ -46,6 +46,7 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC { get => _ammo; } + public override bool HasMagazine => false; public float Progress { diff --git a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs index 62e4f4b14..52b69d196 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs @@ -104,6 +104,14 @@ public abstract class Weapon : ActivatedBehavior public abstract int Ammo { get; } // Rounds in the ship's cargo that reload this weapon's magazine: crates of AmmoType, 0 when the weapon draws none. public int Reserve => _data.AmmoType.IsSet() ? Entity.CountItemsInCargo(_data.AmmoType.Key) : 0; + // Whether Ammo counts a magazine. A weapon that names an AmmoType and fires from one (InstantWeapon) does; a beam (ConstantWeapon) draws one + // crate per AmmoInterval straight from the cargo and has none. + public virtual bool HasMagazine => true; + // What the HUD's ammunition label shows: "magazine/reserve" for a magazine weapon, the reserve alone for one without a magazine, empty when + // the weapon draws no ammunition. The one rule the HUD reads, so the label cannot show a magazine a weapon does not have. + public string AmmoReadout => !ShowsAmmoReadout ? "" : HasMagazine ? $"{Ammo}/{Reserve}" : Reserve.ToString(); + // Whether the HUD shows the ammunition label at all (and not the infinite-ammunition icon): the weapon names an AmmoType. + public bool ShowsAmmoReadout => _data.AmmoType.IsSet(); public WeaponData WeaponData => _data; public float RangeFactor(float at) => WeaponData.RangeFactor(MinRange, EffectiveRange, Range, _data.DamageAtMaxRange, at); diff --git a/Assets/Scripts/ServerShared/Corporations.cs b/Assets/Scripts/ServerShared/Corporations.cs index e527606d9..680436520 100644 --- a/Assets/Scripts/ServerShared/Corporations.cs +++ b/Assets/Scripts/ServerShared/Corporations.cs @@ -49,7 +49,10 @@ public class Faction // Keys 13 to 15 (overworldMusic, combatMusic, bossMusic) held Wwise ids; retired, never reuse them. - // Key 16 is reserved for Relations (operator ruling faction-relations-field). + // How this faction regards each other faction; absent is Neutral. Directed: this map says how this faction regards them, theirs + // says how they regard it. Read only through Entity.Regard (ruling faction-relations-field). + [Inspectable, CultReference(typeof(Faction), many: true), JsonProperty("relations"), Key(16)] + public Dictionary, FactionRelationship> Relations = new Dictionary, FactionRelationship>(); // The faction's rules of engagement; null fights as FactionDoctrine.Default. [Inspectable, JsonProperty("doctrine"), Key(17)] @@ -58,7 +61,7 @@ public class Faction // The maker's final assembly: the distribution every lot of theirs draws its own quality from, and the hard ceiling on each // of its roles (quality-lean-assembly-hard-ceiling). Null is not authored: a lot of theirs assembles at AssemblyDistribution's // defaults. assembly-from-maker derives it once at the part mean plus a tolerance margin (quality-min-tolerance-binned-assembly); - // tune it in Studio after that. Key 16 is reserved for Relations and 18 for Livery. Key 20 was assemblyDeviation (retired); never reuse it. + // tune it in Studio after that. Key 18 is reserved for Livery. Key 20 was assemblyDeviation (retired); never reuse it. [Inspectable, JsonProperty("assembly"), Key(19)] public AssemblyDistribution Assembly; @@ -84,5 +87,8 @@ public class FactionPlace // treats an invalid entry as absent; AetherDb place-names refuses a table that holds one. public static bool IsValidName(string name) => !string.IsNullOrEmpty(name) && name == name.Trim() && !name.StartsWith("EAC-", StringComparison.OrdinalIgnoreCase); + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } diff --git a/Assets/Scripts/ServerShared/Credits.cs b/Assets/Scripts/ServerShared/Credits.cs new file mode 100644 index 000000000..9b7ac4226 --- /dev/null +++ b/Assets/Scripts/ServerShared/Credits.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +// The third-party attributions the shipped game must show the player. One list, owned here: the credits screen only +// renders it, and CreditsTests holds it against the licence files in Assets. Unity-free so the headless build checks it. +public class Credit +{ + public string Name; + public string Licence; + // What the licence requires shown: copyright holders, and any change notice. + public string Notice; + // The licence file in the repo that carries the full text and that this entry answers for. + public string LicenceFile; +} + +public static class Credits +{ + public const string TwemojiFile = "Assets/Fonts/Emoji/LICENSE.txt"; + public const string PlaydeadFile = "Assets/Plugins/Playdead/LICENSE.txt"; + public const string NounProjectFile = "Assets/Resources/Sprites/Attribution.txt"; + public const string LiberationFile = "Assets/TextMesh Pro/Fonts/LiberationSans - OFL.txt"; + // Fonts state their holder and licence in their own name tables; the licence texts shipped beside them are these. + public const string UbuntuLicenceFile = "Assets/Fonts/Ubuntu/UFL-1.0.txt"; + public const string MontserratLicenceFile = "Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt"; + public const string UniRxFile = "Assets/Plugins/UniRx/ReadMe.txt"; + public const string AmbientCgFile = "Assets/Materials/PBR/SOURCES.md"; + public const string KdTreeFile = "Assets/Scripts/ServerShared/NIH/KDTree/KDTree.cs"; + public const string SimplexNoiseFile = "Assets/Plugins/GPU Noise/SimplexNoise2D.cginc"; + // Works whose notice is only a source-file header; each answers through the file whose header states it. + public const string UnityShaderFile = "Assets/Shaders/Particle Standard Unlit.shader"; + public const string AdditiveUiFile = "Assets/Shaders/AdditiveUI.shader"; + public const string AcesFile = "Assets/Shaders/CustomDoF/ACES.hlsl"; + public const string BezierPathFile = "Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Utilities/BezierPath.cs"; + public const string ClassicNoiseFile = "Assets/Plugins/Celestial Body/Scripts/Shaders/Includes/SimplexNoise2.cginc"; + // The first line of the attribution file; the icon credits are the lines after it. + public const string NounProjectHeading = "Noun Project"; + // Where the player build loads the Noun Project credit lines from (Resources path, no extension). + public const string NounProjectResource = "Sprites/Attribution"; + + // The full list. The Noun Project icon credits are the lines of its attribution file, whose text the caller supplies + // (Unity reads it as a Resources TextAsset; tests read it from disk), so the file stays the one copy of those names. + public static IReadOnlyList All(string nounProjectAttribution) + { + var credits = new List + { + new Credit + { + Name = "Twemoji", + Licence = "CC BY 4.0", + Notice = "Copyright (c) 2022-present Jason Sofonia & Justine De Caires; copyright (c) 2014-2021 Twitter. " + + "Graphics licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). " + + "Converted to a colour font; the artwork itself is not edited.", + LicenceFile = TwemojiFile + }, + new Credit + { + Name = "Playdead temporal anti-aliasing", + Licence = "MIT", + Notice = "Copyright (c) 2015 Playdead", + LicenceFile = PlaydeadFile + }, + new Credit + { + Name = "Liberation Sans", + Licence = "SIL Open Font License 1.1", + Notice = "Digitized data copyright (c) 2010 Google Corporation with Reserved Font Arimo, Tinos and Cousine. " + + "Copyright (c) 2012 Red Hat, Inc. with Reserved Font Name Liberation.", + LicenceFile = LiberationFile + }, + new Credit + { + Name = "Ubuntu and Ubuntu Mono fonts", + Licence = "Ubuntu Font Licence 1.0", + Notice = "Copyright 2011 Canonical Ltd.", + LicenceFile = UbuntuLicenceFile + }, + new Credit + { + Name = "Montserrat", + Licence = "SIL Open Font License 1.1", + Notice = "Copyright(c) 2014 by Julieta Ulanovsky", + LicenceFile = MontserratLicenceFile + }, + new Credit + { + Name = "UniRx", + Licence = "MIT", + Notice = "Created by Yoshifumi Kawai (neuecc)", + LicenceFile = UniRxFile + }, + new Credit + { + Name = "KDTree", + Licence = "MIT", + Notice = "Copyright (c) 2018 Vili Volčini / viliwonka", + LicenceFile = KdTreeFile + }, + new Credit + { + Name = "webgl-noise simplex noise", + Licence = "MIT", + Notice = "Copyright (C) 2011 Ashima Arts. Author: Ian McEwan, Ashima Arts " + + "(https://github.com/ashima/webgl-noise). Translated to Unity shaders and modified by Keijiro Takahashi " + + "(https://github.com/keijiro/NoiseShader).", + LicenceFile = SimplexNoiseFile + }, + new Credit + { + Name = "Celestial Body noise shaders", + Licence = "MIT", + Notice = "Copyright (C) 2011 Ashima Arts. Copyright (C) 2011 by Ashima Arts (Simplex noise). " + + "Copyright (C) 2011 by Stefan Gustavson (Classic noise).", + LicenceFile = ClassicNoiseFile + }, + new Credit + { + Name = "Unity built-in shaders", + Licence = "MIT", + Notice = "Copyright (c) 2016 Unity Technologies. Shader source adapted from Unity's built-in shaders " + + "(Particle Standard Unlit, StretchedSkybox, MaskedWorldSpaceUI, MaskedWorldSpaceAdditiveUI).", + LicenceFile = UnityShaderFile + }, + new Credit + { + Name = "AdditiveUI shaders", + Licence = "MIT for the Unity Technologies portion; the Supyrb portion states no licence", + Notice = "Copyright (c) 2017 Supyrb. All rights reserved. Author: Johannes Deml. " + + "Built on Unity's built-in UI shader, copyright (c) 2016 Unity Technologies, MIT.", + LicenceFile = AdditiveUiFile + }, + new Credit + { + Name = "ACES colour transforms", + Licence = "Academy Color Encoding System licence", + Notice = "Copyright 2015 Academy of Motion Picture Arts and Sciences (A.M.P.A.S.). " + + "Portions contributed by others as indicated. All rights reserved. " + + "Source: https://github.com/ampas/aces-dev", + LicenceFile = AcesFile + }, + new Credit + { + Name = "Bezier path (UI Extensions)", + Licence = "No named licence; permissive grant in the file header", + Notice = "Author: Herman Tulleken, dev.mag.org.za (http://devmag.org.za/2011/04/05/bzier-curves-a-tutorial/). " + + "Use this code as you wish, at your own risk.", + LicenceFile = BezierPathFile + }, + new Credit + { + Name = "ambientCG PBR materials", + Licence = "CC0 1.0 Universal", + Notice = "Texture sets from ambientCG (https://ambientcg.com), public domain", + LicenceFile = AmbientCgFile + }, + new Credit + { + Name = "Noun Project icons", + Licence = "Noun Project attribution licence", + Notice = string.Join("\n", NounProjectLines(nounProjectAttribution)), + LicenceFile = NounProjectFile + } + }; + Validate(credits); + return credits; + } + + // The icon credit lines of the attribution file: everything after its "Noun Project" heading, one line per icon (the + // file's "Other" sub-heading and its lines follow in the same list). A file that does not open with the heading is + // refused rather than having its first line dropped. + public static IEnumerable NounProjectLines(string attribution) + { + var lines = (attribution ?? "").Split('\n').Select(line => line.Trim()).Where(line => line.Length > 0).ToArray(); + if (lines.Length < 2 || lines[0] != NounProjectHeading) + throw new InvalidOperationException($"{NounProjectFile} must open with the heading '{NounProjectHeading}' followed by icon credits"); + return lines.Skip(1); + } + + // Throws on an entry a player-facing screen could not honestly show. + public static void Validate(IReadOnlyList credits) + { + foreach (var credit in credits) + if (string.IsNullOrWhiteSpace(credit.Name) || string.IsNullOrWhiteSpace(credit.Licence) || + string.IsNullOrWhiteSpace(credit.Notice) || string.IsNullOrWhiteSpace(credit.LicenceFile)) + throw new InvalidOperationException($"Credit '{credit.Name}' is missing its name, licence, notice or licence file"); + var duplicate = credits.GroupBy(credit => credit.LicenceFile).FirstOrDefault(group => group.Count() > 1); + if (duplicate != null) throw new InvalidOperationException($"Licence file {duplicate.Key} is credited twice"); + } +} diff --git a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta b/Assets/Scripts/ServerShared/Credits.cs.meta similarity index 83% rename from Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta rename to Assets/Scripts/ServerShared/Credits.cs.meta index 3f7c8777a..e88730bb6 100644 --- a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta +++ b/Assets/Scripts/ServerShared/Credits.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 94d688b37c5044dd9b67865c706d8918 +guid: b3333d3c0203441fbadd64fad27b60e5 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 2394a6134..9edf45e19 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -1261,13 +1261,15 @@ public abstract class Entity // This observer's stance toward `other`: its own override, else its belief. Allies (the observer's own non-null faction) are // known by datalink; any other contact is believed by the telemetry received with its track, and unknown (never hostile) - // without it. In a zone owned by a faction a contact is hostile when its claimed faction is the owner's and the owner does - // not permit its presence, or when this is the owner's ship and believes the contact trespasses. + // without it. A contact whose claimed faction this observer's faction Hates is hostile in any zone, owned or not; Hostile to + // Beloved govern presence instead. In a zone owned by a faction a contact is hostile when its claimed faction is the owner's and + // the owner does not permit its presence, or when this is the owner's ship and believes the contact trespasses. public bool IsHostileTo(Entity other) { if (_iffOverrides.TryGetValue(other, out var overrideHostile)) return overrideHostile; if (Faction != null && other.Faction == Faction) return false; if (!_telemetry.TryGetValue(other, out var claimed)) return false; + if (Regard(Faction, claimed) == FactionRelationship.Hated) return true; var owner = Zone.GalaxyZone.Owner; if (owner == null) return false; return (claimed == owner && !(PresencePermitted?.Value ?? true)) || (Faction == owner && BelievesTrespassing(other)); @@ -1300,14 +1302,27 @@ public abstract class Entity return false; } - // TODO: Inter-faction relationships + // How `faction` regards this entity's faction. public FactionRelationship GetFactionRelationship(Faction faction) { if (faction == null) return FactionRelationship.Neutral; if (this is Ship {IsPlayerShip: true}) return Zone.Galaxy.FactionRelationships[faction]; - return faction == Faction ? FactionRelationship.Beloved : FactionRelationship.Neutral; + return Regard(faction, Faction); + } + + // The one reader of Faction.Relations: how `regarding` regards `regarded`. Unset either side is Neutral, a faction regards + // itself Beloved, and absent from the map is Neutral. A faction the catalog does not hold has no key and is Neutral. + private FactionRelationship Regard(Faction regarding, Faction regarded) + { + if (regarding == null || regarded == null) return FactionRelationship.Neutral; + if (regarding == regarded) return FactionRelationship.Beloved; + if (regarding.Relations == null || regarding.Relations.Count == 0) return FactionRelationship.Neutral; + var key = ItemManager.ItemData.TryGetHandle(regarded)?.Key; + return key != null && regarding.Relations.TryGetValue(new CultRecordRef(key.Value), out var relationship) + ? relationship + : FactionRelationship.Neutral; } public static bool IsPresencePermitted(FactionRelationship relationship, SecurityLevel securityLevel) => @@ -1525,7 +1540,8 @@ public abstract class Entity // Check whether the given item will fit when its origin is placed at the given coordinate. For hardpoint gear, // hardpoint is the one hardpoint the item would occupy there (HardpointAt); Tool gear occupies none. - private bool ItemFits(EquippableItemData itemData, HullData hullData, EquippableItem item, int2 hullCoord, out HardpointData hardpoint) + private bool ItemFits(EquippableItemData itemData, HullData hullData, EquippableItem item, int2 hullCoord, out HardpointData hardpoint, + EquippedItem moving = null) { hardpoint = null; // Items without specific hardpoints on the ship can be freely rotated and placed anywhere @@ -1538,49 +1554,64 @@ public abstract class Entity // general gear may take it until hardpoint gear claims it, which is the same rule // UnoccupiedSpace reports, so what generation is offered and what equipping accepts agree. var itemCoord = hullCoord + itemData.Shape.Rotate(i, item.Rotation); - if (!hullData.InteriorCells[itemCoord] || GearOccupancy[itemCoord.x, itemCoord.y] != null) + if (!hullData.InteriorCells[itemCoord] || !IsFree(itemCoord.x, itemCoord.y, moving)) return false; } } else { - hardpoint = HardpointAt(itemData, hullData, hullCoord); + hardpoint = HardpointAt(itemData, hullData, hullCoord, item.Rotation, moving); if (hardpoint == null) return false; - item.Rotation = hardpoint.Rotation; } return true; } + // A cell is free when no gear occupies it, or when the only occupant is the item being moved: a re-place of + // equipped gear is judged against the hull minus that item's own cells (the caller unequips, then equips). + private bool IsFree(int x, int y, EquippedItem moving) => GearOccupancy[x, y] == null || GearOccupancy[x, y] == moving; + // The one placement rule for hardpoint gear. At this origin the item lies within a hardpoint of its type, turned to // that hardpoint's rotation (HardpointData.TakesAt, the fit rule); its own cells are free, since a hardpoint's // leftover cells may hold general gear (operator, 2026-09-30: "saving slots in a hardpoint can be a valid tradeoff - // for crowded ships"); and that hardpoint holds no other hardpoint item, since it holds one at most. - private HardpointData HardpointAt(EquippableItemData itemData, HullData hullData, int2 hullCoord) + // for crowded ships"); and that hardpoint holds no other hardpoint item, since it holds one at most. Where several hardpoints accept the origin, the + // one whose rotation equals the item's own (saved) rotation is preferred, so reload seats gear where it was; an item whose + // rotation names none of them takes the first (stable order). + private HardpointData HardpointAt(EquippableItemData itemData, HullData hullData, int2 hullCoord, ItemRotation seated, EquippedItem moving) { - foreach (var hardpoint in hullData.Hardpoints) + foreach (var hardpoint in hullData.Hardpoints.OrderBy(h => h.Rotation == seated ? 0 : 1)) { if (!hardpoint.TakesAt(itemData, hullCoord - hardpoint.Position)) continue; var ownCellsFree = itemData.Shape.Coordinates .Select(v => hullCoord + itemData.Shape.Rotate(v, hardpoint.Rotation)) - .All(c => GearOccupancy[c.x, c.y] == null); + .All(c => IsFree(c.x, c.y, moving)); var holdsAnother = hardpoint.Shape.Coordinates .Select(v => GearOccupancy[hardpoint.Position.x + v.x, hardpoint.Position.y + v.y]) - .Any(occupant => occupant != null && occupant.Data.HardpointType != HardpointType.Tool); + .Any(occupant => occupant != null && occupant != moving && occupant.Data.HardpointType != HardpointType.Tool); if (ownCellsFree && !holdsAnother) return hardpoint; } return null; } - // Check whether the given item will fit when its origin is placed at the given coordinate on the hull - public bool ItemFits(EquippableItem item, int2 hullCoord) + // Check whether the given item will fit when its origin is placed at the given coordinate on the hull. An item that + // is already equipped here is judged without its own cells, so a gun can be moved within its own hardpoint; + // TryEquip stays strict (it never sees an item as its own occupant), so equipping an equipped item twice is refused. + public bool ItemFits(EquippableItem item, int2 hullCoord) => ItemFits(item, hullCoord, out _); + + // As above, and reports the rotation TryEquip would seat the item at: its hardpoint's for hardpoint gear, otherwise + // its own. A probe never writes item.Rotation; TryEquip is the only seat. + public bool ItemFits(EquippableItem item, int2 hullCoord, out ItemRotation seated) { + seated = item.Rotation; // Don't allow equipping while deployed if (_active) return false; var itemData = ItemManager.GetData(item); var hullData = ItemManager.GetData(Hull) as HullData; - return ItemFits(itemData, hullData, item, hullCoord, out _); + if (!ItemFits(itemData, hullData, item, hullCoord, out var hardpoint, Equipment.FirstOrDefault(e => e.EquippableItem == item))) + return false; + seated = hardpoint?.Rotation ?? item.Rotation; + return true; } public bool TryFindSpace(EquippableItem item, out int2 hullCoord) @@ -1653,7 +1684,9 @@ public abstract class Entity var hullData = ItemManager.GetData(Hull) as HullData; if (!ItemFits(itemData, hullData, item, hullCoord, out var hardpoint)) return false; - + // The one seat of hardpoint gear's rotation, before EquippedItem's ctor reads it. + if (hardpoint != null) item.Rotation = hardpoint.Rotation; + EquippedItem equippedItem; if (itemData.HardpointType == HardpointType.Tool) { @@ -2458,7 +2491,7 @@ public class EquippedCargoBay : EquippedItem // For simple commodities, search for existing item stacks to add to foreach (var cargoItem in Cargo.Keys) { - if (!item.Data.Key.Equals(cargoItem.Data.Key)) continue; + if (!item.Data.Key.Equals(cargoItem.Data.Key) || item.Lot != cargoItem.Lot) continue; var cargoCommodity = (SimpleCommodity) cargoItem; if (cargoCommodity.Quantity >= itemData.MaxStack) continue; @@ -2556,7 +2589,7 @@ public class EquippedCargoBay : EquippedItem ItemsOfType[item.Data.Key] = new List(); ItemsOfType[item.Data.Key].Add(item); } - else if (Occupancy[cargoCoord.x, cargoCoord.y] is SimpleCommodity cargoCommodity && cargoCommodity.Data.Key.Equals(item.Data.Key)) + else if (Occupancy[cargoCoord.x, cargoCoord.y] is SimpleCommodity cargoCommodity && cargoCommodity.Data.Key.Equals(item.Data.Key) && cargoCommodity.Lot == item.Lot) { if (cargoCommodity.Quantity + item.Quantity <= itemData.MaxStack) { @@ -2636,7 +2669,7 @@ public class EquippedCargoBay : EquippedItem item.Quantity -= quantity; Mass -= itemData.Mass * quantity; ThermalMass -= itemData.Mass * itemData.SpecificHeat * quantity; - return new SimpleCommodity{Data = item.Data, Quantity = quantity, Rotation = item.Rotation}; + return new SimpleCommodity{Data = item.Data, Lot = item.Lot, Quantity = quantity, Rotation = item.Rotation}; } public void Remove(CraftedItemInstance item) diff --git a/Assets/Scripts/ServerShared/EntitySerializer.cs b/Assets/Scripts/ServerShared/EntitySerializer.cs index 7f0f04ebd..73656b87e 100644 --- a/Assets/Scripts/ServerShared/EntitySerializer.cs +++ b/Assets/Scripts/ServerShared/EntitySerializer.cs @@ -60,8 +60,8 @@ public static class EntitySerializer && itemManager.GetData(commodity).MaxStack >= 1) { var maxStack = itemManager.GetData(commodity).MaxStack; - var first = new SimpleCommodity { Data = commodity.Data, Rotation = commodity.Rotation, Quantity = maxStack }; - var rest = new SimpleCommodity { Data = commodity.Data, Rotation = commodity.Rotation, Quantity = commodity.Quantity - maxStack }; + var first = new SimpleCommodity { Data = commodity.Data, Lot = commodity.Lot, Rotation = commodity.Rotation, Quantity = maxStack }; + var rest = new SimpleCommodity { Data = commodity.Data, Lot = commodity.Lot, Rotation = commodity.Rotation, Quantity = commodity.Quantity - maxStack }; if (!bay.TryStore(first, position)) rest.Quantity += first.Quantity; spill.Add((bay, rest)); return; @@ -82,7 +82,7 @@ public static class EntitySerializer var remaining = rest.Quantity; while (remaining > 0) { - var chunk = new SimpleCommodity { Data = rest.Data, Rotation = rest.Rotation, Quantity = Math.Min(remaining, maxStack) }; + var chunk = new SimpleCommodity { Data = rest.Data, Lot = rest.Lot, Rotation = rest.Rotation, Quantity = Math.Min(remaining, maxStack) }; var placed = home.TryStore(chunk) || bays.Where(b => b != home).Any(b => b.TryStore(chunk)); // A refused store may still have topped up a stack; what is left in the chunk found no room. remaining -= Math.Min(remaining, maxStack) - (placed ? 0 : chunk.Quantity); @@ -294,4 +294,7 @@ public abstract class EntityPack return _price; } + + // Element identity: minted by the cache on write; "" means unset. + [Key(23)] [CultElementId] public string Id = ""; } diff --git a/Assets/Scripts/ServerShared/Extensions.cs b/Assets/Scripts/ServerShared/Extensions.cs index 97433a299..6ac7b5186 100644 --- a/Assets/Scripts/ServerShared/Extensions.cs +++ b/Assets/Scripts/ServerShared/Extensions.cs @@ -32,16 +32,13 @@ public static class Extensions // Every loadable type assignable to this one. An assembly whose dependencies are missing (a Unity plugin // referencing UnityEngine outside Unity) still yields the types that do load. - private static readonly Dictionary ChildClasses = new Dictionary(); - public static Type[] GetAllChildClasses(this Type type) + // Read from parallel loaders (catalog validation, parallel tests), so the memo is concurrent. + private static readonly System.Collections.Concurrent.ConcurrentDictionary ChildClasses = new System.Collections.Concurrent.ConcurrentDictionary(); + public static Type[] GetAllChildClasses(this Type type) => ChildClasses.GetOrAdd(type, t => AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => { - if (ChildClasses.TryGetValue(type, out var children)) return children; - return ChildClasses[type] = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => - { - try { return assembly.GetTypes(); } - catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } - }).Where(type.IsAssignableFrom).ToArray(); - } + try { return assembly.GetTypes(); } + catch (ReflectionTypeLoadException e) { return e.Types.Where(x => x != null); } + }).Where(t.IsAssignableFrom).ToArray()); public static string SplitCamelCase(this string str) => Regex.Replace(Regex.Replace(str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2"), @"(\p{Ll})(\P{Ll})", "$1 $2"); diff --git a/Assets/Scripts/ServerShared/FactionProduct.cs b/Assets/Scripts/ServerShared/FactionProduct.cs index 14f7af57d..87ac72f7d 100644 --- a/Assets/Scripts/ServerShared/FactionProduct.cs +++ b/Assets/Scripts/ServerShared/FactionProduct.cs @@ -61,6 +61,9 @@ public class ProductRole [Inspectable, JsonProperty("standardDeviation"), Key(2)] public float StandardDeviation = .15f; + + // Element identity: minted by the cache on write; "" means unset. + [Key(3)] [CultElementId] public string Id = ""; } // A bin of one of the maker's lines (ruling maker-design-tiers-allowed): the line it bins (the same design and maker, itself diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 1581e3457..9102b16eb 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -7,6 +7,7 @@ using System.Buffers; using System.Collections.Generic; using System.Linq; using CultMath; +using GameCult.Caching; using static CultMath.math; using float2 = CultMath.float2; using float3 = CultMath.float3; @@ -84,10 +85,10 @@ public static class FireControl // Whether the shooter's next round from this weapon is refused: the weapons ask before they spend anything, so // a refused round costs no ammo, energy, sound, heat, wear or visibility (operator ruling 2026-09-30). The // answer is Solve's own -- there is no second copy of the arming test. - public static bool Refuses(Weapon weapon, Entity shooter) => Refuses(weapon, shooter, shooter.Target.Value.Entity); + public static bool Refuses(Weapon weapon, Entity shooter) => Refuses(weapon, shooter, shooter.Target.Value); // The same answer against a target the shooter's pilot has commanded but not yet applied. - public static bool Refuses(Weapon weapon, Entity shooter, Entity target) => + public static bool Refuses(Weapon weapon, Entity shooter, TargetRef target) => !IsMineLayer(weapon) && Solve(weapon, weapon.Item, shooter, target).Outcome == FireOutcome.Refused; // A mine layer lays a body, not a round: it is never refused, never arc-gated, and Fire routes it to Lay. @@ -139,27 +140,18 @@ public static class FireControl // The one owner of a gun's solution against its subject (the designated target; ruling controls-solution-subject). // Bears: the gun can engage the subject, so the player fires on it without the aim. Free: the aim is inside the // arc, so the gun can fire along it. Direction: where a round from this gun travels and where its barrel points -- - // the subject's intercept when it bears, else the arc-clamped aim. A chunk subject bears through its pose and - // flies the aim, as an untargeted round (Subject is null for it). Derived on every read and never stored: turrets + // the subject's intercept when it bears (a rock's too), else the arc-clamped aim. Subject is null for a rock. Derived on every read and never stored: turrets // traverse instantly in the simulation. Traverse is the weapon's Tracking (ruling mount-arc-gun-traverse), priced in // TrackingRate; this holds no slew state, and a rig's slew is presentation. It never prices; HitProbability is the one price. public static GunSolution Solution(Weapon weapon, Entity shooter, TargetRef subject) { - var bears = false; - if (subject.Entity != null) bears = Bears(weapon, shooter, subject.Entity, out _); - else if (subject.Chunk is ChunkId chunk) - { - var at = shooter.Zone.ChunkPose(chunk.Field, chunk.Index).xy; - bears = InArc(weapon.Item, float3(at.x, 0, at.y) - shooter.Position); - } + var bears = Bears(weapon, shooter, subject, out _); return new GunSolution { Subject = subject.Entity, Bears = bears, Free = InArc(weapon.Item, shooter.Aim), - Direction = bears && subject.Entity != null - ? TravelDirection(weapon, shooter, subject.Entity) - : AimDirection(weapon.Item, shooter) + Direction = bears ? TravelDirection(weapon, shooter, subject) : AimDirection(weapon.Item, shooter) }; } @@ -224,8 +216,8 @@ public static class FireControl return degrees(abs(offset.x * relativeVelocity.y - offset.y * relativeVelocity.x) / (range * range)); } - public static float AngularVelocity(Entity source, Entity target) => - AngularVelocity((target.Position - source.Position).xz, target.Velocity - source.Velocity); + public static float AngularVelocity(Entity source, TargetRef target) => + AngularVelocity((PositionOf(source, target) - source.Position).xz, VelocityOf(source, target) - source.Velocity); // The gun's rate times the ship's gear over the unaided baseline (ruling tracking-per-gun, "gun times ship"): the // one product of the two. An unauthored gun is +infinity and so is its rate whatever the gear reads: a mount with no @@ -241,14 +233,31 @@ public static class FireControl // be judged against another. This is the one function; CombatState (and FireControl.Fire below) both call // it instead of touching CultMath.first_order_intercept directly. Planar: source velocity is never fed in // (no shooter here leads its own motion into the shot), matching every existing call site this replaces. - public static float3 PredictedIntercept(Weapon weapon, Entity source, Entity target) + // Mining Cut 4b: a target is an entity or a rock; its position and velocity come from PositionOf and VelocityOf. + public static float3 PredictedIntercept(Weapon weapon, Entity source, TargetRef target) { - var targetVelocity = float3(target.Velocity.x, 0, target.Velocity.y); + var position = PositionOf(source, target); + var velocity = VelocityOf(source, target); return weapon.Velocity > .01f - ? first_order_intercept(source.Position, float3.zero, weapon.Velocity, target.Position, targetVelocity) - : target.Position; + ? first_order_intercept(source.Position, float3.zero, weapon.Velocity, position, float3(velocity.x, 0, velocity.y)) + : position; } + // Where a target is now: an entity's position, a rock's pose at the shooter's height (everything here is planar). + private static float3 PositionOf(Entity source, TargetRef target) + { + if (target.Chunk is ChunkId chunk) + { + var at = source.Zone.ChunkPose(chunk.Field, chunk.Index).xy; + return float3(at.x, source.Position.y, at.y); + } + return target.Entity.Position; + } + + // How fast a target moves: an entity's velocity, a rock's from Zone.ChunkVelocity, the one owner. + private static float2 VelocityOf(Entity source, TargetRef target) => + target.Chunk is ChunkId chunk ? source.Zone.ChunkVelocity(chunk) : target.Entity.Velocity; + // Cut 3, R1/R3: the targeting solution (0b table) -- pure, no draw, recomputed fresh on every call. AI // reads this to decide whether a shot is worth taking; the HUD reads it to draw a number; Fire below reads // it once, at the instant the trigger is pulled, and freezes the result into the shot (R10, Q6). Two reads @@ -263,13 +272,13 @@ public static class FireControl // freezes (R10), gated exactly as HitProbability gates. Nothing about the target's facing or silhouette // enters here; that is Silhouette's and PSpread's job, priced fresh by HitProbability below and again, // live, by Commit at the commit tick. 0 the moment any gate closes. - private static float PFire(Weapon weapon, Entity source, Entity target) => PFire(weapon, source, target, out _, out _, out _); + private static float PFire(Weapon weapon, Entity source, TargetRef target) => PFire(weapon, source, target, out _, out _, out _); // The `out range` overload is HitProbability's own gate call -- one computation of `target.Position - // source.Position`, not two. HitProbability used to recompute its own copy for PSpread, which is exactly // the kind of split authority Cut 3 named as the risk (two places computing the same vector, free to // drift or to have their subtraction order flipped in only one of them). - private static float PFire(Weapon weapon, Entity source, Entity target, out float range) => + private static float PFire(Weapon weapon, Entity source, TargetRef target, out float range) => PFire(weapon, source, target, out range, out _, out _); // The one answer to "does the shooter hold valid targeting data on this target": visible, in range and locked @@ -279,25 +288,29 @@ public static class FireControl // visible, out of range) already denies the target. Planar (R7: the simulation is 2D): the range gate, the // burst reach and the range clamp all measure the same distance, so a target's height never moves one of // them without the others. - public static bool Designated(Weapon weapon, Entity source, Entity target, out float range) + // Mining Cut 4b: a rock is designated by the same range gates, seen when Entity.ChunkVisible says so; a + // LockWeapon (a launcher) is never designated on a rock (ruling Q12 = A, 2026-09-30). + public static bool Designated(Weapon weapon, Entity source, TargetRef target, out float range) { range = 0f; - if (target == null) return false; - range = length((target.Position - source.Position).xz); - return source.VisibleEntities.Contains(target) && range >= weapon.MinRange && range <= weapon.Range && + if (target.IsNone) return false; + range = length((PositionOf(source, target) - source.Position).xz); + var inRange = range >= weapon.MinRange && range <= weapon.Range; + if (target.Chunk is ChunkId chunk) return inRange && !(weapon is LockWeapon) && source.ChunkVisible(chunk); + return source.VisibleEntities.Contains(target.Entity) && inRange && !(weapon is LockWeapon lockWeapon && !lockWeapon.IsLocked); } // Whether this gun can engage this target: designated and inside the arc. The one test of it; PFire prices a shot // at zero unless it holds, and Solution reads it to decide whether the gun fires on the target. `designated` is // the answer above, kept apart for Solve's burst flight: a designated target out of arc still sets the burst range. - public static bool Bears(Weapon weapon, Entity source, Entity target, out float range) => + public static bool Bears(Weapon weapon, Entity source, TargetRef target, out float range) => Bears(weapon, source, target, out range, out _); - private static bool Bears(Weapon weapon, Entity source, Entity target, out float range, out bool designated) + private static bool Bears(Weapon weapon, Entity source, TargetRef target, out float range, out bool designated) { designated = Designated(weapon, source, target, out range); - return designated && InArc(weapon.Item, target.Position - source.Position); + return designated && InArc(weapon.Item, PositionOf(source, target) - source.Position); } // `designated` is the answer above. `inArc` is Bears, asked only once a target is designated. @@ -305,13 +318,14 @@ public static class FireControl // (operator rulings 2026-09-30): without valid data it has no target and bursts at max range; with data but // out of arc it bursts at the target's range, along the aim. The HUD reads Designated and the // arc from Solve and Inspect and decides nothing. - private static float PFire(Weapon weapon, Entity source, Entity target, out float range, out bool designated, out bool inArc) + private static float PFire(Weapon weapon, Entity source, TargetRef target, out float range, out bool designated, out bool inArc) { inArc = Bears(weapon, source, target, out range, out designated); if (!inArc) return 0f; var settings = source.ItemManager.GameplaySettings; - var info = source.EntityInfoGathered.TryGetValue(target, out var gathered) ? gathered : 0f; + var info = target.Chunk is ChunkId chunk ? source.ChunkInfo(chunk) + : source.EntityInfoGathered.TryGetValue(target.Entity, out var gathered) ? gathered : 0f; return Accuracy(source) * PSensor(settings, Resolution(source), info); } @@ -364,22 +378,33 @@ public static class FireControl return (sil, pSpread, evasion); } - public static float HitProbability(Weapon weapon, Entity source, Entity target) => + public static float HitProbability(Weapon weapon, Entity source, TargetRef target) => HitProbability(weapon, source, target, (AimTarget?) null); // Priced on `aim` rather than the source's aim slot: the aim its pilot commands this step. - public static float HitProbability(Weapon weapon, Entity source, Entity target, AimTarget aim) => + public static float HitProbability(Weapon weapon, Entity source, TargetRef target, AimTarget aim) => HitProbability(weapon, source, target, (AimTarget?) aim); // A null aim reads source.ResolvedAim, after the gate, so a gated-out shot reads nothing more. - private static float HitProbability(Weapon weapon, Entity source, Entity target, AimTarget? aim) + // Mining Cut 4b: a rock is priced by the same factors as a ship at equal range, precision and info -- its disc + // through the same integrator, its evasion 0 (a rock is not a Ship), and no aim point: the disc is aimed at. + private static float HitProbability(Weapon weapon, Entity source, TargetRef target, AimTarget? aim) { var pFire = PFire(weapon, source, target, out var range); if (pFire <= 0f) return 0f; - var targetHull = source.ItemManager.GetData(target.Hull) as HullData; - var (sil, pSpread, evasion) = Forecast(weapon, source, target, targetHull, Precision(source), range, aim ?? source.ResolvedAim); - return pFire * PMount(AngularVelocity(source, target), TrackingRate(weapon, source)) * pSpread * sil.POnHull * PDeviation(evasion, Tracking(source)); + var pMount = PMount(AngularVelocity(source, target), TrackingRate(weapon, source)); + if (target.Chunk is ChunkId chunk) + { + var mass = RockMass(source.Zone, chunk, Precision(source), out var span); + var pSpreadRock = PSpread(weapon.Spread, span, range, source.ItemManager.GameplaySettings.SchematicCellSize); + return pFire * pMount * pSpreadRock * mass * PDeviation(0f, Tracking(source)); + } + + var entity = target.Entity; + var targetHull = source.ItemManager.GetData(entity.Hull) as HullData; + var (sil, pSpread, evasion) = Forecast(weapon, source, entity, targetHull, Precision(source), range, aim ?? source.ResolvedAim); + return pFire * pMount * pSpread * sil.POnHull * PDeviation(evasion, Tracking(source)); } // Presentation only: the debug HUD's view of exactly the factors HitProbability multiplies. It computes @@ -457,7 +482,7 @@ public static class FireControl // at Fire (R10); HitProbability and Inspect recompute it fresh, at the current source/target positions, // for their forecast. Below a length of 1e-6 (point-blank, source and intercept coincide) it falls back // to world +z, the same fallback Apply used before this cut (`:463`). - public static float2 TravelDirection(Weapon weapon, Entity source, Entity target) + public static float2 TravelDirection(Weapon weapon, Entity source, TargetRef target) { var toIntercept = (PredictedIntercept(weapon, source, target) - source.Position).xz; return lengthsq(toIntercept) < 1e-6f ? float2(0, 1) : normalize(toIntercept); @@ -505,12 +530,21 @@ public static class FireControl // The commit price's deviation: what the target has already moved off the frozen forecast, plus what it can and // does move off the line of fire (Evasion). The second part applies at any flight time, so an instant weapon // (flight time 0, realized deviation 0) still feels a jinking target. - public static float DeviationProbability(PendingShot shot, float now, out float deviation) + // Mining Cut 4b: a rock's deviation is where its pose is now against that projection, with no evasion; its + // zone is the shooter's (a shot that outlives its shooter is resolved by Step, which passes the zone it runs in). + public static float DeviationProbability(PendingShot shot, float now, out float deviation) => + DeviationProbability(shot.Source?.Zone, shot, now, out deviation); + + private static float DeviationProbability(Zone zone, PendingShot shot, float now, out float deviation) { + deviation = 0f; + if (shot.Target == null && shot.Chunk == null) return 1f; var elapsed = now - shot.FireTime; var predicted = shot.FireTargetPosition + shot.FireTargetVelocity * elapsed; - deviation = shot.Target == null ? 0f : length((shot.Target.Position - predicted).xz) + Evasion(shot.Target, shot.TravelDirection); - return shot.Target == null ? 1f : PDeviation(deviation, shot.Tracking); + deviation = shot.Chunk is ChunkId chunk + ? length(zone.ChunkPose(chunk.Field, chunk.Index).xy - predicted.xz) + : length((shot.Target.Position - predicted).xz) + Evasion(shot.Target, shot.TravelDirection); + return PDeviation(deviation, shot.Tracking); } // How far a target can and does move off the line of fire in the solution window: the term DeviationProbability @@ -608,7 +642,7 @@ public static class FireControl // BurstReach the planar distance from the shooter at which the payload is delivered (a direct round's target, a fused // round's burst point, 0 for an untargeted direct round), which Fire's range factor reads for every outcome. Refused: a fused round whose blast // radius (its arming distance) exceeds the weapon's Range; it cannot be fired. - public static FireSolution Solve(Weapon weapon, EquippedItem item, Entity source, Entity target) + public static FireSolution Solve(Weapon weapon, EquippedItem item, Entity source, TargetRef target) { var pFire = PFire(weapon, source, target, out var fireRange, out var designated, out var inArc); @@ -639,14 +673,14 @@ public static class FireControl // that leaves the zone cancels it like any other. A round whose Range is shorter than the arming distance // cannot be fired at all: it is refused, per round, where Range is read after Execute refreshed it (a // burst's later rounds and a power-starved Range included). - var engaged = fuse != null && !(designated && inArc) ? null : target; + var engaged = fuse != null && !(designated && inArc) ? TargetRef.None : target; var origin = source.Position; var travelDirection = Solution(weapon, source, target).Direction; var arming = fuse != null ? blastRadius : 0f; - var burstPosition = engaged != null ? engaged.Position : origin; + var burstPosition = !engaged.IsNone ? PositionOf(source, engaged) : origin; var flightDistance = 0f; - if (fuse != null && engaged != null) + if (fuse != null && !engaged.IsNone) { // Nothing bursts beyond max range: an intercept a receding target leads the round past Range is // pulled back along its own line to Range. @@ -662,7 +696,7 @@ public static class FireControl burstPosition = Armed(origin, travelDirection, arming, origin + float3(travelDirection.x, 0, travelDirection.y) * reach); flightDistance = max(reach, arming); } - else if (engaged != null) flightDistance = fireRange; + else if (!engaged.IsNone) flightDistance = fireRange; var solution = new FireSolution { @@ -710,8 +744,7 @@ public static class FireControl Lay(weapon, item, source); return 0; } - // Mining Cut 3: a chunk target fires as an untargeted round until Cut 4 routes shots at chunks. - var target = source.Target.Value.Entity; + var target = source.Target.Value; var now = zone.Time - age; // R1's engage gate and the shooter-side probability, evaluated now and frozen: nothing at commit time @@ -721,7 +754,7 @@ public static class FireControl var solution = Solve(weapon, item, source, target); if (solution.Outcome == FireOutcome.Refused) return 0; // The mount factor is frozen with the shooter-side probability: nothing at commit time re-reads the sweep. - var pFire = solution.PFire * (solution.Engaged != null ? PMount(AngularVelocity(source, solution.Engaged), TrackingRate(weapon, source)) : 1f); + var pFire = solution.PFire * (!solution.Engaged.IsNone ? PMount(AngularVelocity(source, solution.Engaged), TrackingRate(weapon, source)) : 1f); var fireRange = solution.FireRange; var engaged = solution.Engaged; var travelDirection = solution.TravelDirection; @@ -732,10 +765,11 @@ public static class FireControl var targetVelocity = float3.zero; var targetPosition = origin; - if (engaged != null) + if (!engaged.IsNone) { - targetVelocity = float3(engaged.Velocity.x, 0, engaged.Velocity.y); - targetPosition = engaged.Position - targetVelocity * age; + var velocity = VelocityOf(source, engaged); + targetVelocity = float3(velocity.x, 0, velocity.y); + targetPosition = PositionOf(source, engaged) - targetVelocity * age; } var flightTime = weapon.Velocity > .01f ? solution.FlightDistance / weapon.Velocity : 0f; @@ -746,7 +780,8 @@ public static class FireControl { ShotId = zone.NextShotId(), Source = source, - Target = engaged, + Target = engaged.Entity, + Chunk = engaged.Chunk, Weapon = item, Aimed = aim.Item, AimedMount = aim.Mount, @@ -773,7 +808,7 @@ public static class FireControl // The commit horizon exists so the target's facing can be read late (Bearing timing). A round fired at // nothing has no facing to read, so it commits at Fire: its burst point is decided from the poses of // the moment it leaves, and a Contact round short of max range can arrive as early as it truly does. - CommitTime = fuse != null && engaged == null ? now : now + max(0f, flightTime - commitHorizon), + CommitTime = fuse != null && engaged.IsNone ? now : now + max(0f, flightTime - commitHorizon), BurstPosition = burstPosition, Fuse = fuse, BlastRadius = blastRadius, @@ -861,7 +896,7 @@ public static class FireControl { var shot = shots[i]; - var targetGone = shot.Target != null && !zone.Entities.Contains(shot.Target); + var targetGone = TargetGone(zone, shot); if (targetGone) { // Cut 11 (Soul C4): a shot whose target has left the zone resolves as a miss whichever @@ -908,7 +943,7 @@ public static class FireControl if (i < 0) continue; var shot = shots[i]; - var targetGone = shot.Target != null && !zone.Entities.Contains(shot.Target); + var targetGone = TargetGone(zone, shot); if (targetGone) { // As in the commit walk: a shot whose target left the zone in this step resolves as a miss. @@ -930,6 +965,10 @@ public static class FireControl } } + // A shot's target has left the zone, or a rock it flies at no longer exists (broken in flight): the shot is a miss. + private static bool TargetGone(Zone zone, PendingShot shot) => + (shot.Target != null && !zone.Entities.Contains(shot.Target)) || (shot.Chunk is ChunkId chunk && !zone.ChunkExists(chunk)); + // R3/R4: the one roll. p_base was frozen at fire, PFire carrying the mount factor; the only thing measured live is how far the target has // actually strayed, by now, from where a straight-line projection of its fire-time velocity said it would // be -- forgiven by the targeting system's Tracking, likewise frozen at fire. @@ -945,15 +984,25 @@ public static class FireControl // (bearing) -- is read live, here, at the commit tick. The Cut 7 guard extends to cover the new factors: // when PFire x pDeviation is already 0, no Silhouette is built. Shared by Commit's own roll and by the // debug HUD's forecast (TheHudEstimateIsTheCommitPrice) -- one function, one commit-time price. - public static float CommitProbability(PendingShot shot, float now, out Silhouette sil) + public static float CommitProbability(PendingShot shot, float now, out Silhouette sil) => + CommitProbability(shot.Source?.Zone, shot, now, out sil); + + // Mining Cut 4b: a rock's price is PFire x PDeviation x PSpread(span 2R) x the disc's mass; it reads no hull. + private static float CommitProbability(Zone zone, PendingShot shot, float now, out Silhouette sil) { sil = default; - if (shot.Target == null) return 0f; + if (shot.Target == null && shot.Chunk == null) return 0f; - var pDeviation = DeviationProbability(shot, now, out _); + var pDeviation = DeviationProbability(zone, shot, now, out _); var p = shot.PFire * pDeviation; if (p <= 0f) return 0f; + if (shot.Chunk is ChunkId chunk) + { + var mass = RockMass(zone, chunk, shot.Precision, out var span); + return p * PSpread(shot.Spread, span, shot.FireRange, zone.SchematicCellSize) * mass; + } + var bearing = Bearing(shot.Target, shot.TravelDirection); var hullData = shot.Target.ItemManager.GetData(shot.Target.Hull) as HullData; sil = Silhouette(shot.Target, hullData, shot.Aimed, bearing, shot.Precision, null, shot.AimedMount); @@ -984,7 +1033,7 @@ public static class FireControl // drawing once is the documented way to get a correlated first output, and a follow-up to give // CultMath.Random a mixed-seed entry point of its own is recorded for a separate CultLib cut. var random = new Random(SimulationDice.Mix((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u)); - var p = CommitProbability(shot, now, out var sil); + var p = CommitProbability(zone, shot, now, out var sil); var hit = p > 0f && random.NextFloat() < p; var cell = int2.zero; @@ -993,7 +1042,8 @@ public static class FireControl var shielded = false; var shieldBroken = false; - if (hit) + // A rock hit has no lane and no shield: Cell, Bearing and Lateral stay zero (Apply wears the rock). + if (hit && shot.Chunk == null) { // Cut 12.2: the same silhouette pOnHull drew its mass from -- same bearing (live, at this commit // tick), same sigma (the frozen Precision). A shot that passed the roll always lands on metal (R3: @@ -1185,7 +1235,13 @@ public static class FireControl // Detonate is still the one blast path. if (shot.Outcome.Result == ShotResult.Burst || shot.Fuse == WeaponFuse.Proximity) { - Detonate(zone, shot.Outcome.BurstPoint, shot.BlastRadius, shot.Damage, shot.DamageType); + Detonate(zone, shot.Outcome.BurstPoint, shot.BlastRadius, shot.Damage, shot.DamageType, shot); + return; + } + + if (shot.Chunk is ChunkId rock) + { + ApplyRockHit(zone, shot, rock); return; } @@ -1201,6 +1257,28 @@ public static class FireControl } } + // Mining Cut 4b: a committed hit on a rock. A round without a fuse wears the rock by its Damage (the falloff was + // read at Fire) and publishes one absorb on the zone's ChunkCapabilities (through Publish, at height 0 like a blast's), at the + // rock's surface facing the shot and before the wear shrinks it. A contact or delayed round detonates at the rock's centre as it arrives (the + // arming rule kept), through Detonate, the one area owner. + private static void ApplyRockHit(Zone zone, PendingShot shot, ChunkId rock) + { + if (!shot.Outcome.Hit) return; + + var centre = zone.ChunkPose(rock.Field, rock.Index).xy; + if (shot.Fuse == null) + { + var direction = float3(shot.TravelDirection.x, 0, shot.TravelDirection.y); + var surface = centre - shot.TravelDirection * zone.ChunkRadius(rock); + Publish(zone.ChunkCapabilities, AbsorbLayer.Hull, float3(surface.x, 0f, surface.y), direction, shot.Damage, shot.DamageType); + var absorbed = zone.Wear(rock, shot.Damage); + Extract(zone, rock, absorbed, shot.Source, SimulationDice.For(zone.DropSeed, SimulationDice.OreStream, (uint) shot.ShotId)); + return; + } + var point = Armed(shot.FireOrigin, shot.TravelDirection, shot.BlastRadius, float3(centre.x, shot.FireOrigin.y, centre.y)).xz; + Detonate(zone, point, shot.BlastRadius, shot.Damage, shot.DamageType, shot); + } + // Cut 12.3 (docs/fire-control-cut.md, "How a direct hit travels"): replaces Entity.ApplyHit's 0.5-step // march and Entity.DamageSchematic's even split over the whole hit shape. Spread is width (Q12-2 = A): // 2n+1 parallel lanes, sharing the shot's damage evenly over whichever lanes actually meet metal -- the @@ -1221,7 +1299,7 @@ public static class FireControl if (shot.Outcome.Shielded) { - Publish(shot.Target, AbsorbLayer.Shield, ImpactPoint(shot.Target, shot.Outcome.Cell), + Publish(shot.Target.Capabilities, AbsorbLayer.Shield, ImpactPoint(shot.Target, shot.Outcome.Cell), float3(shot.TravelDirection.x, 0, shot.TravelDirection.y), shot.Damage, shot.DamageType); shot.Target.Shield.TakeHit(shot.DamageType, shot.Damage); return; @@ -1266,7 +1344,7 @@ public static class FireControl for (var li = 0; li < laneCount; li++) ArrayPool.Shared.Return(buffers[li]); - Publish(target, AbsorbLayer.Hull, ImpactPoint(target, shot.Outcome.Cell), + Publish(target.Capabilities, AbsorbLayer.Hull, ImpactPoint(target, shot.Outcome.Cell), float3(shot.TravelDirection.x, 0, shot.TravelDirection.y), shot.Damage, shot.DamageType); target.DamageHull(hullDamage); } @@ -1278,17 +1356,18 @@ public static class FireControl return float3(world.x, target.Position.y, world.y); } - // The one publisher of an absorbed impact: once per receiver, on its Capabilities, before the damage it reports. - private static void Publish(Entity receiver, AbsorbLayer layer, float3 position, float3 direction, float magnitude, DamageType damageType) => - receiver.Capabilities.PublishAbsorb(new AbsorbEvent(position, direction, magnitude, damageType, layer)); + // The one publisher of an absorbed impact: once per receiver, on its CapabilityEvents (an entity's, or the zone's + // for a rock), before the damage it reports. + private static void Publish(CapabilityEvents receiver, AbsorbLayer layer, float3 position, float3 direction, float magnitude, DamageType damageType) => + receiver.PublishAbsorb(new AbsorbEvent(position, direction, magnitude, damageType, layer)); - // A blast's impact on one entity: at the blast point (on the entity's height), travelling from the blast out through - // the entity's centre, or zero when they coincide. - private static void PublishBlast(Entity entity, float2 blast, AbsorbLayer layer, float magnitude, DamageType damageType) + // A blast's impact on one receiver: at the blast point (at the receiver's height), travelling from the blast out + // through the receiver's planar centre, or zero when they coincide. An entity and a rock go through it alike. + private static void PublishBlast(CapabilityEvents receiver, float2 centre, float height, float2 blast, AbsorbLayer layer, float magnitude, DamageType damageType) { - var away = entity.Position.xz - blast; + var away = centre - blast; var direction = lengthsq(away) > 0f ? normalize(away) : float2.zero; - Publish(entity, layer, float3(blast.x, entity.Position.y, blast.y), float3(direction.x, 0, direction.y), magnitude, damageType); + Publish(receiver, layer, float3(blast.x, height, blast.y), float3(direction.x, 0, direction.y), magnitude, damageType); } // Cut 12.4(b) (docs/fire-control-cut.md, "Where P is"): a contact or delayed blast needs a committed hit -- @@ -1336,7 +1415,7 @@ public static class FireControl // the muzzle than the blast radius is detonated on at the radius, along the round's own flight line. var hullPoint = target.ToWorldPoint(schematicPoint); var worldPoint = Armed(shot.FireOrigin, shot.TravelDirection, shot.BlastRadius, float3(hullPoint.x, shot.FireOrigin.y, hullPoint.y)).xz; - Detonate(target.Zone, worldPoint, shot.BlastRadius, shot.Damage, shot.DamageType); + Detonate(target.Zone, worldPoint, shot.BlastRadius, shot.Damage, shot.DamageType, shot); } // Cut 12.4(b) (docs/fire-control-cut.md, "The penetrator", Q12-8): the one penetration-reach owner, moved @@ -1593,6 +1672,7 @@ public static class FireControl ShotId = shot.ShotId, Source = shot.Source, Target = shot.Target, + Chunk = shot.Chunk, Weapon = shot.Weapon, Result = result, Shielded = shielded, @@ -1607,7 +1687,13 @@ public static class FireControl // Cut 12.4(b) (docs/fire-control-cut.md, "Area, per entity"): the one owner of blast damage -- a blast is // an area, not a bundle of rays (Q12-7 dissolved the ray model's remainder question along with the rays - // themselves). Splash's signature with the point made planar (R7). Callers: Apply's three fuse branches. Nothing draws: every candidate entity in radius takes its share, unconditionally. + // themselves). Splash's signature with the point made planar (R7). Callers: Apply's three fuse branches and + // Zone's mine step. Nothing draws: every candidate entity in radius takes its share, unconditionally. + // + // Mining cut 4a (docs/mining-cut-refresh.md, Q10 = A): this is also the one owner of blast area over rocks. + // After the entity pass, every unbroken rock whose disc the blast disc overlaps takes its lens share of the + // damage -- damage * lens / (pi r^2), the cells' own normaliser -- through Zone.Wear, and publishes one absorb + // on Zone.ChunkCapabilities first. Overlapping bodies each take their own overlap; shares off every body are lost. // // For each candidate (an entity whose centre lies within radius plus half its own hull diagonal -- // CandidatesIncludeHullsWhoseCentreIsOutsideTheRadius, which Splash's centre-distance cull could not pass): @@ -1631,7 +1717,7 @@ public static class FireControl // call: doing so would buy no behaviour, per ProbeC in the cut doc). Leftovers -- unoccupied-cell shares, // and whatever an item's pool does not absorb -- join one entity-wide hull total, applied through one // DamageHull call. - public static void Detonate(Zone zone, float2 worldPlanar, float radius, float damage, DamageType damageType) + public static void Detonate(Zone zone, float2 worldPlanar, float radius, float damage, DamageType damageType, PendingShot? shot = null) { // No distance prefilter: RectDiskOverlap is the one decider of whether the disc touches a hull. A // prefilter measured from Position (the centre of mass) with the bounding box's half-diagonal is not a @@ -1673,7 +1759,7 @@ public static class FireControl { if (shield.CanTakeHit(damageType, totalShare)) { - PublishBlast(entity, worldPlanar, AbsorbLayer.Shield, totalShare, damageType); + PublishBlast(entity.Capabilities, entity.Position.xz, entity.Position.y, worldPlanar, AbsorbLayer.Shield, totalShare, damageType); shield.TakeHit(damageType, totalShare); continue; } @@ -1703,11 +1789,112 @@ public static class FireControl for (var i = 0; i < amounts.Length; i++) hullTotal += amounts[i]; } - PublishBlast(entity, worldPlanar, AbsorbLayer.Hull, totalShare, damageType); + PublishBlast(entity.Capabilities, entity.Position.xz, entity.Position.y, worldPlanar, AbsorbLayer.Hull, totalShare, damageType); entity.DamageHull(hullTotal); } + + if (!(radius > 0f) || zone.AsteroidBelts.Count == 0) return; // no area, or no rocks to cover + // Rocks, through the targeting index (no observer: entities stay out of it). Reach is exact on a rock's + // centre, so it is the blast radius plus the widest any rock can be. Walked in (field, index) order so the + // order of wear -- and any later dice on it -- is fixed. + var rocks = _rockScratch ??= new List(); + zone.Targets.Within(new TargetSearch(worldPlanar, radius + Zone.LargestChunkRadius(zone.Settings)), rocks); + rocks.RemoveAll(c => !c.Target.Chunk.HasValue); + rocks.Sort((a, b) => + { + var byField = string.CompareOrdinal(a.Target.Chunk.Value.Field.Value, b.Target.Chunk.Value.Field.Value); + return byField != 0 ? byField : a.Target.Chunk.Value.Index.CompareTo(b.Target.Chunk.Value.Index); + }); + var discArea = PI * radius * radius; + // Mining Cut 5a: a shot's blast pays its Source for the rocks it wears, from the shot's own dice, once for the + // blast, drawn in the rock order above. A mine (no shot) wears rocks and yields nothing. + var dice = shot != null ? SimulationDice.For(zone.DropSeed, SimulationDice.OreStream, (uint) shot.Value.ShotId) : default; + foreach (var rock in rocks) + { + var chunk = rock.Target.Chunk.Value; + if (!zone.ChunkExists(chunk)) continue; + var centre = zone.ChunkPose(chunk.Field, chunk.Index).xy; + var share = damage * CircleCircleOverlap(length(centre - worldPlanar), radius, zone.ChunkRadius(chunk)) / discArea; + if (!(share > 0f)) continue; + PublishBlast(zone.ChunkCapabilities, centre, 0f, worldPlanar, AbsorbLayer.Hull, share, damageType); + var absorbed = zone.Wear(chunk, share); + if (shot != null) Extract(zone, chunk, absorbed, shot.Value.Source, dice); + } } + // Mining Cut 5a: the one loot owner of a rock. A worn rock pays the shooter at the wear site, at arrival or detonation, + // from the shot's own dice: the damage it absorbed is that fraction of its hitpoints, and the same fraction of the + // units its size authors (AsteroidYield), so a rock pays its whole yield however many hits break it. Whole units, and + // one Bernoulli draw on the fraction. Each unit draws an ore by weight: the belt's yields for this province, scaled by + // exp(variance x g), g a stable hash of (field, index, ore) in [-1, 1) -- a rock's composition, derived here every call + // and never stored. A shot with no Source (a mine) yields nothing. The units go to the shooter's cargo bays in + // stacks; what does not fit, or everything when the shooter has left the zone, floats at the rock (ruling + // mining-overflow-floats). + // Draw order: the Bernoulli, then one draw per unit. + public static void Extract(Zone zone, ChunkId chunk, float absorbed, Entity shooter, Random dice) + { + if (shooter == null || !(absorbed > 0f)) return; + var settings = zone.Settings; + var belt = zone.AsteroidBelts[chunk.Field]; + var catalog = shooter.ItemManager.ItemData; + var ores = FieldKinds.Yield(belt.Data.Kind, zone.GalaxyZone?.Province?.Type ?? default, catalog); + if (ores.Length == 0) return; + + var size = belt.Data.Asteroids[chunk.Index].Size; + var owed = absorbed / settings.AsteroidHitpoints.Evaluate(size) * settings.AsteroidYield.Evaluate(size); + var units = (int) floor(owed); + if (dice.NextFloat() < owed - units) units++; + if (units == 0) return; + + var weights = new float[ores.Length]; + var total = 0f; + for (var i = 0; i < ores.Length; i++) + { + var g = $"{chunk.Field.Value}:{chunk.Index}:{ores[i].Commodity.Key.Value}".StableHash() / 2147483648.0 - 1.0; + total += weights[i] = ores[i].Amount * (float) Math.Exp(settings.ChunkCompositionVariance * g); + } + var counts = new int[ores.Length]; + for (var unit = 0; unit < units; unit++) + { + var pick = dice.NextFloat() * total; + var ore = 0; + while (ore < ores.Length - 1 && pick >= weights[ore]) pick -= weights[ore++]; + counts[ore]++; + } + + var at = zone.ChunkPose(chunk.Field, chunk.Index).xy; + var velocity = zone.ChunkVelocity(chunk); + var zoneIndex = zone.Galaxy?.Zones == null ? -1 : Array.IndexOf(zone.Galaxy.Zones, zone.GalaxyZone); + var present = zone.Entities.Contains(shooter); + for (var i = 0; i < ores.Length; i++) + { + var key = ores[i].Commodity.Key; + var commodity = (SimpleCommodityData) catalog.Get(ores[i].Commodity); + var maxStack = Math.Max(1, commodity.MaxStack); + var lot = counts[i] > 0 ? shooter.ItemManager.ExtractedLot(zoneIndex, chunk.Field, commodity) : 0; + var adrift = 0; + for (var left = counts[i]; left > 0; left -= maxStack) + { + var stack = new SimpleCommodity { Data = new CultRecordRef(key), Lot = lot, Quantity = Math.Min(left, maxStack) }; + // A partial store leaves the remainder in Quantity and returns false, so the next bay is offered the rest. + var stored = false; + if (present) foreach (var bay in shooter.CargoBays) if (stored = bay.TryStore(stack)) break; + if (!stored) + { + adrift += stack.Quantity; + zone.Release(stack, at, velocity); + } + } + if (counts[i] > 0) + zone.CargoGained.OnNext(new CargoGain + { + Taker = shooter, Design = new CultRecordRef(key), Lot = lot, Stored = counts[i] - adrift, Adrift = adrift, Kind = GainKind.Mined + }); + } + } + + [ThreadStatic] private static List _rockScratch; + // Whether the disc reaches any occupied hull cell of the entity: Detonate's own coverage test (the same // ToSchematicPoint, SchematicCellSize and CircleSquareOverlap), so what triggers a mine and what its blast // reaches are one geometry. @@ -1721,6 +1908,19 @@ public static class FireControl return false; } + // Mining cut 4a: the exact area shared by two discs at centre distance d -- the lens. Exactly zero when they are + // disjoint or tangent, and the smaller disc's whole area when one contains the other. + public static float CircleCircleOverlap(float d, float r1, float r2) + { + if (r1 <= 0f || r2 <= 0f || d >= r1 + r2) return 0f; + var small = min(r1, r2); + if (d <= abs(r1 - r2)) return PI * small * small; + var a = (d * d + r1 * r1 - r2 * r2) / (2f * d * r1); + var b = (d * d + r2 * r2 - r1 * r1) / (2f * d * r2); + var k = (-d + r1 + r2) * (d + r1 - r2) * (d - r1 + r2) * (d + r1 + r2); + return r1 * r1 * acos(clamp(a, -1f, 1f)) + r2 * r2 * acos(clamp(b, -1f, 1f)) - .5f * sqrt(max(0f, k)); + } + // Cut 12.4(b) (docs/fire-control-cut.md, "Exact overlap, in float"): the exact area of a unit square, // centred on `cell` (the unit square centred on its integer coordinate, the same convention every other // frame rule uses), that lies inside a disc of radius `r` centred at `diskCentre` -- both in the same @@ -1876,9 +2076,7 @@ public static class FireControl var aimPoint = ResolveAimPoint(target, hull, aimed, mount); var a = dot(aimPoint, ell); - var pOnHull = 0f; - for (var i = 0; i < count; i++) - pOnHull += Phi((intervals[i].Hi - a) / sigma) - Phi((intervals[i].Lo - a) / sigma); + var pOnHull = Mass(new ReadOnlySpan(intervals, 0, count), a, sigma); var span = count > 0 ? intervals[count - 1].Hi - intervals[0].Lo : 0f; @@ -1894,6 +2092,27 @@ public static class FireControl }; } + // The one Gaussian integrator: the mass a normal of `sigma` about `aim` puts inside the merged, disjoint + // `intervals`. A hull's shadow and a rock's disc (one interval about its aim) both read it. + private static float Mass(ReadOnlySpan intervals, float aim, float sigma) + { + var mass = 0f; + foreach (var interval in intervals) + mass += Phi((interval.Hi - aim) / sigma) - Phi((interval.Lo - aim) / sigma); + return mass; + } + + // A rock is a disc of radius R schematic cells aimed at its centre: one interval [-R, R] about the aim, span 2R. + // The one price of it, read by HitProbability's forecast and by Commit, at the rock's radius now. + private static float RockMass(Zone zone, ChunkId chunk, float precision, out float span) + { + var radius = zone.ChunkCells(chunk); + span = 2f * radius; + Span disc = stackalloc Interval[1]; + disc[0] = new Interval { Lo = -radius, Hi = radius }; + return saturate(Mass(disc, 0f, Sigma(precision))); + } + // Phi(z) = 1/2 (1 + erf(z / sqrt(2))): the standard normal CDF, CultMath's erf the one function underneath // every Gaussian-mass sum this cut computes. private static float Phi(float z) => .5f * (1f + erf(z * (1f / SQRT2))); @@ -2054,6 +2273,9 @@ public struct PendingShot public int ShotId; public Entity Source; public Entity Target; + // Mining Cut 4b: the rock a shot flies at, frozen at Fire; at most one of Target and Chunk is set. Unity reads + // Target only, so a rock shot draws untargeted until the Unity follow-up (mining-unity-chunk-presentation). + public ChunkId? Chunk; public EquippedItem Weapon; public EquippedItem Aimed; // The mount the aim was at, when it was at a mount rather than an item (Entity.ResolvedAim at Fire), frozen with Aimed: @@ -2113,7 +2335,7 @@ public struct PendingShot // A fused round with no target: where it bursts is decided at its commit (the first hull its aim line meets), so its // damage reads the falloff there rather than at Fire. - public bool DeliveredAtCommit => Fuse != null && Target == null; + public bool DeliveredAtCommit => Fuse != null && Target == null && Chunk == null; } // What a round does when fired (FireControl.Solve): Direct resolves against its target, Burst detonates at a @@ -2147,7 +2369,7 @@ public struct FireSolution public float FireRange; // Whether the shooter holds valid targeting data on the target (Designated); the HUD and the agents read it here. public bool Designated; - public Entity Engaged; + public TargetRef Engaged; public float2 TravelDirection; public float3 BurstPosition; public WeaponFuse? Fuse; @@ -2313,6 +2535,7 @@ public sealed class ShotOutcome public int ShotId; public Entity Source; public Entity Target; + public ChunkId? Chunk; public EquippedItem Weapon; // What the commit decided, typed: a shot rolled and missed, rolled and hit, or was a fused round with no // target and so burst without rolling, or a proximity round whose roll missed but which detonates anyway diff --git a/Assets/Scripts/ServerShared/Galaxy.cs b/Assets/Scripts/ServerShared/Galaxy.cs index 797e77764..929fa3493 100644 --- a/Assets/Scripts/ServerShared/Galaxy.cs +++ b/Assets/Scripts/ServerShared/Galaxy.cs @@ -26,7 +26,10 @@ public class Galaxy public GalaxyZone Exit { get; private set; } public Dictionary FactionRelationships { get; } = new Dictionary(); private Action Log { get; } - public bool IsPrelude { get; } + + // How far each faction's authored InfluenceDistance reaches in this galaxy (InfluenceOf): the cast's InfluenceScale, + // 1 for a main galaxy. Carried by the save because every zone generated after Continue reads it. + public float InfluenceScale { get; } // The run's seed, minted once by GalaxyStage.SeedFrom and carried by the save (SavedGame.Seed). It seeds // generation, the run's item draws (RunStart) and the zone's drop dice (Zone.DropSeed). @@ -51,7 +54,9 @@ public class Galaxy public Galaxy(CultCache cultCache, SavedGame savedGame, Action log) { - IsPrelude = savedGame.IsTutorial; + InfluenceScale = savedGame.InfluenceScale > 0 + ? savedGame.InfluenceScale + : throw new InvalidOperationException($"the save has no {nameof(InfluenceScale)} ({savedGame.InfluenceScale}); a run saved before InfluenceScale existed cannot be continued"); _cache = cultCache; Log = log; Background = savedGame.Background; @@ -112,7 +117,7 @@ public class Galaxy uint seed) { _cache = cache; - IsPrelude = false; + InfluenceScale = 1; Background = background; Log = log; var factions = cache.GetAll(); @@ -186,11 +191,11 @@ public class Galaxy return _cache.GetAll().FirstOrDefault(f => f.Name.StartsWith(name, StringComparison.InvariantCultureIgnoreCase)); } - // A cast member of a prelude galaxy, by name. A name the catalog does not hold refuses the galaxy, naming the field. + // A cast member of a cast galaxy, by name. A name the catalog does not hold refuses the galaxy, naming the field. private Faction ResolveCast(string field, string name) => ResolveFaction(name) ?? throw new InvalidOperationException($"cast faction {name} ({field}) is not in the catalog"); - // Gives a prelude galaxy its gate: the antagonist's home is the boss zone and the exit. The only writer of Exit + // Gives a cast galaxy its gate: the antagonist's home is the boss zone and the exit. The only writer of Exit // besides the constructors. public void PlaceGate(Faction antagonist) { @@ -198,23 +203,24 @@ public class Galaxy Exit = HomeZones[antagonist]; } - // How many jumps a faction's influence reaches in this galaxy: its authored distance, halved (rounding up) in a - // prelude. Derived, never written back to the catalog's Faction, so one galaxy's generation cannot change the next. + // How many jumps a faction's influence reaches in this galaxy: its authored distance scaled by the galaxy's + // InfluenceScale (the cast decides the scale), rounding up. Derived, never written back to the catalog's Faction, + // so one galaxy's generation cannot change the next. public int InfluenceOf(Faction faction) => - IsPrelude ? (faction.InfluenceDistance + 1) / 2 : faction.InfluenceDistance; + (int) MathF.Ceiling(faction.InfluenceDistance * InfluenceScale); public Galaxy( - TutorialGenerationSettings settings, + GalaxyCast cast, SectorBackgroundSettings background, CultCache cache, - PlayerSettings playerSettings, - DirectoryInfo narrativeDirectory, Action log, Action progressCallback, uint seed) { _cache = cache; - IsPrelude = true; + InfluenceScale = cast.InfluenceScale > 0 + ? cast.InfluenceScale + : throw new InvalidOperationException($"the cast's {nameof(cast.InfluenceScale)} must be positive, got {cast.InfluenceScale}"); Background = background; Log = log; @@ -223,32 +229,32 @@ public class Galaxy var factions = new List(); - var protagonistFaction = ResolveCast(nameof(settings.ProtagonistFaction), settings.ProtagonistFaction); + var protagonistFaction = ResolveCast(nameof(cast.ProtagonistFaction), cast.ProtagonistFaction); factions.Add(protagonistFaction); - var antagonistFaction = ResolveCast(nameof(settings.AntagonistFaction), settings.AntagonistFaction); + var antagonistFaction = ResolveCast(nameof(cast.AntagonistFaction), cast.AntagonistFaction); factions.Add(antagonistFaction); - var bufferFaction = ResolveCast(nameof(settings.BufferFaction), settings.BufferFaction); + var bufferFaction = ResolveCast(nameof(cast.BufferFaction), cast.BufferFaction); factions.Add(bufferFaction); // A cast without a quest faction places no quest zone. - var questFaction = string.IsNullOrEmpty(settings.QuestFaction) + var questFaction = string.IsNullOrEmpty(cast.QuestFaction) ? null - : ResolveCast(nameof(settings.QuestFaction), settings.QuestFaction); + : ResolveCast(nameof(cast.QuestFaction), cast.QuestFaction); if (questFaction != null) factions.Add(questFaction); - var neutralFactions = settings.NeutralFactions - .Select(name => ResolveCast(nameof(settings.NeutralFactions), name)) + var neutralFactions = cast.NeutralFactions + .Select(name => ResolveCast(nameof(cast.NeutralFactions), name)) .ToArray(); factions.AddRange(neutralFactions); Factions = factions.ToArray(); foreach (var faction in Factions) FactionRelationships[faction] = FactionRelationship.Neutral; - Zones = GenerateZones(settings.ZoneCount, ref random, progressCallback); + Zones = GenerateZones(cast.ZoneCount, ref random, progressCallback); - GenerateLinks(settings.LinkDensity, progressCallback); + GenerateLinks(cast.LinkDensity, progressCallback); CalculateDistanceMatrix(progressCallback); @@ -302,15 +308,11 @@ public class Galaxy CalculateFactionInfluence(progressCallback); - // No boss zone and no Exit yet (PlaceGate comes after): the prelude is one region. - BuildProvinces(settings.ProvinceZones); + // No boss zone and no Exit yet (PlaceGate comes after): a cast galaxy is one region. + BuildProvinces(cast.ProvinceZones); NamePlaces(ref random, progressCallback); - // progressCallback?.Invoke("Weaving Narrative"); - // var processor = new StoryProcessor(playerSettings, narrativeDirectory, this, ref random, Log); - // processor.ProcessStories(); - progressCallback?.Invoke("Done!"); if(progressCallback!=null) Thread.Sleep(500); // Inserting Delay to make it seem like it's doing more work lmao } diff --git a/Assets/Scripts/ServerShared/GalaxyStage.cs b/Assets/Scripts/ServerShared/GalaxyStage.cs index a93e25f89..4bea4d6c7 100644 --- a/Assets/Scripts/ServerShared/GalaxyStage.cs +++ b/Assets/Scripts/ServerShared/GalaxyStage.cs @@ -1,5 +1,4 @@ using System; -using System.IO; using GameCult.Caching; using MessagePack; using static CultMath.math; @@ -13,11 +12,8 @@ public sealed class GalaxyStage { private readonly SectorGenerationSettings _sector; private readonly SectorBackgroundSettings _sectorBackground; - private readonly TutorialGenerationSettings _prelude; - private readonly SectorBackgroundSettings _preludeBackground; + private readonly SectorBackgroundSettings _castBackground; private readonly CultCache _cache; - private readonly PlayerSettings _playerSettings; - private readonly DirectoryInfo _narrativeDirectory; private readonly Action _log; private readonly Action _progress; private readonly Func _clock; @@ -25,22 +21,16 @@ public sealed class GalaxyStage public GalaxyStage( SectorGenerationSettings sector, SectorBackgroundSettings sectorBackground, - TutorialGenerationSettings prelude, - SectorBackgroundSettings preludeBackground, + SectorBackgroundSettings castBackground, CultCache cache, - PlayerSettings playerSettings, - DirectoryInfo narrativeDirectory, Action log, Action progress = null, Func clock = null) { _sector = sector; _sectorBackground = sectorBackground; - _prelude = prelude; - _preludeBackground = preludeBackground; + _castBackground = castBackground; _cache = cache; - _playerSettings = playerSettings; - _narrativeDirectory = narrativeDirectory; _log = log; _progress = progress; _clock = clock ?? (() => (uint) (DateTime.Now.Ticks % uint.MaxValue)); @@ -65,13 +55,10 @@ public sealed class GalaxyStage return new Galaxy(_sector, background, _cache, _log, _progress, Seed); } - // A prelude galaxy: the tutorial settings and their fixed factions, centred in dense cloud. - public Galaxy Prelude() => Prelude(_prelude); - - // A prelude galaxy of the given fixed cast, centred in dense cloud. - public Galaxy Prelude(TutorialGenerationSettings cast) + // A galaxy of the given fixed cast, centred in dense cloud. + public Galaxy Cast(GalaxyCast cast) { - var background = Copy(_preludeBackground); + var background = Copy(_castBackground); var random = new Random(Seed); var iteration = 1; do @@ -79,7 +66,7 @@ public sealed class GalaxyStage background.NoisePosition = random.NextFloat() * 1000; _progress?.Invoke($"Finding Galaxy Position: iteration {iteration++}"); } while (background.CloudDensity(float2(.5f)) < .5f); - return new Galaxy(cast, background, _cache, _playerSettings, _narrativeDirectory, _log, _progress, Seed); + return new Galaxy(cast, background, _cache, _log, _progress, Seed); } private static SectorBackgroundSettings Copy(SectorBackgroundSettings settings) => diff --git a/Assets/Scripts/ServerShared/HaulFeed.cs b/Assets/Scripts/ServerShared/HaulFeed.cs new file mode 100644 index 000000000..b6f4055c8 --- /dev/null +++ b/Assets/Scripts/ServerShared/HaulFeed.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +public enum GainKind { Mined, Collected } + +// One entry into a hold: what Extract stored (and let float) of one ore, or what a pickup collected. Stored plus Adrift is +// the units; a pickup has Adrift 0. Published on Zone.CargoGained by its two writers and read by presentations only. +public struct CargoGain +{ + public Entity Taker; + public CultRecordRef Design; + public int Lot; + public int Stored; + public int Adrift; + public GainKind Kind; +} + +// The words for a cargo gain, and the taker's hold fill. Nothing here is stored: the line and the fill are derived on +// every call. +public static class HaulFeed +{ + public static string Line(CargoGain gain, ItemManager items) + { + var name = items.ItemData.Get(gain.Design).Name; + var (used, total) = HoldFill(gain.Taker?.CargoBays ?? Enumerable.Empty()); + var hold = $"(hold {used}/{total})"; + if (gain.Kind == GainKind.Collected) return $"Collected {gain.Stored} {name} {hold}"; + return gain.Adrift > 0 + ? $"+{gain.Stored} {name}, {gain.Adrift} adrift {hold}" + : $"+{gain.Stored} {name} {hold}"; + } + + // Occupied cells over the bays' interiors, a multi-cell item counted per cell. + public static (int used, int total) HoldFill(IEnumerable bays) + { + int used = 0, total = 0; + foreach (var bay in bays) + foreach (var v in bay.Data.InteriorShape.AllCoordinates) + { + if (!bay.Data.InteriorShape[v]) continue; + total++; + if (bay.Occupancy[v.x, v.y] != null) used++; + } + return (used, total); + } +} diff --git a/Assets/Scripts/ServerShared/HaulFeed.cs.meta b/Assets/Scripts/ServerShared/HaulFeed.cs.meta new file mode 100644 index 000000000..b9b4b88b6 --- /dev/null +++ b/Assets/Scripts/ServerShared/HaulFeed.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d3ef606ec5240119cbb3d7dd51123d9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/InputLayout.cs b/Assets/Scripts/ServerShared/InputLayout.cs index a688598b2..7e942c519 100644 --- a/Assets/Scripts/ServerShared/InputLayout.cs +++ b/Assets/Scripts/ServerShared/InputLayout.cs @@ -29,7 +29,10 @@ public class InputLayout Union(0, typeof(InputLayoutRowSpacer)), Union(1, typeof(InputLayoutKeyRow)) ] -public abstract class InputLayoutRow { } +public abstract class InputLayoutRow { + // Element identity: minted by the cache on write; "" means unset. + [Key(1)] [CultElementId] public string Id = ""; +} [MessagePackObject, JsonObject(MemberSerialization.OptIn)] public class InputLayoutRowSpacer : InputLayoutRow @@ -52,6 +55,9 @@ public class InputLayoutKeyRow : InputLayoutRow public abstract class InputLayoutColumn { [Key(0), JsonProperty("width")] public float Width; + + // Element identity: minted by the cache on write; "" means unset. + [Key(5)] [CultElementId] public string Id = ""; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index 72c07fc9a..ab9c9dcfc 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -348,6 +348,9 @@ public class ItemRole [Inspectable, JsonProperty("count"), Key(1)] public int Count = 1; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } [CultDocument("aetheria.compoundcommoditydata", "1"), Inspectable, MessagePackObject] @@ -635,6 +638,9 @@ public class HardpointData } private static Dictionary _tintColors; + + // Element identity: minted by the cache on write; "" means unset. + [Key(8)] [CultElementId] public string Id = ""; } // What a PerformanceStat reads to resolve one number: the lot it prices quality against, and the per-context @@ -680,6 +686,9 @@ public class StatTerm // The design role whose part quality this term reads; unset reads the item's effective quality (Lot.EffectiveQuality). // Njordr states the same rule as a derivation over dimensions; this is that rule with one dimension. [Inspectable, JsonProperty("role"), Key(2)] public string Role; + + // Element identity: minted by the cache on write; "" means unset. + [Key(3)] [CultElementId] public string Id = ""; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/ItemInstance.cs b/Assets/Scripts/ServerShared/ItemInstance.cs index 80a891666..a16553b9f 100644 --- a/Assets/Scripts/ServerShared/ItemInstance.cs +++ b/Assets/Scripts/ServerShared/ItemInstance.cs @@ -24,6 +24,11 @@ public abstract class ItemInstance { [JsonProperty("data"), Key(0)] public CultRecordRef Data; [JsonProperty("rotation"), Key(1)] public ItemRotation Rotation; + + // The lot this unit was minted or mined from: crafted units' design, provenance, workmanship and role fills all + // live there; a mined SimpleCommodity names its Extracted lot (zone, belt, ore). Lot 0 is no lot: bought, staged + // and loadout commodities, and every save from before the field reached SimpleCommodity. + [JsonProperty("lot"), Key(11)] public int Lot; } [Union(0, typeof(CompoundCommodity)), @@ -33,9 +38,7 @@ public abstract class ItemInstance public abstract class CraftedItemInstance : ItemInstance { // Keys 2 (Quality), 9 (Ingredients) and 10 (Product) belonged to fields moved to Lot; do not reuse them. - - // The lot this unit was minted from: its design, provenance, workmanship and role fills all live there. - [JsonProperty("lot"), Key(11)] public int Lot; + // Key 11 (Lot) lives on ItemInstance. } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/ItemManager.cs b/Assets/Scripts/ServerShared/ItemManager.cs index 090fe1545..d5c1e05dd 100644 --- a/Assets/Scripts/ServerShared/ItemManager.cs +++ b/Assets/Scripts/ServerShared/ItemManager.cs @@ -25,6 +25,11 @@ public class ItemManager public CultCache ItemData { get; } public ProvenanceLedger Lots { get; } + + // (zone index, belt, commodity) -> the Extracted lot minted for it. Derived from Lots at construction and on mint, + // never persisted: a reload rebuilds it from the ledger, so the same source finds the same lot. + private readonly Dictionary<(int, CultRecordKey, CultRecordKey), int> _extracted = + new Dictionary<(int, CultRecordKey, CultRecordKey), int>(); public GameplaySettings GameplaySettings { get; } public ItemManager(uint seed, CultCache itemData, ProvenanceLedger lots, GameplaySettings settings, Action logger) @@ -33,10 +38,32 @@ public class ItemManager Random = new Random(seed); ItemData = itemData; Lots = lots; + foreach (var (id, lot) in lots.Lots) + if (lot.Origin is Extracted extracted) + _extracted[(extracted.Zone, extracted.Body.Key, extracted.Commodity.Key)] = id; GameplaySettings = settings; _logger = logger; } + // A restore point over everything building items draws or mints: the item stream and the lot ledger, which a run save + // persists. Rewind puts both back, so a refused build is neither a draw nor a lot. + public readonly struct Checkpoint + { + internal readonly Random Stream; + internal readonly int NextLot; + internal Checkpoint(Random stream, int nextLot) { Stream = stream; NextLot = nextLot; } + } + + public Checkpoint Mark() => new Checkpoint(Random, Lots.NextLot); + + public void Rewind(Checkpoint mark) + { + Random = mark.Stream; + foreach (var id in Lots.Lots.Keys.Where(id => id >= mark.NextLot).ToList()) Lots.Lots.Remove(id); + Lots.NextLot = mark.NextLot; + foreach (var key in _extracted.Where(entry => entry.Value >= mark.NextLot).Select(entry => entry.Key).ToList()) _extracted.Remove(key); + } + public void Log(string s) { _logger(s); @@ -72,8 +99,9 @@ public class ItemManager }; } - // The one resolution path from a crafted instance to the lot it was minted from. - public Lot GetLot(CraftedItemInstance item) => Lots[item.Lot]; + // The one resolution path from an instance to the lot it was minted or mined from. Lot 0 throws: a bought or + // staged commodity has no lot, and the caller asks Lot != 0 first. + public Lot GetLot(ItemInstance item) => Lots[item.Lot]; // Returns stat when not equipped: a null-entity context with no heat, no power and no modifiers. It says so // in its own name (UnequippedStatContext) rather than being a third quiet dialect of the arithmetic. @@ -180,6 +208,24 @@ public class ItemManager return Lots.Add(lot); } + // Mining Cut 5b: the lot of every unit mined from one commodity in one belt of one zone, found or minted. Unbranded + // (Product unset) and unworked (Quality 1, no roles). FireControl.Extract is the only caller. + public int ExtractedLot(int zone, CultRecordKey belt, SimpleCommodityData commodity) + { + var key = (zone, belt, ItemData.RefOf(commodity).Key); + if (_extracted.TryGetValue(key, out var found)) return found; + var id = Lots.Add(new Lot + { + Design = ItemData.RefOf(commodity), + Origin = new Extracted + { + Zone = zone, Body = new CultRecordRef(belt), Commodity = ItemData.RefOf(commodity) + }, + Quality = 1 + }); + return _extracted[key] = id; + } + // The one writer of a crafted instance's Data: copied from the lot's design, never independently set. public CraftedItemInstance CreateInstance(int lot) { diff --git a/Assets/Scripts/ServerShared/Loadout.cs b/Assets/Scripts/ServerShared/Loadout.cs index 4866aa406..b423eb1a0 100644 --- a/Assets/Scripts/ServerShared/Loadout.cs +++ b/Assets/Scripts/ServerShared/Loadout.cs @@ -28,6 +28,9 @@ public class LoadoutSlot [Key(1)] public ItemRotation Rotation; [Key(2)] public CultRecordRef Design; [Key(3)] public CultRecordRef Product; // unset: design-only, chosen at materialization + + // Element identity: minted by the cache on write; "" means unset. + [Key(4)] [CultElementId] public string Id = ""; } // Why a faction has no boss Loadout to build; see Loadouts.BossOf. diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index fcd554efd..62e8632a1 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -257,8 +257,11 @@ public class LoadoutGenerator // Whether a product is on the market at all (ruling off-market-is-unoffered-product). The one reader of NotOffered. A bin is // offered only if both it and its line are (ruling bin-inherits-line-offered); the catalog read guarantees a bin's line exists. - public static bool IsOffered(CultCache items, FactionProductData product) => - !product.NotOffered && (product.Bin == null || !items.Get(product.Bin.Line).NotOffered); + public static bool IsOffered(CultCache items, FactionProductData product) => IsOffered(product, line => items.Get(line)); + + // The same reader for a caller whose bin lines are not all in one catalog yet (ShipModCatalog.MarketFault, over a package's own products). + public static bool IsOffered(FactionProductData product, Func, FactionProductData> lineOf) => + !product.NotOffered && (product.Bin == null || !lineOf(product.Bin.Line).NotOffered); // How much this outfitter favors a product: its maker's preference times the product's share of it. The one weight of // generation and of ChooseProduct. A bin takes the share of its maker's stock that would pass its floor and its line takes diff --git a/Assets/Scripts/ServerShared/Provenance.cs b/Assets/Scripts/ServerShared/Provenance.cs index 4121332d6..71c260496 100644 --- a/Assets/Scripts/ServerShared/Provenance.cs +++ b/Assets/Scripts/ServerShared/Provenance.cs @@ -92,6 +92,9 @@ public class Lot foreach (var fill in Roles) sum += Math.Min(fill.Quality, Quality); return sum / Roles.Count; } + + // Element identity: minted by the cache on write; "" means unset. + [Key(5)] [CultElementId] public string Id = ""; } // One filled slot: the design's role name and how good the part that went into it turned out to be. Stats read it through @@ -101,6 +104,9 @@ public class RoleFill { [Key(0)] public string Role; [Key(1)] public float Quality; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // Who built a lot, where, and from what. Terminus mints Attributed placeholders; Produced and Extracted are the @@ -131,6 +137,8 @@ public class Produced : Provenance [MessagePackObject] public class Extracted : Provenance { + // Zone is the zone's index in galaxy.Zones (SavedGame's convention), -1 with no galaxy; Body is the belt. [Key(0)] public int Zone; [Key(1)] public CultRecordRef Commodity; + [Key(2)] public CultRecordRef Body; } diff --git a/Assets/Scripts/ServerShared/Recipes.cs b/Assets/Scripts/ServerShared/Recipes.cs index e434a84a5..f9aa3ee4a 100644 --- a/Assets/Scripts/ServerShared/Recipes.cs +++ b/Assets/Scripts/ServerShared/Recipes.cs @@ -63,6 +63,9 @@ public class CommodityCount [JsonProperty("count"), Key(1)] public int Count = 1; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // A region gate's trade with the world beyond it: what the outside buys and sells, at what price and at most how fast. @@ -96,6 +99,9 @@ public class OutsideMarketRow [JsonProperty("ratePerHour"), Key(4)] public float RatePerHour; + + // Element identity: minted by the cache on write; "" means unset. + [Key(5)] [CultElementId] public string Id = ""; } // The one reader of recipes: which recipe makes a good, a recipe's role slots (RoleInputsOf), which commodities fill a role, and diff --git a/Assets/Scripts/ServerShared/RunStart.cs b/Assets/Scripts/ServerShared/RunStart.cs index cadd66bcc..6278c0cbc 100644 --- a/Assets/Scripts/ServerShared/RunStart.cs +++ b/Assets/Scripts/ServerShared/RunStart.cs @@ -27,42 +27,40 @@ public static class RunStart { SeedItems(itemManager, galaxy, ArenaStep); return galaxy.Entrance.PackedContents = ZoneGenerator.GenerateZone( - itemManager, zoneSettings, planetSettings, galaxy, galaxy.Entrance, galaxy.IsPrelude, scenario.Ambient); + itemManager, zoneSettings, planetSettings, galaxy, galaxy.Entrance, scenario.EntranceStation, scenario.Ambient); } - // Runs the scenario's Stage, then admits its player and everything it placed: each entity's stance set both ways - // with the player, a pilot for each piloted one. Returns null, with every failure listed and the arena unchanged, + // Runs a start and answers whether it produced a run: null, with the reason in `failures`, when `start` throws or + // returns nothing. The caller shows the failure and clears its run; nothing past a null may run the game. + public static Staged Launch(Func start, List failures, Action log = null) + { + Staged staged = null; + try { staged = start(); } + catch (Exception exception) + { + log?.Invoke(exception); + failures.Add(exception.Message); + } + if (staged == null && failures.Count == 0) failures.Add("the start produced no run"); + return staged; + } + + // Runs the scenario's Stage, then has the stage admit its player and everything it placed. + // Returns null, with every failure listed and the arena unchanged, // unless the whole scenario staged. public static Staged Stage(ItemManager itemManager, Zone arena, Scenario scenario, string startingHull, - TutorialGenerationSettings tutorialGenerationSettings, List failures) + List failures) { SeedItems(itemManager, arena.Galaxy, StageStep); - var stage = new ScenarioStage(itemManager, arena, startingHull, tutorialGenerationSettings); + var stage = new ScenarioStage(itemManager, arena, startingHull); scenario.Stage(stage); var reported = failures.Count; failures.AddRange(stage.Failures); if (!stage.PlayerPlaced) failures.Add("player: the scenario places no player"); if (failures.Count > reported) return null; - stage.StockUnauthoredAmmunition(); - - var player = stage.PlayerShip; - player.IsPlayerShip = true; - arena.Admit(player, piloted: false); - foreach (var placed in stage.Placed) - { - var hostile = placed.Stance == ScenarioStance.Hostile; - placed.Entity.SetIff(player, hostile); - player.SetIff(placed.Entity, hostile); - arena.Admit(placed.Entity, placed.Piloted, placed.Task); - } - - // A start state includes what a pilot knows (ruling stage-states-pilot-knowledge): its anchor is tracked from the first - // step, by the sensors' own path (info gathered past the detection threshold), so they can lose it like any track. - foreach (var placed in stage.Placed) - if (placed.Knows != null && placed.Piloted) - placed.Entity.EntityInfoGathered[placed.Knows] = (itemManager.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f; - return new Staged { Player = player, Credits = stage.Credits, Entities = stage.Placed.Select(placed => placed.Entity).ToList() }; + stage.Admit(); + return new Staged { Player = stage.PlayerShip, Credits = stage.Credits, Entities = stage.Placed.Select(placed => placed.Entity).ToList() }; } // A new run's item draws (each lot's quality, each generated fit) come from its galaxy's seed, not the process clock, diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index 88ff8c9bf..867714a5e 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -42,8 +42,7 @@ public class SavedGame [Key(10)] public SavedActionBarBinding[] ActionBarBindings; - [Key(11)] - public bool IsTutorial; + // Key(11): retired, do not reuse (a retired run-mode flag) // Read only by a save written before Standings: its entries follow galaxy.Factions order, not Factions order, so // Galaxy trusts it only when the two orders cannot differ (see Galaxy's save constructor). @@ -68,6 +67,11 @@ public class SavedGame // null in a save written before it, which then reads Relationships. [Key(16)] public List Standings; + + // Galaxy.InfluenceScale: every zone generated after Continue reads it (ZoneGenerator's factionPresence). Written only + // by RunSave.Capture and read only by Galaxy's save constructor, which refuses a save without one (0). + [Key(17)] + public float InfluenceScale; } [MessagePackObject] @@ -78,6 +82,9 @@ public class SavedStanding [Key(1)] public FactionRelationship Relationship; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } [MessagePackObject] @@ -88,6 +95,9 @@ public class SavedProvince [Key(1)] public CultRecordRef Type; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // The run's lifecycle over the run store. Only Commit creates SavedGame, SavedZone and ProvenanceLedger records; @@ -116,7 +126,7 @@ public static class RunSave CurrentZoneEntity = currentZone.Entities.IndexOf(currentEntity), Entrance = Array.IndexOf(galaxy.Zones, galaxy.Entrance), Exit = Array.IndexOf(galaxy.Zones, galaxy.Exit), - IsTutorial = galaxy.IsPrelude, + InfluenceScale = galaxy.InfluenceScale, ActionBarBindings = actionBar, Credits = credits, Seed = galaxy.Seed @@ -216,10 +226,12 @@ public static class RunSave .Select(stored => stored.Key) .ToArray(); game.Zones = keys.Select(key => new CultRecordRef(key)).ToArray(); + // Every crafted item roots, Lot 0 included: a crafted item with no lot is corruption and Reachable throws on it. + // A SimpleCommodity roots only when it names a lot; Lot 0 is bought, staged or loadout stock. var roots = zones .SelectMany(zone => zone.Contents?.Entities ?? new List()) .SelectMany(EntitySerializer.Items) - .OfType() + .Where(item => item != null && (item is CraftedItemInstance || item.Lot != 0)) .Select(item => item.Lot); cache.Commit(batch => { @@ -301,6 +313,9 @@ public class SavedZone ] public abstract class SavedActionBarBinding { + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } [MessagePackObject] diff --git a/Assets/Scripts/ServerShared/Scenario.cs b/Assets/Scripts/ServerShared/Scenario.cs index 72b084866..1db6d7687 100644 --- a/Assets/Scripts/ServerShared/Scenario.cs +++ b/Assets/Scripts/ServerShared/Scenario.cs @@ -22,13 +22,19 @@ public abstract class Scenario // the scenario's conditions. public virtual bool Ambient => true; - // Which galaxy the run is in: stage.Main() or stage.Prelude(). + // True: the arena's zone always gets a generated faction station with a docking bay, whatever its seed rolls + // (ZoneGenerator). False: its stations are rolled like any other zone's. + public virtual bool EntranceStation => true; + + // Which galaxy the run is in: stage.Main() or stage.Cast(cast). public abstract Galaxy Generate(GalaxyStage stage); // What the run starts with: exactly one stage.Player, and anything else the scenario places. public abstract void Stage(ScenarioStage stage); } +// A run-start placement's stance toward the player. Hostile is written as an override both ways; Neutral writes nothing, +// so the faction rule and grudges decide. public enum ScenarioStance { Neutral, diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index a813bbf49..a39a94578 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -8,14 +8,18 @@ using float2 = CultMath.float2; using float3 = CultMath.float3; // The run half of a scenario's vocabulary (docs/scenarios-cut.md, R.4). A scenario's Stage builds its fits and places -// them here; nothing joins the arena until Stage returns with no failure, and then RunStart admits it all at once. +// them here; nothing joins the arena until Stage returns with no failure, and then the stage admits it all at once. // Every verb names what it could not do instead of throwing, so one bad name in a script lists every bad name. -// Designs, hulls and products are named as the catalog names them. Only RunStart builds a stage. -public sealed class ScenarioStage +// Designs, hulls and products are named as the catalog names them. +// ZoneStage is the placement vocabulary and the admission of what it placed; Zone.Admit stays the only admission. +// RunStart builds a ScenarioStage (a ZoneStage that also stages the player and authors stance); ZoneStage.Summon builds a +// ZoneStage for a running zone. A ZoneStage has no Player verb and no stance, so a summon placing a player or writing who +// fights whom is unrepresentable: a summon's stance is the faction rule's and its grudges'. +public class ZoneStage { private readonly ItemManager _items; private readonly Func _choose; - private readonly List _failures = new List(); + private protected readonly List _failures = new List(); private readonly List _placed = new List(); private int _placements; // The entities this stage built from a fit (a packed fit is a saved ship, whose cargo is its own) and those whose cargo the scenario @@ -23,13 +27,10 @@ public sealed class ScenarioStage private readonly HashSet _fitted = new HashSet(); private readonly HashSet _cargoAuthored = new HashSet(); - internal ScenarioStage(ItemManager items, Zone arena, string startingHull, TutorialGenerationSettings tutorialGenerationSettings) + internal ZoneStage(ItemManager items, Zone arena) { _items = items; Arena = arena; - StartingHull = startingHull; - TutorialGenerationSettings = tutorialGenerationSettings; - Credits = items.GameplaySettings.StartingCredits; // A design named without a product is chosen by the generator's ChooseProduct. The stage outfits with no faction, // so every maker is reachable and the run's seed draws. _choose = new LoadoutGenerator(ref items.Random, items, arena.Galaxy, arena.GalaxyZone, null, 2).ChooseProduct; @@ -37,29 +38,21 @@ public sealed class ScenarioStage public Galaxy Galaxy => Arena.Galaxy; public Zone Arena { get; } - public string StartingHull { get; } - public TutorialGenerationSettings TutorialGenerationSettings { get; } - - // What the run starts with: the gameplay settings' starting credits unless the scenario sets another amount. - public int Credits { get; set; } internal IReadOnlyList Failures => _failures; // Staging's last step: a fitted entity whose cargo the scenario did not author gets the crates its weapons draw, like every other // newly built armed entity (Loadouts.StockAmmunition). Draws nothing, so it moves no item roll. - internal void StockUnauthoredAmmunition() + private protected void StockUnauthoredAmmunition() { foreach (var entity in _fitted.Where(entity => !_cargoAuthored.Contains(entity))) Loadouts.StockAmmunition(_items, entity); } - internal bool PlayerPlaced { get; private set; } - internal Ship PlayerShip { get; private set; } internal IReadOnlyList Placed => _placed; internal sealed class Placement { public Entity Entity; - public ScenarioStance Stance; public bool Piloted; public AgentTask Task; // What the pilot already knows at the start: an entity its sensors hold a track of (Approach). Seeded through the @@ -115,39 +108,31 @@ public sealed class ScenarioStage public ScenarioFit Preset(string name) { var preset = _items.ItemData.GetAll().FirstOrDefault(loadout => loadout.Name == name); - if (preset != null) return new ScenarioFit(preset); - _failures.Add($"preset {name}: no such preset"); - return null; - } - - // The player's ship. A run has exactly one, and it is a ship hull. - public Ship Player(ScenarioFit fit, float2 at, float2 facing = default) - { - if (PlayerPlaced) + if (preset == null) { - _failures.Add("player: the scenario places a second player"); + _failures.Add($"preset {name}: no such preset"); return null; } - PlayerPlaced = true; - var entity = Build(fit, "player", at, facing); - if (entity == null) return null; - if (entity is Ship ship) return PlayerShip = ship; - _failures.Add($"player: {entity.Name} is not a ship hull"); - return null; + // A faction's boss is the zone generator's to place (boss-hulls-exclusive): Loadouts.BossOf owns which loadout it is. + if (_items.ItemData.GetAll().Any(faction => Loadouts.BossOf(_items.ItemData, faction, out _)?.Name == preset.Name)) + { + _failures.Add($"preset {name}: a faction's boss loadout is placed only by the zone generator"); + return null; + } + return new ScenarioFit(preset); } - // Anything else in the arena. A stance holds both ways between it and the player. A piloted ship gets the zone's - // pilot; an unpiloted entity has none and goes nowhere on its own unless it is placed moving: velocity is the planar - // velocity it starts with, and the sim carries it from there. A turret hull stays where it is put. - public Entity Place(ScenarioFit fit, float2 at, float2 facing = default, ScenarioStance stance = ScenarioStance.Neutral, bool piloted = false, - float2 velocity = default) + // Anything else in the arena. A piloted ship gets the zone's pilot; an unpiloted entity has none and goes nowhere on its + // own unless it is placed moving: velocity is the planar velocity it starts with, and the sim carries it from there. A + // turret hull stays where it is put. It writes no stance: who fights whom is the faction rule's (stance is ScenarioStage's). + public Entity Place(ScenarioFit fit, float2 at, float2 facing = default, bool piloted = false, float2 velocity = default) { var where = $"entity {_placements++}"; var entity = Build(fit, where, at, facing); if (entity == null) return null; entity.Velocity = velocity; if (piloted && !(entity is Ship)) _failures.Add($"{where}: {entity.Name} is not a ship hull, so it cannot be piloted"); - _placed.Add(new Placement { Entity = entity, Stance = stance, Piloted = piloted }); + _placed.Add(new Placement { Entity = entity, Piloted = piloted }); return entity; } @@ -168,7 +153,8 @@ public sealed class ScenarioStage } // Items in the entity's first cargo bay, one per name. A name is an equippable or consumable design (open: the stage - // chooses its product) or a product of one (pinned); a name that is neither is a failure. + // chooses its product) or a product of one (pinned), or a commodity (one unit: the crates an AmmoType weapon reloads + // from); a name that is none of these is a failure. public void Cargo(Entity entity, params string[] names) { if (entity == null) return; @@ -177,6 +163,13 @@ public sealed class ScenarioStage var bay = entity.CargoBays.FirstOrDefault(); foreach (var name in names) { + var commodity = _items.ItemData.GetAll().FirstOrDefault(data => data.Name == name); + if (commodity != null) + { + if (bay == null || !bay.TryStore(new SimpleCommodity { Data = new CultRecordRef(_items.ItemData.RefOf(commodity).Key), Quantity = 1 })) + _failures.Add($"{where}: no room for {name}"); + continue; + } var (data, product) = NamedOrProduct(name, where, found => found is EquippableItemData || found is ConsumableItemData); if (data == null) continue; var build = Loadouts.Resolve(_items, _items.ItemData.RefOf(data), @@ -187,7 +180,42 @@ public sealed class ScenarioStage } } - private Entity Build(ScenarioFit fit, string where, float2 at, float2 facing) + // Admits what was placed: Zone.Admit with a pilot for each piloted one. It writes no stance. A start state includes what a pilot knows (ruling stage-states-pilot-knowledge): its anchor is tracked + // from the first step, by the sensors' own path (info gathered past the detection threshold), so they can lose it + // like any track. The one owner of admitting placements. + private protected void AdmitPlaced() + { + foreach (var placed in _placed) + { + Arena.Admit(placed.Entity, placed.Piloted, placed.Task); + } + foreach (var placed in _placed) + if (placed.Knows != null && placed.Piloted) + placed.Entity.EntityInfoGathered[placed.Knows] = (_items.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f; + } + + // Places ships into a running zone through the admission a run start uses: the script places with the stage's verbs, + // and the entities join with a pilot when piloted and the knowledge the script stated. A summon writes no stance: the + // faction rule decides who fights whom, and a grudge (Entity.Provoke) turns the summoned faction on whoever attacks it. + // Returns the placed entities in order, or null with every failure listed and the zone and the item stream and lot ledger unchanged. + // It draws from the live item stream and does not reseed (a reseed would give every summon the same fits). + public static IReadOnlyList Summon(ItemManager items, Zone zone, Action script, List failures) + { + var mark = items.Mark(); + var stage = new ZoneStage(items, zone); + script(stage); + failures.AddRange(stage._failures); + if (stage._failures.Count > 0) + { + items.Rewind(mark); // a refusal draws and mints nothing: the fits it built are discarded with it + return null; + } + stage.StockUnauthoredAmmunition(); + stage.AdmitPlaced(); + return stage._placed.Select(placed => placed.Entity).ToList(); + } + + private protected Entity Build(ScenarioFit fit, string where, float2 at, float2 facing) { if (fit == null) return null; // the verb that made it named why @@ -227,8 +255,71 @@ public sealed class ScenarioStage } } +// The run-start stage: a ZoneStage that also stages the player, the credits the run starts with and the hull it +// starts in, and the one place a script authors stance: a Hostile placement is hostile both ways with the player, written +// once at admission. Neutral writes nothing (the faction rule and grudges decide). Only RunStart builds one. +public sealed class ScenarioStage : ZoneStage +{ + internal ScenarioStage(ItemManager items, Zone arena, string startingHull) : base(items, arena) + { + StartingHull = startingHull; + Credits = items.GameplaySettings.StartingCredits; + } + + public string StartingHull { get; } + + // What the run starts with: the gameplay settings' starting credits unless the scenario sets another amount. + public int Credits { get; set; } + + private readonly List _hostile = new List(); + + // Anything else in the arena, as ZoneStage.Place, with a stance toward the player: Hostile holds both ways from the start. + public new Entity Place(ScenarioFit fit, float2 at, float2 facing = default, ScenarioStance stance = ScenarioStance.Neutral, bool piloted = false, + float2 velocity = default) + { + var entity = base.Place(fit, at, facing, piloted, velocity); + if (entity != null && stance == ScenarioStance.Hostile) _hostile.Add(entity); + return entity; + } + + internal bool PlayerPlaced { get; private set; } + internal Ship PlayerShip { get; private set; } + + // The player's ship. A run has exactly one, and it is a ship hull. + public Ship Player(ScenarioFit fit, float2 at, float2 facing = default) + { + if (PlayerPlaced) + { + _failures.Add("player: the scenario places a second player"); + return null; + } + PlayerPlaced = true; + var entity = Build(fit, "player", at, facing); + if (entity == null) return null; + if (entity is Ship ship) return PlayerShip = ship; + _failures.Add($"player: {entity.Name} is not a ship hull"); + return null; + } + + // Run start's admission: stock unauthored ammunition, the player, then everything placed. Nothing at admission or + // activation reads cargo (ammunition is read when a weapon fires), so stocking is not ordered by admission; it keeps + // the run start's order. + internal void Admit() + { + StockUnauthoredAmmunition(); + PlayerShip.IsPlayerShip = true; + Arena.Admit(PlayerShip, piloted: false); + foreach (var entity in _hostile) + { + entity.SetIff(PlayerShip, true); + PlayerShip.SetIff(entity, true); + } + AdmitPlaced(); + } +} + // What a scenario places: a fit built from named designs or a preset, or a ship generated as the game generates them. -// Only ScenarioStage makes one. +// Only a ZoneStage makes one. public sealed class ScenarioFit { internal readonly Loadout Loadout; diff --git a/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs b/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs index beb4235da..bdfc153fd 100644 --- a/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs +++ b/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs @@ -13,7 +13,7 @@ public sealed class AiFusedDiscipline : Scenario public static readonly CultMath.float2 Hostile = float2(0, 700), Neutral = float2(500, 300); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs index f0c3f5553..6da63b0e2 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs @@ -1,3 +1,4 @@ +using System.Linq; using static CultMath.math; using static ItemRotation; @@ -20,7 +21,12 @@ public sealed class Arcs : Scenario public static readonly CultMath.float2 Bow = float2(0, 400), Stern = float2(0, -400), Turret = float2(600, 300), Port = float2(-400, 0), Starboard = float2(400, 0); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + // Crates of ammunition each shooter's hold is stocked with: the measured draw over a run (ScenarioAmmunitionRunTests: at most ten minutes of play, and in + // practice the ~260 s a shooter holding every gun down lasts before it dies of heat; a pilot who vents heat is unmeasured) plus half again and one. The turret drew 14 Ammo with the player in its range; the player drew 27 Ammo + // holding every gun down. The guided launchers fire only on a lock, which that run cannot give them, so they carry the default three crates. + public const int TurretAmmoCrates = 22, PlayerAmmoCrates = 42, PlayerMissileCrates = 3; + + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { @@ -40,7 +46,8 @@ public sealed class Arcs : Scenario ("not if i see you first", int2(5, 10), None), // Compact Sensor ("Panopticon Prime", int2(3, 6), Clockwise), // Fire Control Array ("🫳🔫", int2(8, 4), Clockwise), // Autocannon - ("ChargeBlast SG", int2(0, 4), CounterClockwise)); // Charged Scatter Blaster + ("ChargeBlast SG", int2(0, 4), CounterClockwise), // Charged Scatter Blaster + ("Store-All Plus", int2(4, 8), None)); // Cargo Bay: the only 2x2 the hull has free var turret = stage.Fit("Turret", ("ClearPath", int2(1, 2), None), // Light Machine Gun ("ClearPath", int2(5, 2), None), // Light Machine Gun @@ -49,12 +56,15 @@ public sealed class Arcs : Scenario ("Compact Reactor", int2(3, 3), None), ("Turret Control Module", int2(3, 5), None), ("not if i see you first", int2(4, 5), None), // Compact Sensor - ("Panopticon Prime", int2(3, 6), None)); // Fire Control Array + ("Panopticon Prime", int2(3, 6), None), // Fire Control Array + ("Store-All Plus", int2(3, 1), None)); // Cargo Bay: the only 2x2 the turret hull has free - stage.Player(fighter, float2(0, 0), facing: float2(0, 1)); + var player = stage.Player(fighter, float2(0, 0), facing: float2(0, 1)); + stage.Cargo(player, Enumerable.Repeat("Ammo", PlayerAmmoCrates).Concat(Enumerable.Repeat("Missiles", PlayerMissileCrates)).ToArray()); stage.Place(stage.Bare("Longinus"), Bow); stage.Place(stage.Bare("Longinus"), Stern); - stage.Place(turret, Turret, stance: ScenarioStance.Hostile); + // The turret's guns reload from its hold, a crate of Ammo per magazine. + stage.Cargo(stage.Place(turret, Turret, stance: ScenarioStance.Hostile), Enumerable.Repeat("Ammo", TurretAmmoCrates).ToArray()); stage.Place(stage.Bare("Longinus"), Port); stage.Place(stage.Bare("Longinus"), Starboard); } diff --git a/Assets/Scripts/ServerShared/Scenarios/Belt.cs b/Assets/Scripts/ServerShared/Scenarios/Belt.cs index 50c815f6d..7058b993b 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Belt.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Belt.cs @@ -17,7 +17,7 @@ public sealed class Belt : Scenario public override uint Seed => 86; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Crossing.cs b/Assets/Scripts/ServerShared/Scenarios/Crossing.cs index 61529d6d9..be5a1fe06 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Crossing.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Crossing.cs @@ -6,8 +6,8 @@ public sealed class Crossing : Scenario public override string Name => "Crossing"; public override string Id => "crossing"; public override string Brief => "A Lightning Projector at the starboard gun and a Cell Blaster at the port gun, an unpiloted Djinni coasting across the bow " + - "close ahead and an unpiloted one waiting at range. The crosser is launched to port at 50 m/s and only coasts: nothing steers it, " + - "its hull drag slows it to about 25 m/s at the bow line, and it does not shoot back. Make the pass coasting: give no throttle until the Djinni has crossed the bow, then fly freely " + + "close ahead and an unpiloted one waiting at range. The crosser is launched to port at 25 m/s and only coasts: nothing steers it, " + + "a hull coasts at its launch speed below its top speed, and it does not shoot back. Make the pass coasting: give no throttle until the Djinni has crossed the bow, then fly freely " + "(thrusting from the start carries you past it). Verify: as the Djinni crosses close, FastBlast lands some and projector " + "almost none; against the Djinni at range both land. Fly it again without the Fire Control Array: " + "with it the small gun lands more."; @@ -16,13 +16,15 @@ public sealed class Crossing : Scenario // Where the Djinni sit: the player is at Origin facing +z. Origin is 250 m or more from every body, where the zone's // pull is weakest (about 1.4 u/s^2; the sum of the wells never drops to nothing, and at the old origin the player sat on the star). - // The crosser is unpiloted and placed moving at the Djinni's 50 m/s cap, so its pass is ballistic: bent by the field and slowed - // by hull drag (it reaches the bow line at about 25 m/s relative to the player, 3.6 s in), and nothing steers it. + // The crosser is unpiloted and placed moving at 25 m/s, well under the Djinni's 50 m/s top speed, so its pass is ballistic: a hull + // coasts below its top speed (aetheria-gravity:ruling:no-drag-below-top-speed) and only the field bends it, so it reaches the + // bow line at 25 m/s relative to the player, 3.6 s in, and nothing steers it. (Launched at the cap with drag slowing it to 25 m/s, + // as this scenario was first tuned, it would now hold 50 m/s and cross in 2.6 s.) // CrosserAt is the centre of the start window in which the pass holds: shifting it by 10 m along either axis keeps the pass // inside the test's time and distance windows (CrossingHoldsAcrossTheStartWindow). // The waiting Djinni sits inside the Lightning Projector's arc at 80% of its Range. public static readonly CultMath.float2 Origin = float2(724, 124); - public static readonly CultMath.float2 CrosserAt = Origin + float2(-128, 45), CrosserFacing = float2(1, 0), CrosserVelocity = float2(50, 0); + public static readonly CultMath.float2 CrosserAt = Origin + float2(-90, 45), CrosserFacing = float2(1, 0), CrosserVelocity = float2(25, 0); // The fighter is staged at this quality, so its gear and the range below do not ride the item stream. public const float StagedQuality = .6f; // The Lightning Projector's Range in metres at the staged fit: 996.99 after the three seconds the test settles for @@ -31,7 +33,7 @@ public sealed class Crossing : Scenario public const float ProjectorRange = 997f; public static readonly CultMath.float2 Waiting = Origin + float2(0, ProjectorRange * .8f); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs b/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs index f4dce7be7..7d8fbe330 100644 --- a/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs +++ b/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs @@ -2,10 +2,10 @@ using float2 = CultMath.float2; // The demo: one gate, one region and one boss, with a fixed cast. The Pirates are the protagonist's ostensible // employer, Zhestokost the antagonist whose home is the boss zone and the exit, Lucent Media and Aeronautics Unlimited -// the neutrals. A prelude galaxy of that cast; the player, who is not a Pirate, flies the base Longinus. +// the neutrals. A galaxy of that cast at half influence; the player, who is not a Pirate, flies the base Longinus. public sealed class DemoTerminus : Scenario { - public static readonly TutorialGenerationSettings Cast = new TutorialGenerationSettings + public static readonly GalaxyCast Cast = new GalaxyCast { ProtagonistFaction = "Pirates", AntagonistFaction = "Zhe", @@ -13,7 +13,8 @@ public sealed class DemoTerminus : Scenario NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, - LinkDensity = .5f + LinkDensity = .5f, + InfluenceScale = .5f }; public override string Name => "Terminus (Demo)"; @@ -23,7 +24,7 @@ public sealed class DemoTerminus : Scenario public override Galaxy Generate(GalaxyStage stage) { - var galaxy = stage.Prelude(Cast); + var galaxy = stage.Cast(Cast); galaxy.PlaceGate(galaxy.ResolveFaction(Cast.AntagonistFaction)); return galaxy; } diff --git a/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs b/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs index 43d23d0b3..1b853571c 100644 --- a/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs +++ b/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs @@ -14,7 +14,7 @@ public sealed class DjinniShakedown : Scenario // Where the targets sit: the ballistic mount faces +z, so Ahead is inside its arc and Abeam outside it. public static readonly float2 Ahead = new float2(0, 400), Abeam = new float2(400, 0); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Duel.cs b/Assets/Scripts/ServerShared/Scenarios/Duel.cs index 67bca118d..508277643 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Duel.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Duel.cs @@ -10,7 +10,7 @@ public sealed class Duel : Scenario public override uint Seed => 104; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs b/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs index 7498465c3..8f3fd024e 100644 --- a/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs +++ b/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs @@ -26,7 +26,7 @@ public sealed class FusedRounds : Scenario // The shooter is staged at this quality, so the damage its Cluster Cannon deals does not ride the item stream. public const float StagedQuality = .6f; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs b/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs index 61a798b1c..efd13e1aa 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs @@ -10,7 +10,7 @@ public sealed class LauncherAngles : Scenario public override uint Seed => 105; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs index 4f8c4dfa9..8e14c3ff6 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs @@ -35,7 +35,7 @@ public sealed class LockOn : Scenario _quality = quality; } - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs b/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs index 18e158247..692a5adbc 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs @@ -8,7 +8,7 @@ public sealed class LongHaul : Scenario "warp, quit and Continue keep items, tier and brand; death disables Continue."; public override uint Seed => 106; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) => stage.Player(stage.Generated(stage.StartingHull), float2.zero); diff --git a/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs b/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs index 3e4482d3c..d8a484b7b 100644 --- a/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs +++ b/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs @@ -7,6 +7,8 @@ public sealed class MainGalaxy : Scenario public override string Id => "main-galaxy"; public override string Brief => "The full galaxy: factions drawn at random, bosses guarding the road to the exit."; + public override bool EntranceStation => false; + public override Galaxy Generate(GalaxyStage stage) => stage.Main(); public override void Stage(ScenarioStage stage) => diff --git a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs index d6d630a88..7bde23745 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs @@ -1,3 +1,4 @@ +using System.Linq; using static CultMath.math; using static ItemRotation; @@ -7,6 +8,11 @@ public sealed class Pursuit : Scenario // cloud breaking a sensor's lock, and well outside the 40 at which AStrongCloseSensorBurnsThrough shows a close // sensor burning through. private const float Astern = 300; + // Crates each shooter's hold is stocked with: the measured draw over a run (ScenarioAmmunitionRunTests: at most ten minutes of play, and in + // practice the ~250-270 s a shooter holding every gun down lasts before it dies of heat; a pilot who vents heat is unmeasured) plus half again and one where the hold has room. The player laid four crates of Mines and drew + // 33 Ammo; its hold takes 54 crates after five consumables and Mines, so its Ammo stops at 39. The pursuer drew 31 Ammo and one Missiles. A launcher + // that drew under a reload carries the default three crates. + public const int MineCrates = 7, PlayerAmmoCrates = 39, PlayerMissileCrates = 3, PursuerAmmoCrates = 47, PursuerMissileCrates = 3; public override string Name => "Pursuit"; public override string Id => "pursuit"; @@ -16,7 +22,7 @@ public sealed class Pursuit : Scenario public override uint Seed => 111; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { @@ -55,7 +61,9 @@ public sealed class Pursuit : Scenario ("Store-All Plus", int2(2, 8), None)); // Cargo Bay var player = stage.Player(layer, float2(0, 0), facing: float2(0, 1)); - stage.Cargo(player, "Morning Fog", "Morning Fog", "Morning Fog", "send it", "send it"); - stage.Place(pursuer, float2(0, -Astern), facing: float2(0, 1), stance: ScenarioStance.Hostile, piloted: true); + stage.Cargo(player, new[] { "Morning Fog", "Morning Fog", "Morning Fog", "send it", "send it" } + .Concat(Enumerable.Repeat("Mines", MineCrates)).Concat(Enumerable.Repeat("Ammo", PlayerAmmoCrates)).Concat(Enumerable.Repeat("Missiles", PlayerMissileCrates)).ToArray()); + var hostile = stage.Place(pursuer, float2(0, -Astern), facing: float2(0, 1), stance: ScenarioStance.Hostile, piloted: true); + stage.Cargo(hostile, Enumerable.Repeat("Ammo", PursuerAmmoCrates).Concat(Enumerable.Repeat("Missiles", PursuerMissileCrates)).ToArray()); } } diff --git a/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs b/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs index 88cdd3fdb..384a7f286 100644 --- a/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs +++ b/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs @@ -15,7 +15,7 @@ public sealed class RefusedRounds : Scenario // The one target, ahead of the nose: inside every forward mount's arc. public static readonly CultMath.float2 Target = float2(0, 300); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs b/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs index 752b33e28..60d291985 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs @@ -5,7 +5,7 @@ public static class Scenarios { public static readonly Scenario[] Modes = { new DemoTerminus() }; - public static readonly Scenario[] Development = { new TutorialGalaxy(), new MainGalaxy() }; + public static readonly Scenario[] Development = { new MainGalaxy() }; public static readonly Scenario[] Tests = { diff --git a/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs b/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs index 2f3dff97b..ccef7e151 100644 --- a/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs +++ b/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs @@ -10,7 +10,7 @@ public sealed class StarvedReactor : Scenario public override uint Seed => 102; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs b/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs deleted file mode 100644 index 1ff521865..000000000 --- a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs +++ /dev/null @@ -1,17 +0,0 @@ -using float2 = CultMath.float2; - -// New Game as it has always been: a prelude galaxy, entered in the starting hull of the protagonist faction. -public sealed class TutorialGalaxy : Scenario -{ - public override string Name => "Tutorial Galaxy"; - public override string Id => "tutorial-galaxy"; - public override string Brief => "A small galaxy of fixed factions, entered in a ship of the protagonist faction."; - - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); - - public override void Stage(ScenarioStage stage) - { - var protagonist = stage.Galaxy.ResolveFaction(stage.TutorialGenerationSettings.ProtagonistFaction); - stage.Player(stage.Generated(stage.StartingHull, protagonist), float2.zero); - } -} diff --git a/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs b/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs index 0817cfa80..f6f8eb337 100644 --- a/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs +++ b/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs @@ -14,7 +14,7 @@ public sealed class WeaponFeel : Scenario // The one target, ahead of the nose: inside every forward mount's arc. public static readonly CultMath.float2 Target = float2(0, 400); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 8326f76da..523e773f1 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -29,6 +29,11 @@ public class PlanetSettings public ExponentialLerp AsteroidSize; public ExponentialLerp AsteroidHitpoints; public ExponentialLerp AsteroidRespawnTime; + // Units of ore a whole rock of normalized size s gives (FireControl.Extract), however many hits break it. + public ExponentialLerp AsteroidYield; + // How far a rock's mix of its belt's ores strays from the kind's ratio: each ore's weight is scaled by + // exp(variance x g), g in [-1, 1) a stable hash of (rock, ore). Zero reads the kind's ratio. + public float ChunkCompositionVariance; public float SecureAreaRadiusMultiplier = .45f; @@ -89,8 +94,10 @@ public class SectorGenerationSettings public int BossCount; } -[Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject] -public class TutorialGenerationSettings +// The fixed cast of a galaxy a scenario generates through GalaxyStage.Cast: who plays which part, how big the galaxy is, +// and how far the factions' authored influence reaches (Galaxy.InfluenceOf). Held by the scenario that casts it; no +// asset or store holds one. +public class GalaxyCast { public string ProtagonistFaction; public string AntagonistFaction; @@ -101,6 +108,8 @@ public class TutorialGenerationSettings public int ZoneCount = 32; // Zones per resource province (Provinces.Partition): calibration, not a gate. public int ProvinceZones = Provinces.DefaultZonesPerProvince; + // Multiplies every faction's authored InfluenceDistance in this galaxy (rounding up); 1 leaves them as authored. + public float InfluenceScale = 1; } [Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject] diff --git a/Assets/Scripts/ServerShared/ShipAuthoring.cs b/Assets/Scripts/ServerShared/ShipAuthoring.cs index 3962fa468..8441d0332 100644 --- a/Assets/Scripts/ServerShared/ShipAuthoring.cs +++ b/Assets/Scripts/ServerShared/ShipAuthoring.cs @@ -33,6 +33,9 @@ public sealed class ShipJoint [Key(2)] public float[] Axes; [Key(3)] public float[] Min; [Key(4)] public float[] Max; + + // Element identity, derived from the bone id so it never changes across rewrites. + [Key(5)] [CultElementId(nameof(Id))] public string ElementId = ""; } [MessagePackObject] @@ -50,6 +53,9 @@ public sealed class ShipAnchor [Key(4)] public int Order; // On a weapon-mount anchor: the id of the nearest joint above its node in the model; null or empty is a fixed mount. [Key(5)] public string Joint; + + // Element identity, derived from the anchor id so it never changes across rewrites. + [Key(6)] [CultElementId(nameof(Id))] public string ElementId = ""; } // Evaluated or baked Grease Pencil stroke coordinates in Blender's right-handed Z-up @@ -64,6 +70,9 @@ public sealed class ShipPolyline [Key(4)] public float[] Opacities; [Key(5)] public bool Cyclic; [Key(6)] public float[] Color; + + // Element identity: minted by the cache on write; "" means unset. + [Key(7)] [CultElementId] public string Id = ""; } public static class ShipAuthoringStore diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs index e9ed613a2..91bbc296d 100644 --- a/Assets/Scripts/ServerShared/ShipModCatalog.cs +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using GameCult.Caching; using Newtonsoft.Json.Linq; +using System.Numerics; using System.Text; // Builds the one catalog snapshot CultCache needs. Sources remain the shipped catalog and each @@ -110,6 +111,7 @@ public static class ShipModCatalog if (shipIds.Contains(ship.Id)) Exclude(directory, $"ship ID collides with an existing catalog ship authoring record."); if (StationKinds.HullKindFault(cache, hull) is { } kindFault) Exclude(directory, kindFault); + if (MarketFault(cache, ship, package.Products) is { } marketFault) Exclude(directory, marketFault); foreach (var product in package.Products) { if (!factionKeys.Contains(product.Manufacturer.Key)) @@ -157,6 +159,26 @@ public static class ShipModCatalog } } + // Why a package's products cannot join the catalog, or null; the one judgement Compose and `ship-authoring validate` share. + // `items` is the shipped catalog. A product's bin may name only a product line the shipped catalog holds or one of the + // package's own products (and that line must not be a bin itself): the catalog read refuses any other bin, and a line in + // another package is no promise, since packages compose independently. With every bin resolved, a hull offered through any of its + // products is drawn on the map and the schematic by its lines (ShipModVisual.BuildLineMesh builds nothing from none), so an + // offered hull without any is refused; an unoffered stand-in is left alone. Offered is LoadoutGenerator.IsOffered, the one + // reader of NotOffered (ruling off-market-is-unoffered-product), resolving a line among the package's own products too. + public static string MarketFault(CultCache items, ShipAuthoring ship, FactionProductData[] products) + { + var own = new Dictionary(); + foreach (var product in products) own[ProductKey(ship.Id, product.Manufacturer.Key)] = product; + FactionProductData LineOf(CultRecordRef line) => items.Get(line) ?? (own.TryGetValue(line.Key, out var found) ? found : null); + foreach (var product in products.Where(product => product.Bin != null)) + if (LineOf(product.Bin.Line) is not { } line || line.Bin != null) + return $"{ship.Id}: product '{product.Name}' bins a line that is neither an unbinned shipped product nor an unbinned product of this package."; + if (ship.SchematicLines != null && ship.SchematicLines.Any(line => line?.Points != null && line.Points.Length > 0)) return null; + return products.Any(product => LoadoutGenerator.IsOffered(product, LineOf)) + ? $"{ship.Id}: the hull is offered on the market but has no schematic lines." : null; + } + public static Package ReadPackage(string shipPath) { var path = Path.GetFullPath(shipPath); @@ -251,17 +273,19 @@ public static class ShipModCatalog foreach (var anchor in ship.Anchors) if (!modelNodes.ContainsKey(anchor.ModelNodeId)) throw new InvalidOperationException($"{ship.Id}: model has no node with aetheria.id={anchor.ModelNodeId} for anchor {anchor.Id}."); - // Assemble reads a renderer or collider mesh from these anchors' nodes and refuses without one, and reads the shield - // node's scale as three positive radii (ruling thrusters-radiators-are-meshes). These refusals stand in for Assemble's - // throws, so a package Compose includes is one the importer's assembler can build; the exhaust emission surface and - // the glowing radiator are meshes by that same ruling. A weapon mount and a tractor may be empties. + // Assemble reads a renderer or collider mesh from these anchors' nodes, and the shield node's scale as three positive + // radii (ruling thrusters-radiators-are-meshes). These refusals cover everything the package's files say about whether + // the importer can build a node (skin, dangling or empty mesh, not only "names a mesh") and are Assemble's only judge, + // so a package Compose includes is one the importer's assembler can build; the exhaust emission surface and the + // glowing radiator are meshes by that same ruling. A weapon mount and a tractor may be empties. foreach (var anchor in ship.Anchors) if ((anchor.Role == "thruster-emitter" || anchor.Role == "radiator-mesh" || anchor.Role == "map-icon" || anchor.Role == "hull-collider") && !modelNodes[anchor.ModelNodeId].HasMesh) - throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} needs a mesh, but model node {anchor.ModelNodeId} has none."); + throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} needs a mesh, but model node {anchor.ModelNodeId} has none the importer can build."); foreach (var anchor in ship.Anchors) if (anchor.Role == "shield" && !modelNodes[anchor.ModelNodeId].PositiveScale) throw new InvalidOperationException($"{ship.Id}: shield anchor {anchor.Id} needs three positive scale radii on model node {anchor.ModelNodeId}, with no matrix."); + BindExhaust(hull, ship, modelNodes, modelPath); BindRig(ship, modelNodes); CultRecordRefs.Validate(hull); return new Package @@ -271,6 +295,166 @@ public static class ShipModCatalog }; } + // A thruster emitter's mesh is the surface its exhaust is born from, along each triangle's normal, so the mesh has to face + // the way the exhaust goes. Every thruster is a directional thruster today: its Rotation faces its exhaust, the push + // is the opposite way, and an emitter triangle whose normal has a non-negative dot with the push would fire exhaust + // along it (a closed box fires both ways). A thruster of another class, a ring thruster whose exhaust leaves radially, + // is not this rule's to judge: it would come with its own class on the hardpoint and its own rule beside this one. + private static void BindExhaust(HullData hull, ShipAuthoring ship, Dictionary nodes, string modelPath) + { + var emitters = ship.Anchors.Where(anchor => anchor.Role == "thruster-emitter").ToArray(); + if (emitters.Length == 0) return; + var model = GlbGeometry.Read(modelPath); + foreach (var anchor in emitters) + { + var hardpoint = hull.Hardpoints.FirstOrDefault(candidate => candidate.Type == HardpointType.Thruster && candidate.Transform == anchor.Id); + // An emitter anchor with no thruster hardpoint is already a package fault: ShipAuthoringStore.Validate (run by Read and + // PackageOf before Bind) refuses a mount-role anchor that is not the mount of a hardpoint of its type. + if (hardpoint == null) continue; + var facing = hardpoint.Rotation.Direction(); + // The model's frame is glTF's, nose toward +Z and port toward +X (the Blender kit's nose at -Y and port at +X, + // through the exporter's Y-up conversion): a hardpoint facing (x, y) in the grid faces (-x, 0, y) in the model. + var push = -new Vector3(-facing.x, 0f, facing.y); + var wrong = model.Normals((int)nodes[anchor.ModelNodeId].Index).Count(normal => Vector3.Dot(normal, push) >= 0f); + if (wrong > 0) + throw new InvalidOperationException($"{ship.Id}: thruster emitter {anchor.Id} has {wrong} face or vertex normal(s) that do not face its exhaust " + + $"({hardpoint.Rotation}); a directional thruster's emitter fires only along its exhaust, so it must be one-sided, not a closed box."); + } + } + + // The triangles of a GLB as the node tree places them, read for the one question the emitter rule asks: which way each + // face points. Float positions and normals, indices of 1, 2 or 4 bytes or none, no sparse, no compression: a model the + // exporter writes. Anything else is refused as unreadable rather than guessed at. + private sealed class GlbGeometry + { + private readonly JObject _json; + private readonly byte[] _bin; + private readonly string _path; + + private GlbGeometry(JObject json, byte[] bin, string path) { _json = json; _bin = bin; _path = path; } + + public static GlbGeometry Read(string path) + { + var bytes = File.ReadAllBytes(path); + var jsonLength = (int)BitConverter.ToUInt32(bytes, 12); + var json = JObject.Parse(Encoding.UTF8.GetString(bytes, 20, jsonLength)); + var at = 20 + jsonLength; + var bin = at + 8 <= bytes.Length && BitConverter.ToUInt32(bytes, at + 4) == 0x004E4942u + ? bytes.Skip(at + 8).Take((int)BitConverter.ToUInt32(bytes, at)).ToArray() : Array.Empty(); + return new GlbGeometry(json, bin, path); + } + + // Unit normals in the model frame: each triangle's face normal (its winding, flipped when the node's world transform + // mirrors, as glTF says) and each vertex normal the primitive carries. + public IEnumerable Normals(int node) + { + var world = World(node); + var mirrored = world.GetDeterminant() < 0f; + var meshIndex = (int?)_json["nodes"][node]["mesh"]; + if (meshIndex == null) yield break; + foreach (var primitive in (JArray)_json["meshes"][meshIndex.Value]["primitives"]) + { + var attributes = (JObject)primitive["attributes"]; + if (primitive["extensions"] is JObject extensions && extensions.Properties().Any(p => HidesGeometry(p.Name))) + throw Unreadable($"mesh {meshIndex} is compressed by {extensions.Properties().First(p => HidesGeometry(p.Name)).Name}"); + var normalMatrix = Matrix4x4.Invert(world, out var inverse) ? Matrix4x4.Transpose(inverse) : throw Unreadable($"node {node} has a transform that cannot be inverted"); + var positions = Vectors((int)attributes["POSITION"]).Select(point => Vector3.Transform(point, world)).ToArray(); + var indices = primitive["indices"] == null ? Enumerable.Range(0, positions.Length).ToArray() : Indices((int)primitive["indices"]); + for (var i = 0; i + 2 < indices.Length; i += 3) + { + var face = Vector3.Cross(positions[indices[i + 1]] - positions[indices[i]], positions[indices[i + 2]] - positions[indices[i]]); + if (face.LengthSquared() < 1e-12f) continue; + yield return Vector3.Normalize(mirrored ? -face : face); + } + if (attributes["NORMAL"] != null) + foreach (var normal in Vectors((int)attributes["NORMAL"])) + if (normal.LengthSquared() > 1e-12f) yield return Vector3.Normalize(Vector3.TransformNormal(normal, normalMatrix)); + } + } + + // Row-vector matrices, so a child's world is its local times its parent's world. + private Matrix4x4 World(int node) + { + var parents = new Dictionary(); + var nodes = (JArray)_json["nodes"]; + for (var parent = 0; parent < nodes.Count; parent++) + foreach (var child in nodes[parent]["children"]?.Select(token => (int)token) ?? Enumerable.Empty()) parents[child] = parent; + var world = Matrix4x4.Identity; + for (int at = node, steps = 0; steps <= nodes.Count; steps++) + { + world *= Local((JObject)nodes[at]); + if (!parents.TryGetValue(at, out at)) break; + } + return world; + } + + private static Matrix4x4 Local(JObject node) + { + if (node["matrix"] is JArray m) + { + var v = m.Select(token => (float)token).ToArray(); + return new Matrix4x4(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14], v[15]); + } + float[] Of(string key, float[] fallback) => node[key] is JArray a ? a.Select(token => (float)token).ToArray() : fallback; + var scale = Of("scale", new[] { 1f, 1f, 1f }); + var rotation = Of("rotation", new[] { 0f, 0f, 0f, 1f }); + var translation = Of("translation", new[] { 0f, 0f, 0f }); + return Matrix4x4.CreateScale(scale[0], scale[1], scale[2]) * + Matrix4x4.CreateFromQuaternion(new Quaternion(rotation[0], rotation[1], rotation[2], rotation[3])) * + Matrix4x4.CreateTranslation(translation[0], translation[1], translation[2]); + } + + // The bytes an accessor reads from: its view's slice of the BIN chunk, at the view's stride. + private (int Offset, int Stride, int Count, int Component, string Type) Locate(int accessor) + { + var a = (JObject)_json["accessors"][accessor]; + if (a["sparse"] != null || a["bufferView"] == null) throw Unreadable($"accessor {accessor} is sparse or has no buffer view"); + var view = (JObject)_json["bufferViews"][(int)a["bufferView"]]; + if (view["extensions"] is JObject viewExtensions && viewExtensions.Properties().Any(p => HidesGeometry(p.Name))) + throw Unreadable($"accessor {accessor} is compressed by {viewExtensions.Properties().First(p => HidesGeometry(p.Name)).Name}"); + var component = (int)a["componentType"]; + var type = (string)a["type"]; + var width = (component == 5126 || component == 5125 ? 4 : component == 5123 ? 2 : 1) * (type == "VEC3" ? 3 : 1); + var offset = ((int?)view["byteOffset"] ?? 0) + ((int?)a["byteOffset"] ?? 0); + var stride = (int?)view["byteStride"] ?? width; + var count = (int)a["count"]; + if (offset < 0 || count < 0 || (count > 0 && offset + (long)(count - 1) * stride + width > _bin.Length)) throw Unreadable($"accessor {accessor} reaches past the BIN chunk"); + return (offset, stride, count, component, type); + } + + private Vector3[] Vectors(int accessor) + { + var (offset, stride, count, component, type) = Locate(accessor); + if (component != 5126 || type != "VEC3") throw Unreadable($"accessor {accessor} is not float VEC3"); + var result = new Vector3[count]; + for (var i = 0; i < count; i++) + { + var at = offset + i * stride; + result[i] = new Vector3(BitConverter.ToSingle(_bin, at), BitConverter.ToSingle(_bin, at + 4), BitConverter.ToSingle(_bin, at + 8)); + } + return result; + } + + private int[] Indices(int accessor) + { + var (offset, stride, count, component, type) = Locate(accessor); + if (type != "SCALAR" || component != 5121 && component != 5123 && component != 5125) throw Unreadable($"accessor {accessor} is not an index accessor"); + var result = new int[count]; + for (var i = 0; i < count; i++) + { + var at = offset + i * stride; + result[i] = component == 5121 ? _bin[at] : component == 5123 ? BitConverter.ToUInt16(_bin, at) : (int)BitConverter.ToUInt32(_bin, at); + } + return result; + } + + // The extensions that store geometry in a form this reader does not decode; any other (materials, variants) leaves the + // positions and normals where the accessors say. + private static bool HidesGeometry(string extension) => extension == "KHR_draco_mesh_compression" || extension == "EXT_meshopt_compression"; + + private InvalidOperationException Unreadable(string reason) => new InvalidOperationException($"{_path}: emitter geometry is unreadable: {reason}."); + } + // The rig the record states must be the rig the model has: every joint is a node, each joint's Parent and each mount's // Joint is the nearest joint above its node, ancestors without an id being walked through by ReadNodeIds, and a radiator // mesh sits under no joint. @@ -309,7 +493,23 @@ public static class ShipModCatalog private static bool PositiveScale(JObject node) => node["matrix"] == null && (node["scale"] == null || node["scale"].Select(component => (double)component).All(component => component > 0)); - // GLB is the xenos asset boundary. Only its node extras, whether each node names a mesh, and its nearest identified ancestor's node index + // A mesh the importer builds as a plain mesh node: no skin (glTFast makes a skinned node a SkinnedMeshRenderer, which + // Assemble's MeshRenderer/MeshFilter reads cannot see), a mesh index inside meshes, at least one primitive, and every + // primitive with POSITION and a mode absent or 4 (triangles). Geometry accessors and buffers are not read. + private static bool BuildsMesh(JObject json, JObject node) + { + if (node["skin"] != null && node["skin"].Type != JTokenType.Null) return false; + var meshes = json["meshes"] as JArray; + if (node["mesh"] == null || node["mesh"].Type != JTokenType.Integer || meshes == null) return false; + var index = (long)node["mesh"]; + if (index < 0 || index >= meshes.Count) return false; + var primitives = (meshes[(int)index] as JObject)?["primitives"] as JArray; + return primitives != null && primitives.Count > 0 && primitives.All(primitive => + primitive is JObject p && p["attributes"]?["POSITION"] != null && + (p["mode"] == null || (p["mode"].Type == JTokenType.Integer && (int)p["mode"] == 4))); + } + + // GLB is the xenos asset boundary. Only its node extras, whether each node carries a mesh the importer builds as a plain mesh node, and its nearest identified ancestor's node index // (-1 for none) are read here, plus whether the node's scale is three positive radii with no matrix; geometry belongs to the runtime importer. public static Dictionary ReadNodeIds(string path) { @@ -333,7 +533,7 @@ public static class ShipModCatalog { var id = (string)node["extras"]?["aetheria.id"]; if (string.IsNullOrEmpty(id)) { index++; continue; } - if (!ids.TryAdd(id, (index, node["mesh"] != null && node["mesh"].Type != JTokenType.Null, IdentifiedAncestor(parents, nodes, (int)index), PositiveScale(node)))) + if (!ids.TryAdd(id, (index, BuildsMesh(json, node), IdentifiedAncestor(parents, nodes, (int)index), PositiveScale(node)))) throw new InvalidOperationException($"{path}: duplicate GLB node aetheria.id={id}."); index++; } diff --git a/Assets/Scripts/ServerShared/SimulationDice.cs b/Assets/Scripts/ServerShared/SimulationDice.cs index adc440299..c8cb9e759 100644 --- a/Assets/Scripts/ServerShared/SimulationDice.cs +++ b/Assets/Scripts/ServerShared/SimulationDice.cs @@ -18,6 +18,9 @@ public static class SimulationDice // seed (CombatSeed): the run seed feeds drops and mines only (ruling run-seed-drops-only), and placement never rides // ItemManager.Random. public const uint ScatterStream = 5; + // The ore a shot's wear of rocks pays, ordinal the shot's ShotId, on the zone's DropSeed (mined ore is a drop): + // FireControl.Extract is the one reader. + public const uint OreStream = 6; // 9.1 (docs/fire-control-cut.md): fmix32, MurmurHash3's 32-bit finalizer -- xor-shift, multiply, // xor-shift, multiply, xor-shift. Diffuses a structured seed (a zone seed XORed with a small, diff --git a/Assets/Scripts/ServerShared/StationKinds.cs b/Assets/Scripts/ServerShared/StationKinds.cs index dad1ce2aa..eb2662eee 100644 --- a/Assets/Scripts/ServerShared/StationKinds.cs +++ b/Assets/Scripts/ServerShared/StationKinds.cs @@ -35,6 +35,9 @@ public class StationKindStandIn // The kind whose model this faction builds in place of the owning kind's. [JsonProperty("kind"), Key(1)] public CultRecordRef Kind; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // The one owner of which kinds a faction builds, which kind a station gets, and which hull kind stands in. diff --git a/Assets/Scripts/ServerShared/StationServices.cs b/Assets/Scripts/ServerShared/StationServices.cs index 153fc595d..dace9288e 100644 --- a/Assets/Scripts/ServerShared/StationServices.cs +++ b/Assets/Scripts/ServerShared/StationServices.cs @@ -94,19 +94,50 @@ public static class StationServices public static int BuyableQuantity(ItemManager items, SimpleCommodity stock, int typed, int credits) => Math.Max(1, Math.Min(Math.Min(typed, credits / BuyPrice(items, stock)), stock.Quantity)); - // The sale: the item leaves the bay for one of the station's cargo bays and the station pays SellPrice. False, - // with the item in its bay and the credits unchanged, when no station bay can take it. + // The sale: the item leaves the bay and the station pays SellPrice. A crafted item goes to one of the station's + // cargo bays; false, with the item in its bay and the credits unchanged, when no bay can take it. A simple + // commodity always sells (aetheria-release:ruling:station-market-absorbs-sold-commodity): the bays take as much of + // the stack as fits and the market absorbs the rest, at the full price. public static bool TrySell(EquippedCargoBay from, Entity station, ItemInstance item, ref int credits) { var price = SellPrice(station.ItemManager, item); - var moved = item is SimpleCommodity commodity - ? station.CargoBays.Any(bay => from.TryTransferItem(bay, commodity, commodity.Quantity)) - : station.CargoBays.Any(bay => from.TryTransferItem(bay, (CraftedItemInstance) item)); - if (!moved) return false; + if (item is SimpleCommodity commodity) + { + if (!from.Cargo.ContainsKey(commodity)) return false; + var offered = commodity.Quantity; + for (var quantity = offered; quantity >= 1; quantity--) + if (station.CargoBays.Any(bay => from.TryTransferItem(bay, commodity, quantity))) break; + if (from.Cargo.ContainsKey(commodity)) from.Remove(commodity, commodity.Quantity); + } + else if (!station.CargoBays.Any(bay => from.TryTransferItem(bay, (CraftedItemInstance) item))) return false; credits += price; return true; } + // The mined stacks of the bays: simple commodities with a lot whose origin is Extracted. Ammunition and consumables are + // simple commodities too, and a bought or staged commodity has Lot 0, which GetLot cannot resolve. + private static ItemInstance[] OreStacks(ItemManager items, IEnumerable bays) => + bays.SelectMany(bay => bay.Cargo.Keys.OfType().Where(stack => stack.Lot != 0 && items.GetLot(stack).Origin is Extracted).Select(stack => (ItemInstance) stack)).ToArray(); + + // What the station pays for every mined stack of the bays: the sum of SellPrice over the stacks TrySellOre sells. + public static int OreValue(ItemManager items, IEnumerable bays) => + (int) Math.Min(OreStacks(items, bays).Sum(stack => (long) SellPrice(items, stack)), int.MaxValue); + + // Sells every mined stack of the bays, each through TrySell, so the market's absorb rule and the price are the + // single-stack path's. Returns the units sold. + public static int TrySellOre(IEnumerable bays, Entity station, ref int credits) + { + var bayList = bays.ToArray(); + var units = 0; + foreach (var stack in OreStacks(station.ItemManager, bayList)) + { + var quantity = ((SimpleCommodity) stack).Quantity; + var from = bayList.First(bay => bay.Cargo.ContainsKey(stack)); + if (TrySell(from, station, stack, ref credits)) units += quantity; + } + return units; + } + // The repair: armour and every durability go back to design and the station charges RepairCost. False, with // nothing restored, when the credits fall short. public static bool TryRepair(Entity entity, ref int credits) diff --git a/Assets/Scripts/ServerShared/Targeting/BeltTargets.cs b/Assets/Scripts/ServerShared/Targeting/BeltTargets.cs index 3e12536c3..a64e0c624 100644 --- a/Assets/Scripts/ServerShared/Targeting/BeltTargets.cs +++ b/Assets/Scripts/ServerShared/Targeting/BeltTargets.cs @@ -48,8 +48,7 @@ public sealed class BeltTargets : ITargetProvider _zone = zone; _field = field; _data = data; - var size = settings.AsteroidSize; - _largestRadius = size.Exponent > 0 ? max(abs(size.Minimum), abs(size.Maximum)) : float.PositiveInfinity; + _largestRadius = Zone.LargestChunkRadius(settings); var count = data.Asteroids.Length; _periods = new double[count]; diff --git a/Assets/Scripts/ServerShared/VerseGrammar.cs b/Assets/Scripts/ServerShared/VerseGrammar.cs index 00e24833d..1219e70b6 100644 --- a/Assets/Scripts/ServerShared/VerseGrammar.cs +++ b/Assets/Scripts/ServerShared/VerseGrammar.cs @@ -40,6 +40,9 @@ public class VerseRole { [Key(1)] public string Name; [Key(2)] public VerseReferentKind Binds; + + // Element identity: minted by the cache on write; "" means unset. + [Key(3)] [CultElementId] public string Id = ""; } // The actor is the invoking subject and is never a role. diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index 6ba9ef7d7..74d1486c3 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -62,6 +62,9 @@ public class Zone // the entities, and one provider per belt. The reticle, cycling and any range query over rocks go through it; // nothing else scans a belt. public readonly TargetingIndex Targets = new TargetingIndex(); + // Mining cut 4a: the receiver of every rock impact FireControl.Detonate publishes. Notification only: a presenter + // subscribes once per zone, and nothing in ServerShared reads it. + public readonly CapabilityEvents ChunkCapabilities = new CapabilityEvents(); private readonly List _suns = new List(); private HashSet _updatedOrbits = new HashSet(); @@ -87,6 +90,8 @@ public class Zone public Subject ShotResolved = new Subject(); // Contacts.Step publishes each hull-on-hull contact it resolves; presentations are the only readers. public Subject Contacted = new Subject(); + // Published by FireControl.Extract and TryPickUp once ore or an item enters (or is offered to) a hold; read by presentations only. + public Subject CargoGained = new Subject(); private int _nextShotId; public int NextShotId() => ++_nextShotId; @@ -438,8 +443,16 @@ public class Zone { var floating = FloatingItems.FirstOrDefault(f => f.Id.Equals(id)); if (floating == null || (floating.Holder != null && !ReferenceEquals(floating.Holder, taker))) return false; + // The quantity is read before the store: a store that merges into a part-filled stack and spills the rest into a + // new cell rewrites the item's Quantity. + var stored = floating.Item is SimpleCommodity stack ? stack.Quantity : 1; if (!taker.CargoBays.Any(bay => bay.TryStore(floating.Item))) return false; FloatingItems.Remove(floating); + CargoGained.OnNext(new CargoGain + { + Taker = taker, Design = floating.Item.Data, Lot = floating.Item.Lot, Kind = GainKind.Collected, + Stored = stored + }); return true; } @@ -674,16 +687,25 @@ public class Zone return belt.DamagedSize(chunk.Index, wear.Damage, Settings); } - // Cut 2: the only writer of chunk wear. Returns whether this hit broke the chunk. The break threshold is + // No rock of any belt, whole or worn, is wider than this (AsteroidSize's bound over every argument, so over the + // Asteroid.Size range the generator writes). The index's visibility bound and a blast's query reach both use it. + public static float LargestChunkRadius(PlanetSettings settings) + { + var size = settings.AsteroidSize; + return size.Exponent > 0 ? max(abs(size.Minimum), abs(size.Maximum)) : float.PositiveInfinity; + } + + // Cut 2: the only writer of chunk wear. Returns the damage the rock absorbed: the damage, or the hitpoints it had + // left when the hit broke it; 0 on a chunk that is already broken. Whether it broke is ChunkExists. The break threshold is // strictly greater-than, matching the deleted per-tick miner's own comparison against accumulated damage: // damage exactly equal to hitpoints does not yet break the chunk, only damage that exceeds them does. - // A chunk that is currently broken (zone time < BrokenUntil) absorbs nothing: this hit did not break it - // (it was already broken), and its wear stays zeroed until it respawns and starts fresh. - public bool Wear(ChunkId chunk, float damage) + // A chunk that is currently broken (zone time < BrokenUntil) absorbs nothing, and its wear stays zeroed until it + // respawns and starts fresh. + public float Wear(ChunkId chunk, float damage) { _wear.TryGetValue(chunk, out var wear); if (wear.BrokenUntil.HasValue && wear.BrokenUntil.Value > _time) - return false; + return 0f; var beltData = (AsteroidBeltData) Planets[chunk.Field]; var size = beltData.Asteroids[chunk.Index].Size; @@ -695,11 +717,11 @@ public class Zone { var respawnTime = Settings.AsteroidRespawnTime.Evaluate(size); _wear[chunk] = new ChunkWear { Damage = 0f, BrokenUntil = _time + respawnTime }; - return true; + return max(hitpoints - wear.Damage, 0f); } _wear[chunk] = new ChunkWear { Damage = newDamage, BrokenUntil = null }; - return false; + return damage; } // Cut 1 (docs/mining-cut.md): a chunk's pose is a pure function of zone time, computed when asked. No stored @@ -715,6 +737,20 @@ public class Zone return AsteroidBelts[belt].Pose(index, time, parentPosition, size); } + // Mining Cut 4b: the one owner of a chunk's planar velocity, the central difference of the pose function at zone + // time. Derived on every read, never stored: the intercept, the fire-time projection and the mount's sweep all + // read it here. + public float2 ChunkVelocity(ChunkId chunk) + { + const double h = .05; + var ahead = ChunkPose(chunk.Field, chunk.Index, _time + h).xy; + var behind = ChunkPose(chunk.Field, chunk.Index, _time - h).xy; + return (ahead - behind) / (float) (2 * h); + } + + // A chunk's radius in schematic cells: what visibility and a shot's silhouette both measure it in. + public float ChunkCells(ChunkId chunk) => ChunkRadius(chunk) / SchematicCellSize; + // Mining Cut 3 (docs/mining-cut-refresh.md): how bright a chunk is -- Reflector's rule (cross-section × the light // on it), with the field kind's reflectivity per schematic cell times the chunk's area in cells. Computed when // asked; nothing about it is stored. A worn chunk shrinks and dims; a broken one, or one of a kindless belt, is dark. @@ -723,7 +759,7 @@ public class Zone if (!ChunkExists(chunk)) return 0f; var kind = _itemManager.ItemData.Get(((AsteroidBeltData) Planets[chunk.Field]).Kind); if (kind == null) return 0f; - var cells = ChunkRadius(chunk) / _itemManager.GameplaySettings.SchematicCellSize; + var cells = ChunkCells(chunk); return kind.CrossSection * PI * cells * cells * GetLight(ChunkPose(chunk.Field, chunk.Index).xy); } diff --git a/Assets/Scripts/ServerShared/ZoneData.cs b/Assets/Scripts/ServerShared/ZoneData.cs index a08895aaa..e76963a43 100644 --- a/Assets/Scripts/ServerShared/ZoneData.cs +++ b/Assets/Scripts/ServerShared/ZoneData.cs @@ -67,6 +67,9 @@ public class ChunkWearPack [JsonProperty("brokenUntil"), Key(3)] public double? BrokenUntil; + + // Element identity: minted by the cache on write; "" means unset. + [Key(4)] [CultElementId] public string Id = ""; } [JsonObject(MemberSerialization.OptIn)] @@ -149,6 +152,9 @@ public class FieldYield [JsonProperty("regional"), Key(2)] public bool Regional; + + // Element identity: minted by the cache on write; "" means unset. + [Key(3)] [CultElementId] public string Id = ""; } // Ore geography (rulings provinces-within-regions, ores-are-regional): a kind of ground, authored. A region deals its @@ -182,6 +188,9 @@ public class ProvinceKindWeight [JsonProperty("weight"), Key(1)] public float Weight = 1; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] @@ -192,6 +201,9 @@ public class ProvinceOre [JsonProperty("weight"), Key(1)] public float Weight = 1; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // Mining Cut 3 (Q16 B): the one owner of which kind a belt is. Ore geography: and of what it yields. @@ -485,6 +497,9 @@ public class Asteroid [JsonProperty("rotationSpeed"), Key(3)] public float RotationSpeed; + + // Element identity: minted by the cache on write; "" means unset. + [Key(4)] [CultElementId] public string Id = ""; } [CultDocument("aetheria.orbitdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index 5b82a9a1a..42c4c15c0 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -43,7 +43,7 @@ public static class ZoneGenerator PlanetSettings planetSettings, Galaxy galaxy, GalaxyZone galaxyZone, - bool isTutorial = false, + bool entranceStation = false, bool ambient = true) { var pack = new ZonePack(); @@ -294,15 +294,15 @@ public static class ZoneGenerator var storyStations = galaxyZone.Locations.Where(story => story.Type == LocationType.Station).ToArray(); var stationCount = (int)(random.NextFloat() * (factionPresence + 1)) + storyStations.Length; - // Enemy count below is based on this pre-override value, so the tutorial entrance doesn't gain an enemy + // Enemy count below is based on this pre-override value, so the entrance station zone doesn't gain an enemy // just because its station got forced. var baseStationCount = stationCount; - // Operator ruling, 2026-09-25 (docs/locomotion-cut.md, "Tutorial station"): the entrance zone always - // gets a generated faction station with a docking bay, deterministically. Galaxy.cs halves influence and - // picks the lowest-influence unowned zone for Entrance, which otherwise rolls stationCount 0 on every - // seed. galaxy.Entrance is reference-identity, not a name comparison. - var isTutorialEntrance = isTutorial && galaxyZone == galaxy.Entrance; - if (isTutorialEntrance && stationCount < 1) stationCount = 1; + // Operator ruling, 2026-09-25 (docs/locomotion-cut.md): a scenario that declares an entrance station + // (Scenario.EntranceStation) gets a generated faction station with a docking bay in its entrance zone, + // deterministically. A cast galaxy's halved influence and its lowest-influence unowned Entrance otherwise roll + // stationCount 0 on every seed. galaxy.Entrance is reference-identity, not a name comparison. + var isEntranceStation = entranceStation && galaxyZone == galaxy.Entrance; + if (isEntranceStation && stationCount < 1) stationCount = 1; // A station's source is a well-bearing body alone on its ring whose rail clears every massive sibling's extent (the // sibling's support, or its Roche margin if more) and the largest reach of any station or turret hull: whatever hull // is built there, its Lagrange orbit then sits clear of any other body. @@ -318,7 +318,7 @@ public static class ZoneGenerator // (the rail, how far a body on it keeps others out, whether it is a station's own orbit rather than a base's) var sources = candidates.Skip(candidates.Length / 2).Take(stationCount) .Select(p => (orbit: orbitMap[p], extent: Extent(p), direct: false)).ToArray(); - if (isTutorialEntrance && candidates.Length == 0) + if (isEntranceStation && candidates.Length == 0) { // The entrance gets a station whatever its bodies: it orbits a root node beyond its ring group (or, for a body, its // whole family), never at a ring member's distance, and sits there, not at a Lagrange point. @@ -326,7 +326,7 @@ public static class ZoneGenerator var rootNode = roots.FirstOrDefault(p => p.Children.Count > 0) ?? (roots.Count > 1 ? roots.OrderByDescending(p => p.Mass).First() : null); if (rootNode == null) throw new InvalidOperationException( - "The tutorial entrance zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); + "The entrance station zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); var distance = rootNode.Empty ? (1 + GravityField.RingReach) * GravityField.Beta * rootNode.Children.Where(Massive).Min(c => c.Distance) : Extent(rootNode); @@ -445,9 +445,9 @@ public static class ZoneGenerator StationKinds.Choose(cache, nearestFaction, $"{seed}:station:{i}", itemManager.Log)); if (station == null) { - if (isTutorialEntrance) + if (isEntranceStation) throw new InvalidOperationException( - $"The tutorial entrance zone must always get a station, but {nearestFaction?.Name} has no station loadout to generate."); + $"The entrance station zone must always get a station, but {nearestFaction?.Name} has no station loadout to generate."); continue; } station.Orbit = cache.RefOf(lagrangeOrbit); diff --git a/Assets/Scripts/UI/HUD/SchematicDisplay.cs b/Assets/Scripts/UI/HUD/SchematicDisplay.cs index 526a83c80..90b4271d3 100644 --- a/Assets/Scripts/UI/HUD/SchematicDisplay.cs +++ b/Assets/Scripts/UI/HUD/SchematicDisplay.cs @@ -132,8 +132,8 @@ public class SchematicDisplay : MonoBehaviour //x.ListElement.Label.text = x.Item.EquippableItem.Name; if (!_enemy) { - x.ListElement.InfiniteAmmoIcon.gameObject.SetActive(!x.Weapon.WeaponData.AmmoType.IsSet()); - x.ListElement.AmmoLabel.gameObject.SetActive(x.Weapon.WeaponData.AmmoType.IsSet()); + x.ListElement.InfiniteAmmoIcon.gameObject.SetActive(!x.Weapon.ShowsAmmoReadout); + x.ListElement.AmmoLabel.gameObject.SetActive(x.Weapon.ShowsAmmoReadout); } } } @@ -233,8 +233,8 @@ public class SchematicDisplay : MonoBehaviour if (x.Cooldown != null) x.ListElement.CooldownFill.anchorMax = new Vector2(x.Cooldown.Progress, 1); x.ListElement.DurabilityLabel.text = $"{(int)(x.Row.Item.EquippableItem.Durability / itemData.Durability * 100)}%"; - if (x.Weapon.WeaponData.AmmoType.IsSet()) - x.ListElement.AmmoLabel.text = $"{x.Weapon.Ammo}/{x.Weapon.Reserve}"; + if (x.Weapon.ShowsAmmoReadout) + x.ListElement.AmmoLabel.text = x.Weapon.AmmoReadout; } if (x.ListElement.RangeLabel) diff --git a/Assets/Scripts/UI/MainMenu.cs b/Assets/Scripts/UI/MainMenu.cs index 9eef387ca..f867b9e8c 100644 --- a/Assets/Scripts/UI/MainMenu.cs +++ b/Assets/Scripts/UI/MainMenu.cs @@ -7,7 +7,9 @@ using System.Threading; using System.Threading.Tasks; using TMPro; using UniRx; +using UniRx.Triggers; using UnityEngine; +using UnityEngine.EventSystems; using UnityEngine.SceneManagement; using UnityEngine.UI; using static CultMath.math; @@ -118,9 +120,14 @@ public class MainMenu : MonoBehaviour Debug.Log("run store has no SavedGame; Continue disabled"); _nextMenu.panel.AddButton("Continue", saved == null ? (Action) null : () => { - try { RunSave.RequireDesigns(cache, saved); } + Galaxy galaxy; + try + { + RunSave.RequireDesigns(cache, saved); + galaxy = new Galaxy(cache, saved, Debug.Log); + } catch (InvalidOperationException error) { Refuse("Cannot continue this run", error.Message); return; } - ActionGameManager.CurrentGalaxy = new Galaxy(cache, saved, Debug.Log); + ActionGameManager.CurrentGalaxy = galaxy; EnterGame(); }); } @@ -136,9 +143,79 @@ public class MainMenu : MonoBehaviour ShowSettings(); Fade(true); }); + _nextMenu.panel.AddButton("Credits", + () => + { + if (ShowCredits()) Fade(true); + }); _nextMenu.panel.AddButton("Quit", Application.Quit); } + // The third-party attributions the build must show, one button per entry; the selected entry's name, licence and one + // row per notice line fill the detail pane. The list is Credits.All; this only renders it. The screen follows the + // New Game screen: list rows are out of automatic navigation, the focused Back button takes Up and Down to step the + // selection and Cancel to leave, and a click on empty space does not drop that focus. + // False when the list could not be built and a dialog says why; the menu stays where it was. + private bool ShowCredits() + { + var attribution = Resources.Load(Credits.NounProjectResource); + if (attribution == null) + { + Refuse("Credits are unavailable", $"{Credits.NounProjectResource} is missing from this build."); + return false; + } + IReadOnlyList credits; + try { credits = Credits.All(attribution.text); } + catch (InvalidOperationException error) + { + Refuse("Credits are unavailable", error.Message); + return false; + } + Next("credits"); + var list = _nextMenu.panel; + var detail = _nextMenu.detail; + detail.gameObject.SetActive(true); + var focus = new FocusHold(); + var selected = -1; + Button back = null; + void Leave() + { + FocusHold.Focus(null); + focus.Release(); + ShowMain(); + Fade(false); + } + void Select(int index) + { + selected = Mathf.Clamp(index, 0, credits.Count - 1); + var credit = credits[selected]; + detail.Clear(); + detail.Title.text = list.Title.text; + detail.Title.color = Color.clear; + detail.AddProperty(() => credit.Name); + detail.AddProperty(() => credit.Licence); + detail.AddSpacer(); + foreach (var line in credit.Notice.Split('\n')) detail.AddProperty(() => line); + FocusHold.Focus(back.gameObject); + } + for (var i = 0; i < credits.Count; i++) + { + var index = i; + list.AddButton(credits[i].Name, () => Select(index)).Button.navigation = new Navigation { mode = Navigation.Mode.None }; + } + back = list.AddButton("Back", Leave).Button; + back.navigation = new Navigation { mode = Navigation.Mode.None }; + back.OnMoveAsObservable().Subscribe(move => + { + if (move.moveDir == MoveDirection.Up) Select(selected - 1); + else if (move.moveDir == MoveDirection.Down) Select(selected + 1); + }); + back.OnCancelAsObservable().Subscribe(_ => Leave()); + focus.Hold(); + Select(0); + return true; + } + // New Game: every way to set up a run, each with its brief. A release build lists only the modes; the other ways // to set up a run and the test arenas are listed only in editor and development builds. private void ShowScenarios() @@ -174,11 +251,8 @@ public class MainMenu : MonoBehaviour var stage = new GalaxyStage( Settings.SectorGenerationSettings, Settings.SectorBackgroundSettings, - Settings.TutorialGenerationSettings, - Settings.TutorialBackgroundSettings, + Settings.CastBackgroundSettings, ActionGameManager.CultCache, - ActionGameManager.PlayerSettings, - ActionGameManager.GameDataDirectory.CreateSubdirectory("Narrative"), Debug.Log, state => generatorState = state); Task.Run(() => RunStart.Generate(scenario, stage)).ContinueWith(generation => diff --git a/Assets/Scripts/UI/Menu/InventoryPanel.cs b/Assets/Scripts/UI/Menu/InventoryPanel.cs index 2087a3870..eaa6212ac 100644 --- a/Assets/Scripts/UI/Menu/InventoryPanel.cs +++ b/Assets/Scripts/UI/Menu/InventoryPanel.cs @@ -386,11 +386,11 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler var itemData = GameManager.ItemManager.GetData(item); if (!(item is EquippableItem equippableItem)) return; var placementPosition = v + itemDragObject.OriginCellOffset; - if (entity.ItemFits(equippableItem, placementPosition)) + if (entity.ItemFits(equippableItem, placementPosition, out var seated)) { //foreach (var cell in _dragCells) cell.gameObject.SetActive(false); FakeItem = item; - FakeOccupancy = hullData.Shape.Inset(itemData.Shape, placementPosition, item.Rotation); + FakeOccupancy = hullData.Shape.Inset(itemData.Shape, placementPosition, seated); RefreshCells(); GameManager.RegisterDragTarget(drag => { diff --git a/Assets/Scripts/UI/Menu/TradeMenu.cs b/Assets/Scripts/UI/Menu/TradeMenu.cs index 13345f88a..5f4123ff2 100644 --- a/Assets/Scripts/UI/Menu/TradeMenu.cs +++ b/Assets/Scripts/UI/Menu/TradeMenu.cs @@ -312,6 +312,17 @@ public class TradeMenu : MonoBehaviour Dialog.MoveToCursor(); } + // Sells every mined stack of the player's ships' bays in one step; the station pays through TrySell, so nothing refuses. + private void SellOre() + { + StationServices.TrySellOre(PlayerBays(), GameManager.DockedEntity, ref GameManager.Credits); + UpdateCreditsLabel(); + Populate(); + } + + private IEnumerable PlayerBays() => + GameManager.CurrentEntity.Parent.Children.Where(e => e is Ship {IsPlayerShip: true}).SelectMany(s => s.CargoBays); + private void Repair() { if (StationServices.TryRepair(GameManager.CurrentEntity, ref GameManager.Credits)) @@ -398,6 +409,8 @@ public class TradeMenu : MonoBehaviour }); var repairCost = StationServices.RepairCost(GameManager.ItemManager, GameManager.CurrentEntity); if (repairCost > 0) ContextMenu.AddOption($"Repair ({repairCost:N0})", Repair); + var oreValue = StationServices.OreValue(GameManager.ItemManager, PlayerBays()); + if (oreValue > 0) ContextMenu.AddOption($"Sell Ore ({oreValue:N0})", SellOre); ContextMenu.Show(); }); } diff --git a/Assets/Scripts/UI/ScenarioPicker.cs b/Assets/Scripts/UI/ScenarioPicker.cs index e0cd93134..f5f3a1ca4 100644 --- a/Assets/Scripts/UI/ScenarioPicker.cs +++ b/Assets/Scripts/UI/ScenarioPicker.cs @@ -30,7 +30,7 @@ public sealed class ScenarioPicker private static readonly Color Accent = new Color(1, .4458f, .05f); private int _selected; private bool _launched; - private bool _restoreDeselect; + private readonly FocusHold _focus = new FocusHold(); private ScenarioPicker(PropertiesPanel list, PropertiesPanel detail, Action launch, Action back) { @@ -115,7 +115,7 @@ public sealed class ScenarioPicker picker._launchButton.OnCancelAsObservable().Subscribe(_ => picker.Back()); picker.StyleScrollbars(); - picker.HoldFocus(); + picker._focus.Hold(); picker.Select(0); // Layout is not live until the frame after Show; edit mode has no frames. if (Application.isPlaying) Observable.NextFrame().Subscribe(_ => picker.FitViewport()); @@ -229,7 +229,7 @@ public sealed class ScenarioPicker _rows[i].colors = colors; _rows[i].targetGraphic.color = i == _selected ? Accent : _rowFills[i]; } - Focus(_launchButton.gameObject); + FocusHold.Focus(_launchButton.gameObject); Reveal((RectTransform) _rows[_selected].transform); } @@ -253,36 +253,42 @@ public sealed class ScenarioPicker { if (_launched) return; _launched = true; - Focus(null); - ReleaseFocus(); + FocusHold.Focus(null); + _focus.Release(); _launch(Selected); } // Leaves the screen; the same path for the Back button and Cancel. private void Back() { - Focus(null); - ReleaseFocus(); + FocusHold.Focus(null); + _focus.Release(); _back(); } +} - // While the picker is up, a click on empty space must not drop focus from Launch, or the arrows and Enter go dead. - // The input module's flag is scene-wide, so the picker takes it for its own lifetime and gives it back on leaving. - private void HoldFocus() +// Keeps keyboard and gamepad focus on one control while a menu screen is up. While held, a click on empty space must +// not drop focus, or the arrows and Enter go dead. The input module's flag is scene-wide, so the screen takes it for its +// own lifetime and gives it back on leaving. The New Game and Credits screens both use it. +public sealed class FocusHold +{ + private bool _restoreDeselect; + + public void Hold() { if (EventSystem.current == null || !(EventSystem.current.currentInputModule is InputSystemUIInputModule module) || !module.deselectOnBackgroundClick) return; module.deselectOnBackgroundClick = false; _restoreDeselect = true; } - private void ReleaseFocus() + public void Release() { if (!_restoreDeselect) return; _restoreDeselect = false; if (EventSystem.current != null && EventSystem.current.currentInputModule is InputSystemUIInputModule module) module.deselectOnBackgroundClick = true; } - private static void Focus(GameObject target) + public static void Focus(GameObject target) { if (EventSystem.current != null) EventSystem.current.SetSelectedGameObject(target); } diff --git a/Assets/Scripts/Zone Display/ZoneRenderer.cs b/Assets/Scripts/Zone Display/ZoneRenderer.cs index f63f746bd..24ce8a494 100644 --- a/Assets/Scripts/Zone Display/ZoneRenderer.cs +++ b/Assets/Scripts/Zone Display/ZoneRenderer.cs @@ -508,6 +508,7 @@ public class ZoneRenderer : MonoBehaviour void LateUpdate() { + if (!ActionGameManager.RunLive) return; Map.Draw(Zone, ActionGameManager.Clock.Lead); } @@ -550,6 +551,7 @@ public class ZoneRenderer : MonoBehaviour void Update() { + if (!ActionGameManager.RunLive) return; var lead = ActionGameManager.Clock.Lead; GravityLowering.Lower(Zone, lead, ref _gravityWells); foreach (var loot in _floatingItems.Values) diff --git a/Assets/Shaders/Brushes/SimplexBrush.shader b/Assets/Shaders/Brushes/SimplexBrush.shader index 3a6bf56e5..af54035b2 100644 --- a/Assets/Shaders/Brushes/SimplexBrush.shader +++ b/Assets/Shaders/Brushes/SimplexBrush.shader @@ -25,7 +25,7 @@ Category { #pragma target 2.0 #include "UnityCG.cginc" - #include "Assets/Plugins/GPU Noise/SimplexNoise3D.cginc" + #include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl" float _Depth; float _Power; @@ -68,7 +68,7 @@ Category { fixed4 frag (v2f i) : SV_Target { float dist = length(i.texcoord - float2(.5,.5)); - return powerPulse(dist * 2,_Power) * (_Depth * abs(snoise(float3(i.texcoord1.xy*_Frequency,_Time.y*_Speed)))+_Constant); + return powerPulse(dist * 2,_Power) * (_Depth * abs(cultmath_snoise(float3(i.texcoord1.xy*_Frequency,_Time.y*_Speed)))+_Constant); } ENDCG } diff --git a/Assets/Shaders/Clouds.shader b/Assets/Shaders/Clouds.shader index 11e3fe0a3..ccbda8835 100644 --- a/Assets/Shaders/Clouds.shader +++ b/Assets/Shaders/Clouds.shader @@ -29,7 +29,7 @@ #pragma fragment frag #include "UnityCG.cginc" - #include "Assets/Plugins/GPU Noise/SimplexNoise3D.cginc" + #include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl" struct appdata { @@ -64,7 +64,7 @@ float sum = 0; for(int i = 0; i < 6; i++) { - sum += snoise(p * freq + Parallax * ParallaxDirection) * amp; + sum += cultmath_snoise(p * freq + Parallax * ParallaxDirection) * amp; parallax /= ParallaxLacunarity; freq *= NoiseLacunarity; amp *= NoiseGain; @@ -83,7 +83,7 @@ fixed4 frag (v2f i) : SV_Target { float3 p = float3(i.uv,_Time.x*Speed); - float noise = saturate((1-abs(snoise(p*NoiseFrequency/2))) * fbm(p)); + float noise = saturate((1-abs(cultmath_snoise(p*NoiseFrequency/2))) * fbm(p)); return noise * _Color * (1-length(i.uv)/FadeDistance); } ENDCG diff --git a/Assets/Shaders/Compute/Lightning/Lightning.compute b/Assets/Shaders/Compute/Lightning/Lightning.compute index 0750006b9..7edd707d4 100644 --- a/Assets/Shaders/Compute/Lightning/Lightning.compute +++ b/Assets/Shaders/Compute/Lightning/Lightning.compute @@ -5,7 +5,7 @@ #define NUM_THREAD_X 64 #include "LightningVertex.cginc" -#include "Assets/Plugins/GPU Noise/SimplexNoise2D.cginc" +#include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl" struct Node { @@ -46,7 +46,7 @@ float fbm(float2 p) float sum = 0; for(int i = 0; i < 4; i++) { - sum += snoise(p * freq) * amp; + sum += cultmath_snoise(p * freq) * amp; freq *= _NoiseLacunarity; amp *= _NoiseGain; } diff --git a/Assets/Shaders/GalaxyMap.shader b/Assets/Shaders/GalaxyMap.shader index 567396a35..109cd96d0 100644 --- a/Assets/Shaders/GalaxyMap.shader +++ b/Assets/Shaders/GalaxyMap.shader @@ -36,7 +36,7 @@ Shader "Unlit/GalaxyMap" #pragma fragment frag #include "UnityCG.cginc" - #include "Assets/Plugins/GPU Noise/SimplexNoise2D.cginc" + #include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl" struct appdata { @@ -86,8 +86,8 @@ Shader "Unlit/GalaxyMap" for(int i = 0; i < octaves; i++) { if(i<4) - sum += (1-abs(snoise(p * freq))) * amp; - else sum += abs(snoise(p * freq)) * amp; + sum += (1-abs(cultmath_snoise(p * freq))) * amp; + else sum += abs(cultmath_snoise(p * freq)) * amp; freq *= NoiseLacunarity; amp *= NoiseGain; } diff --git a/Assets/Steel.mat b/Assets/Steel.mat deleted file mode 100644 index fc4d8d0ca..000000000 --- a/Assets/Steel.mat +++ /dev/null @@ -1,83 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Steel - m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: _MAINTEX _METALLICGLOSSMAP _NORMALMAP _OCCLUSIONMAP _PARALLAXMAP - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 4, y: 4} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 4, y: 4} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _GlossMapScale: 1 - - _Glossiness: 0.5 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/Directory.Build.props b/Directory.Build.props index 05d5e4d22..62160b34f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,12 +2,12 @@ $(CULTLIB_ROOT) $(MSBuildThisFileDirectory)..\CultLib - - b8fc5eb07720a187a0421424ac2cb3aa2966ca1d + + 7225835d11fd08a3de2a2ef24742fc351b3b08fb $(CULTMATH_ROOT) $(CultLibRoot) - - 7a8933b085468e1fc6f9d3bce4a85e7d101aaca3 + + f1edfa458dd8e7e107214e9d9884254359475b8c C:\Program Files\Git\cmd\git.exe git diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index 553e6bcce..b58ec27b4 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0f81d35d4cec8f57178220f20bca98ffaa6709783349efe3cc28aa64ea1f02b1 -size 220607 +oid sha256:58e9e0ceadc3b4908491563eb9dfad8ee062024b036a4d3d3cab1e00c168cda9 +size 225267 diff --git a/GameData/Mods/aetheria.nakovalnya/ship.cc b/GameData/Mods/aetheria.nakovalnya/ship.cc index ebe05cd33..1def7b776 100644 --- a/GameData/Mods/aetheria.nakovalnya/ship.cc +++ b/GameData/Mods/aetheria.nakovalnya/ship.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:87d8cbcca252460d1ec2bfeb895c1447ab185172a4a4449b237a297b83ea5057 -size 40059 +oid sha256:0228aa7ec3a2e060bd49e46aa64f52eea4c4cdb25951c164646c1d031ad17851 +size 30457 diff --git a/GameData/Mods/aetheria.nakovalnya/ship.glb b/GameData/Mods/aetheria.nakovalnya/ship.glb index 3dac76cc9..af1e370e6 100644 --- a/GameData/Mods/aetheria.nakovalnya/ship.glb +++ b/GameData/Mods/aetheria.nakovalnya/ship.glb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:90a503473e3b12251c225b7fe283b2fc5b45a25e6e47839d1c3d78e3ac61b00c -size 843452 +oid sha256:ab3fdd340bf27fc8c2a6149ce6be9159215cf26b3eabd290064ffe40b2e96512 +size 839556 diff --git a/GameData/Mods/aetheria.wren/ship.cc b/GameData/Mods/aetheria.wren/ship.cc deleted file mode 100644 index d81f9bba5..000000000 --- a/GameData/Mods/aetheria.wren/ship.cc +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6b1744dfa7dd6c5325ca3bd04fba941408cdc1255c06d1fc0d52fa67c97dc100 -size 10514 diff --git a/GameData/Mods/aetheria.wren/ship.glb b/GameData/Mods/aetheria.wren/ship.glb deleted file mode 100644 index 03b70b729..000000000 --- a/GameData/Mods/aetheria.wren/ship.glb +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:98bf1b4a0e19e67568930ca79b9d61529c21c63dd74ee8df3d3f1d419d3a81cc -size 6964 diff --git a/Packages/manifest.json b/Packages/manifest.json index 7693bd94f..ef01307a8 100644 --- a/Packages/manifest.json +++ b/Packages/manifest.json @@ -53,7 +53,7 @@ "com.unity.modules.wind": "1.0.0", "com.unity.modules.xr": "1.0.0", "org.gamecult.caching.unity": "https://github.com/GameCult/CultLib.git?path=/src/GameCult.Unity/Assets/Caching#caching-unity-v2.0.0", - "org.gamecult.cultlib": "https://github.com/GameCult/CultLib.git?path=/unity/org.gamecult.cultlib#cultlib-unity-v2.0.1", - "org.gamecult.cultmath": "https://github.com/GameCult/CultLib.git?path=/packages/cultmath/unity/org.gamecult.cultmath#cultmath-unity-v0.5.0" + "org.gamecult.cultlib": "https://github.com/GameCult/CultLib.git?path=/unity/org.gamecult.cultlib#cultlib-unity-v3.0.0", + "org.gamecult.cultmath": "https://github.com/GameCult/CultLib.git?path=/packages/cultmath/unity/org.gamecult.cultmath#cultmath-unity-v0.5.1" } } diff --git a/Packages/packages-lock.json b/Packages/packages-lock.json index 919cf94d1..4db845c3b 100644 --- a/Packages/packages-lock.json +++ b/Packages/packages-lock.json @@ -265,20 +265,20 @@ "hash": "42dce3611a81adc5c5fac54cadbaa5637d6022d3" }, "org.gamecult.cultlib": { - "version": "https://github.com/GameCult/CultLib.git?path=/unity/org.gamecult.cultlib#cultlib-unity-v2.0.1", + "version": "https://github.com/GameCult/CultLib.git?path=/unity/org.gamecult.cultlib#cultlib-unity-v3.0.0", "depth": 0, "source": "git", "dependencies": { - "org.gamecult.cultmath": "0.5.0" + "org.gamecult.cultmath": "0.5.1" }, - "hash": "b8fc5eb07720a187a0421424ac2cb3aa2966ca1d" + "hash": "7225835d11fd08a3de2a2ef24742fc351b3b08fb" }, "org.gamecult.cultmath": { - "version": "https://github.com/GameCult/CultLib.git?path=/packages/cultmath/unity/org.gamecult.cultmath#cultmath-unity-v0.5.0", + "version": "https://github.com/GameCult/CultLib.git?path=/packages/cultmath/unity/org.gamecult.cultmath#cultmath-unity-v0.5.1", "depth": 0, "source": "git", "dependencies": {}, - "hash": "7a8933b085468e1fc6f9d3bce4a85e7d101aaca3" + "hash": "f1edfa458dd8e7e107214e9d9884254359475b8c" }, "com.unity.modules.accessibility": { "version": "1.0.0", diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index 1b000cd89..76b6938ad 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1f95917a4ca95a4f6977be90d80185648b012099467fa2275b31b868aca88b6f -size 24058 +oid sha256:900f257853e7bf436c28cb323c323f2ef43e8d0659253ca7545cd23255d8ea57 +size 24033 diff --git a/docs/aetheria-fauna-map.md b/docs/aetheria-fauna-map.md index b698baf41..5276db97e 100644 --- a/docs/aetheria-fauna-map.md +++ b/docs/aetheria-fauna-map.md @@ -398,7 +398,7 @@ the lore branch `eureka/aetheria-fauna-lore` `74c7e212`, note `Open Water` (`OW` | # | Question | Result | |---|---|---| | B28 | What does CultMath already give a node library? | Integer PCG hashes `pcg`, `pcg3d`, `pcg4d` (Jarzynski and Olano), "integer-only, so dxc and C# agree bit for bit" (`packages/cultmath/src/CultMath/math.cs:393-426`, `shaders/CultMath.hlsl:396-426`). `cellular(float3)`: Worley F1 and F2 - F1 with analytic gradients, jitter from `pcg3d` of the integer cell, 3D, unweighted (`math.cs:849-975`, `CultMath.hlsl:440-503`). `smin_grad` (`math.cs:831-847`, `CultMath.hlsl:428-437`). `distance_to_segment` in C# only (`math.cs:319`; no HLSL twin). No weighted cellular, no diagram over explicit weighted sites, no site-graph gate. | -| B29 | How does CultMath own parity? | Two legs, one owner each (`packages/cultmath/docs/design.md:202-206`): HLSL against C# by the mirror test, which compiles the text of `CultMath.hlsl` as C# and compares float32 bit patterns (`design.md:118-124`), plus a clean `dxc -T lib_6_3` compile (`design.md:114-116`); GLSL against C# by golden fixtures run on a device. The mirror proves the composition in the text, not that a GPU agrees (`design.md:119-121`); device HLSL runs are consumers' today (Asura `gpu-snoise-parity`; Aetheria `FlowFieldParityVerify`). CultMath ships a Unity compute smoke (`packages/cultmath/scripts/unity-smoke/`). Aetheria pins `cultmath-unity-v0.4.1` (`Packages/manifest.json`). | +| B29 | How does CultMath own parity? | Two legs, one owner each (`packages/cultmath/docs/design.md:202-206`): HLSL against C# by the mirror test, which compiles the text of `CultMath.hlsl` as C# and compares float32 bit patterns (`design.md:118-124`), plus a clean `dxc -T lib_6_3` compile (`design.md:114-116`); GLSL against C# by golden fixtures run on a device. The mirror proves the composition in the text, not that a GPU agrees (`design.md:119-121`); device HLSL runs are consumers' today (Asura `gpu-snoise-parity`; Aetheria `FlowFieldParityVerify`). CultMath ships a Unity compute smoke (`packages/cultmath/scripts/unity-smoke/`). Aetheria pins `cultmath-unity-v0.5.1` (`Packages/manifest.json`). | | B30 | Does Aetheria already keep a math twin outside CultMath? | Yes. `FlowField` uses CultMath's `math`, but its `Tri`, `Tri3` and `Tri3D` are Aetheria functions (`FlowField.cs:66-72`) whose HLSL twin is `Volumetric.cginc`, pinned by Aetheria's own `FlowFieldParityVerify` (`RelativeTolerance` 1.5e-4). That is a second parity owner beside CultMath. | | B31 | What is parked in CultMath that a DAG would use? | The tape: steps 2-5 (expression graph lowered to bytecode with C# evaluators, pruning, an HLSL interpreter, meshing) are parked until Asura is stable (`docs/cultmath-tape-target.md:3-8`, ruling `tape-target-unparks-when-asura-stable`). "Truth and lowerings" (`:84-92`): the field is a typed CultCache document, and the CPU evaluator and the HLSL interpreter are lowerings of it. Step 1 (intervals) and affine forms are on main. | | B32 | Do the candidates make filaments? (`docs/research/2026-10-14-trophic-dag-probe/`, README there; wells orbit, slope terms on, t = 0) | `skein` draws strands between neighbouring wells, bent by the flow (`density_skein.png`); `lattice` draws a fine cellular web, dense on the shoulders, dim elsewhere, with no long links (`density_lattice.png`); `skein-web` draws both: strands from well to well with a web hanging off them (`density_skein-web.png`, `layer_L2-krill.png`). Correlation with the B20 Physarum map at 64x32 blocks (this measures the envelope, not filaments: a block is 62 u, wider than a strand): band .512, lattice .359, skein-web .296, krill .277, skein .225, slack .171. Hosted krill at 16 u: band 2,075, skein-web 1,475, skein 639, lattice 419. | diff --git a/docs/aetheria-release-map.md b/docs/aetheria-release-map.md index 18f9b6941..83892fc69 100644 --- a/docs/aetheria-release-map.md +++ b/docs/aetheria-release-map.md @@ -502,10 +502,8 @@ record. | follow-up | `hull-damage-wear` | demo | Damage visible on the hull (line 6). | | follow-up | `mod-ship-single-existence-gate` | demo | A skipped package throws on spawn; demo hulls are packages. | | follow-up | `ambiguous-hardpoint-origin` | demo | Save correctness for package hulls. | -| follow-up | `remove-sbsar-files` | demo | Clean break from Substance before a public build. | | follow-up | `delaunay-exact-predicates` | demo | Galaxy links; a silently unlinked zone could strand a demo run. | | follow-up | `failed-start-scene-halts` | demo | The New Game failure path the demo's missing-cast refusal uses. | -| follow-up | `stale-docs-after-scenarios-menu` | demo | Docs that describe the old New Game path. | | follow-up | `scratch-carry-drafts` | demo | The ship `.cc` draft bears on `demo-ship-cc-timing`. | | follow-up | `faction-lore-notes-r3` | full game | Vault setting notes; no demo cut reads them. | | follow-up | `mining-impacts-through-contract` | full game | Mining Cut 4 is parked. | @@ -2188,7 +2186,7 @@ wear comes from baked maps. Grunge is baked into `ship.maps.png` A. - r2's region tint (`_PaintStrength`, `RegionLuminance`, a tiling `_WearNoise`) and its `Livery` of three colours are never built. - Revision 1's vertex mask is gone. - - The 41 `.sbsar` files go with follow-up `remove-sbsar-files`. + - The 41 `.sbsar` files are removed (follow-up `remove-sbsar-files`). #### Parity @@ -7459,7 +7457,9 @@ That file's Cut 4 (AI heading planner) and Cut 5 (combat facing) are carried as is `stage.Generated("Djinni")`, `EvasionTermTests.cs:520`, so the target's fit follows the galaxy). The cause is 0.3.0's breaking `snoise` kernel (its CHANGELOG), read in C# by `Settings.cs:72-73` (galaxy cloud density), `GlobalData.cs:30` and `Environment.cs:132,144`. Shaders use the GPU Noise plugin, not - CultMath (`Background.shader:39`), so nothing on the GPU moves. Every other DemoTerminus test passes. + CultMath (`Background.shader:39`), so nothing on the GPU moved at 0.3.0. GalaxyMap, Clouds, SimplexBrush and + Lightning.compute now include `CultMath.hlsl`; Background keeps its 2D gradient copy because CultMath has no 2D + `snoise_grad`. Every other DemoTerminus test passes. Between the tags CultMath also adds `phacelle` (MPL-2.0 files), `cellular`, `smin_grad`, the `*_grad` noises and `BoundedLeastSquares`; no existing signature changes. - **TA9. The pin guard.** `Directory.Build.targets:21` conditions `VerifyCultLibRevision` on a diff --git a/docs/cultcache-migration-cut.md b/docs/cultcache-migration-cut.md index 16e885490..f27bde97d 100644 --- a/docs/cultcache-migration-cut.md +++ b/docs/cultcache-migration-cut.md @@ -95,7 +95,7 @@ recorded, none blocking: `WeaponData.AmmoType` refs. - One cache holds all three stores for the process. - `RunSave` commits a save atomically with stable zone keys and clears the run - on New Game or death. + on death or victory (`RunSave.Replace` drops the old run once a new one has staged). - `SavedRun`, the msgpack settings and layout I/O, `.loadout`, `SaveState`, `SaveZone` and the importer are deleted. - **Loadouts are authored ship presets in the catalog.** This was reworked @@ -138,9 +138,6 @@ The first Soul pass found untested all-or-nothing, availability and price rules, weapon-group corruption, dictionary-ordered product choice, and a premature "done". All are fixed. -Recorded, not fixed: New Game clears the previous run before generation, as the -spec says, so a generation fault loses that run. - `GameData/PlayerSettings.msgpack` entered history through `5c5c3d5e`. It holds defaults and the username, and about 65 earlier versions are already in LFS history, so history is left alone. @@ -151,7 +148,7 @@ death clearing the run across relaunch, stance toggle, `FieldShieldTest`. It fou migration defect: CultMath types are not Unity-serializable, so Unity-serialized CultMath fields load as zero. Mouse sensitivity (lost look control) moved to `PlayerSettings` in `00ebe46a`; the rest, including the black rarity colours, is `docs/settings-globals-cut.md`. -Scene materials are broken by the dead Substance plugin, not by this migration. +The Substance maps are removed and the materials repointed to Assets/Materials/PBR. History, before the smoke: - nothing else from agents. The preset rework's Soul findings were fixed in @@ -651,7 +648,9 @@ After Cut 10, every runtime write is a single-store `Commit` on one cache that holds catalog, run and player stores from first access: - `RunSave.Commit` saves the run at wormhole arrival and quit, with stable `SavedZone` keys. -- `RunSave.Clear` deletes every run record at New Game and at death. +- `RunSave.Clear` deletes every run record at death and victory (`ActionGameManager.EndRun`). +- `RunSave.Replace` swaps the saved run for a new one only after the new run has + staged; a start that fails leaves the saved run in place. - The settings getter creates `PlayerSettings` on first launch, and `SavePlayerSettings` commits it. - `Loadouts.Save` writes loadouts to the player store, and @@ -849,7 +848,7 @@ reads a global back (Q4). | Global | Store | Read by | Existence owned by | Missing at main menu | Missing at resume | Missing at new game | |---|---|---|---|---|---|---| | `PlayerSettings` | Player | `MainMenu` (name, tutorial flag), `ActionGameManager` (credits) | boot: `ActionGameManager.Awake` after `AetheriaStores.Open`, when `GetGlobal()` is null, upserts one and flushes (Cut 10) | cannot happen after boot | same | same | -| `SavedGame` | Run | `MainMenu` (resume), `Galaxy(CultCache, SavedGame, ...)` | new game: `ActionGameManager.BeginRun()` creates the run store and writes it; `Die()` deletes the run store (Cut 10) | no run file: Resume hidden; run file without `SavedGame`: refuse to resume, log the key, New Game only | as main menu | new game deletes any run store first | +| `SavedGame` | Run | `MainMenu` (resume), `Galaxy(CultCache, SavedGame, ...)` | new run: `RunSave.Replace` writes the new run's records and removes the old run's once the scenario has staged; `EndRun` calls `RunSave.Clear` at death and victory | no run file: Continue disabled; run file without `SavedGame`: Continue disabled, log the key | as main menu | a new run keeps the saved run until it has staged | | catalog globals | Catalog | none exist | authored data; catalog is read-only | `AetheriaStores.Open` throws naming every `[CultGlobal]` type routed to the catalog with no record | same | same | **CultLib's role.** `[CultGlobal]` means exactly: at most one record of the @@ -1772,8 +1771,8 @@ Probes behind 8a (scratch copies; nothing committed): Math audit: - **Not used:** `float4x4`, `transpose`, `determinant`, `_11` names. The - `determinant` hits (`AetheriaMath.cs:98-112`, `NIH\MIConvexHull`) are locals - and comments; the `half` hits are locals. `float2x2`/`float3x3`, `int3`/`int4`, + `determinant` hits were locals and comments (in `AetheriaMath.cs` and the + vendored `NIH\MIConvexHull`, both since deleted); the `half` hits are locals. `float2x2`/`float3x3`, `int3`/`int4`, `double2`/`double3`, `quaternion.LookRotation`, `Random` and `snoise` all compile against CultMath. - **Accepted by Cut 6b:** `hash`, `normalize`, `Random`, `snoise` and NaN @@ -2596,28 +2595,31 @@ AetherDb and test edits made by Cut 9 (landed `70fbaca1`, recorded `e3af23fa`). - `SavedGame` global and `savedzone-{i}` records in `run.cc`. - `PlayerSettings` global in `player.cc`. - Orbit and body records in `run.cc`, written by zone generation and landed by the next save. - - **Run begins:** New Game calls `RunSave.Clear(CultCache)` as its first - statement (the `MainMenu.cs:110` handler), before the `Task.Run` at `:127` - or `:154`. - - Galaxy generation writes nothing. - - Zone generation (`PopulateLevel` `:615`, then `ZoneGenerator.cs:99, 108, - 200-201, 239, 253`) upserts orbits and bodies into the attached run store. - They stay staged until the next `RunSave.Commit`. + - **Run begins:** a scenario launch (`MainMenu.Launch`) generates the galaxy on a + background task and writes nothing to the run store. `StartGame` then calls + `StartScenario`, which runs arena generation, `PopulateLevel` and staging + inside `RunSave.Replace(CultCache, ...)`. The saved run's records are removed + only when staging succeeds; on failure the records the start wrote are removed + and the saved run stays. + - Zone generation (`PopulateLevel`, then `ZoneGenerator`) upserts orbits and + bodies into the attached run store. They stay staged until the next + `RunSave.Commit`, or are removed by `Replace` on a failed start. - **Run saves:** `ActionGameManager.SaveRun()`: - - It is `if (CurrentGalaxy != null) { var (game, zones) = RunSave.Capture(CultCache, CurrentGalaxy, Zone, DockedEntity ?? CurrentEntity, IsTutorial, _actionBarSlots.Select(s => s.Save()).ToArray()); RunSave.Commit(CultCache, game, zones); }`. + - It captures the live run (`RunSave.Capture`, which writes `SavedGame.IsTutorial` from `galaxy.IsPrelude`) and commits it with `RunSave.Commit` (`ActionGameManager.SaveRun`, `:284`). - Callers: wormhole arrival (`:605`) and `OnApplicationQuit() { SaveRun(); SavePlayerSettings(); }`. - - **Run ends:** `Die` replaces `SavePlayerSettings()` at `:1059` with - `RunSave.Clear(CultCache); SavePlayerSettings();`. - - `CurrentGalaxy` is already null (`:1058`), so a quit afterwards does not save a run. + - **Run ends:** `EndRun` (death and victory) nulls `CurrentGalaxy`, then calls + `RunSave.Clear(CultCache); SavePlayerSettings();` (`ActionGameManager.cs:1224-1232`). + - `CurrentGalaxy` is already null, so a quit afterwards does not save a run. - **Run exists:** derived only as `CultCache.GetGlobal() != null`. - `MainMenu.ShowMain` enables Continue from it. Continue sets - `IsTutorial = saved.IsTutorial` and - `CurrentGalaxy = new Galaxy(CultCache, saved, Debug.Log)`. - - `StartGame` (`:695-741`) reads it once at the top: `null` takes the - new-run branch; otherwise it resumes from `CurrentZone`, - `CurrentZoneEntity` and `ActionBarBindings` (`:722, 723, 737`). + `CurrentGalaxy = new Galaxy(CultCache, saved, Debug.Log)`, whose `IsPrelude` + comes from `saved.IsTutorial`. + - `StartGame` (`ActionGameManager.cs:820`) branches on `PendingScenario`: set + means a new run (`StartScenario`); otherwise it resumes from `CurrentZone`, + `CurrentZoneEntity` and `ActionBarBindings` of the saved run. - A run store that holds records but no `SavedGame` logs - `run store has no SavedGame; Continue disabled`. New Game clears it. + `run store has no SavedGame; Continue disabled`. The next scenario launch + replaces those records once it has staged. - **Player settings:** - The `ActionGameManager.PlayerSettings` getter returns `CultCache.GetGlobal()`. - When that is absent (first launch), the getter commits @@ -2651,7 +2653,7 @@ AetherDb and test edits made by Cut 9 (landed `70fbaca1`, recorded `e3af23fa`). - The cache never creates either. `AetheriaStores.Open` keeps its missing-global check catalog-only (`AetheriaStores.cs:24-29`). - **Derived state:** - "Run exists" is derived from the `SavedGame` global. - - `IsTutorial` is set from it on Continue and written back by `Capture`. + - `Galaxy.IsPrelude` is set from `SavedGame.IsTutorial` on Continue; `Capture` writes it back from `galaxy.IsPrelude`. No static copy exists. - `PlayerSettings.SavedRun` is deleted, not demoted. - **Forbidden writers:** - `File.*` I/O for game state anywhere in `Assets\Scripts`. @@ -2660,10 +2662,10 @@ AetherDb and test edits made by Cut 9 (landed `70fbaca1`, recorded `e3af23fa`). - A second `AetheriaStores.Open` in `Assets\Scripts`. - Any upsert of `SavedGame` or `SavedZone` outside `RunSave.Commit`. - **Shared paths:** - - Normal and tutorial New Game both call `Clear`. + - Every scenario launch goes through `RunSave.Replace`. - Continue and a new run's `StartGame` read the same global. - Wormhole and quit call `SaveRun`. - - Death calls `Clear`. + - Death and victory call `Clear` through `EndRun`. - **Deletion line:** `SavedRun`, `SaveState`, the msgpack settings and layout I/O, `SaveLoadout`, `SaveZone` and the `SavedGame` constructor go before `RunSave` lands. diff --git a/docs/element-ids.md b/docs/element-ids.md new file mode 100644 index 000000000..32ccdafc8 --- /dev/null +++ b/docs/element-ids.md @@ -0,0 +1,42 @@ +# Element ids and the CultLib pin (cultlib-unity-v3.0.0) + +CultLib 3.0.0 (Unity tag `cultlib-unity-v3.0.0`, commit `7225835d`, which is the headless pin in `Directory.Build.props`; CultMath `cultmath-unity-v0.5.1`, `f1edfa45`) gives every element of an object list an identity. Every +element type reachable through a list of a `[CultDocument]` type carries one string member with `[Key(n)]` and `[CultElementId]`; +the registry refuses to open otherwise, naming the type and list. + +- **Where the slot goes.** A union base takes the member above its subclasses' highest key. `BehaviorData.Id` is key 37, so an + array-format behavior is 38 slots on the wire (`PaintModeTests`, `ShipRigTests` pin it). A new `BehaviorData` subclass must keep + its keys below 37 or move the slot, which is a wire change. +- **Derived ids.** `ShipJoint` and `ShipAnchor` already had a readable `Id`; CultLib refuses a readable id inside a marked member, + so each gained a trailing `ElementId` marked `[CultElementId(nameof(Id))]`. +- **Minting.** A writer mints random ids for elements that have none. A store written before ids (every file under `GameData/`) + loads with ids minted in memory and persists them on its next write; `CultCache.MintElementIds()` does that in one pass. + `ElementIdUpgradeTests` opens a copy of the shipped catalog, mints, flushes and reopens it. +- **Comparing content.** Random ids differ between two writes of the same content. Tests that compare bytes use + `ElementIdBlind`. +- **One list element is one object.** The same instance twice in a list is refused (`CultElementIdException`). +- **Retyping.** Writing a different type onto a held key is refused unless the record is removed first + (`EconomyAuthor.Write` does). + +## The bump is one-way + +A store holding element ids is format v3 (single file) or v5 (directory). The previous pin (`cultlib-unity-v2.0.1`, `b8fc5eb0`) refuses a v3 store loudly +(`NotSupportedException: Store format cultcache.store.v3 is not readable`; checked by Soul on PR 12). CultLib #98 (`7002c252`) records +that some intermediate pins read a single-file v3 store silently and drop the ids on the next write. So: upgrade readers before +writers, keep a pre-upgrade copy of any real store (`GameData/Aetheria.cc` and the mod packages are tracked in git; player saves and +run stores are not), and do not roll the pin back after a store has been written under the new one. + +The shipped mod package (`GameData/Mods/aetheria.nakovalnya/ship.cc`) and the test fixture package (`tests/fixtures/mods/aetheria.wren/ship.cc`) held only default +placeholders (`0` and `[]`) in the retired `HullData` slots 21 and 22, which the new CultLib refuses to write over +(`CultSchemaConflictException`). They were regenerated with `AetherDb ship-authoring regenerate apply`, which loads the +records, writes them into a fresh file under the current schema, requires them to read back identical and replaces the file. Both +now hold persisted element ids and nil in slots 21 and 22; `EveryShippedModPackageCanBeWrittenOver` fails if a package regresses. +A mod file that fails the same way is regenerated the same way. A rewritten catalog is about 15% larger: every behavior row is 38 +slots, mostly nil. A regenerated ship package can still shrink: the old nakovalnya file stored its floats as float64 and the +fresh write stores the typed `float` fields as float32 (40059 to 30457 bytes; each value equals the old one rounded to float32). + +The Unity manifest (`Packages/manifest.json`) pins `org.gamecult.cultlib` at `cultlib-unity-v3.0.0` and `org.gamecult.cultmath` at +`cultmath-unity-v0.5.1` (the version v3.0.0 depends on). `org.gamecult.caching.unity` stays at `caching-unity-v2.0.0`: it is editor +tooling, unchanged in v3.0.0. The v3.0.0 plugin `GameCult.Caching.dll` exports `CultElementIdAttribute` (sealed, fields and +properties, one optional `derivedFrom` argument), the shape `ServerShared` uses. The Unity editor compile of this branch has not +been run; the headless build and tests are the evidence so far. diff --git a/docs/headless-playground-cut.md b/docs/headless-playground-cut.md index bea30aa46..d6ca6104a 100644 --- a/docs/headless-playground-cut.md +++ b/docs/headless-playground-cut.md @@ -10,6 +10,13 @@ probe was built with `--artifacts-path` in scratch, so this tree got no `bin`/`o writes. CultLib was a temporary detached worktree at `a0813c6`, since removed. The probe source is not kept; §2.8 records what it did. +Since this map, the new-run path moved: `MainMenu.Launch` starts a `Scenario` and +`ActionGameManager.StartScenario` replaces the saved run through `RunSave.Replace` +after `RunStart` stages it (`docs/scenarios-cut.md` R.9); the `IsTutorial` static is +gone (`Galaxy.IsPrelude` is the one owner) and `ItemManager` takes its seed in its +constructor. Passages below that name the old `MainMenu` new-game anchors or those +statics are rewritten to that path; the `Run` owner itself is still unbuilt. + ## 0. Target Operator, 2026-09-17: player inputs "map directly to the same entity inputs the AI @@ -107,11 +114,11 @@ All of this is Unity code: | Concern | Anchor | Unity dependencies | |---|---|---| | Store composition | `ActionGameManager.cs:43-63` (static, `Application.dataPath`) | path only | -| Handoff across scene load | statics `CurrentGalaxy`, `IsTutorial` (`:96-97`), written by `MainMenu.cs:104-105,126,138,152,166`, read by `SectorMap.cs:114-310` | `SceneManager.LoadScene` (`MainMenu.cs:106,139,167`) | -| New game: clear | `MainMenu.cs:112` | none | -| New game: galaxy | `MainMenu.cs:125,148` (`UnityEngine.Random.value` background noise), `:127-141,153-169` (`Task.Run`, then `Observable.NextFrame`) | Random, UniRx main-thread scheduler | -| ItemManager | `ActionGameManager.cs:264`; RNG clock-seeded at `ItemManager.cs:20` | `Debug.Log` | -| Start / Continue | `StartGame` `:725-770`: spawn player ship `:733-744`; Continue resolves the docked child `:751-762`; action bar restore `:764-767` | renderer binding, `SectorMap` reveal | +| Handoff across scene load | statics `CurrentGalaxy` and `PendingScenario` (`ActionGameManager.cs:108,113`), written by `MainMenu.Launch` and Continue, read by `SectorMap` | `SceneManager.LoadScene` (`MainMenu.EnterGame`, `MainMenu.cs:287`) | +| New game: replace | `ActionGameManager.StartScenario` (`:855-876`): `RunSave.Replace` drops the saved run only after the scenario stages; `MainMenu` clears nothing | none | +| New game: galaxy | `MainMenu.Launch` builds a `GalaxyStage` and runs `Task.Run(() => RunStart.Generate(scenario, stage))`, then `Observable.NextFrame`; background noise and galaxy draw from `GalaxyStage.Seed`, not `UnityEngine.Random` | UniRx main-thread scheduler | +| ItemManager | `ActionGameManager.cs:309`; seed is a constructor argument, `RunStart.ItemSeed(galaxy, step)` (`RunStart.cs:99`), reseeded by `RunStart.SeedItems` | `Debug.Log` | +| Start / Continue | `StartGame` (`:820`): `PendingScenario` set runs `StartScenario` (new run, player staged by `RunStart.Stage`); otherwise Continue resolves the saved zone and docked child and restores the action bar | renderer binding, `SectorMap` reveal | | Zone entry | `PopulateLevel` `:639-675`: generate/unpack `:643-654`; move pilot `:659-666` | `ZoneRenderer.LoadZone`, `Debug.Log` | | Wormhole placement (a game rule) | `ZoneRenderer.cs:222-231` (`dir * Pack.Radius * GameSettings.WormholeDistanceRatio`) | lives in a MonoBehaviour | | Warp | detect `ActionGameManager.cs:312-316`; `EnterWormhole` `:615-637`, which saves on arrival (`:635`) | `ZoneRenderer.WormholeInstances` as the wormhole list | @@ -120,10 +127,11 @@ All of this is Unity code: | Save | `SaveRun` `:241-249`, called at quit `:236` and warp `:635` | action-bar slots (`:246`) | | Death | `BindToEntity` subscribes `Death` -> `Die` (`:1053`); `Die` `:1080-1115` clears the run (`:1088`) | `Time.time`, `Observable.EveryUpdate` post-fx | | Tick | `Update` `:1151-1220`: input `:1189-1216`, then `Zone.Update(Time.deltaTime)` `:1218` | `Time.deltaTime`, pause flag | -| Dead code | `IntroCutscene` `:772-799`; its only call is commented out (`:760`) | coroutine, `Time.time` | ### 2.2 Already headless +- Past probe: the measurements below were taken at an earlier commit and their line anchors + are not maintained; re-run the probe before relying on a number or an anchor. - `Aetheria.Shared/Aetheria.Shared.csproj` compiles `Assets/Scripts/ServerShared/**` plus UniRx (`UniRxLibrary`) and Ink with no Unity defines. It is the Unity-independence check. @@ -134,23 +142,23 @@ All of this is Unity code: - a player `LonginusX` spawned through `LoadoutGenerator`; - thrust by hand-set `MovementDirection` reached 142 m/s in 5 s; - a `Minion` patrol moved the player ship 642 units in 10 s; - - `TryDock` and `TryUndock` succeeded (`Entity.cs:721-755`); - - `Ship.EnterWormhole` followed by stepping fired `OnEnteredWormhole` (`Ship.cs:82-90,372`); - - `Death` fired on hull damage (`Entity.cs:277-280`); + - `TryDock` and `TryUndock` succeeded; + - `Ship.EnterWormhole` followed by stepping fired `OnEnteredWormhole`; + - `Death` fired on hull damage; - `RunSave.Capture` and `RunSave.Commit` wrote a 489 KB `run.cc`. - Settings: `GameSettings` is a ScriptableObject (`GameSettings.cs:11`) holding ServerShared classes. - `tools/AetherDb/AuthoredSettings.cs` reads them from the asset YAML. The probe placed every field (0 unplaced). - Two lifecycle inputs are Unity-only `GameSettings` fields: `StartingHullName` - (`GameSettings.cs:17`, authored `LonginusX`) and `WormholeDistanceRatio` (`:23`, + (`GameSettings.cs:13`, authored `Longinus`) and `WormholeDistanceRatio` (`:16`, authored 0.75). - Randomness: - - `ItemManager.Random` is clock-seeded (`ItemManager.cs:20`). - - `Galaxy` is clock-seeded only when `seed == 0` (`Galaxy.cs:108,158`). - - `Zone` seeds from the zone name (`Zone.cs:54`). - - `Zone.Update` runs belt updates on `Task.Run` (`Zone.cs:144`). It is still - deterministic (probe: identical traces). + - `ItemManager.Random` is seeded by the constructor argument (`ItemManager.cs:35`); a new run's seed is `RunStart.ItemSeed(galaxy, step)`, from `Galaxy.Seed`. + - `Galaxy` takes its seed from the run (`Galaxy.cs:119`); a zero seed throws. + - `Zone` seeds from the zone name: `CombatSeed` (`Zone.cs:162`), with `DropSeed` mixing in the run's seed (`:163`). + - Probe: `Zone.Update` was deterministic (identical traces) when belt updates ran on `Task.Run`; + no `Task.Run` remains in `Zone.cs`. ### 2.3 Agents @@ -243,7 +251,7 @@ Continue and death. There is one instance per run. It holds no Unity type. - `GameplaySettings`, `ZoneGenerationSettings`, `PlanetSettings`; - a `uint seed` for `ItemManager`; - `Action log`; - - for a new run, a caller-built `Galaxy` and `isTutorial`; + - for a new run, a caller-built `Galaxy` (`Galaxy.IsPrelude` says whether it is the prelude) and the staged start (`RunStart.Stage`); - `dt` per step; - commands from either lowering; - `SavedActionBarBinding[]` at save, owned by the Unity action bar (the playground @@ -305,10 +313,8 @@ Continue and death. There is one instance per run. It holds no Unity type. - `ActionGameManager`: bodies of `SaveRun`, `EnterWormhole`, `PopulateLevel`'s simulation half, `StartGame`, `Dock`, `DoDock`'s state half, `Undock`'s checks, `TowShip`, `Die`'s clear, and `IntroCutscene` (entirely); - - statics `CurrentGalaxy` and `IsTutorial`; - - `MainMenu.cs:104-105,112`; - - `ZoneRenderer.cs:222-231`'s wormhole construction; - - `ItemManager.cs:20`'s clock seed. + - statics `CurrentGalaxy` and `PendingScenario`; + - `ZoneRenderer.cs:222-231`'s wormhole construction. All of these go in the same cut that adds `Run`. None survives as a fallback. @@ -318,12 +324,12 @@ Unity dependencies, each injected or cut: |---|---|---| | `Time.deltaTime` | `:1218` | injected: `Run.Step(float dt)` | | `Time.time` | `IntroCutscene`, `Die` post-fx | cutscene deleted; post-fx stays in Unity, on `Died` | -| `UnityEngine.Random` | `MainMenu.cs:125,148` (background noise), `EntityInstance.cs:413-428` (loot) | noise stays in the menu as a galaxy-generation input; loot roll moves to `Zone` on `ItemManager.Random` (Cut 2); effect spread jitter (`ProjectileManager.cs:20-26`) stays visual | -| Clock RNG | `ItemManager.cs:20` | cut; the seed is a constructor argument, and Unity passes a clock-derived one | +| `UnityEngine.Random` | `EntityInstance.cs:413-428` (loot) | galaxy noise already draws from `GalaxyStage.Seed`; loot roll moves to `Zone` on `ItemManager.Random` (Cut 2); effect spread jitter (`ProjectileManager.cs:20-26`) stays visual | +| Clock RNG | `Scenario.Seed` of 0 (`GalaxyStage.SeedFrom`) | the clock seeds only the galaxy seed; every item stream derives from it through `RunStart.ItemSeed` | | Coroutines | `IntroCutscene` | deleted (dead) | | UniRx | `Observable.NextFrame` in the menu, `EveryUpdate` in `Die` | stay in Unity; `Run` uses C# events, and `Entity.Death` (UniRx, headless-compiled) is what `Run` subscribes to | | `Debug.Log` | `:264`, `:657`, `MainMenu` | injected `Action` | -| Scene load | `MainMenu` | stays; the handoff static becomes `ActionGameManager.NewRun : (Galaxy, bool)?`, command-only, consumed once in `Start`; null means Continue | +| Scene load | `MainMenu` | stays; the handoff static is `ActionGameManager.PendingScenario`, command-only, consumed once by `StartGame`; null means Continue | | MonoBehaviour state | `_currentEntity`, `DockedEntity`, `DockingBay`, `TowingStation`, `Zone`, `ItemManager` | projections of `Run` | | Barrel transforms | `EntityInstance.cs:516` -> `HardpointTransforms` | `HardpointTransforms` deleted (Cut 2); the arc is item rotation plus `FiringArc` (fork A); barrels and `ArticulationPoint` are presentation only, `GetBarrel` | | `Physics.*` hit queries | `Projectile`, `GuidedProjectile`, `Laser`, `Lightning`, `HullCollider` subjects | deleted from damage paths; `FireControl` rolls (Cut 2) | @@ -374,7 +380,7 @@ This is subtraction first, then one new file. - Deletes and moves: - `ActionGameManager.cs`: - `IntroCutscene` `:772-799` (dead). - - Statics `CurrentGalaxy` and `IsTutorial` (`:96-97`). + - Statics `CurrentGalaxy` and `PendingScenario` (`:108,113`). - `SaveRun` body `:243-248` becomes `Run?.Save(actionBar)`. Quit (`:236`) calls it. - `EnterWormhole` `:615-637` and the detect loop `:312-316` become `Run.TryEnterWormhole()`. `WarpArrived` drives `SectorMap.QueueZoneReveal`. @@ -393,14 +399,13 @@ This is subtraction first, then one new file. `Run.Died`. - `:264` constructs no `ItemManager`. - `Update` `:1218` becomes `Run.Step(Time.deltaTime)`. - - `MainMenu.cs`: - - Continue (`:102-107`) sets `ActionGameManager.NewRun = null` and loads the scene. - - New Game drops `:112` and sets `NewRun = (sector, tutorial)` at `:138,166`. + - `MainMenu`: already built. Continue (`ShowMain`) loads the scene with no + `PendingScenario`; `MainMenu.Launch` sets `PendingScenario` and clears nothing. - `SectorMap.cs:114-310` reads `ActionGameManager.Instance.Run.Galaxy`. - `InventoryPanel.cs:117-118` becomes `GameManager.Run.Board(ship)`. - `ZoneRenderer.cs:222-231` iterates `zone.Wormholes`. - - `ItemManager.cs:20`: the seed becomes a constructor argument. Call sites: 11 in - tests, 1 in `AetherDb`, and `Run`. + - `ItemManager`: the seed is already a constructor argument (`ItemManager.cs:35`); + `Run` supplies `RunStart.ItemSeed(galaxy, step)`. - Settings (fork S (a)): - `StartingHullName` and `WormholeDistanceRatio` move from `GameSettings.cs:17,23` to `GameplaySettings` (`Settings.cs:155`). @@ -412,8 +417,8 @@ This is subtraction first, then one new file. `GalaxyZone.AdjacentZones` with the rule from `ZoneRenderer.cs:226-230`. Null galaxy zone gives an empty array. - New `Run.cs`: types and rules, no bodies here. - - `static Run New(CultCache, GameplaySettings, ZoneGenerationSettings, PlanetSettings, Galaxy, bool isTutorial, uint seed, Action log)` - 1. `RunSave.Clear`. + - `static Run New(CultCache, GameplaySettings, ZoneGenerationSettings, PlanetSettings, Galaxy, Scenario, Action log)` + 1. `RunSave.Replace` around steps 2-5 (the saved run goes only once the scenario has staged). 2. `ItemManager` over `RunSave.Lots`, seeded. 3. `EnterZone(Entrance)`. 4. Spawn the player ship per `:734-743`. @@ -446,7 +451,7 @@ This is subtraction first, then one new file. child; updates `Bay.DockedShip`. - `void Tow()`: the rule from `:891-911`. - `void Save(SavedActionBarBinding[] actionBar)` - - `RunSave.Capture(cache, Galaxy, Zone, Station ?? Pilot, isTutorial, actionBar)`, + - `RunSave.Capture(cache, Galaxy, Zone, Station ?? Pilot, actionBar, credits)`, then `Commit(…, ItemManager.Lots)`. - No-op when `Ended`. - Remembers `actionBar` for warp saves. @@ -461,7 +466,7 @@ This is subtraction first, then one new file. | Test | Asserts | Mutation that must kill it | |---|---|---| -| `NewRunSpawnsPilotInEntrance` | pilot is a `Ship` with `IsPlayerShip`, in `Zone.Entities`, `Zone.GalaxyZone == Galaxy.Entrance`; the run store is cleared of a prior `SavedGame` | `New` skips `RunSave.Clear`; spawn omits `Zones.Entities.Add` | +| `NewRunSpawnsPilotInEntrance` | pilot is a `Ship` with `IsPlayerShip`, in `Zone.Entities`, `Zone.GalaxyZone == Galaxy.Entrance`; the run store holds no prior `SavedGame` once the run has staged | `New` skips `RunSave.Replace`; spawn omits `Zones.Entities.Add` | | `WarpMovesPilotAndSaves` | stepping after `TryEnterWormhole` lands the pilot in the target zone, out of the old zone's entities, with `SavedGame.CurrentZone` equal to the target index after reopen | arrival skips `Save`; `EnterZone` leaves the pilot in the old zone | | `ContinueLandsDocked` | save while docked, reopen, `Continue`: `Station` is the saved orbital, `Pilot` is its player child | `Land` binds to the orbital itself | | `DeathEndsAndClears` | hull death clears every run record; `Step` throws; `Save` writes nothing | `Died` handler omits `Clear`; `Ended` not set | @@ -473,7 +478,7 @@ This is subtraction first, then one new file. - Unity batchmode has no `error CS`. - Negative greps: - `rg -n "RunSave\.(Clear|Commit|Capture)" Assets/Scripts --glob '!ServerShared/**'` is empty. - - `rg -n "CurrentGalaxy|IsTutorial\s*=" Assets/Scripts` is empty. + - `rg -n "CurrentGalaxy|PendingScenario" Assets/Scripts` matches only the `Run` lowering in `ActionGameManager` and `MainMenu`. - `rg -n "new Wormhole" Assets/Scripts` matches only `Zone.cs`. - `rg -n "new ItemManager\(" Assets/Scripts` matches only `Run.cs`. - `rg -n "ZoneGenerator\.GenerateZone|new Zone\(" Assets/Scripts --glob '!ServerShared/**'` is empty. @@ -1161,7 +1166,7 @@ Options as mapped before the ruling: - **Recommend (a).** **N. Is the scene handoff static acceptable?** Low-blocking. -- (a) `ActionGameManager.NewRun : (Galaxy, bool)?`, consumed once by `Start`. +- (a) `ActionGameManager.PendingScenario : Scenario`, consumed once by `StartGame` (built this way). - (b) `MainMenu` builds the whole `Run` on its generation thread. That moves zone generation's run-store upserts off the main thread, and the `CultCache` threading contract is not checked here. diff --git a/docs/item-provenance-cut.md b/docs/item-provenance-cut.md index 473ec76c2..a0ccd947f 100644 --- a/docs/item-provenance-cut.md +++ b/docs/item-provenance-cut.md @@ -166,9 +166,9 @@ Contradictions and corrections found in the Body: `LoadoutTests` fixture is not: `FirstAvailableProductInKeyOrderBuildsTheSlot` (`LoadoutTests.cs:289-312`) adds two same-maker Lamp products and reads `.Product`. 6. **`ItemManager` lives one scene load, and every run starts with a scene load.** It is - constructed in `ActionGameManager.Start` (`:264`). There is one scene, `ARPG`. New Game - and Continue both end in `SceneManager.LoadScene("ARPG")` (`MainMenu.cs:106,139,167`), and - no `DontDestroyOnLoad` exists. So a ledger held by `ItemManager` spans exactly one run. + constructed in `ActionGameManager.Start` (`:309`). There is one scene, `ARPG`. A scenario + launch and Continue both end in `SceneManager.LoadScene("ARPG")` (`MainMenu.EnterGame`, + `:287`), and no `DontDestroyOnLoad` guards the `ItemManager`. So a ledger held by `ItemManager` spans exactly one run. 7. **Aside, not this cut:** `CreateInstance(CraftedItemData, float)` mints a `CompoundCommodity` for a `ConsumableItemData` design (`ItemManager.cs:136-141`), while `TryActivateConsumable` casts to `ConsumableItem` (`Entity.cs:336`). This map keeps @@ -252,9 +252,11 @@ Not probed: CultCache Studio's rendering of the ledger (operator check); Unity c `ZoneGenerator`'s staged-upsert pattern (`ZoneGenerator.cs:99-108`) is not used for lots: the ledger is live simulation state, captured at commit like entities. - Lifecycle: the run begins with a scene load (§1.6), whose `Start` reads - `RunSave.Lots(CultCache)`. New Game has already cleared the run store (`MainMenu.cs:112`), - so it gets an empty ledger. Continue gets the stored one. Death clears the run store - (`ActionGameManager.cs:1090`); the next run reloads the scene. + `RunSave.Lots(CultCache)`. A scenario launch has `PendingScenario` set, so `Start` builds an + empty `ProvenanceLedger` instead (`ActionGameManager.cs:312`); the saved run's records stay + in the store until `RunSave.Replace` drops them once the new run has staged + (`SavedGame.cs:247`). Continue reads the stored ledger. Death and victory end in `EndRun`, + which calls `RunSave.Clear` (`ActionGameManager.cs:1224-1231`); the next run reloads the scene. **Branding.** - Owner: `ItemManager.Brand(CraftedItemInstance)` -> `(Faction Maker, FactionProductData Product)`. @@ -526,7 +528,7 @@ Subtraction, plus a data rewrite. worktrees. Operator-only checks after Cut C: -- New Game and fly through one zone. The starting ship's items show tier colour, and the +- New Game, pick a scenario, and fly through one zone. The starting ship's items show tier colour, and the properties panel shows Manufacturer, product name and flavour text for branded gear. - Dock and buy an item: its brand still shows in your cargo. - Kill an NPC and pick up loot: brand shown. diff --git a/docs/item-provenance-substrate.md b/docs/item-provenance-substrate.md index 0bc310942..956d79138 100644 --- a/docs/item-provenance-substrate.md +++ b/docs/item-provenance-substrate.md @@ -68,8 +68,7 @@ catalog, built a 196-zone sector galaxy from the authored `Settings.asset`, and `47189c8a`). The commented `HaulingControllerData` union (`Behaviors.cs:179`) is the same kind of residue. - **No recipe, blueprint or ingredient model exists.** "Factory", "fabricat", - "assembler", "blueprint", "recipe" and "refiner" appear in no live C# outside - `NIH/MIConvexHull`. + "assembler", "blueprint", "recipe" and "refiner" appear in no live C#. `ItemData.Manufacturer` readers: `PropertiesPanel.cs:371-372` (shows "Manufacturer", falling back to "GameCult"), `tools/AetherDb/Program.cs:54` (census), and the @@ -83,7 +82,7 @@ All crafted instances come from three `ItemManager` overloads: - `CreateInstance(CraftedItemData, float quality)` (`ItemManager.cs:126-142`) sets Quality and Durability, with no product and no ingredients. - `CreateInstance(CraftedItemData)` (`:144-160`) rolls a rarity tier with the - **time-seeded** `ItemManager.Random` (`:20`) and stores the tier's *discrete* + `ItemManager.Random` (`:22`; seeded per run from the galaxy seed by `RunStart.ItemSeed`) and stores the tier's *discrete* Quality. - `CreateInstance(FactionProductData)` (`:164-187`) calls the previous overload, sets `Product`, and draws a gaussian `RoleFill` per design role. Since no role is @@ -130,9 +129,12 @@ unexecuted stubs. `TradeMenu.Inventory = entity.CargoBays.First()` (`ActionGameManager.cs:827-829`). - **Zones generate lazily on first entry** (`ActionGameManager.cs:643-652`, `PackedContents ??=`) from a deterministic zone seed - (`ZoneGenerator.cs:47`: name hash xor position hash). Item *selection* follows that - seed, but item *quality* comes from the time-seeded `ItemManager.Random`. A zone is - never regenerated within a run. New Game clears the run store (`MainMenu.cs:111`). + (`ZoneGenerator.cs:52`: name hash xor position hash). Item *selection* follows that + seed, but item *quality* comes from `ItemManager.Random`, a stream seeded per run from + the galaxy seed (`RunStart.SeedItems`, steps `ArenaStep`, `StageStep`, `ContinueStep`) + and drawn in the order zones are entered. A zone is never regenerated within a run. A + new run does not clear the run store up front: `RunSave.Replace` drops the old run's + records once the new run has staged (`SavedGame.cs:247`). - Each station carries hull, hardpoint gear, one docking bay, cargo bay, capacitor and stock, all embedded by value. No station equips a factory; none can, because factory designs have no product (§1). @@ -150,8 +152,9 @@ unexecuted stubs. `FactionProductData`, `PersonalityAttribute`, `NameFile`, `InputLayout`, `Loadout`. - Run (`:10`): `OrbitData`, `BodyData`, `SavedZone`, `SavedGame`. Written only by `RunSave.Commit`, which does one commit, keys zones `savedzone-{i}` and removes stale - zones (`SavedGame.cs:96-111`). `RunSave.Clear` removes every run-typed record - (`:114-124`). The single-file store writes its whole view on commit. + zones (`SavedGame.cs:216`). `RunSave.Clear` removes every run-typed + record (`:242`); `RunSave.Replace` (`:247`) does the same for a new run, but only once + the new run has staged. The single-file store writes its whole view on commit. - Player (`:11`): `PlayerSettings`. - **Every item instance is a value** embedded in `EntityPack` (hull, equipment, bays, cargo contents; `EntitySerializer.cs:179-196`), inside `SavedZone.Contents`. No @@ -237,7 +240,7 @@ Every stat and wear reader goes through the instance: "F" marks a fork (§9). "D" marks a recorded default. -| Kind | Named by | Mint | Transfer / loot / sell | Consume | Zone unload / save | New Game / death | Decides | +| Kind | Named by | Mint | Transfer / loot / sell | Consume | Zone unload / save | New run / death | Decides | |---|---|---|---|---|---|---|---| | **Lot** (provenance node) | run-scoped `LotId` (F1) | synthesis, at the mint site's call (F3) | never moves; instances point at it (D) | synthesized inputs are consumed at synthesis and have no instance (D) | kept while reachable from any instance, route or station; GC on `RunSave.Commit` (D, from the orphan-SavedZone scar) | cleared with the run store (D) | the synthesizer, one function in `ServerShared` | | **Lot properties** (mocked quality per role) | on the lot (F4) | rolled once at synthesis from factory quality and input qualities, seeded by lot id (F4) | immutable | n/a | with the lot | with the lot | synthesizer; stat readers only read | @@ -301,7 +304,7 @@ synthesized?** Blocks station identity, routes, stock and loot provenance. pirated freighter's cargo should come from a station the player can fly to. The skeleton is about 200 stations, small next to 16k instances. It demotes `ZoneGenerator`'s station count and faction choice to reading the roster. It also - moves item quality from the time-seeded `ItemManager.Random` to seeded synthesis, + moves item quality from the per-run `ItemManager.Random` stream, which depends on the order zones are entered, to lot-seeded synthesis, which makes the chain regenerable. - Sub-default: stations keep no identity outside a run. Zones never regenerate within one. diff --git a/docs/merge-to-master-checklist.md b/docs/merge-to-master-checklist.md index d5d70e17b..664f464b2 100644 --- a/docs/merge-to-master-checklist.md +++ b/docs/merge-to-master-checklist.md @@ -33,7 +33,7 @@ Compiled 2026-09-29 by Eyes from the maps on the branch. Pointers are `doc:line` ### 2b. Fresh launch (no `run.cc`, no `player.cc`) 3. **Launch to main menu.** Expect no Addressables errors, and the Groups window shows `Assets/Content` under `Default Local Group` (`addressables-cut.md:301`). `player.cc` appears and Continue is disabled (`cultcache-migration-cut.md:2746`). Proves: Addressables Cut 1, CultCache cutover. The 09-17 smoke covered the last two on the old tree; this is a cheap recheck on the new schema. -4. **New Game (tutorial).** Expect the galaxy generates and the start ship is the Longinus (`settings-globals-cut.md:498`, an expectation, not a recorded check for this stack). Expect a Zenith station with a docking bay in the entrance zone every time (`locomotion-cut.md:375`). Proves: locomotion Cut 1 station rule. +4. **New Game, then a scenario.** New Game opens the scenario picker (`MainMenu.ShowScenarios`); a development build lists modes (Terminus (Demo)), development (Main Galaxy) and test arenas, a release build lists only the modes. Pick Terminus (Demo). Expect the galaxy generates and the start ship is the Longinus (`settings-globals-cut.md:498`, an expectation, not a recorded check for this stack). Expect a Zenith station with a docking bay in the entrance zone every time, because the scenario declares `EntranceStation` (`locomotion-cut.md:375`). Proves: locomotion Cut 1 station rule. 5. **Addressables, "Use Asset Database".** Ships, turret and Zenith spawn; thruster and aether-drive particles show; fire an instant weapon (Autocannon) and a charged one (ChargeBlast SG); action bar icons show (`addressables-cut.md:362-366`). Proves: Addressables Cut 2. ### 2c. Flight, power and economy diff --git a/docs/mining-cut-refresh.md b/docs/mining-cut-refresh.md index a96d10b40..8a5fdcd9e 100644 --- a/docs/mining-cut-refresh.md +++ b/docs/mining-cut-refresh.md @@ -63,8 +63,9 @@ rows are kept for the combined test count. The three file sets are disjoint. I checked with `git diff --name-only` over each branch's own range, and none of the three pairs shares a file. So each anchored line is byte-identical in the merged tree. - **Tests ran on Yggdrasil, against synthetic merges** (section 0). CultLib `45c2f40` and CultMath `6d5e209` are - the pins in `Directory.Build.props`. The two LFS files the tests read (`GameData/Aetheria.cc`, - `Assets/Resources/Settings.asset`) were staged beside the job, because the verify mirror carries no LFS. + the pins in `Directory.Build.props`. The LFS files the tests read were staged beside the job, because the verify mirror carries no LFS. The Mining + cut tests needed `GameData/Aetheria.cc` and `Assets/Resources/Settings.asset`; `SubstanceCleanBreakTests` needs 97 and the whole suite needs more + (see the LFS staging set under Verification). - **Catalog facts** come from a probe that opens the merged tree's `GameData/Aetheria.cc` through `AetheriaStores.Open` (section 0). @@ -289,7 +290,7 @@ Every mining question is ruled. - Mark the `:396-412` table as history, anchored at `8bd25f6f`. - **Verification:** - Yggdrasil, the same job that section 0 ran: - `ygg-verify.sh dotnet ''`. + `ygg-verify.sh dotnet ''`. Both roots are mandatory (shared precondition). - The job mounts the Yggdrasil mirrors read-only with `DOCKER_ARGS="-v /home/gamecultadmin/eureka-verify/repos:/repos:ro -v /home/gamecultadmin/eureka-verify/lfs-aetheria:/lfs:ro"`. @@ -298,8 +299,16 @@ Every mining question is ruled. Rule pinned: fire control and mining compose without a behaviour change on either side. Every pre-existing test passes unchanged. - The verify mirror has no LFS (the push from `F:\Projects\Aetheria` fails in the LFS pre-push hook on an - `ssh:` remote). Push from a `--shared --no-checkout` clone, and mount the two LFS blobs. This is recorded + `ssh:` remote). Push from a `--shared --no-checkout` clone, and mount the LFS blobs. This is recorded so the next Hands does not rediscover it. + - LFS staging set. `SubstanceCleanBreakTests` fails loudly on any LFS pointer it scans, so the job must restore + every LFS-tracked file under `Assets/`, `Packages/`, `ProjectSettings/`, `GameData/*.cc` and `tests/fixtures/mods/*.cc` that is not a + binary-media extension (the test's `BinaryExtensions` denylist): 99 files at `83e6957de`, 96 `*.asset` and 3 + `*.cc` (`GameData/Aetheria.cc`, `GameData/Mods/aetheria.nakovalnya/ship.cc`, `tests/fixtures/mods/aetheria.wren/ship.cc`), + which includes `ProjectSettings/ProjectSettings.asset` and `Assets/Resources/Settings.asset`. Derive the list from + the merged tree instead of hand-copying it: + `git ls-files Assets Packages ProjectSettings 'GameData/*.cc' 'tests/fixtures/mods/*.cc' | git check-attr --stdin filter | grep 'lfs$' | sed 's/: filter: lfs//' | grep -viE '\.(png|jpg|jpeg|tga|tif|tiff|psd|bmp|gif|exr|hdr|dds|wav|mp3|ogg|mp4|fbx|glb|blend|ttf|otf|dll|so|pdb|msgpack|zip|bank)$'`, + then copy each path from the `/lfs` mount over the checkout. That set (99: the 97 the sbsar guards read plus the two mod `ship.cc` files the Nakovalnya and Wren tests open) makes `SubstanceCleanBreakTests` green and nothing more: staging only two files turns it red. For a fully green suite also stage `GameData/Mods/*/ship.glb` and `tests/fixtures/mods/*/ship.glb` (the catalog excludes a package with an invalid GLB header, failing about 520 tests) and the LFS `.ttf`/`.otf` fonts `CreditsTests.FontCreditsShowWhatTheFontsThemselvesEmbed` reads. - Unity batchmode compile of the merged tree (Self, in a worktree, never with the operator's editor open on the main tree). This is the Cut 1 renderer compile the map still owes. - Operator: fly through a belt (the Cut 1 check the map still owes). Rocks orbit smoothly, and the minimap diff --git a/docs/mining-cut.md b/docs/mining-cut.md index 7c5be8297..ce23094dc 100644 --- a/docs/mining-cut.md +++ b/docs/mining-cut.md @@ -301,7 +301,7 @@ resources **(probe: 8 belts, 0 authored)**. - A: Composition is derived: `Comp_c(o) = Abundance_o × exp(Variance × g(hash(belt key, index, o)))`, normalized, with `g ∈ [-1, 1]`. Nothing is stored. Existing saves work, and key 4 is retired. - B: `ZoneGenerator` writes `BodyData.Resources` per belt at generation, and the chunk jitter is derived. Belts in - runs started before Cut 5 have empty compositions until New Game. + runs started before Cut 5 have empty compositions until a new run. - C: Per-belt only, with no per-chunk variation. - **Recommended: A.** It has one owner (the catalog) and nothing to migrate. It follows the same "derived, never stored" spirit as branding. The operator's wording ("the chunk's composition") argues against C. If B is chosen, diff --git a/docs/moddable-ship-authoring.md b/docs/moddable-ship-authoring.md index 81871b2dc..057b7d511 100644 --- a/docs/moddable-ship-authoring.md +++ b/docs/moddable-ship-authoring.md @@ -216,7 +216,12 @@ a radiator, `weapon-mount` for an energy, ballistic or launcher hardpoint. An internal hardpoint (reactor, sensors, shield and the rest) has no anchor, and an anchor taking its id is refused. A thruster's or radiator's anchor node is a mesh: the thruster's is not rendered and is the surface its exhaust emits from, -the radiator's is rendered. A weapon mount is a point, and each one needs at +the radiator's is rendered. A directional thruster's emitter is one-sided: the +exhaust is born along each triangle's normal, so every normal must face the way +the hardpoint's Rotation faces (opposite the push), and a closed box, which also +fires along the push, is refused by Compose and `validate` naming the anchor. In +the Blender kit's frame a hull source's emit mesh is cut to the side facing its +anchor's yaw. A ring thruster would be its own class with its own rule. A weapon mount is a point, and each one needs at least one `weapon-muzzle` anchor whose `ParentId` is the weapon's mount id. `articulation` is reserved for pivots and is never a mount; no pivot is planned until pivots move onto `HullData`. `ShipModPlan` then maps the diff --git a/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md b/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md index 42f0ee20c..87a1bb7c9 100644 --- a/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md +++ b/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md @@ -390,7 +390,8 @@ Battlecode, Halite, CodinGame, BWAPI/SSCAIT/AIIDE/CIG, SC2 AI Arena, Lux, CodeCl - **The Colosseum follow-up.** `aetheria-release:follow_up:colosseum-npc-lab` (in force; owner "Aetheria Agents and the headless simulation") names its foundations: - an observation and action seam (agents hold live `Ship`, `Zone` and `ItemManager` references); - - seeding `ItemManager.Random` and the MIConvexHull randoms; + - seeding for tournament reproducibility: `ItemManager.Random` already takes the run's seed + (`RunStart.ItemSeed`), and no MIConvexHull source remains in the repo; - a replay recorder; - a headless tournament runner on Yggdrasil with ratings; - a primitive vocabulary; diff --git a/docs/settings-globals-cut.md b/docs/settings-globals-cut.md index b031ba4bf..f1b2e0582 100644 --- a/docs/settings-globals-cut.md +++ b/docs/settings-globals-cut.md @@ -495,8 +495,9 @@ landed type differs from it by the one attribute. (the helper) [2 now]. - `rg -n "ScriptableObject" Assets/Scripts/ServerShared` must stay 0. - operator: - - Play smoke: main menu, then New Game (tutorial). The tutorial galaxy generates, - and the starting ship is LonginusX. + - Play smoke: main menu, then New Game, then the Tutorial Galaxy scenario (listed under + development, in editor and development builds). The prelude galaxy generates, and the + starting ship is `Settings.StartingHullName` (`Longinus`). - In a station trade menu and the properties panel, item names show tier colours: Legendary orange, Uncommon green. None is black. - The inventory shows armour and durability gradients, and hit flashes use the diff --git a/docs/tutorial-script-sketch.md b/docs/tutorial-script-sketch.md index 7e9233988..3fcbbebb6 100644 --- a/docs/tutorial-script-sketch.md +++ b/docs/tutorial-script-sketch.md @@ -16,7 +16,7 @@ Status: sketch for the operator to react to. Nothing here is built or canon. ## Shape -One contained tutorial run in a small prelude galaxy (`IsTutorial`, +One contained tutorial run in a small prelude galaxy (`Galaxy.IsPrelude`, `TutorialGenerationSettings`). The player is a newly incorporated subsidiary of the protagonist faction. Threefra, a debt-born assessor with opinions, walks them through a "qualification module" whose checklist is theatre. The real test is how the player diff --git a/native/aetherlight/Cargo.lock b/native/aetherlight/Cargo.lock new file mode 100644 index 000000000..494df4f1d --- /dev/null +++ b/native/aetherlight/Cargo.lock @@ -0,0 +1,430 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aetherlight" +version = "0.1.0" +dependencies = [ + "rmp-serde", + "serde", + "serde_json", + "sha2", + "thiserror", + "unicode-normalization", + "unicode-properties", + "uuid", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "uuid" +version = "1.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cefc03fd367c0c6d4305de1b312cf00248c4114f4a0418ce6a6af769e3b0bd9" +dependencies = [ + "getrandom", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/native/aetherlight/Cargo.toml b/native/aetherlight/Cargo.toml new file mode 100644 index 000000000..49c9a5965 --- /dev/null +++ b/native/aetherlight/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "aetherlight" +version = "0.1.0" +edition = "2024" +license = "MIT" +publish = false + +# Its own workspace: the crate builds on its own, outside any parent manifest. +[workspace] + +[dependencies] +rmp-serde = "1.3" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +thiserror = "2" +unicode-normalization = "0.1.25" +unicode-properties = "0.1.4" +uuid = { version = "1", features = ["serde"] } + +[dev-dependencies] +# Test fixtures draw random ids; no shipped path does. +uuid = { version = "1", features = ["v4"] } diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md new file mode 100644 index 000000000..d56b93a69 --- /dev/null +++ b/native/aetherlight/PROVENANCE.md @@ -0,0 +1,628 @@ +# Aetherlight provenance + +Aetherlight is a fork of the synchronous world kernel of Ghostlight. + +- Upstream: `GameCult/Ghostlight`, `crates/ghostlight/` +- Commit: `c43eb54962ed4a09cc737ecac73a16b0d7ce62b4` (origin/main) +- Taken: 2026-11-19 +- Authority: cut `aetherlight-fork-import` r1 of campaign `aetheria-release`; + rulings `aetherlight-narrative-state-owner` and `dialogue-is-world-action`. + +Every file below was copied as a raw git blob (`git show`), never `git archive`. +The blobs are LF, as upstream. A Windows checkout with `core.autocrlf` turns the +`.rs` files and the two text fixtures into CRLF; rustc, the fixture readers +(`lines()`, `trim()`) and the golden test absorb that, so no `.gitattributes` is +kept (a first commit had one; its stated reason did not hold). The recorded-world +fixture (removed in AL2a) was binary and no newline rule touched it. Line ranges are in the c43eb54 file. + +## Taken + +| c43eb54 path (under `crates/ghostlight/`) | Here | Range | Edits | +| --- | --- | --- | --- | +| `src/lib.rs` | `src/lib.rs` | all | E1-E5, E10-E12 | +| `src/action.rs` | `src/action.rs` | all | E11, E12 | +| `src/clock.rs` | `src/clock.rs` | all | none | +| `src/journal.rs` | `src/journal.rs` | all | E12 | +| `src/grammar.rs` | `src/grammar.rs` | all | none | +| `src/grammar/tests.rs` | `src/grammar/tests.rs` | all | E12 | +| `src/import_key_tests.rs` | `src/import_key_tests.rs` | all | E12 | +| `src/patch.rs` | `src/patch.rs` | 1-6059 and 7906-9606 (dropped 6060-7905: the patch tool catalog, `PATCH_TOOLS`, `patch_tools()`, the `field_example` helpers, `mod catalog_tests`) | E6, E7, E12 | +| `Cargo.lock` | `Cargo.lock` | all | pruned by cargo to the dependencies below | + +`Cargo.toml` is new: package `aetherlight`, its own `[workspace]`, no features, +dependencies rmp-serde, serde, serde_json, sha2, thiserror, unicode-normalization, +unicode-properties, uuid (serde only); dev uuid with v4 (AL3a). + +## Edits + +- E1. `lib.rs`: dropped the `mod` lines and every `pub`/`pub(crate) use` of + aetheria, consumer, controllers, elaboration, local_inference (with its + `cfg(feature = "test-support")` re-export), mailbox, sdk_inference, table, + tool_schema, vault, verse. +- E2. `lib.rs` crate docs: retitled to Aetherlight with a pointer to this file; + the `compile_fail` doc-tests name `aetherlight::` instead of `ghostlight::`. + The sealing prose is kept. +- E3. `lib.rs`: `#![allow(dead_code)]`. The kernel has no entry point until AL4 + adds the ABI; AL4 removes the attribute. +- E4. `lib.rs`: imports that only dropped code used are removed + (`cover::{CellId, Constituent, Resolution}`), or moved under `#[cfg(test)]` + because only tests use them (`patch::{Bounds, Declaration, EntityDeclaration, + SubjectDeclaration}`). +- E5. `lib.rs`: `let mut` removed from the closures `confine_subject` and + `confine_place` (unused-mut in the non-test build). +- E6. `patch.rs`: deleted `use super::tool_schema;`, + `use codex_connector::CodexToolDefinition;` and `use serde_json::{Value, json};` + (only the dropped catalog used the last one); `let mut` removed from the + `controller_id` closure. +- E7. `patch.rs`: lines 6060-7905 dropped as above. +- E8. `lens.rs`: deleted test `every_lead_names_a_patch_tool` and its + `use crate::patch::PATCH_TOOLS;`, which read the dropped catalog. +- E9. `lens.rs`: the doc comment on `leads_with` says "patch tool names" instead + of naming `PATCH_TOOLS`. +- E10. `lib.rs` crate docs describe the fork as it is (no runner, no ports, no + controllers); the compile_fail doc-tests keep no error code (stable rustdoc does + not check one) and the two that named items absent from the fork + (`fixture_controller_opportunities`, `fixture_inference_output`) are deleted. + The `VerifiedPrincipalEvidence` doc no longer links `WorldMailbox`/`SeedPort` + and says nothing here enforces `valid_until`; the ABI must (AL4). +- E11. New tests, not upstream, each killing a mutant that survived upstream's 810 + tests: `action::tests::holding_exactly_the_threshold_satisfies_holds`, + `clock_tests::committed_requires_the_named_counterparty`, + `clock_tests::committed_requires_the_named_kind`, + `soul_knowledge_tests::a_telling_by_a_speaker_outside_its_audience_does_not_apply`. + +- E12. Cut AL2a deletes the model-guidance lanes; see the section below. It + supersedes E4's `cover` import, E8 and E9 (`lens.rs` is gone), and `lib.rs`, + `patch.rs`, `journal.rs`, `action.rs`, `grammar/tests.rs` and + `import_key_tests.rs` lose the symbols and tests listed there. + +The `ghostlight.*` schema ids were renamed in AL3a (see the last section). The +golden replay AL2a removed is back as `fixtures/golden.digests` (AL3a). + +## Left behind + +| Upstream file | Why it is not here | +| --- | --- | +| `mailbox.rs` | the async port/mailbox lane around the kernel; AL4's ABI replaces it | +| `controllers.rs` | model decider lane; composes an invocation's speech text, which Aetheria's player and C# brains do themselves | +| `elaboration.rs` | model elaboration lane | +| `consumer.rs` | consumer patch admission over HTTP-shaped ports; speech only in its fixtures | +| `table.rs` | encodes actor calls as model tools | +| `vault.rs` | evidence source over a vault | +| `local_inference.rs`, `sdk_inference.rs` | model backends (tokio, reqwest, codex-connector) | +| `tool_schema.rs` | tool schemas for model calls | +| `aetheria.rs`, `aetheria/` | Ghostlight's Aetheria catalog reader; Aetheria content is read by Aetheria | +| `verse/` | one example world; its speech affordances are a pattern to copy into Aetheria content, not a kernel dependency | +| `tests/external_admission.rs` | the cross-crate proof that forged, serde-minted opportunities and ids are refused at the public surface; dropped with the consumer lane it drove. AL4 must carry an equivalent proof against the ABI's own surface | +| crates `ghostlight-persona-projection`, `ghostlight-verse`; `sidecar/` | outside the synchronous kernel | + +Speech as world action stays whole: affordance declarations with `carries_speech`, +preconditions, audience, effect slots and outcome bands, `Communicate` and +`Display`, `Knowledge` and `Told`, commitments (`patch.rs`); exercise, role +binding, preconditions, audience, band selection and lowering (`action.rs`); +`DecisionInvocation`, `DecisionEvent` and `ResolvedOp::Communicate` apply +(`lib.rs`); the `SpeakRenderPath` check (`grammar.rs`). + +## Dependency pin + +The crate no longer pins CultLib: `cultcache-rs` (Ghostlight's rev +`85f7024a35ea42cf9f0a0199a064526427150191`) left the manifest in AL3a with the +redb store it served. + +## Pulling a later Ghostlight fix + +By hand, against this file: read the upstream diff for the taken files, apply it +here, and record it in this file with its upstream commit and the files it +touched. A fix that lands in a left-behind file is not pulled. + +## Cut AL2a: the model-guidance lanes + +Authority: cut `aetherlight-cut-agency-a` r1 of campaign `aetheria-release`; +rulings `aetherlight-narrative-state-owner` and `dialogue-is-world-action`. +Deleted, with their c43eb54 homes: + +- Lens (`src/lens.rs`, 361 lines): `Lens`, `LensWeights`; the genesis input, + `WorldState`, snapshot and creation field `lens_weights`; + `CommandBody::SetLensWeights`; `WorldEffect::LensWeightsReplaced`; + `Mismatch::LensWeightsNeverDraw`; the draw-rule check in `verify_state_shape`. +- Cover and agency graph (`src/cover.rs`, 1105 lines): `Cover`, `Cell`, + `CoverBudget`, `derive_cover`, `AgencyGraph`; `WorldKernel::agency_graph` and + `fn agency_graph` (`lib.rs`); `CommandId::for_cell`, `for_cell_constituent`. +- Persona material (`lib.rs`, `patch.rs`): `PersonaMaterial`, `PersonaReadRef`, + `ComponentOp::SetPersonaMaterial` and `ResolvedOp::SetPersonaMaterial` with + resolution, apply and confinement arms, `WorldState.persona_material`, the + subject snapshot's `material`, `WorldPatch::sets_persona_of_existing_subject`. + The op set goes from 34 to 33. +- Brief: the `brief` string in `CreateWorld`, `CreateWorldIntent`, `WorldState`, + `WorldEffect::WorldCreated`, the snapshot and the shape checks. +- Elaborator lane: `SystemCapability::Elaborator`, `PatchAnswer`, + `CausalBoundary`, `BoundaryDigest` and `derive_boundaries`, `exact_boundary`, + `require_answer` (the `AnswerRequired` gate), `jurisdiction_deficit`, + `ground_covers`, `place_in`, `PatchGround::Jurisdiction`; `WorldScaleIntent`, + `WorldScaleIntentRef`, `JurisdictionKey`, `ScaleDeficitRow`, `qualifies`, + `derive_scale_deficit`, the subject snapshot's `qualified`, the snapshot's + `boundaries` and `scale_deficit`, `CreateWorld.scale_intent`, + `CreateWorldIntent.targets` and `jurisdictions`, `CreateJurisdictionIntent`, + `WorldState.scale_intent`; `CommandBody::AdmitPatch.answers` and + `WorldEffect::PatchAdmitted.answers`; `KernelError::AnswerRequired`, + `AnswerNotDerived`, `AnswerNotSatisfied`; `Mismatch::UnknownJurisdictionRoot` + and `ScaleWeightsExceedWhole`. `resolve_patch` loses its intent parameter. +- The golden replay `grammar::tests::existing_world_reopens_with_unchanged_digests` + and the recorded-world fixtures under `tests/fixtures`: removing state fields changed the state + shape, so Ghostlight's recorded world no longer decodes. AL4 adds + Aetherlight's own golden. + +Behaviour with the gate gone: `require_play_active` keeps the one rule +`require_answer` also held (`Play` authors nothing in Draft) and states the other +as a plain rule: in Active, declaring (new structure or evidence) is `Play`'s act +alone, and the owner is refused. A confined author's only remaining check is +`confine_to_ground`, which now serves the consumer ground alone. + +AL4's ABI must route the host through typed commands (the sim reports events, +scripts propose), never through owner declarations in Active: under +`aetherlight-narrative-state-owner` an owner declaring in Active would be a second +door beside that path. + +Kept untouched for AL2b: controllers and `ControllerMode`, consumers +(`ConsumerId`, `SystemCapability::Consumer`, `PatchGround::Consumer`, +`bound_to_consumer`), the draft phase and approvals, `VerifiedPrincipalEvidence`. +(Opportunities, scope digests, the attention order, `ExerciseDecision` and +`DeclineDecision` went in AL2b-1, below.) + +## Leave-set vocabulary still compiled (AL2b's and AL4's triage list) + +`#![allow(dead_code)]` still hides the dead code of a crate with no entry point. +What the cut deletes is gone; what remains is part B's: + +- Authenticated-caller vocabulary: `AuthenticatedCaller::fixture`, + `verified_principal` and `verified_play`; id helpers `text` and `nil_for_test`; + `commits_for_test`; grammar `verbs`. AL4's ABI + decides which of these it needs. +- Patch ingress: `decode_patch`, `check_patch_caps`, `PatchDecodeError` and + `MAX_PATCH_BYTES`, `MAX_PATCH_DECLARATIONS`, `MAX_PATCH_OPERATIONS`, + `MAX_PATCH_EVIDENCE`; the consumer ingress and elaboration lane read them, and + nothing here does. They stay: AL4's ABI decides whether it decodes patches + itself. +- Mailbox and vault comments (`WorldMailbox`, `vault:` evidence strings). + +Reproduce the list with `RUSTFLAGS=--force-warn dead_code cargo test --lib --no-run`: +under test configuration the items nothing exercises show up. + +## Cut AL2b-1: Play's Act replaces opportunity-based exercise + +Base `bf92a054f`. An act is one command, `Act { actor, invocation }`, admitted for +`System(Play)` in Active only, and one effect, `Acted { invocation, event }`. +`require_granted(state, actor, affordance)` is the only constructor of +`GrantedAffordance`: the actor's `affordance_grants` entry holds the affordance +and the catalog defines it, otherwise `AffordanceDenied`. `Retire` removes a +subject's grants, so a retired actor is refused by that check alone. +`action::exercise` takes the actor in place of an opportunity; its pipeline is +unchanged and the band draw keeps `command_id` as its only per-command term. +`DecisionEvent` carries `actor`, not `scope` and `controller_id`. `STATE_SCHEMA` +and `COMMIT_SCHEMA` moved to `consumer.v8`. + +Deleted, with their `bf92a054f` locations in `lib.rs`: + +- `ScopeDigest`, `ScopePreimage`, `DecisionOpportunity` (459-506) and + `scope_digest`, `exact_opportunity`, `derive_opportunities`, + `order_opportunities`, `pressure_total`, `attention_debt`, `granted_entries` + (3841-4034). `WorldSnapshot.opportunities`, `WorldState.last_opportunity_at` and + the attention-stamp shape check in `journal.rs` (730-738). +- `CommandBody::ExerciseDecision` and `DeclineDecision`, `WorldEffect:: + DecisionExercised` and `DecisionDeclined`, their `reduce` and `apply_effect` + arms, and `KernelError::OpportunityMismatch`, `ScopeChanged`, + `ControllerMismatch`. +- The operator log: `operator_log`, `OperatorEvent`, `BoundRole` (3518-3579, + 1109-1134), and the kernel readers `opportunities`, `clock_advances`, + `controller_receipt`, `controller_decline_receipt`. +- `WorldJournal::commits` and `FictionalMinutes::since`, dead once the readers + above went. + +Kept: the whole dialogue lane (`carries_speech`, `Communicate`, `Display`, the +kernel Speak entry, the grammar, `preconditions_hold`). `DecisionScope` stays the +grant key and `ControllerAssignment` stays; the owner's `AdmitPatch` and +`AdvanceTime` doors and `SystemCapability::Clock` stay. + +AL2b-2a (below) took the writers; AL2b-2b still owns the controller half under +`aetherlight-play-only-after-genesis`: `ControllerAssignment` (which until then +holds only the `Retired` flag and unread identity data), `NewController`, +`ControllerId`, `ControllerMode`, `DecisionScope` as the grant key, +`SubjectState.retired`, `Mismatch::UnadmittedController`, the `admits_human` +rename and the snapshot's controller fields. + +`last_acted_at` and `minted_at` in `snapshot` still read `state.events` (by +`event.actor`). AL3 needs keyed rows instead of a scan; that is the AL3 cut's. + +## Cut AL2b-2a: after genesis only Play writes + +Base `f51275c61`. A world is born Active: the genesis commit is the owner's +only act, and `WorldState::empty` has no phase and no approvals. After it +`CallerId::Play` is the only caller any command body admits. `CallerId` is +`{ Principal, Play }`; `Principal` survives as the genesis creator (and as the +refused caller of every post-genesis body). One rule, `require_play`, decides it +at the top of `reduce` and again at the top of `apply_effect`, so it holds on +commit and at replay; the journal gains no caller rule. +`require_ruler` is `forbid_rulings_at_genesis`: genesis may not rule or mint, +Play may. A grant row exists if and only if the subject holds a verb; a subject +may be declared with none, and revoking the last verb removes the row. +`GrantsOutsideControl` is `GrantsToRetired`. `STATE_SCHEMA` and `COMMIT_SCHEMA` +moved to `consumer.v9`. + +Deleted, with their `f51275c61` locations in `lib.rs` unless noted: + +- The Clock and Consumer capabilities and `CallerId::Controller`: + `SystemCapability` (388-406), `AuthenticatedCaller::verified_controller` (433), + `require_system_capability`, `require_clock_caller`, `require_play_active`, + `require_owner` and `require_patch_author` (1456-1514, 3594-3625, 3989-4006), + and `apply_effect`'s capability table. +- The consumer lane: `ConsumerId` and its namespace (317-338), `PatchGround` + (408-419), `NewController::External`, `ControllerAssignment:: + ExternallyControlled`, `expected_caller`, `consumer()`, `bound_to_consumer`, + `candidate_places`, `confine_to_ground` (3628-3792), `operation_ground` + (3826-3987), and in `patch.rs` the mirror and human candidate sets, + `Mismatch::OutsideJurisdiction`, `RetiresAMirror`, `ControllerGrantMismatch`. +- The draft phase: `WorldPhase`, `WorldState.phase` and `draft_approvals`, + `CommandBody::ApproveDraft` and `ActivateWorld`, `WorldEffect::DraftApproved` + and `WorldActivated`, `required_approvers`, `KernelError::WrongPhase`, + `NotDraftApprover`, `DraftAlreadyApproved`, `MissingApprovals`, the snapshot's + `phase`, `draft_approvals` and `required_approvers`, `Mismatch::RetiresAnApprover`, + and the Draft-only shape clause in `journal.rs`. +- The never-mute rule and the controller/grant pairing: in `admit_resolved`, the + resolver, `Mismatch::WouldLeaveSubjectMute`, and the shape clauses in + `verify_state_shape` that required a grant row per controlled scope. +- `CommandId::derived`, whose only caller was `ConsumerId::of_name`. +- `VerifiedPrincipalEvidence` (106-146), `CreateWorldIntent` (366-376) and + `PrincipalCommandIntent` (521-529). The `valid_until` enforcement that + Ghostlight's mailbox did is no longer an AL4 obligation: the type that carried + it is gone. + +Kept: the whole dialogue lane, `decode_patch`, `check_patch_caps`, +`PatchDecodeError` and the `MAX_PATCH_*` constants (AL4's ABI decides whether +it decodes patches itself), the `ghostlight.*` schema namespaces (AL3 renames +them), `Retire`, `GrantAffordance` and `RevokeAffordance` as Play's patch +operations, and `#![allow(dead_code)]`. + +Nothing decides with a controller after this cut. `ControllerAssignment`, +`NewController::{Human, NarrativePersona, OperationalAgent}`, `ControllerId`, +`ControllerMode`, `DecisionScope` as the grant key, `validate_assignment`, +`Mismatch::UnadmittedController` and `admits_human` (the genesis predicate three +places read) stay compiled for AL2b-2b, which removes the controllers and +renames the predicate. + +`last_acted_at` and `minted_at` in `snapshot` still read `state.events`; the +count of code readers of `state.events` did not rise (idea +`cutspecs-1119.al3-needs-keyed-rows`). + +## Obligations this cut hands to AL4 + +- A cross-crate proof that forged opportunities and ids are refused, equivalent to + the dropped `tests/external_admission.rs`, against the ABI's surface. +- Removal of `#![allow(dead_code)]`. + +## AL2b-2b: controllers go, retirement on the subject + +The subject controller is gone: `ControllerAssignment`, `ControllerId`, +`ControllerMode`, `NewController`, `DecisionScope`, `SubjectDeclaration.controller`, +`Mismatch::UnadmittedController`, `validate_assignment`, the snapshot's controller +fields and `ControllerId::issue`. Retirement is `SubjectState.retired`, and +`is_retired` is its only statement. `affordance_grants` is keyed by `SubjectId`. +`admits_human` is `is_genesis`: it says what the from-nothing lane may build (the +kernel Speak entry and the first subjects), not who may be bound. The schema is +`consumer.v10`; v9 rows are refused at the schema gate, with no migration. + +Not this cut's, and kept: the channel controller (`ChannelRecord.controller`, +`SetController`, `resolve_controller`), which is dialogue +(`dialogue-is-world-action`). An earlier version of this file listed +`resolve_controller` and `controller_key` as AL2b-2b's; that was wrong. + +## Cut AL3a: the journal is in memory; ids are derived + +Authority: cut `aetherlight-journal-a` r1 of campaign `aetheria-release`; rulings +`aetherlight-narrative-state-owner`, `cultnet-scale-is-not-negotiable`, +`dialogue-is-world-action`. Base `09a1c3256` (spec base `39c50acfc`; no `native/` +change between them). + +Ids. `CommandEnvelope::id()` is the first 16 bytes of sha256 over +`aetherlight.command.v1`, the world id, the big-endian expected revision and the +named messagepack of caller and body. `CreateWorld::id()` is the same over +`aetherlight.create.v1` and the whole creation. `WorldId::of(creation id)` is the +same over `aetherlight.world.v1`; a genesis commit whose world id is not that is +refused at open. The `id` fields on `CreateWorld` and `CommandEnvelope`, +`CommandId::new`/`parse_uuid` and `WorldId::issue` are gone; `CommandId::issue` +is a test fixture. Retry identity went with them: `SubmitReceipt` collapsed into +`CommitReceipt`, and a resubmitted applied command is a `RevisionMismatch`. +`WorldCommit.committed_at` is gone: wall time is the C# store's `stored_at`. + +Journal. `WorldJournal { commits }` is the only record of a world. `export()` is +canonical named messagepack of `{ schema: aetherlight.journal.v1, commits }`; +`open(bytes)` decodes canonically and replays through `verify_history`, which +reads the revision-ordered slice and returns the head state it derives. There is +no state row, no expected world id, no health or ownership check and no +`verify_append`. `STATE_SCHEMA` and `COMMIT_SCHEMA` are +`aetherlight.world_state.v1` and `aetherlight.world_commit.v1`; any `ghostlight.*` +schema is refused at the schema gate and at the commit chain. + +Dependencies. chrono, cultcache-rs (and with it redb) and tempfile left the +manifest; uuid keeps `serde` in `[dependencies]` and `v4` only in +`[dev-dependencies]`, so no shipped path draws a random id (`cargo build --lib` +compiles without it). + +Not taken from the spec's text: the spec's negative pattern `id: CommandId` +matches the `command_id: CommandId` parameters of the band draw and derivation +(the per-command term the spec keeps); the doc comment said `synchronous`, which +`chrono` matches, and now says `single-threaded`. + +Host contracts (AL3a, from Soul's pass): + +- Two byte-equal creations share a `WorldId` and every id under it. A host that + wants distinct worlds salts each run or profile into the creation, for example + a run seed in the patch. +- Truncation and rollback open: a chain verifies as a prefix, so an export with + its tail dropped, or an older export, opens as a valid shorter world. The + holder of the bytes keeps the head (revision and state digest from `snapshot()` + at export time) and compares after `open`. AL5's C# store owns this. +- The band draw is grindable through the command id (it hashes the body, so the + text, a magnitude or the revision re-roll it). Only Play submits acts after + genesis and Play is trusted, so it is not an authority hole. + +## Cut AL3b: partitions are tracked documents, the state digest is a set digest + +Authority: cut `aetherlight-journal-b` r1 of campaign `aetheria-release`; rulings +`aetherlight-narrative-state-owner`, `cultnet-scale-is-not-negotiable`, +`terminus-clockwork-world`. Base `36d1d2507`. + +Tracked documents. Each partition of `WorldState` is a `Docs` (`docs.rs`): +a map whose every write method records the key's value as it stood when the +transaction first touched it. `finish` reports the keys whose value really +changed with their old value; `rollback` puts the touched keys back. The world's +own fields (id, owner, title, grammar, clock) are one `Tracked`. +`revision`, the accumulator, `state_digest` and `last_commit_digest` are the +chain head, outside every document. `submit` checks, reduces, opens a +transaction, applies to the live state, then folds the change set and seals the +commit; any error before the commit is sealed rolls the state back. There is no +candidate clone, and replay uses the same begin, apply, finish path, so opening +a world costs what its commits touched. + +Set digest. A document digest is sha256 over `u64be len(schema)`, schema, +`u64be len(key)`, key and the named messagepack of the value. The accumulator is +LtHash16 (Lewi et al. 2019): a document digest is expanded to 2048 bytes by +sha256(digest, block) for blocks 0 to 63, read as 1024 little-endian `u16` +lanes, and added (or subtracted) with wrapping. An updated document subtracts +its old digest and adds its new one. `state_digest` is `sha256:` plus the hex of +sha256 over `aetherlight.world_state.v2`, `u64be revision` and the lanes. It +depends on the set of documents alone, never on write order. + +Document names are `aetherlight..v1` for world, subject, entity, edge, +position, holdings, dependencies, fact, channel, knowledge, authority, +selection, redress, commitments, pressures, affordance and affordance_grants. +Keys are the id's uuid text; redress is keyed by the grievance name and knowledge +by `subject/fact`. These schema ids exist only as digest input. + +Schemas. `aetherlight.world_state.v2` and `aetherlight.world_commit.v2`. An +export whose commits carry v1 is refused. Every state digest, every commit +digest and the export hash moved; `fixtures/golden.digests` was regenerated and +reproduces on Linux. + +Events and knowledge. `WorldState` no longer holds events: an event lives once, +in the `Acted` effect of the commit that applied it. `snapshot` folds +`minted_at` and `last_acted_at` over the journal (still one O(history) pass; an +index is the follow-up's). `verify_state_shape` no longer judges events; replay +re-derives each through `action::exercise` in `apply_effect`. Knowledge is one +document per (subject, fact), so a subject's knowledge is a range over the key +and forgetting removes one key. `WorldState` has no `Serialize` or `Deserialize`: +only documents are encoded, one at a time. + +The change set is transient here. AL3c records it through the CultLib type. + +Timing. The ratio of 1600 to 100 persons is not gated by this cut: the world +reads a commit makes (`audience`, `derive_motion`, the snapshot) are still +O(world), and follow-up `aetherlight-read-indexes-timing-gate` owns the gate. What +this cut owns is the work it does for the digest, which +`golden_tests::digest_work_is_equal_at_100_and_1600` pins: document digests per +commit equal at both sizes and equal to Added + Removed + 2 x Updated. + +## Cut AL3b-2: partition read indexes, and the read-work gate + +Authority: cut `aetherlight-read-indexes` r1 of campaign `aetheria-release`; +rulings `aetherlight-narrative-state-owner`, `cultnet-scale-is-not-negotiable`, +`terminus-clockwork-world`. Base `576605c7b`. No digested byte moves: +`fixtures/golden.digests` is identical at every commit of the cut. + +Read indexes are derived state. A `Docs` may carry a `Projection`, a pure function +of one document's value (`DueAt`, `StandsAt`, `ChildOf`, `BySource`, `ByEndpoint`, +`ByController`, `ByIncumbent`, in `lib.rs` beside `world_state!`). The index is the +projection of the map as of the last `finish`, folded by `Docs::finish` from the +same changed-key list the digest folds. It is not a partition: not digested, not +encoded, ignored by equality, never exported. Opening a world builds it by replay, +since genesis and every replayed commit close through `finish`; there is no rebuild +path. `Docs::indexed(range)` returns (point, key) in order and is corrected by the +open log (a logged key's committed entries are dropped and its current points are +read from the map), so it is true mid-transaction; `rollback` never touches the +index because the index never saw the transaction. `Docs` no longer derefs to its +map: every read is an inherent method, so no reader can step around the counter. + +Read work is counted where reads are owned. In test builds `docs::rows_read()` is +the number of rows any `Docs` iterator has yielded plus the entries every `indexed` +call returned. `golden_tests::read_work_is_equal_at_100_and_1600` asserts that a +tick (two routines rolled, two obligations pressed) and a colocated speech read +the same number of rows at 100 and 1600 persons; `operation_reads_are_equal_at_100_and_1600` +does the same for the reads no submit shape reaches (a two-level `under_place`, a +`DischargeCommitment` among N pressure rows, one incumbent's `delegated_authority`, +a three-route `reachable`). Wall time is reported by `clockwork_commit_cost` and +asserted nowhere: it is noise at this scale. The gate world holds a route, a +`Reach::Place` channel and an institution with an office per place, because an +empty partition hides its scan. + +Eight scans became index reads: `under_place`, `audience` (colocated), the pressure +holders of `DischargeCommitment`, `scope_components`' routes and controls, +`delegated_authority`, `derive_motion`'s commitment walk and `reachable`'s outbound +edges. Each old scan is kept as a `cfg(test)` `*_by_scan` reference, and +`index_reads_equal_reference_scans` compares them over every revision of the golden +session, the populated worlds and forty clockwork commits. `indexes_are_derived` +rebuilds every index from its map after each commit, after reopen and after each +failed apply; `a_corrupted_index_is_detected` damages each index both ways. + +Reads that still scan, each with its owner: `snapshot` (the host's whole-world +projection, never on the commit path); the resolver's reads of the whole world in +`AdmitPatch` (`aetherlight-resolver-reads-world`). The +"Timing" paragraph of AL3b above is superseded: the gate it deferred is +`read_work_is_equal_at_100_and_1600`. + +## Cut AL3d-2: cross-partition views + +Authority: cut `aetherlight-cross-partition-views` r1 of campaign +`aetheria-release`; rulings `cultnet-scale-is-not-negotiable`, +`aetherlight-narrative-state-owner`, `terminus-clockwork-world`, +`dialogue-is-world-action`. Base `609b3ba5e`. No digested byte moves: +`fixtures/golden.digests` is identical at every commit of the cut. + +Two questions the clock asks are joins, so no one partition's index answers them +(a `Docs` projection is a pure function of one document). Whether a dependency is +failing joins `dependencies` with `edges`, `holdings` and `positions`, and two of +its arms are anti-joins (a resource not held, a subject not placed); whether a due +commitment is live joins `commitments` with `subjects.retired`. `views.rs` owns +both as `Views { live_due, failing }`: `live_due` is the subjects with a +commitment due at each minute, retired subjects excluded, and `failing` is the +(dependent, target) pairs failing a live dependent. + +`Views` is derived state, a sibling of the `Docs` indexes and not a projection: a +field of `WorldState` outside `partitions()`, so not digested, not encoded and +never exported; its `PartialEq` is always true, so equality is the documents'. +Its one writer is `Views::fold`, called by `WorldState::finish` before the logs +close, from the `changes()` of the six partitions the views join. A subject whose +commitments or retirement changed loses its due points and regains them if it is +live; a subject whose dependencies, holdings or retirement changed has its +failing rows re-judged; a changed route or placement re-judges its dependents, +which the new `DependsOn` index on `dependencies` names. Rollback never touches +it, because the view never saw the transaction; genesis and every replayed +commit close through the same `finish`, so open rebuilds it by replay. + +`derive_motion` reads the views only with clean logs (`debug_assert` on the six +partitions; both callers satisfy it: `reduce`, and `apply_effect`'s +`TimeAdvanced` arm before its first write). `DueAt` is deleted, so the due +question has one owner, and `motion_of` no longer walks every dependency row or +visits retired subjects' past-due routines. Motion is byte-identical. The old +walks are `cfg(test)`: `derive_motion_by_scan` over every promisor and every +dependency, and `Views::rebuild`. A test that forges partitions and then calls +`derive_motion` must close its writes through `finish`; a forged state that never +finishes has a stale view by design, the same contract as a `Docs` index. + +Oracles: `views_are_derived` (the view is the rebuild after every walked commit, +reopen and failed apply, over a scenario world that closes and reopens a route, +empties and refills a holding, removes a depended-on subject's position, releases +a dependency and retires a subject holding past-due routines and a failing +dependency), `view_reads_equal_reference_scans`, `a_corrupted_view_is_detected` +and a debug refusal of a read with an open log. View reads are counted where they +are owned, like `Docs` reads, so the gate sees them. + +The gate world grows with them: a dependency per person (to the previous live +person, so each stays satisfied), two failing (persons 0 and 1 on the last +place's grain), a forum per place, every routine checking that its person holds +their place's grain, every tenth person from the 35th retired, and the clock +moved one period so every routine is past due. The fixed-count pins on +`dependencies` and `redress` are gone; `read_work_is_equal_at_100_and_1600` now +asserts the population at scale. + +Soul pass 1 (fix batch). The fold's moved-targets arm reads the dependencies +`DependsOn` index through `Docs::indexed_unchanged`, which names the committed +entries of keys the open log did not change and does not walk the log; a changed +dependencies key is already re-judged whole, so a bulk commit (genesis, every +replayed commit at open) folds in rows proportional to what it changed +(`folding_a_bulk_commit_reads_rows_in_proportion_to_the_change`). The clean-log +check on a view read is an `assert!`, not a `debug_assert!`: six flag tests, held +in every build. `Release` now clears the pressure its dependency raised through +`set_pressure`; before, a pressed dependency's pressure row outlived it and the +export failed to reopen (pre-existing at `609b3ba5e`). A seeded differential test +(`views_equal_their_rebuild_and_the_scans_over_random_commands`) holds the views +to their rebuild and the motion to the scans over random bind, release, route, +holding, relocate, retire, tick, speech and refused commands, reopening every 50. + +Not defended by the gate, on purpose: a tick's cost is linear in the number of +failing dependencies, because each failing dependency presses a pressure row each +tick. The gate world pins failing at two, so growth in failing is not seen; that +cost is inherent to pressing and is not a read of the world. `open` of a large +world is superlinear in rows from readers outside this cut (the resolver's reads +of the whole world at genesis, owner `aetherlight-resolver-reads-world`); +`open_cost` reports it. + +## Cut AL3d-1: the patch lane reads what the patch touches + +Authority: cut `aetherlight-resolver-reads-world` r1 of campaign +`aetheria-release`; rulings `cultnet-scale-is-not-negotiable`, +`aetherlight-narrative-state-owner`, `terminus-clockwork-world`, +`dialogue-is-world-action`. Base `609b3ba5e`. No digested byte moves: +`fixtures/golden.digests` is identical at every commit of the cut. + +`resolve_patch` used to seed fifteen candidate maps by copying every partition, +collect every catalog kind and every subject's import key into sets, and re-judge +every holder for overlap after each widening operation. Its reads grew with the +world: 936, 3696 and 14736 rows for one `DischargeCommitment` at 100, 400 and 1600 +persons, and 14,000 or more for every other shape. It now reads what the patch +touches. + +`patch/candidate.rs` owns the candidate graph of one resolution. Each candidate map +is an `Overlay`: the committed partition read through a base function (a point get; +a `Key::Draft` key has none), and the patch's writes in a local map. `Candidate` +holds the fifteen overlays and the named reads, each bounded by what the patch +wrote plus what it returns: `occupants_under` (`under_place` over `ChildOf` and +`StandsAt`, corrected by the written positions), `offices_of` and `offices_held_by` +(the committed row or `ByIncumbent`, corrected by the written offices), `kind_taken` +(`ByKind` on the catalog) and `import_key_held` (`ByImportKey` on the subjects), +`custody` (the sums over the written holders only: every other holder is on both +sides of the equation and cancels). `authority`, `selection` and `retired` are +private to the module: a write goes through `set_grants`, `set_office` or `retire`, +which re-judge the holders whose effective authority it can change (the holder and +an institution's incumbents; an office's old and new incumbent) and keep +`overlapping`, the set of holders with two grants of one kind over overlapping +ground. A widening operation is `OverlappingJurisdiction` exactly when the set is +non-empty. That is what `graph_overlaps` answered, because the committed world is +disjoint (every commit checks it and opening a world verifies it), so only a holder +the patch touched can enter the set. The mismatch list is unchanged, including the +later widening operations after a first overlap and a revoke that clears it +(`overlap_mismatches_are_unchanged`). The candidate lives for one `resolve_patch` +call and is never written back; `admit_resolved` stays the only writer of the +ontology partitions. + +`apply_operations` derives its two checks from the transaction's log. Conservation +sums the holders `holdings` logged as changed, each from its value when the +operations began (so a holder already written by the declarations above it is +measured from there). Disjointness judges only the holders whose grants, offices or +institution the transaction touched, through `holder_overlaps`, which +`overlapping_holder` also calls for the open-time whole-world check +(`verify_state_shape`, whole-world on purpose). `resource_total` survives only as +the test reference `resource_total_by_scan`. + +Two partitions gained read indexes, `subjects` by `ByImportKey` and +`affordance_catalog` by `ByKind`, so `held_import_keys` and the per-patch kind set +are gone and `import_key_fault` asks a predicate. + +The seeding block, `graph_overlaps`, the old effective-authority walk and +`key_covers_place` live on only as `cfg(test)` references (`Materialized`, whose +`seeded` is the old block verbatim). `candidate_reads_equal_materialized_scans` +walks a civic world through the shapes that move each read (a subject leaving and +entering a subtree, a declared place and subject, a retirement, a vacated and +refilled office, an overlapping grant and its revocation, the retirement of the +lending institution, a declared institution, custody written both ways) and holds +every named read and the overlap set to the scan after every step; +`an_untouched_overlay_reads_what_the_seeding_copied` holds every base function to +the copy in each populated world. The gate is +`golden_tests::patch_read_work_is_equal_at_100_and_1600`: ten patch shapes through +`AdmitPatch` read the same rows at 100, 400 and 1600 persons (at most 21 each), +and `apply_checks_read_the_log` pins the commit lane's two checks. The +`DischargeCommitment` case of `operation_reads_are_equal_at_100_and_1600`, which +called `apply_operation` directly, moved into the gate. + +Reads that still scan: `snapshot` (follow-up `aetherlight-snapshot-history-fold`) +and `verify_state_shape` at open, by design. + +Fix batch (verdict s1). `apply_operations` sums the union of the holders written at +entry and the holders the log reports, so a holder written before the operations and +restored to its start value still counts. Three missed mutants were not equivalent +and are pinned by `golden_tests::within_one_patch`; `random_patch_sequences_agree_with_the_scan_references` +runs seeded random patches through the kernel and holds resolver, apply and the scan +references to one answer. The retirement-flip clause of `touched_holders` is gone +(a retirement only removes lent authority). Accepted, not fixed +(`counter-blind-sizes`): the read gates count rows through the counted API, which +point reads bypass by design, and wire patches are capped at 128 operations +(`MAX_PATCH_OPERATIONS`), so the flat-read gates measure patches no larger than that; +nothing measures a patch whose operation count grows with the world. diff --git a/native/aetherlight/fixtures/golden.digests b/native/aetherlight/fixtures/golden.digests new file mode 100644 index 000000000..cd2c826c8 --- /dev/null +++ b/native/aetherlight/fixtures/golden.digests @@ -0,0 +1,10 @@ +0 sha256:2ca3c099943ec537cd4dad9eef0b79b7368daa5b2dbd93baac0cb57cba3dcabe sha256:a94b938beddc671d28803581c9c3711fc520603f2dc8ac192b7cb54e73b3ff14 +1 sha256:cc421710aaa5d92b07abe0d7c4d0506fd6f9b66d1c806e863942e8a0113c7620 sha256:1abfc74079a3894ad21923f6d195f5e067adf58c5806f6cfc6bf08094f72ce9f +2 sha256:c2c2c2631caa85f9a0721778a7a05515a6687dda65af71f916a6565314f20f1b sha256:58a46e1def214cba12ed5d6ba1e991fa43d6927f6467fe10c276c0bc5ec38691 +3 sha256:5326e779106a076a35b26deb2d1116813accd9c8ad7da32569d240d4631de85c sha256:1cb8fd189c2c64c7ebf8708ae7db856b020b156c5660ac9178a27b50421ddbd4 +4 sha256:8b6e54464a24af395e8f5c0149aab8993355fa79994c09c4be53eabc5688d23a sha256:c78021e910c535f333fa4fdf97742a1329c5eb788b874c5c6302613abeef639b +5 sha256:78af2b889c301251919c6d68cf397d2befdf9b4fc012d73887c7d56894e86ecf sha256:3ab475b3e27f2e4d0afabd973ff69fff3523182216aa1f4ff3331de1747e1482 +6 sha256:2ce1eee99f2a650d9ef212ec04c2042b5e63005c5c263063d4e53b79d7ba7214 sha256:575b25743bc6d1673a71d9d0dc7be3825bec261f485bae13984065028601fb98 +7 sha256:fd5454f623359764bb4afaae6305a9ca41bca8670c36fd1f4f1c38779add4aa4 sha256:ba97a6d5c09e018c6abe91f782ab8bc5e618d0d8a45ac22cb637f40ad01755ef +8 sha256:7762f695b8205cba054d957e9a9242399320683d6d34c30ee9612dc89844ff2f sha256:b531e0d1afdb4f11033fc19e5280f7b46fc2b27911194e5c34dcbe8d57fae10e +export sha256:ef186452fd00de5b85a44e4a623489264e649810ab95847a45f25d82a0ae36fd diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs new file mode 100644 index 000000000..4d3b3edad --- /dev/null +++ b/native/aetherlight/src/action.rs @@ -0,0 +1,2762 @@ +//! The invocation pipeline: catalog lookup, role binding, precondition +//! evaluation, effect-ceiling checking, band selection, and lowering. +//! +//! One entry point, [`exercise`], reached from `reduce`'s `Act` arm +//! and from `apply_effect`'s `Acted` arm, so a forged effect is +//! re-derived by the same function that produced the honest one. Nothing else +//! draws a band, and the draw goes through the one `digest()` owner. + +use super::patch::{ + self, Affordance, Audience, AudienceSpec, BoundPrecondition, Bounds, ComponentOpKind, Cost, + Precondition, Quantity, RefKind, Role, WorldPatch, +}; +use super::{ + AffordanceId, AuthorityGrant, AuthorityTarget, CommandId, DecisionEvent, DecisionInvocation, + EdgeId, EntityId, EventId, FictionalMinutes, GrantedAffordance, + KernelError, Magnitude, SubjectId, Target, WorldId, WorldState, digest, +}; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet}; + +/// The complete failure set of one affordance invocation. Sorted and complete +/// like `Mismatch`, and like it never serialized: it states the affordance +/// contract, which no commit records. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum ActionMismatch { + UnboundRole { + role: Role, + }, + UnknownRole { + role: Role, + }, + DuplicateRoleBinding { + role: Role, + }, + UnknownTarget { + role: Role, + }, + TargetKindMismatch { + role: Role, + expected: RefKind, + actual: RefKind, + }, + ActorNotPresent { + precondition: usize, + }, + TargetUnreachable { + precondition: usize, + }, + InsufficientHolding { + precondition: usize, + }, + SlotNotProposed { + slot: usize, + }, + UnknownSlot { + slot: usize, + }, + DuplicateSlotProposal { + slot: usize, + }, + MagnitudeShapeMismatch { + slot: usize, + }, + MagnitudeOverCeiling { + slot: usize, + }, + ZeroMagnitude { + slot: usize, + }, + SpeechRequired, + SpeechNotCarried, + EmptySpeech, + EmptyDisplay, + /// The acting subject's effective authority covers no such target under + /// this kind. A target that walked out of the jurisdiction while the + /// proposal was in flight arrives here: what the actor is authorized over + /// is in its scope, the world it reaches is not. + NotAuthorized { + precondition: usize, + }, + /// No forum takes this grievance, or its standing does not reach the actor. + NoStanding { + precondition: usize, + }, + /// An invocation bound the reserved `actor` role. + ActorRoleBound, + /// A slot would grant authority the acting subject does not itself hold + /// over that ground. Without this, any holder mints unlimited authority in + /// one step and the whole component is decorative. + DelegationNotMonotone { + slot: usize, + }, + /// The actor does not hold the bound fact at the required confidence. A + /// re-appraisal that lowered its own confidence while the proposal was in + /// flight arrives here: confidence is admission-only. + FactUnknown { + precondition: usize, + }, + /// The actor has no audience at all: unplaced for co-location, or outside a + /// channel it does not control. + NoAudience { + precondition: usize, + }, + /// The addressed subject is not inside that audience. A target that walked + /// out of the room while the proposal was in flight arrives here: the + /// preimage holds what the actor *is*, not the world it reaches. + CannotReach { + precondition: usize, + }, + /// The actor holds no commitment of that kind to the bound referent. + NotCommitted { + precondition: usize, + }, +} + +/// The band draw's whole preimage. Five fields. `command_id` is derived from +/// the world, the expected revision, the caller and the whole body, so the +/// payload does reach the draw through it: changing the speech or display text, +/// a magnitude or the revision re-rolls the band, and a proposer who can vary +/// those can grind for a band. That is not an authority hole: only Play submits +/// an act after genesis, and Play is trusted. `affordance` is the id carried by +/// the kernel-verified grant, so the draw cannot be steered by an affordance the +/// actor does not hold. +#[derive(Serialize)] +struct BandPreimage { + world_id: WorldId, + revision: u64, + command_id: CommandId, + affordance: AffordanceId, + band_count: usize, +} + +/// Catalog lookup, binding, admission, draw, lowering, event. Stages 1 through 4 +/// accumulate one complete rejection set and return it sorted before anything is +/// drawn or lowered, so nothing past the gate can fail on caller input. +/// +/// The entry arrives as a [`GrantedAffordance`], which only `require_granted` +/// can build: the grant check is the type, not a call a third caller might +/// forget. Nothing here reads `invocation.affordance`. +pub(super) fn exercise( + state: &WorldState, + command_id: CommandId, + actor: SubjectId, + granted: &GrantedAffordance<'_>, + invocation: &DecisionInvocation, +) -> Result { + let entry = granted.entry; + let mut rejections = Vec::new(); + + let components = super::scope_components(state, actor); + let authority = super::effective_authority(&components.authority, &components.delegated); + let bindings = bind_roles(state, actor, entry, invocation, &mut rejections); + check_preconditions(state, actor, &authority, entry, &bindings, &mut rejections); + check_proposals(entry, invocation, &mut rejections); + check_delegation(state, &authority, entry, &bindings, &mut rejections); + + if !rejections.is_empty() { + rejections.sort(); + return Err(KernelError::ActionRejected(rejections)); + } + + let band = select_band(state, command_id, granted.id, entry)?; + let operations = lower(entry, band, actor, state.header.now, invocation, &bindings)?; + let mut effects = if operations.is_empty() { + Vec::new() + } else { + // The same resolver, the same per-operation preconditions, the same + // conservation equation the declaration lane passes. + patch::resolve_patch( + state, + command_id, + &WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + ) + .map_err(KernelError::PatchRejected)? + .operations + }; + + // The speech lowering: kernel-owned, not a slot, and unreachable by any + // proposer, band, or effect ceiling. The audience comes from the entry's one + // speech precondition, so a world's `whisper` and `proclaim` lower through + // the same two operations with a different audience and the kernel learns no + // genre. Addressing does not narrow the fan-out: a voice fills its audience. + let speech = match (&invocation.speech, entry.carries_speech) { + (Some(statement), true) => { + let fact = EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + state.header.world_id, + command_id, + &patch::DraftHandle::new(SPEECH_HANDLE), + Some(SPEECH_INDEX), + )); + let to = speech_audience(entry, &bindings)?; + effects.splice( + 0..0, + [ + patch::ResolvedOp::AssertClaim { + fact, + statement: statement.clone(), + by: actor, + }, + patch::ResolvedOp::Communicate { + speaker: actor, + fact, + to, + }, + ], + ); + Some(fact) + } + _ => None, + }; + // The display lowering: the same standing as speech, from the same + // allocation site under the second discriminator. It needs no entry + // field and reads no audience precondition: a body is visible to the room + // whatever the entry addresses, so `proclaim` down a horn still shrugs at + // whoever stands beside the speaker. + let display = invocation.display.as_ref().map(|statement| { + let fact = EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + state.header.world_id, + command_id, + &patch::DraftHandle::new(SPEECH_HANDLE), + Some(DISPLAY_INDEX), + )); + let at = usize::from(speech.is_some()) * 2; + effects.splice( + at..at, + [ + patch::ResolvedOp::AssertClaim { + fact, + statement: statement.clone(), + by: actor, + }, + patch::ResolvedOp::Display { actor, fact }, + ], + ); + fact + }); + + let revision = super::resolution_revision(state)?; + Ok(DecisionEvent { + id: EventId::for_command(command_id), + revision, + actor, + affordance: granted.id, + speech, + display, + band, + effects, + }) +} + +/// The synthetic handle every minted claim allocates under. It is synthesized +/// in an act, which declares nothing, so no world-declared handle can collide +/// with it. +const SPEECH_HANDLE: &str = "ghostlight.speech"; + +/// The speech index, passed as `derive_id`'s discriminator. It is `0` for every +/// invocation because one invocation carries one utterance; it exists so a +/// second minted claim needs no second allocation idiom. +const SPEECH_INDEX: &str = "0"; + +/// The display index: the second claim one invocation may mint, under the +/// same handle and allocation site as speech. +const DISPLAY_INDEX: &str = "1"; + +/// The audience a speech-carrying entry names. The declaration validator already +/// refused an entry with none (`SpeechWithoutAudience`) or two +/// (`AmbiguousSpeechAudience`), so anything else here is a corrupt catalog. +fn speech_audience( + entry: &Affordance, + bindings: &BTreeMap, +) -> Result { + entry + .preconditions + .iter() + .find_map(|precondition| match precondition { + Precondition::CanBroadcast { via } | Precondition::CanReach { via, .. } => { + bound_audience(via, bindings) + } + _ => None, + }) + .ok_or_else(|| KernelError::Invariant("a speech-carrying entry names no audience".into())) +} + +/// Stage 2. The acting subject is never a declared role: the kernel binds the +/// reserved name `actor` to it and refuses an invocation that tries to. A +/// binding that happens to name the actor through a declared role is legal and +/// unremarkable. +fn bind_roles( + state: &WorldState, + actor: SubjectId, + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec, +) -> BTreeMap { + let declared: BTreeMap<&Role, RefKind> = entry + .roles + .iter() + .map(|spec| (&spec.role, spec.kind)) + .collect(); + let mut bound: BTreeMap = BTreeMap::new(); + let mut seen: BTreeSet<&Role> = BTreeSet::new(); + for binding in &invocation.bindings { + if binding.role.0 == patch::ACTOR_ROLE { + rejections.push(ActionMismatch::ActorRoleBound); + continue; + } + if !seen.insert(&binding.role) { + rejections.push(ActionMismatch::DuplicateRoleBinding { + role: binding.role.clone(), + }); + continue; + } + let Some(expected) = declared.get(&binding.role).copied() else { + rejections.push(ActionMismatch::UnknownRole { + role: binding.role.clone(), + }); + continue; + }; + let Some(actual) = live_kind(state, binding.target) else { + rejections.push(ActionMismatch::UnknownTarget { + role: binding.role.clone(), + }); + continue; + }; + let fits = match (expected, actual) { + (RefKind::Subject(None), RefKind::Subject(_)) => true, + (expected, actual) => expected == actual, + }; + if fits { + bound.insert(binding.role.clone(), binding.target); + } else { + rejections.push(ActionMismatch::TargetKindMismatch { + role: binding.role.clone(), + expected, + actual, + }); + } + } + for spec in &entry.roles { + if !seen.contains(&spec.role) { + rejections.push(ActionMismatch::UnboundRole { + role: spec.role.clone(), + }); + } + } + // The kernel's own binding, added after the caller's so nothing can shadow + // it: a slot that must land on the actor says `actor` and the proposer has + // no say. Without it, a levy's `Transfer` would need the proposer to name + // the payee, and an authorized collector could lawfully take a tax and send + // it to a friend. + bound.insert(Role(patch::ACTOR_ROLE.into()), Target::Subject(actor)); + bound +} + +/// What a target actually is in committed state. `None` means the target keys no +/// live partition in its namespace. +fn live_kind(state: &WorldState, target: Target) -> Option { + match target { + Target::Subject(subject_id) => state + .subjects + .get(&subject_id) + .map(|subject| RefKind::Subject(Some(subject.kind))), + Target::Entity(entity_id) => state + .entities + .get(&entity_id) + .map(|record| RefKind::Entity(record.kind)), + Target::Edge(edge_id) => state + .edges + .get(&edge_id) + .map(|_| RefKind::Edge(patch::EdgeKind::Route)), + } +} + +/// Stage 3, in declaration order, each failure carrying its index so a test can +/// name the exact precondition that refused. Role binding is this caller's job: +/// each declared `Precondition` is lowered through stage 2's bindings into a +/// `BoundPrecondition` and handed to the one evaluator. A precondition whose +/// role stage 2 left unbound is skipped here, because stage 2 already named it. +fn check_preconditions( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + entry: &Affordance, + bindings: &BTreeMap, + rejections: &mut Vec, +) { + for (index, precondition) in entry.preconditions.iter().enumerate() { + let Some(bound) = bind_precondition(precondition, bindings) else { + continue; + }; + if let Some(mismatch) = evaluate(state, actor, authority, index, &bound) { + rejections.push(mismatch); + } + } +} + +/// The catalog's role indirection lowered to canonical referents. `None` means +/// a role is unbound or bound to the wrong namespace, which stage 2 named. +fn bind_precondition( + precondition: &Precondition, + bindings: &BTreeMap, +) -> Option { + let place = |role: &Role| match bindings.get(role)? { + Target::Entity(entity_id) => Some(*entity_id), + _ => None, + }; + Some(match precondition { + Precondition::Present { at } => BoundPrecondition::Present { at: place(at)? }, + Precondition::Reachable { to, within } => BoundPrecondition::Reachable { + to: place(to)?, + within: *within, + }, + Precondition::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: place(resource)?, + at_least: *at_least, + }, + Precondition::Authorized { over, kind } => BoundPrecondition::Authorized { + over: bindings.get(over).copied()?, + kind: kind.clone(), + }, + Precondition::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + Precondition::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: place(fact)?, + at_least: *at_least, + }, + Precondition::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: bound_audience(via, bindings)?, + }, + Precondition::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: match bindings.get(subject)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + via: bound_audience(via, bindings)?, + }, + Precondition::Committed { to, kind } => BoundPrecondition::Committed { + to: match bindings.get(to)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + kind: *kind, + }, + }) +} + +/// The one precondition reader, over referents that are already canonical. +/// Returns the complete set in declaration order; an empty set is "all hold". +/// The tick reads only its emptiness — an `ActionMismatch` never surfaces to +/// anyone from there. +pub(super) fn preconditions_hold( + state: &WorldState, + actor: SubjectId, + checks: &[BoundPrecondition], +) -> Vec { + let components = super::scope_components(state, actor); + let authority = super::effective_authority(&components.authority, &components.delegated); + checks + .iter() + .enumerate() + .filter_map(|(index, check)| evaluate(state, actor, &authority, index, check)) + .collect() +} + +/// One check against committed state. `index` is the position within the slice +/// the caller passed in, which is what every `precondition: usize` means. +fn evaluate( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + index: usize, + check: &BoundPrecondition, +) -> Option { + let holds = match check { + BoundPrecondition::Present { at } => { + return (state.positions.get(&actor).map(|position| position.place) != Some(*at)) + .then_some(ActionMismatch::ActorNotPresent { + precondition: index, + }); + } + BoundPrecondition::Reachable { to, within } => { + return (!reachable(state, actor, authority, *to, *within)).then_some( + ActionMismatch::TargetUnreachable { + precondition: index, + }, + ); + } + BoundPrecondition::Holds { resource, at_least } => { + state + .holdings + .get(&actor) + .and_then(|held| held.get(resource)) + .map_or(0, |quantity| quantity.0) + >= at_least.0 + } + BoundPrecondition::Authorized { over, kind } => { + return (!authority + .iter() + .any(|grant| &grant.kind == kind && super::covers(state, grant.over, *over))) + .then_some(ActionMismatch::NotAuthorized { + precondition: index, + }); + } + BoundPrecondition::HasStanding { grievance } => { + return (!state.redress.get(grievance).is_some_and(|forum| { + super::covers(state, forum.standing, Target::Subject(actor)) + })) + .then_some(ActionMismatch::NoStanding { + precondition: index, + }); + } + BoundPrecondition::Knows { fact, at_least } => { + return (!state + .knowledge + .get(&(actor, *fact)) + .is_some_and(|held| held.confidence >= *at_least)) + .then_some(ActionMismatch::FactUnknown { + precondition: index, + }); + } + BoundPrecondition::CanBroadcast { via } => { + return (!super::can_broadcast(state, actor, via)).then_some( + ActionMismatch::NoAudience { + precondition: index, + }, + ); + } + BoundPrecondition::CanReach { subject, via } => { + return (!super::audience(state, actor, via).contains(subject)).then_some( + ActionMismatch::CannotReach { + precondition: index, + }, + ); + } + // A linear scan of one subject's own small map. No key lookup is needed + // and none is offered, which is why a `CommitmentKey` never has to be + // guessable. + BoundPrecondition::Committed { to, kind } => { + return (!state.commitments.get(&actor).is_some_and(|held| { + held.values().any(|commitment| { + commitment.counterparty == Some(*to) && commitment.kind == *kind + }) + })) + .then_some(ActionMismatch::NotCommitted { + precondition: index, + }); + } + }; + (!holds).then_some(ActionMismatch::InsufficientHolding { + precondition: index, + }) +} + +/// The catalog's role indirection lowered to the canonical audience: the entry +/// names a role, the invoker binds a channel to it, and every reader of reach +/// sees one shape. `None` means the role is unbound, which stage 2 already named. +fn bound_audience(via: &AudienceSpec, bindings: &BTreeMap) -> Option { + match via { + AudienceSpec::Colocated => Some(Audience::Colocated), + AudienceSpec::Channel(role) => match bindings.get(role).copied() { + Some(Target::Entity(entity_id)) => Some(Audience::Channel(entity_id)), + _ => None, + }, + } +} + +/// Stage 4, beside the ceilings: an authority a slot would grant or revoke +/// must not exceed the actor's own. For a grant this is the monotonicity +/// envelope — no holder mints authority it does not itself hold. For a +/// revocation it is the same envelope read the other way: an actor may not +/// strip ground it holds no jurisdiction over, so revocation is not a lever +/// for reaching past one's own authority. Every slot is checked, not just the +/// drawn band's, for the same reason every ceiling is — the proposer commits +/// to a complete attempt and cannot see the band. +/// +/// The rule is action-lane only, and that is not two truths. The patch lane's +/// `GrantAuthority`/`RevokeAuthority` is admitted for Play; +/// monotonicity *is* the action lane's authority envelope, and both lanes +/// reach one `apply_operation` with the identical mutation. +fn check_delegation( + state: &WorldState, + authority: &BTreeSet, + entry: &Affordance, + bindings: &BTreeMap, + rejections: &mut Vec, +) { + for (index, slot) in entry.effect_slots.iter().enumerate() { + let kind = match &slot.op_kind { + ComponentOpKind::GrantAuthority { kind } + | ComponentOpKind::RevokeAuthority { kind } => kind, + _ => continue, + }; + let Some(over) = slot + .roles + .get(1) + .and_then(|role| bindings.get(role)) + .copied() + .and_then(authority_target_of) + else { + continue; + }; + if !authority.iter().any(|grant| { + &grant.kind == kind && super::covers(state, grant.over, over.as_referent()) + }) { + rejections.push(ActionMismatch::DelegationNotMonotone { slot: index }); + } + } +} + +/// The authority target a bound referent names. A route is jurisdictional +/// ground but never a grant's target, so a slot bound to one lowers to nothing. +fn authority_target_of(target: Target) -> Option { + match target { + Target::Subject(subject_id) => Some(AuthorityTarget::Subject(subject_id)), + Target::Entity(entity_id) => Some(AuthorityTarget::PlaceSubtree(entity_id)), + Target::Edge(_) => None, + } +} + +/// Dijkstra over the live route graph, admitting the open routes this subject +/// may traverse — the same `route_admits` rule the resolver applies to a +/// `Relocate`, so a subject with the right authority can plan a path through +/// its own restricted ground — and +/// relaxing in `EdgeId` order, pruning any path whose accumulated cost exceeds +/// `within`. Cost 0 — already standing there — succeeds; `Present` is the strict +/// form. An unplaced actor reaches nothing. +/// +/// Admission runs at commit against live state, so a route that closed while +/// the proposal was in flight makes this fail rather than letting a stale path +/// commit. +pub(super) fn reachable( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + destination: EntityId, + within: Cost, +) -> bool { + reach(state, actor, authority, destination, within, |place| { + state + .edges + .indexed(place..=place) + .into_iter() + .map(|(_, edge_id)| edge_id) + .collect() + }) +} + +/// What `reachable` was before the index: every edge asked at every settled place. +#[cfg(test)] +pub(super) fn reachable_by_scan( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + destination: EntityId, + within: Cost, +) -> bool { + reach(state, actor, authority, destination, within, |place| { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == place || to == place + }) + .map(|(edge_id, _)| *edge_id) + .collect() + }) +} + +/// The search, given how the routes touching a place are found, in `EdgeId` +/// order. +fn reach( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + destination: EntityId, + within: Cost, + routes_at: impl Fn(EntityId) -> Vec, +) -> bool { + let Some(origin) = state.positions.get(&actor).map(|position| position.place) else { + return false; + }; + let mut best: BTreeMap = BTreeMap::from([(origin, 0)]); + let mut settled: BTreeSet = BTreeSet::new(); + let ceiling = u64::from(within.0); + loop { + let Some((place, cost)) = best + .iter() + .filter(|(place, _)| !settled.contains(place)) + .min_by_key(|(place, cost)| (**cost, **place)) + .map(|(place, cost)| (*place, *cost)) + else { + return false; + }; + if place == destination { + return true; + } + settled.insert(place); + let outbound: Vec<(EdgeId, EntityId, u64)> = routes_at(place) + .into_iter() + .map(|edge_id| (edge_id, &state.edges[&edge_id])) + .filter(|(_, record)| record.is_open()) + .filter_map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + let next = if from == place { + to + } else if to == place { + from + } else { + return None; + }; + patch::route_admits(state, authority, record.access(), next) + .then(|| (edge_id, next, u64::from(record.cost().0))) + }) + .collect(); + for (_, next, step) in outbound { + let total = cost + step; + if total <= ceiling && best.get(&next).is_none_or(|known| total < *known) { + best.insert(next, total); + } + } + } +} + +/// Stage 4. Every slot is checked, not just the ones the selected band names: +/// the proposer cannot see the band, so it commits to a complete attempt, and +/// checking every slot makes the ceiling total. +fn check_proposals( + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec, +) { + let mut seen: BTreeSet = BTreeSet::new(); + for proposed in &invocation.proposed { + if !seen.insert(proposed.slot) { + rejections.push(ActionMismatch::DuplicateSlotProposal { + slot: proposed.slot, + }); + continue; + } + let Some(slot) = entry.effect_slots.get(proposed.slot) else { + rejections.push(ActionMismatch::UnknownSlot { + slot: proposed.slot, + }); + continue; + }; + match (slot.bounds, proposed.magnitude) { + (Bounds::None, Magnitude::None) => {} + (Bounds::Quantity(ceiling), Magnitude::Quantity(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + (Bounds::Cost(ceiling), Magnitude::Cost(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + _ => rejections.push(ActionMismatch::MagnitudeShapeMismatch { + slot: proposed.slot, + }), + } + } + for slot in 0..entry.effect_slots.len() { + if !seen.contains(&slot) { + rejections.push(ActionMismatch::SlotNotProposed { slot }); + } + } + // `Statement` is serde-transparent, so a value that arrived through + // deserialization rather than through the constructor is re-checked here + // rather than trusted. + match (&invocation.speech, entry.carries_speech) { + // A speech-carrying entry addresses someone; a silent turn that only + // displays still addresses the room, so it is not `SpeechRequired`. + (None, true) if invocation.display.is_none() => { + rejections.push(ActionMismatch::SpeechRequired); + } + (Some(_), false) => rejections.push(ActionMismatch::SpeechNotCarried), + (Some(speech), true) if !patch::is_canonical_text(speech.as_str()) => { + rejections.push(ActionMismatch::EmptySpeech); + } + _ => {} + } + if invocation + .display + .as_ref() + .is_some_and(|display| !patch::is_canonical_text(display.as_str())) + { + rejections.push(ActionMismatch::EmptyDisplay); + } +} + +/// The only entropy in the kernel: one digest, one modulo, one cumulative walk. +/// Modulo rather than rejection sampling — the bias is bounded by +/// `total_weight / 2^64`, and a rejection loop would need its counter in the +/// preimage, which is a second entropy shape for a rounding error nobody can +/// measure. +fn select_band( + state: &WorldState, + command_id: CommandId, + affordance: AffordanceId, + entry: &Affordance, +) -> Result { + let draw = digest(&BandPreimage { + world_id: state.header.world_id, + revision: state.revision, + command_id, + affordance, + band_count: entry.outcome_bands.len(), + })?; + let head = draw + .strip_prefix("sha256:") + .and_then(|hex| hex.get(..16)) + .and_then(|head| u64::from_str_radix(head, 16).ok()) + .ok_or_else(|| KernelError::Invariant("band draw digest is not hex".into()))?; + let total: u128 = entry + .outcome_bands + .iter() + .map(|band| u128::from(band.weight)) + .sum(); + if total == 0 { + return Err(KernelError::Invariant( + "affordance has no outcome band".into(), + )); + } + let mut position = u128::from(head) % total; + for (index, band) in entry.outcome_bands.iter().enumerate() { + let weight = u128::from(band.weight); + if position < weight { + return Ok(index); + } + position -= weight; + } + Err(KernelError::Invariant( + "band weights did not cover the draw".into(), + )) +} + +/// Stage 7. One arm per `ComponentOpKind`, every referent read from the slot's +/// roles resolved through the bindings, every magnitude from the proposal for +/// that slot. An empty band lowers to nothing. +fn lower( + entry: &Affordance, + band: usize, + actor: SubjectId, + now: FictionalMinutes, + invocation: &DecisionInvocation, + bindings: &BTreeMap, +) -> Result, KernelError> { + let malformed = || KernelError::Invariant("admitted affordance slot is malformed".into()); + let band = entry + .outcome_bands + .get(band) + .ok_or_else(|| KernelError::Invariant("selected band does not exist".into()))?; + let mut operations = Vec::new(); + for slot_index in &band.effects { + let slot = entry.effect_slots.get(*slot_index).ok_or_else(malformed)?; + let magnitude = invocation + .proposed + .iter() + .find(|proposed| proposed.slot == *slot_index) + .map(|proposed| proposed.magnitude) + .ok_or_else(malformed)?; + let target = |position: usize| -> Result { + slot.roles + .get(position) + .and_then(|role| bindings.get(role)) + .copied() + .ok_or_else(malformed) + }; + let subject = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Subject(subject_id) => Ok(patch::Ref::Existing(subject_id)), + _ => Err(malformed()), + } + }; + let entity = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Entity(entity_id) => Ok(patch::Ref::Existing(entity_id)), + _ => Err(malformed()), + } + }; + let edge = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Edge(edge_id) => Ok(patch::Ref::Existing(edge_id)), + _ => Err(malformed()), + } + }; + let quantity = || -> Result { + match magnitude { + Magnitude::Quantity(value) => Ok(value), + _ => Err(malformed()), + } + }; + let dependency = |position: usize| -> Result { + Ok(match target(position)? { + Target::Subject(subject_id) => { + patch::DependencyRef::Subject(patch::Ref::Existing(subject_id)) + } + Target::Entity(entity_id) => { + patch::DependencyRef::Resource(patch::Ref::Existing(entity_id)) + } + Target::Edge(edge_id) => patch::DependencyRef::Route(patch::Ref::Existing(edge_id)), + }) + }; + let grant_over = |position: usize| -> Result { + Ok(match target(position)? { + Target::Subject(subject_id) => { + patch::AuthorityTargetRef::Subject(patch::Ref::Existing(subject_id)) + } + Target::Entity(entity_id) => { + patch::AuthorityTargetRef::PlaceSubtree(patch::Ref::Existing(entity_id)) + } + Target::Edge(_) => return Err(malformed()), + }) + }; + operations.push(match &slot.op_kind { + // `due` is computed here, so a proposer cannot set one, and the + // pressure source is the acting subject, so it cannot be forged. + ComponentOpKind::CreateCommitment { + kind, + horizon, + period, + } => patch::ComponentOp::CreateCommitment { + subject: subject(0)?, + counterparty: Some(subject(1)?), + kind: *kind, + due: now.checked_add(*horizon).ok_or_else(malformed)?, + period: *period, + checks: Vec::new(), + // The world named the action; that name is what was promised. + // A proposer cannot supply the text, so it cannot promise more + // than the affordance carries. + statement: patch::Statement::new(format!("a promise made through {}", entry.kind.0)) + .ok_or_else(malformed)?, + }, + ComponentOpKind::AdvancePressure { by } => patch::ComponentOp::AdvancePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ReducePressure { by } => patch::ComponentOp::ReducePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ResolvePressure => patch::ComponentOp::ResolvePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + }, + ComponentOpKind::Relocate => patch::ComponentOp::Relocate { + subject: subject(0)?, + via: edge(1)?, + }, + ComponentOpKind::OpenRoute => patch::ComponentOp::OpenRoute { route: edge(0)? }, + ComponentOpKind::CloseRoute => patch::ComponentOp::CloseRoute { route: edge(0)? }, + ComponentOpKind::AlterCost => patch::ComponentOp::AlterCost { + route: edge(0)?, + cost: match magnitude { + Magnitude::Cost(value) => value, + _ => return Err(malformed()), + }, + }, + ComponentOpKind::Transfer => patch::ComponentOp::Transfer { + from: subject(0)?, + to: subject(1)?, + resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Transform => patch::ComponentOp::Transform { + holder: subject(0)?, + from_resource: entity(1)?, + into_resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Consume => patch::ComponentOp::Consume { + holder: subject(0)?, + resource: entity(1)?, + qty: quantity()?, + }, + ComponentOpKind::Bind => patch::ComponentOp::Bind { + subject: subject(0)?, + target: dependency(1)?, + }, + ComponentOpKind::Release => patch::ComponentOp::Release { + subject: subject(0)?, + target: dependency(1)?, + }, + ComponentOpKind::GrantAuthority { kind } => patch::ComponentOp::GrantAuthority { + holder: subject(0)?, + grant: patch::AuthorityGrantRef { + kind: kind.clone(), + over: grant_over(1)?, + }, + }, + ComponentOpKind::RevokeAuthority { kind } => patch::ComponentOp::RevokeAuthority { + holder: subject(0)?, + grant: patch::AuthorityGrantRef { + kind: kind.clone(), + over: grant_over(1)?, + }, + }, + ComponentOpKind::InstallIncumbent { office } => patch::ComponentOp::InstallIncumbent { + institution: subject(0)?, + office: office.clone(), + incumbent: subject(1)?, + }, + ComponentOpKind::VacateOffice { office } => patch::ComponentOp::VacateOffice { + institution: subject(0)?, + office: office.clone(), + }, + ComponentOpKind::AcquireKnowledge { confidence } => { + patch::ComponentOp::AcquireKnowledge { + subject: subject(0)?, + fact: entity(1)?, + source: patch::AuthoredSource::Witnessed, + confidence: *confidence, + } + } + ComponentOpKind::Witness { confidence } => patch::ComponentOp::Witness { + fact: entity(0)?, + place: entity(1)?, + confidence: *confidence, + }, + ComponentOpKind::Forget => patch::ComponentOp::Forget { + subject: subject(0)?, + fact: entity(1)?, + }, + }); + } + Ok(operations) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::custody_tests::custody_kernel; + use crate::patch::{ + AffordanceDeclaration, ComponentOp, DraftHandle, OutcomeBand, Ref as PatchRef, ResolvedOp, + RoleSpec, + }; + use crate::tests::{ + ADMIT_KIND, COMMAND_KIND, Civic, LEVY_KIND, OPENING_BALANCE, SEIZURE_GRIEVANCE, Topology, + WARDEN_OFFICE, act, affordance_named, authority_kind, civic_world, + command, custody_world, grant_to, grievance, office, operations, over_place, + over_subject, play_caller, reject_play, submit_play, tick_body, + }; + use crate::{ + AffordanceKindName, AuthenticatedCaller, AuthoredSource, CommandBody, Confidence, + Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, CommitReceipt, + WorldEffect, WorldKernel, WorldPatch, WorldSnapshot, apply_effect, + }; + use std::collections::BTreeSet; + + struct Bench { + kernel: WorldKernel, + active: WorldSnapshot, + carry: AffordanceId, + clerk: SubjectId, + keeper: SubjectId, + tithe: EntityId, + ingot: EntityId, + yard: EntityId, + gate: EntityId, + shutter: EdgeId, + } + + fn bench(title: &str) -> Bench { + let mut kernel = custody_kernel(title); + let (topology, custody, active) = custody_world(&mut kernel); + let carry = affordance_named(&active, "carry"); + Bench { + kernel, + active, + carry, + clerk: custody.holder, + keeper: custody.counterparty, + tithe: custody.tithe, + ingot: custody.ingot, + yard: topology.yard, + gate: topology.gate, + shutter: topology.shutter, + } + } + + /// `exercise` only accepts a grant the kernel resolved, so a test walks the + /// same gate `reduce` does rather than reaching into the catalog. + fn draw_once( + state: &WorldState, + command_id: CommandId, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Result { + let granted = crate::require_granted(state, actor, invocation.affordance)?; + exercise(state, command_id, actor, &granted, invocation) + } + + /// Commit `invocation` as the first command whose derived id draws `band`. + /// A band is a pure function of the pre-commit state and the command id, + /// and a command's id derives from the revision it targets, so a test + /// reaches a band by committing ordinary ticks until the id it would + /// carry draws it. + fn act_drawing( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: &DecisionInvocation, + band: usize, + ) -> CommitReceipt { + for _ in 0..256 { + let snapshot = kernel.snapshot().unwrap(); + let envelope = command( + &snapshot, + play_caller(), + CommandBody::Act { + actor, + invocation: invocation.clone(), + }, + ); + let draws = draw_once(&kernel.state, envelope.id(), actor, invocation) + .expect("the invocation is admissible") + .band; + if draws == band { + return kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the invocation commits"); + } + submit_play(kernel, &snapshot, tick_body(1)); + } + panic!("a two-band entry reaches both bands within 256 revisions"); + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + impl Bench { + /// A Carry the clerk proposes. The actor is never a role, so a Carry + /// that moves the actor's own goods binds `from` to its own id. + fn carry_of(&self, qty: u64, place: EntityId, resource: EntityId) -> DecisionInvocation { + DecisionInvocation { + affordance: self.carry, + bindings: vec![ + binding("from", Target::Subject(self.clerk)), + binding("recipient", Target::Subject(self.keeper)), + binding("place", Target::Entity(place)), + binding("resource", Target::Entity(resource)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(qty)), + }], + speech: None, + display: None, + } + } + + fn carry(&self, qty: u64, place: EntityId) -> DecisionInvocation { + self.carry_of(qty, place, self.tithe) + } + + fn try_exercise( + &self, + invocation: &DecisionInvocation, + ) -> Result { + draw_once( + &self.kernel.state, + CommandId::issue(), + self.clerk, + invocation, + ) + } + + fn rejections(&self, invocation: &DecisionInvocation) -> Vec { + match self.try_exercise(invocation) { + Err(KernelError::ActionRejected(rejected)) => rejected, + other => panic!("expected an action rejection, got {other:?}"), + } + } + + fn commit(&mut self, invocation: DecisionInvocation) -> CommitReceipt { + act(&mut self.kernel, self.clerk, invocation).expect("the invocation commits") + } + + fn held(&self, holder: SubjectId) -> u64 { + self.kernel + .state + .holdings + .get(&holder) + .and_then(|held| held.get(&self.tithe)) + .map_or(0, |quantity| quantity.0) + } + + /// The same Carry attempt against a sibling entry: one dial moved, one + /// name. The catalog is declared structure, so a variant is declared rather + /// than patched into committed state. + fn variant(&self, invocation: &DecisionInvocation, kind: &str) -> DecisionInvocation { + DecisionInvocation { + affordance: affordance_named(&self.active, kind), + ..invocation.clone() + } + } + + fn refresh(&mut self) { + self.active = self.kernel.snapshot().unwrap(); + } + } + + #[test] + fn a_missing_present_precondition_names_itself() { + let bench = bench("Present"); + let before = bench.kernel.state.clone(); + let before_events = bench.kernel.events(); + + // The clerk stands in the yard, so a Carry bound to the gate fails the + // first precondition and nothing else. + assert_eq!( + bench.rejections(&bench.carry(1, bench.gate)), + vec![ActionMismatch::ActorNotPresent { precondition: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.holdings, before.holdings); + assert_eq!(bench.kernel.events(), before_events); + } + + #[test] + fn spending_more_than_held_fails_the_holds_precondition() { + let bench = bench("Holds"); + let greedy = bench.variant(&bench.carry(1, bench.yard), "carry_greedy"); + assert_eq!( + bench.rejections(&greedy), + vec![ActionMismatch::InsufficientHolding { precondition: 1 }] + ); + + // Absence is zero, so a resource the clerk holds none of gives the same + // name at the boundary rather than a second one. + let ingot = bench.variant(&bench.carry_of(1, bench.yard, bench.ingot), "carry_holds"); + assert_eq!( + bench.rejections(&ingot), + vec![ActionMismatch::InsufficientHolding { precondition: 0 }] + ); + } + + /// `at_least` is inclusive: holding exactly the threshold passes. The clerk + /// spends down to one ingot-equivalent, and `carry_holds` asks for one. + #[test] + fn holding_exactly_the_threshold_satisfies_holds() { + let mut bench = bench("HoldsBoundary"); + for _ in 0..2 { + bench.commit(bench.carry(3, bench.yard)); + bench.refresh(); + } + assert_eq!(bench.held(bench.clerk), OPENING_BALANCE - 6); + let exact = bench.variant(&bench.carry(1, bench.yard), "carry_holds"); + bench + .try_exercise(&exact) + .expect("one held satisfies at_least one"); + + bench.commit(bench.carry(1, bench.yard)); + bench.refresh(); + assert_eq!(bench.held(bench.clerk), 0); + assert_eq!( + bench.rejections(&bench.variant(&bench.carry(1, bench.yard), "carry_holds")), + vec![ActionMismatch::InsufficientHolding { precondition: 0 }] + ); + } + + #[test] + fn a_reachable_precondition_reads_only_open_public_routes() { + let mut bench = bench("Reachable"); + // Yard to gate over open public routes is the ramp (12) plus the span + // (7): the shutter is closed and the toll stair is restricted. A budget + // of NEAR_REACH covers only the shutter, FAR_REACH covers the two-hop + // path. + let attempt = bench.carry(1, bench.gate); + let near = bench.variant(&attempt, "carry_near"); + let far = bench.variant(&attempt, "carry_far"); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + assert!(bench.try_exercise(&far).is_ok()); + + // Opening the one-hop shutter shortens the path, and closing it again + // restores the two-hop cost: the check reads the live graph rather than + // anything the proposal was bound against. + let before = bench.kernel.snapshot().unwrap(); + submit_play( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::OpenRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert!(bench.try_exercise(&near).is_ok()); + + let before = bench.kernel.snapshot().unwrap(); + submit_play( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + } + + #[test] + fn an_unbound_or_miskinded_role_is_rejected_with_the_complete_set() { + let bench = bench("Roles"); + let mut invocation = bench.carry(1, bench.yard); + // Drop `recipient`, add an undeclared role, and bind `resource` to a + // place: one rejection carrying all three, sorted. + invocation.bindings = vec![ + binding("from", Target::Subject(bench.clerk)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.yard)), + binding("porter", Target::Subject(bench.keeper)), + ]; + let mut expected = vec![ + ActionMismatch::UnboundRole { + role: Role("recipient".into()), + }, + ActionMismatch::UnknownRole { + role: Role("porter".into()), + }, + ActionMismatch::TargetKindMismatch { + role: Role("resource".into()), + expected: RefKind::Entity(EntityKind::Resource), + actual: RefKind::Entity(EntityKind::Place), + }, + ]; + expected.sort(); + assert_eq!(bench.rejections(&invocation), expected); + } + + #[test] + fn a_duplicated_or_unknown_binding_target_is_rejected() { + let bench = bench("Bindings"); + let mut twice = bench.carry(1, bench.yard); + twice + .bindings + .push(binding("resource", Target::Entity(bench.tithe))); + assert!( + bench + .rejections(&twice) + .contains(&ActionMismatch::DuplicateRoleBinding { + role: Role("resource".into()) + }) + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.bindings[3] = binding("resource", Target::Entity(EntityId::issue())); + assert!( + bench + .rejections(&unknown) + .contains(&ActionMismatch::UnknownTarget { + role: Role("resource".into()) + }) + ); + } + + #[test] + fn a_magnitude_over_its_slot_ceiling_is_rejected_and_within_it_commits() { + let mut bench = bench("Ceiling"); + assert_eq!( + bench.rejections(&bench.carry(4, bench.yard)), + vec![ActionMismatch::MagnitudeOverCeiling { slot: 0 }] + ); + + let clerk_before = bench.held(bench.clerk); + let keeper_before = bench.held(bench.keeper); + let receipt = bench.commit(bench.carry(3, bench.yard)); + assert!(receipt.resulting_revision > 0); + assert_eq!(bench.held(bench.clerk), clerk_before - 3); + assert_eq!(bench.held(bench.keeper), keeper_before + 3); + assert_eq!( + bench.held(bench.clerk) + bench.held(bench.keeper), + clerk_before + keeper_before, + "the conserved total is unchanged" + ); + } + + #[test] + fn a_magnitude_of_the_wrong_shape_or_zero_is_rejected() { + let bench = bench("Shape"); + for magnitude in [Magnitude::Cost(Cost(2)), Magnitude::None] { + let mut invocation = bench.carry(1, bench.yard); + invocation.proposed[0].magnitude = magnitude; + assert_eq!( + bench.rejections(&invocation), + vec![ActionMismatch::MagnitudeShapeMismatch { slot: 0 }] + ); + } + assert_eq!( + bench.rejections(&bench.carry(0, bench.yard)), + vec![ActionMismatch::ZeroMagnitude { slot: 0 }] + ); + } + + #[test] + fn every_slot_must_be_proposed_exactly_once() { + let bench = bench("Slots"); + let mut missing = bench.carry(1, bench.yard); + missing.proposed.clear(); + assert_eq!( + bench.rejections(&missing), + vec![ActionMismatch::SlotNotProposed { slot: 0 }] + ); + + let mut twice = bench.carry(1, bench.yard); + twice.proposed.push(twice.proposed[0]); + assert_eq!( + bench.rejections(&twice), + vec![ActionMismatch::DuplicateSlotProposal { slot: 0 }] + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.proposed.push(ProposedEffect { + slot: 7, + magnitude: Magnitude::None, + }); + assert_eq!( + bench.rejections(&unknown), + vec![ActionMismatch::UnknownSlot { slot: 7 }] + ); + } + + #[test] + fn speech_is_required_exactly_when_the_entry_carries_it() { + let bench = bench("Speech"); + let mut spoken_carry = bench.carry(1, bench.yard); + spoken_carry.speech = Some(Statement::new("Take it.").unwrap()); + assert_eq!( + bench.rejections(&spoken_carry), + vec![ActionMismatch::SpeechNotCarried] + ); + + let speak = affordance_named(&bench.active, "speak"); + let mut silent_speak = DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: None, + }; + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::SpeechRequired] + ); + + // `Statement` is serde-transparent, so a value that arrived without the + // constructor is re-checked here rather than trusted. + silent_speak.speech = Some(serde_json::from_str::("\" \"").unwrap()); + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::EmptySpeech] + ); + } + + #[test] + fn the_same_command_id_always_selects_the_same_band() { + let bench = bench("Bands"); + // Three equally weighted bands, so the draw alone decides. + let invocation = bench.variant(&bench.carry(1, bench.yard), "carry_chance"); + let draw = |command_id: CommandId, invocation: &DecisionInvocation| { + draw_once(&bench.kernel.state, command_id, bench.clerk, invocation) + .expect("the invocation is admissible") + .band + }; + + let command_id = CommandId::issue(); + let fixed = draw(command_id, &invocation); + for _ in 0..100 { + assert_eq!(draw(command_id, &invocation), fixed); + } + + // No caller-supplied value influences the draw: not a binding order, + // not a magnitude. + let mut reordered = invocation.clone(); + reordered.bindings.reverse(); + assert_eq!(draw(command_id, &reordered), fixed); + let mut heavier = invocation.clone(); + heavier.proposed[0].magnitude = Magnitude::Quantity(Quantity(3)); + assert_eq!(draw(command_id, &heavier), fixed); + + // The command id is the only varying term at one revision. + let mut seen = BTreeSet::new(); + for _ in 0..64 { + seen.insert(draw(CommandId::issue(), &invocation)); + } + assert!( + seen.len() > 1, + "varying only the command id must reach more than one band" + ); + } + + #[test] + fn a_zero_effect_band_commits_nothing_but_the_event() { + let mut bench = bench("EmptyBand"); + let idle = bench.variant(&bench.carry(3, bench.yard), "carry_idle"); + + let holdings = bench.kernel.state.holdings.clone(); + let positions = bench.kernel.state.positions.clone(); + let edges = bench.kernel.state.edges.clone(); + let revision = bench.kernel.state.revision; + + let event = bench + .try_exercise(&idle) + .expect("an empty band is admissible"); + assert_eq!(event.band, 0); + assert!(event.effects.is_empty()); + + let receipt = bench.commit(idle); + assert!(receipt.resulting_revision > 0); + assert_eq!(bench.kernel.state.holdings, holdings); + assert_eq!(bench.kernel.state.positions, positions); + assert_eq!(bench.kernel.state.edges, edges); + assert_eq!(bench.kernel.events().len(), 1); + assert_eq!(bench.kernel.state.revision, revision + 1); + } + + #[test] + fn a_committed_event_carries_the_exact_lowered_operations() { + let mut bench = bench("Lowering"); + let receipt = bench.commit(bench.carry(2, bench.yard)); + assert!(receipt.resulting_revision > 0); + let events = bench.kernel.events(); + let event = events.last().expect("the committed event"); + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + } + + /// Soul: contract 10's discriminating case. `a_zero_effect_band_commits_ + /// nothing_but_the_event` proves an empty band commits nothing, and + /// `a_committed_event_carries_the_exact_lowered_operations` proves a + /// one-slot entry lowers what it declares — neither separates a slot the + /// proposer offered from a slot the draw admitted. This entry declares two + /// slots on disjoint bands and proposes both within their ceilings: only + /// the drawn band's slot may appear in `event.effects`, and the other slot + /// must move no partition. Both bands are exercised, so neither branch + /// passes by never being taken. + #[test] + fn soul_only_the_selected_bands_effects_are_committed() { + let mut bench = bench("SelectedBand"); + let split_id = affordance_named(&bench.active, "carry_split"); + let split = DecisionInvocation { + affordance: split_id, + bindings: vec![ + binding("from", Target::Subject(bench.clerk)), + binding("recipient", Target::Subject(bench.keeper)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.tithe)), + ], + proposed: vec![ + ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }, + ProposedEffect { + slot: 1, + magnitude: Magnitude::Quantity(Quantity(1)), + }, + ], + speech: None, + display: None, + }; + let mut seen: BTreeSet = BTreeSet::new(); + + for wanted in [0usize, 1] { + // The draw is a pure function of the pre-commit state and the + // command id; `act_drawing` finds the revision whose id reaches it. + let before_clerk = bench.held(bench.clerk); + let before_keeper = bench.held(bench.keeper); + let receipt = act_drawing(&mut bench.kernel, bench.clerk, &split, wanted); + assert!(receipt.resulting_revision > 0); + bench.refresh(); + let event = bench + .kernel + .events() + .last() + .expect("the committed event") + .clone(); + assert_eq!(event.band, wanted); + seen.insert(event.band); + match event.band { + 0 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 2); + assert_eq!(bench.held(bench.keeper), before_keeper + 2); + } + 1 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Consume { + holder: bench.clerk, + resource: bench.tithe, + qty: Quantity(1), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 1); + assert_eq!(bench.held(bench.keeper), before_keeper); + } + other => panic!("the entry declares two bands, drew {other}"), + } + } + + assert_eq!( + seen.len(), + 2, + "both declared bands must be reachable across command ids" + ); + } + + /// Soul: `RoleSpec` persists inside the catalog, so `RefKind` had to become + /// serializable this pass. An internally tagged newtype over an `Option` + /// does not serialize; this one is adjacently tagged, and a stored + /// `Subject(None)` role is what would fault on first write if that were + /// wrong. The fixture catalog carries four such roles. + #[test] + fn soul_a_stored_role_spec_over_an_optional_subject_kind_round_trips() { + let bench = bench("OptionalSubjectKind"); + let entry = bench + .kernel + .state + .affordance_catalog + .get(&bench.carry) + .expect("the fixture entry"); + assert!( + entry + .roles + .iter() + .any(|spec| spec.kind == RefKind::Subject(None)) + ); + + // The affordance document round-trips through the `to_vec_named` path the + // state digest hashes. + let catalog = rmp_serde::to_vec_named(&bench.kernel.state.affordance_catalog) + .expect("the affordance document encodes"); + let decoded: std::collections::BTreeMap<_, crate::Affordance> = + rmp_serde::from_slice(&catalog).expect("the affordance document decodes"); + assert_eq!(decoded, *bench.kernel.state.affordance_catalog.as_map()); + assert!(bench.kernel.state.full_state_digest().is_ok()); + } + + #[test] + fn a_forged_band_or_forged_effect_does_not_apply() { + let bench = bench("ForgedAction"); + let command_id = CommandId::issue(); + let invocation = bench.carry(2, bench.yard); + let honest = draw_once(&bench.kernel.state, command_id, bench.clerk, &invocation).unwrap(); + let caller = play_caller(); + + for forged in [ + DecisionEvent { + band: 3, + ..honest.clone() + }, + DecisionEvent { + effects: vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(OPENING_BALANCE), + }], + ..honest.clone() + }, + ] { + let mut candidate = bench.kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, bench.kernel.state); + } + + // An event naming another actor does not apply either: the actor is + // read from the event, so a swapped actor is re-derived for the swap. + let mut candidate = bench.kernel.state.clone(); + assert!( + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: DecisionEvent { + actor: bench.keeper, + ..honest.clone() + }, + }, + ) + .is_err() + ); + assert_eq!(candidate, bench.kernel.state); + + // The honest event still applies through the same arm. + let mut candidate = bench.kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: honest, + }, + ) + .unwrap(); + assert_ne!(candidate.holdings, bench.kernel.state.holdings); + } + + #[test] + fn the_kernel_speak_entry_commits_its_utterance_and_no_operation() { + let mut kernel = custody_kernel("SpeakEntry"); + let _topology = kernel.snapshot().unwrap(); + let active = kernel.snapshot().unwrap(); + let speak = affordance_named(&active, "speak"); + let human = active + .subjects + .iter() + .find(|subject| subject.label == "The Human") + .expect("the human subject") + .id; + let holdings = kernel.state.holdings.clone(); + let receipt = act( + &mut kernel, + human, + DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("I open the door.").unwrap()), + display: None, + }, + ) + .expect("the Speak entry commits"); + assert!(receipt.resulting_revision > 0); + let events = kernel.events(); + let event = events.last().unwrap(); + assert_eq!(event.band, 0); + // The two the speech lowering prepends, and nothing from a slot. + assert_eq!(event.effects.len(), 2); + assert_eq!( + crate::tests::spoken(&kernel.state, event), + Some("I open the door.") + ); + assert_eq!(kernel.state.holdings, holdings); + } + + /// The civic bench: one world where an institution holds jurisdiction over + /// a hall, a person holds the same jurisdiction only through an office, and + /// two more people stand inside and outside that ground. + struct Civics { + kernel: WorldKernel, + active: WorldSnapshot, + topology: Topology, + civic: Civic, + } + + fn civics(title: &str) -> Civics { + let mut kernel = custody_kernel(title); + let (topology, civic, active) = civic_world(&mut kernel); + Civics { + kernel, + active, + topology, + civic, + } + } + + impl Civics { + fn refresh(&mut self) { + self.active = self.kernel.snapshot().unwrap(); + } + + fn call( + &self, + kind: &str, + bindings: Vec, + proposed: Vec, + speech: Option, + ) -> DecisionInvocation { + DecisionInvocation { + affordance: affordance_named(&self.active, kind), + bindings, + proposed, + speech, + display: None, + } + } + + /// A levy of `qty` from `payer`, always paid to the actor: the payee is + /// the reserved role, so it is not a binding the caller supplies. + fn levy(&self, payer: SubjectId, qty: u64) -> DecisionInvocation { + self.call( + "levy", + vec![ + binding("payer", Target::Subject(payer)), + binding("resource", Target::Entity(self.civic.grain)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(qty)), + }], + None, + ) + } + + fn delegate(&self, deputy: SubjectId, ground: EntityId) -> DecisionInvocation { + self.call( + "delegate", + vec![ + binding("deputy", Target::Subject(deputy)), + binding("ground", Target::Entity(ground)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + /// Commands a subordinate to traverse a route: the fixture's one + /// `Relocate`-lowering affordance, gated by `command` authority over + /// the subordinate rather than by the subordinate's own consent. + fn deploy(&self, subordinate: SubjectId, via: EdgeId) -> DecisionInvocation { + self.call( + "deploy", + vec![ + binding("subordinate", Target::Subject(subordinate)), + binding("via", Target::Edge(via)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + /// Strips `holder`'s `levy` grant over `ground`: the fixture's one + /// `RevokeAuthority`-lowering affordance, carrying no precondition of + /// its own so a rejection can only be the action lane's revocation + /// envelope. + fn revoke(&self, holder: SubjectId, ground: EntityId) -> DecisionInvocation { + self.call( + "revoke", + vec![ + binding("holder", Target::Subject(holder)), + binding("ground", Target::Entity(ground)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + fn try_as( + &self, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Result { + draw_once( + &self.kernel.state, + CommandId::issue(), + actor, + invocation, + ) + } + + fn rejected_as( + &self, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Vec { + match self.try_as(actor, invocation) { + Err(KernelError::ActionRejected(rejected)) => rejected, + other => panic!("expected an action rejection, got {other:?}"), + } + } + + fn commit_as(&mut self, actor: SubjectId, invocation: DecisionInvocation) -> CommitReceipt { + let receipt = act(&mut self.kernel, actor, invocation).expect("the invocation commits"); + self.refresh(); + receipt + } + + fn admit(&mut self, ops: Vec) { + let before = self.kernel.snapshot().unwrap(); + let receipt = submit_play(&mut self.kernel, &before, operations(ops)); + assert!(receipt.resulting_revision > 0); + self.refresh(); + } + + fn refuse(&mut self, ops: Vec) -> Vec { + let before = self.kernel.snapshot().unwrap(); + reject_play(&mut self.kernel, &before, operations(ops)) + } + } + + /// Contract 7's third rejection: commanding outside authority, with the + /// exact failed precondition and no allocation. + #[test] + fn an_unauthorized_actor_names_the_failed_precondition() { + let bench = civics("Unauthorized"); + let before = bench.kernel.state.clone(); + let before_events = bench.kernel.events(); + assert_eq!( + bench.rejected_as(bench.civic.farmer, &bench.levy(bench.civic.reeve, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.holdings, before.holdings); + assert_eq!(bench.kernel.events(), before_events); + } + + /// A place jurisdiction reaches everything under it and nothing else, and + /// the answer is read live: a target that walks out of the subtree stops + /// being authorized without any digest moving. + #[test] + fn place_jurisdiction_reaches_a_containment_subtree_and_stops_at_its_edge() { + let mut bench = civics("Subtree"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + + // The farmer stands in the chamber, whose container is the hall. + assert!(bench.try_as(treasury, &bench.levy(farmer, 1)).is_ok()); + + // The pedlar stands on the road, outside the hall entirely, and an + // unplaced subject is covered by no place target. + assert_eq!( + bench.rejected_as(treasury, &bench.levy(bench.civic.outsider, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + let unplaced = *bench + .kernel + .state + .subjects + .keys() + .find(|subject_id| !bench.kernel.state.positions.contains_key(subject_id)) + .expect("the genesis world declares an unplaced subject"); + assert_eq!( + bench.rejected_as(treasury, &bench.levy(unplaced, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // Walking the farmer out of the hall flips the same invocation, and a + // grant naming the subject directly authorizes it again. + bench.admit(vec![ + ComponentOp::Relocate { + subject: PatchRef::Existing(farmer), + via: PatchRef::Existing(bench.civic.passage), + }, + ComponentOp::Relocate { + subject: PatchRef::Existing(farmer), + via: PatchRef::Existing(bench.civic.causeway), + }, + ]); + assert_eq!( + bench.rejected_as(treasury, &bench.levy(farmer, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + bench.admit(vec![grant_to(treasury, LEVY_KIND, over_subject(farmer))]); + assert!(bench.try_as(treasury, &bench.levy(farmer, 1)).is_ok()); + } + + /// An office lends jurisdiction its holder does not own, and vacating takes + /// it back: the act is refused at admission. + #[test] + fn office_delegation_grants_and_vacating_revokes() { + let mut bench = civics("Office"); + let reeve = bench.civic.reeve; + let farmer = bench.civic.farmer; + assert!(bench.kernel.state.authority.get(&reeve).is_none()); + assert!(bench.try_as(reeve, &bench.levy(farmer, 1)).is_ok()); + + // The vacated office lends nothing: the act is refused at admission. + let invocation = bench.levy(farmer, 1); + bench.admit(vec![ComponentOp::VacateOffice { + institution: PatchRef::Existing(bench.civic.treasury), + office: office(WARDEN_OFFICE), + }]); + + let holdings = bench.kernel.state.holdings.clone(); + let error = act(&mut bench.kernel, reeve, invocation).unwrap_err(); + assert!(matches!(error, KernelError::ActionRejected(_)), "{error:?}"); + assert_eq!(bench.kernel.state.holdings, holdings); + assert_eq!( + bench.rejected_as(reeve, &bench.levy(farmer, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + } + + /// The reserved role in both directions: an invocation may not bind it, and + /// a catalog entry may not declare it. + #[test] + fn a_levy_cannot_be_directed_away_from_the_actor() { + let bench = civics("ActorRole"); + let mut redirected = bench.levy(bench.civic.farmer, 1); + redirected + .bindings + .push(binding("actor", Target::Subject(bench.civic.outsider))); + assert_eq!( + bench.rejected_as(bench.civic.treasury, &redirected), + vec![ActionMismatch::ActorRoleBound] + ); + + // The declaration half runs at genesis, so it runs against a fresh world. + let mut draft = custody_kernel("ReservedRole"); + let before = draft.snapshot().unwrap(); + let handle = DraftHandle::new("thief"); + let rejected = reject_play( + &mut draft, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: handle.clone(), + kind: AffordanceKindName("thief".into()), + roles: vec![RoleSpec { + role: Role("actor".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!(rejected.contains(&crate::Mismatch::ReservedRole { handle })); + } + + /// The two rejection lanes stay distinguishable: an over-levy inside its + /// declared ceiling passes every affordance check and dies in the ledger. + #[test] + fn an_over_levy_fails_in_the_ledger_not_in_the_contract() { + let bench = civics("OverLevy"); + let error = bench + .try_as(bench.civic.treasury, &bench.levy(bench.civic.farmer, 9)) + .unwrap_err(); + let KernelError::PatchRejected(rejected) = error else { + panic!("an over-levy is a ledger rejection"); + }; + assert_eq!( + rejected, + vec![crate::Mismatch::InsufficientCustody { operation: 0 }] + ); + } + + /// A delegated grant may not exceed the granter's own, and the grant it + /// does mint is still subject to disjointness. + #[test] + fn a_delegated_grant_may_not_exceed_the_granter() { + let mut bench = civics("Monotone"); + let treasury = bench.civic.treasury; + let outsider = bench.civic.outsider; + + // The treasury commands the road but does not levy it, so the + // precondition passes and the delegation alone is refused. + let road = bench.topology.road; + bench.admit(vec![grant_to(treasury, COMMAND_KIND, over_place(road))]); + let outside = bench.delegate(outsider, road); + assert_eq!( + bench.rejected_as(treasury, &outside), + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + + // The chamber is inside it, so the same act commits and the deputy can + // then levy there. + let inside = bench.delegate(outsider, bench.civic.chamber); + assert!(bench.commit_as(treasury, inside).resulting_revision > 0); + assert!( + bench + .try_as(outsider, &bench.levy(bench.civic.farmer, 1)) + .is_ok() + ); + + // An office lends exactly the kinds it delegates: the warden's `levy` + // does not make its holder a commander. + let again = bench.delegate(outsider, bench.civic.chamber); + assert_eq!( + bench.rejected_as(bench.civic.reeve, &again), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The minted grant is ordinary state: repeating it changes nothing, and + // widening it to the hall would overlap what the deputy already holds. + let error = bench.try_as(treasury, &again).unwrap_err(); + let KernelError::PatchRejected(rejected) = error else { + panic!("a duplicate delegation is a patch rejection"); + }; + assert_eq!( + rejected, + vec![crate::Mismatch::NoOperationEffect { operation: 0 }] + ); + let hall = bench.civic.hall; + assert_eq!( + bench.refuse(vec![grant_to(outsider, LEVY_KIND, over_place(hall))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + } + + /// The revocation envelope is the same predicate as the grant one, read + /// the other way: an actor may strip a `levy` grant only over ground its + /// own authority covers, so a bystander cannot use `revoke` to reach past + /// what it may otherwise touch. + #[test] + fn revoking_a_grant_requires_covering_authority_over_its_ground() { + let mut bench = civics("RevokeEnvelope"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let hall = bench.civic.hall; + + // The farmer holds no authority at all, so stripping the treasury's + // own `levy` grant over the hall fails the envelope before the patch + // lane ever sees the operation. + assert_eq!( + bench.rejected_as(farmer, &bench.revoke(treasury, hall)), + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + + // The treasury's own `levy` grant over the hall covers the hall, so + // the treasury may strip its own grant, and the ledger loses it. + assert!(bench.commit_as(treasury, bench.revoke(treasury, hall)).resulting_revision > 0); + assert!( + !bench + .kernel + .state + .authority + .get(&treasury) + .is_some_and(|grants| grants.contains(&crate::AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: crate::AuthorityTarget::PlaceSubtree(hall), + })), + "the revoked grant is gone from the ledger" + ); + } + + /// The fixture's one `Relocate`-lowering affordance: a commander may move + /// a subordinate standing under its ground, and one standing outside it + /// fails the same `Authorized` precondition every other civic act reads. + #[test] + fn deploy_relocates_a_subordinate_under_command_and_refuses_one_outside_it() { + let mut bench = civics("Deploy"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let outsider = bench.civic.outsider; + let chamber = bench.civic.chamber; + let hall = bench.civic.hall; + let passage = bench.civic.passage; + + // The pedlar stands on the road, outside the hall the treasury + // commands, so the precondition alone refuses the attempt. + assert_eq!( + bench.rejected_as(treasury, &bench.deploy(outsider, passage)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The farmer stands in the chamber, under the treasury's command, and + // the passage carries it into the hall the same way a direct + // `Relocate` would. + assert_eq!( + bench + .kernel + .state + .positions + .get(&farmer) + .map(|position| position.place), + Some(chamber) + ); + assert!(bench.commit_as(treasury, bench.deploy(farmer, passage)).resulting_revision > 0); + assert_eq!( + bench + .kernel + .state + .positions + .get(&farmer) + .map(|position| position.place), + Some(hall) + ); + } + + /// `Redress` with a reducer reader: standing is the covering predicate over + /// the forum's target, and closing the forum removes the verb's ground. + #[test] + fn a_petition_requires_standing() { + let mut bench = civics("Petition"); + let petition = bench.call( + "petition", + Vec::new(), + Vec::new(), + Some(Statement::new("The tithe was taken twice.").unwrap()), + ); + assert_eq!( + bench.rejected_as(bench.civic.outsider, &petition), + vec![ActionMismatch::NoStanding { precondition: 0 }] + ); + + let farmer = bench.civic.farmer; + assert!(bench.commit_as(farmer, petition.clone()).resulting_revision > 0); + let events = bench.kernel.events(); + let event = events.last().expect("the committed event"); + assert_eq!(event.effects.len(), 2); + assert_eq!( + crate::tests::spoken(&bench.kernel.state, event), + Some("The tithe was taken twice.") + ); + + bench.admit(vec![ComponentOp::CloseForum { + grievance: grievance(SEIZURE_GRIEVANCE), + }]); + assert_eq!( + bench.rejected_as(farmer, &petition), + vec![ActionMismatch::NoStanding { precondition: 0 }] + ); + } + + /// One predicate, two callers: the resolver's `Relocate` arm and + /// `Reachable`'s edge admission read the same `Restricted` rule, and a + /// same-patch grant then move resolves through the candidate shadow. + #[test] + fn a_restricted_route_admits_exactly_its_named_authority() { + let mut bench = civics("Restricted"); + let walker = bench.topology.walker; + let step = ComponentOp::Relocate { + subject: PatchRef::Existing(walker), + via: PatchRef::Existing(bench.civic.postern), + }; + + // Holding nothing, and holding `admit` over the origin only, are both + // refused: the rule asks about the destination. + assert!( + bench + .refuse(vec![step.clone()]) + .contains(&crate::Mismatch::RouteAccessRestricted { operation: 0 }) + ); + let yard = bench.topology.yard; + bench.admit(vec![grant_to(walker, ADMIT_KIND, over_place(yard))]); + assert!( + bench + .refuse(vec![step.clone()]) + .contains(&crate::Mismatch::RouteAccessRestricted { operation: 0 }) + ); + + // Reachable reads the same rule from the other side. + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(!reachable( + &bench.kernel.state, + walker, + &authority, + bench.civic.chamber, + Cost(4) + )); + + // A grant covering the destination, minted in the same patch as the + // move, resolves through the candidate authority shadow. + let hall = bench.civic.hall; + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(!patch::route_admits( + &bench.kernel.state, + &authority, + bench.kernel.state.edges[&bench.civic.postern].access(), + bench.civic.chamber + )); + bench.admit(vec![grant_to(walker, ADMIT_KIND, over_place(hall)), step]); + assert_eq!( + bench.kernel.state.positions[&walker].place, + bench.civic.chamber + ); + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(patch::route_admits( + &bench.kernel.state, + &authority, + bench.kernel.state.edges[&bench.civic.postern].access(), + bench.civic.chamber + )); + } + + /// The remaining institutional affordances, each proving one lowering arm: + /// `sanction` closes shared topology under a legitimacy check with an + /// interdiction band that fails, and `appoint` makes succession an act + /// someone performs under authority rather than a declared method string. + #[test] + fn sanction_and_appoint_reach_the_reducer_under_authority() { + let mut bench = civics("Institutional"); + let treasury = bench.civic.treasury; + let passage = bench.civic.passage; + let sanction = bench.call( + "sanction", + vec![binding("road", Target::Edge(passage))], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + + // The reeve holds the verb but its office lends only `levy`, so the same + // act names the precondition it failed. + assert_eq!( + bench.rejected_as(bench.civic.reeve, &sanction), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The treasury commands the hall, and the passage has both endpoints + // under it. The draw decides whether the interdiction lands. + let receipt = act_drawing(&mut bench.kernel, treasury, &sanction, 0); + assert!(receipt.resulting_revision > 0); + bench.refresh(); + assert!(!bench.kernel.state.edges[&passage].is_open()); + + // Appointment installs an incumbent through the action lane. + let farmer = bench.civic.farmer; + let appoint = bench.call( + "appoint", + vec![ + binding("institution", Target::Subject(treasury)), + binding("candidate", Target::Subject(farmer)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + assert!(bench.commit_as(treasury, appoint).resulting_revision > 0); + assert_eq!( + bench.kernel.state.selection[&treasury][&office("bailiff")].incumbent, + Some(farmer) + ); + } + + // --- Soul: pass-5 falsification ------------------------------------- + + /// Submits an invocation through the real command path and hands back + /// whatever the kernel decided, refusal included. + fn soul_submit( + bench: &mut Civics, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + act(&mut bench.kernel, actor, invocation) + } + + /// `DelegationNotMonotone` is not a fixture-only verdict: the real `submit` + /// path reaches it, and the refused act commits nothing. + #[test] + fn soul_delegation_not_monotone_reaches_the_real_command_path() { + let mut bench = civics("SoulMonotone"); + let treasury = bench.civic.treasury; + let road = bench.topology.road; + let outsider = bench.civic.outsider; + bench.admit(vec![grant_to(treasury, COMMAND_KIND, over_place(road))]); + let invocation = bench.delegate(outsider, road); + let before = bench.kernel.state.clone(); + let before_events = bench.kernel.events(); + let error = soul_submit(&mut bench, treasury, invocation).unwrap_err(); + let KernelError::ActionRejected(rejected) = error else { + panic!("an over-wide delegation is an action rejection"); + }; + assert_eq!( + rejected, + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.authority, before.authority); + assert_eq!(bench.kernel.events().len(), before_events.len()); + } + + /// The `Restricted` rule is enforced by the component writer, not only by + /// the resolver: a forged `ResolvedOp` that skipped `resolve_patch` still + /// cannot walk a subject through a door it holds no key to, and the same + /// operation succeeds the moment the key exists. + #[test] + fn soul_a_restricted_relocate_is_refused_by_the_component_writer() { + let bench = civics("SoulReducerGate"); + let walker = bench.topology.walker; + let step = ResolvedOp::Relocate { + subject_id: walker, + edge_id: bench.civic.postern, + }; + + let mut forged = bench.kernel.state.clone(); + forged.positions.insert( + walker, + crate::patch::Position { + place: bench.topology.yard, + }, + ); + let mut refused = forged.clone(); + let resolves_to = refused.revision + 1; + let error = + crate::apply_operations(&mut refused, std::slice::from_ref(&step), &[], resolves_to) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + + let mut admitted = forged; + admitted.authority.insert( + walker, + BTreeSet::from([crate::AuthorityGrant { + kind: crate::tests::authority_kind(ADMIT_KIND), + over: crate::AuthorityTarget::PlaceSubtree(bench.civic.hall), + }]), + ); + let resolves_to = admitted.revision + 1; + crate::apply_operations(&mut admitted, std::slice::from_ref(&step), &[], resolves_to) + .expect("the named key opens the door at the component writer too"); + assert_eq!(admitted.positions[&walker].place, bench.civic.chamber); + } + + /// A grant change on the *granter* reaches the delegate: once the + /// treasury's levy ground is revoked, the reeve's act is refused at + /// admission, and nothing commits. + #[test] + fn soul_a_granter_revocation_refuses_the_delegates_act() { + let mut bench = civics("SoulRebind"); + let reeve = bench.civic.reeve; + let farmer = bench.civic.farmer; + let treasury = bench.civic.treasury; + let hall = bench.civic.hall; + + assert!(bench.try_as(reeve, &bench.levy(farmer, 1)).is_ok()); + let invocation = bench.levy(farmer, 1); + bench.admit(vec![ComponentOp::RevokeAuthority { + holder: PatchRef::Existing(treasury), + grant: crate::tests::grant_of(LEVY_KIND, over_place(hall)), + }]); + let events = bench.kernel.events().len(); + let error = act(&mut bench.kernel, reeve, invocation).unwrap_err(); + assert!( + matches!(error, KernelError::ActionRejected(_)), + "a revoked lend is a rejection: {error:?}" + ); + assert_eq!(bench.kernel.events().len(), events); + } + + /// Structural overlap alone does not see a `Subject` grant sitting inside + /// a `PlaceSubtree` grant of the same kind: `targets_overlap` compares + /// shapes, not position, and stays that way so the answer cannot decay + /// when a subject walks somewhere. Admission catches the cross-shape case + /// live instead, in the resolver where the second grant lands, using the + /// same covering predicate `Authorized` reads. Both directions fire the + /// identical check, so whichever grant is minted second is the one that + /// is refused. + #[test] + fn soul_a_subject_grant_inside_a_place_grant_is_a_second_source() { + let mut bench = civics("SoulOverlap"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let hall = bench.civic.hall; + + // The farmer stands under the hall the treasury already levies, so the + // covering predicate says both grants would answer for the same + // target, and admission refuses the narrower grant landing second. + assert!(crate::covers( + &bench.kernel.state, + crate::AuthorityTarget::PlaceSubtree(hall), + Target::Subject(farmer) + )); + assert_eq!( + bench.refuse(vec![grant_to(treasury, LEVY_KIND, over_subject(farmer))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // The symmetric order: a direct grant over the farmer, minted first + // under a fresh kind, blocks a later place grant that would cover + // him too. + const AUDIT_KIND: &str = "audit"; + bench.admit(vec![grant_to(treasury, AUDIT_KIND, over_subject(farmer))]); + assert_eq!( + bench.refuse(vec![grant_to(treasury, AUDIT_KIND, over_place(hall))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + } + + /// Replay for the new arms is not a separate machine: `reduce` is a pure + /// function of committed state and the envelope, so running it twice on the + /// same pre-state yields the same effect, and that effect is exactly what + /// the commit stored. No clock and no draw entropy enter. + #[test] + fn soul_reduce_is_pure_for_every_new_civic_arm() { + let mut bench = civics("SoulReplay"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let outsider = bench.civic.outsider; + let chamber = bench.civic.chamber; + let passage = bench.civic.passage; + + let sanction = bench.call( + "sanction", + vec![binding("road", Target::Edge(passage))], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + let appoint = bench.call( + "appoint", + vec![ + binding("institution", Target::Subject(treasury)), + binding("candidate", Target::Subject(farmer)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + for invocation in [ + bench.levy(farmer, 2), + bench.delegate(outsider, chamber), + sanction, + appoint, + ] { + let before = bench.kernel.state.clone(); + let caller = play_caller(); + let envelope = command( + &bench.active, + caller.clone(), + CommandBody::Act { + actor: treasury, + invocation, + }, + ); + let first = crate::reduce(&before, &envelope).expect("the act reduces"); + let second = crate::reduce(&before, &envelope).expect("the act reduces again"); + assert_eq!(first, second, "reduce is not a pure function of the state"); + let receipt = bench + .kernel + .submit(envelope, &AuthenticatedCaller::fixture(caller)) + .expect("the act commits"); + assert!(receipt.resulting_revision > 0); + bench.refresh(); + let WorldEffect::Acted { event, .. } = first else { + panic!("an acted effect"); + }; + assert_eq!( + bench.kernel.events().last().expect("a committed event"), + &event, + "the committed event is not what reduce produced" + ); + } + } + + /// `resolve_patch`'s candidate knowledge map never models `Communicate`'s + /// fan-out (see the comment beside its construction in `patch.rs`), and + /// that omission is safe only because no `ComponentOpKind` an affordance + /// may declare can lower to a knowledge write carrying + /// `KnowledgeSource::Told`. Two kinds touch knowledge: `AcquireKnowledge`, + /// whose source `lower` fixes to `AuthoredSource::Witnessed` — a type with + /// no `Told` variant to begin with — and `Witness`, which carries no source + /// field and no speaker field at all. This test pins both lowerings, at the + /// call sites that turn a declared slot into a `ComponentOp`, so a future + /// author cannot widen either without this assertion naming the change. + #[test] + fn no_component_op_kind_lowers_to_a_told_knowledge_write() { + let bench = bench("AcquireKnowledgeLowering"); + let entry = Affordance { + kind: AffordanceKindName("witness".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AcquireKnowledge { + confidence: Confidence::Believed, + }, + roles: vec![Role("subject".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }; + let bindings = BTreeMap::from([ + (Role("subject".into()), Target::Subject(bench.clerk)), + (Role("fact".into()), Target::Entity(bench.tithe)), + ]); + let invocation = DecisionInvocation { + affordance: bench.carry, + bindings: Vec::new(), + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + let lowered = lower( + &entry, + 0, + bench.clerk, + FictionalMinutes::default(), + &invocation, + &bindings, + ) + .expect("the acquire slot lowers"); + assert_eq!( + lowered, + vec![ComponentOp::AcquireKnowledge { + subject: PatchRef::Existing(bench.clerk), + fact: PatchRef::Existing(bench.tithe), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }], + "AcquireKnowledge must lower with a Witnessed source, never a forged teller" + ); + + let witnessing = Affordance { + kind: AffordanceKindName("beacon".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Witness { + confidence: Confidence::Believed, + }, + roles: vec![Role("fact".into()), Role("place".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }; + let places = BTreeMap::from([ + (Role("fact".into()), Target::Entity(bench.tithe)), + (Role("place".into()), Target::Entity(bench.yard)), + ]); + let lowered = lower( + &witnessing, + 0, + bench.clerk, + FictionalMinutes::default(), + &invocation, + &places, + ) + .expect("the witness slot lowers"); + assert_eq!( + lowered, + vec![ComponentOp::Witness { + fact: PatchRef::Existing(bench.tithe), + place: PatchRef::Existing(bench.yard), + confidence: Confidence::Believed, + }], + "Witness must lower with no speaker field to forge" + ); + } + + /// The pin above names two knowledge-touching kinds by example, and a list + /// by example goes stale in silence. This match is exhaustive, so a new + /// `ComponentOpKind` breaks the build here and its author must say whether + /// it touches knowledge. The set that does is `AcquireKnowledge`, `Witness`, + /// and `Forget`; the first two are pinned above as unable to carry a teller, + /// and `Forget` writes no row at all — it only removes one, so it has no + /// source to forge. + #[test] + fn soul_every_knowledge_touching_op_kind_is_named_by_the_told_pin() { + fn touches_knowledge(kind: &ComponentOpKind) -> bool { + match kind { + ComponentOpKind::AcquireKnowledge { .. } + | ComponentOpKind::Witness { .. } + | ComponentOpKind::Forget => true, + ComponentOpKind::Relocate + | ComponentOpKind::OpenRoute + | ComponentOpKind::CloseRoute + | ComponentOpKind::AlterCost + | ComponentOpKind::Transfer + | ComponentOpKind::Transform + | ComponentOpKind::Consume + | ComponentOpKind::Bind + | ComponentOpKind::Release + | ComponentOpKind::GrantAuthority { .. } + | ComponentOpKind::RevokeAuthority { .. } + | ComponentOpKind::InstallIncumbent { .. } + | ComponentOpKind::VacateOffice { .. } + | ComponentOpKind::CreateCommitment { .. } + | ComponentOpKind::AdvancePressure { .. } + | ComponentOpKind::ReducePressure { .. } + | ComponentOpKind::ResolvePressure => false, + } + } + + let confidence = Confidence::Believed; + let touching = [ + ComponentOpKind::AcquireKnowledge { confidence }, + ComponentOpKind::Witness { confidence }, + ComponentOpKind::Forget, + ComponentOpKind::Relocate, + ComponentOpKind::Transfer, + ComponentOpKind::ResolvePressure, + ] + .iter() + .filter(|kind| touches_knowledge(kind)) + .count(); + assert_eq!( + touching, 3, + "the knowledge-touching set is not the one this pin names" + ); + } +} diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs new file mode 100644 index 000000000..eaee01512 --- /dev/null +++ b/native/aetherlight/src/clock.rs @@ -0,0 +1,250 @@ +//! The world clock and the motion one tick produces. +//! +//! One entry point into the reducer, [`derive_motion`], reached from `reduce`'s +//! `AdvanceTime` arm and from `apply_effect`'s `TimeAdvanced` arm, so a forged +//! tick is re-derived by the same function that produced the honest one. It is +//! pure over `(state, to)`: no wall clock, no entropy, no caller value beyond +//! the span. + +use super::patch::{Commitment, CommitmentKey, CommitmentKind, DependencyTarget, MAX_ROUTE_COST}; +use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action, views}; +#[cfg(test)] +use super::is_retired; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Minutes since genesis. Monotonic, kernel-owned, world-level. `u64` because a +/// world clock has no bound; `Cost` is `1..=MAX_ROUTE_COST` because it weighs +/// one edge, and reusing it here would put an edge's bound on the world's age. +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, +)] +#[serde(transparent)] +pub struct FictionalMinutes(pub u64); + +impl FictionalMinutes { + pub(crate) fn checked_add(self, span: TickMinutes) -> Option { + self.0.checked_add(u64::from(span.0)).map(Self) + } +} + +/// The span one `AdvanceTime` names, `1..=MAX_ROUTE_COST` (one year of +/// minutes), reusing pass 2's constant as a span bound rather than an edge +/// bound: an unbounded span lets one command jump the clock past every due date +/// in the world and makes the size of a commit a caller-chosen number. +/// +/// The type owns its bound at every door: `new` and decoding both go through +/// it, so a command, a routine's period or a stored commit that names a span +/// outside the bound cannot be read at all, and no reducer or replay clause +/// re-checks it. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(try_from = "u32", into = "u32")] +pub struct TickMinutes(u32); + +impl TryFrom for TickMinutes { + type Error = &'static str; + + fn try_from(minutes: u32) -> Result { + Self::new(minutes).ok_or("a tick span is 1..=525600 minutes") + } +} + +impl From for u32 { + fn from(span: TickMinutes) -> u32 { + span.0 + } +} + +impl TickMinutes { + pub fn new(minutes: u32) -> Option { + (1..=MAX_ROUTE_COST) + .contains(&minutes) + .then_some(Self(minutes)) + } + + pub fn minutes(self) -> u32 { + self.0 + } +} + +/// Everything one tick moves, stated as outcomes rather than deltas so the +/// effect says what the world became. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Motion { + /// Routines that fulfilled, in `(subject, key)` order. + pub(crate) fulfilled: Vec, + /// Pressure rows written, in `(target, source)` order, with the resulting + /// magnitude — not the delta. + pub(crate) pressed: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoutineFulfilled { + pub(crate) subject: SubjectId, + pub(crate) key: CommitmentKey, + pub(crate) next_due: FictionalMinutes, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct PressureWritten { + pub(crate) target: SubjectId, + pub(crate) source: PressureSource, + pub(crate) magnitude: PressureMagnitude, +} + +/// The whole magnitude policy, in one place, with no per-world tuning. A +/// blocked routine raises none at all: it retries on the next tick, which is +/// what keeps an unattended subject free of spurious pressure. +mod step { + pub(super) const OBLIGATION_PAST_DUE: u32 = 1; + pub(super) const GOAL_PAST_DUE: u32 = 1; + pub(super) const DEPENDENCY_UNAVAILABLE: u32 = 1; +} + +/// Three stages, each reading only committed `state` and `to`. No stage sees +/// another stage's writes, which is what makes this a one-pass total function +/// with no ordering hazard and no partial state to reason about. +/// +/// Pressure accrues per command, not per minute: one thousand one-minute ticks +/// and one thousand-minute tick over the same span produce different +/// magnitudes. The kernel stays an exact function of the command sequence, and +/// the tick cadence is one operational constant in `runtime.rs`. +/// +/// What is due, and which dependencies fail, is read from `Views` (the one owner +/// of both questions: a live subject's due commitments and a live subject's +/// unavailable dependencies), so a tick reads the work it does and not the +/// world. A view is true only with clean logs, so it is read behind a check +/// that holds in every build (six flag tests), and both callers (`reduce`, and +/// `apply_effect`'s `TimeAdvanced` arm before its first write) call it clean. +pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion { + assert!(views::readable(state), "the views are read with an open log"); + motion_of(state, to, &state.views.due_by(to), state.views.failing().copied()) +} + +/// What `derive_motion` was before the views: every subject holding a promise +/// and every dependency row, with retirement and availability judged on the +/// spot. The view reads must derive the same motion. +#[cfg(test)] +pub(super) fn derive_motion_by_scan(state: &WorldState, to: FictionalMinutes) -> Motion { + let live = |subject: &SubjectId| !is_retired(state, *subject); + let promisors = state.commitments.keys().copied().filter(live).collect(); + let failing: Vec<_> = state + .dependencies + .iter() + .filter(|(subject, _)| live(subject)) + .flat_map(|(subject, targets)| targets.iter().map(move |target| (*subject, *target))) + .filter(|(subject, target)| dependency_unavailable(state, *subject, *target)) + .collect(); + motion_of(state, to, &promisors, failing.into_iter()) +} + +/// The motion over `promisors`, which must hold every live subject with a +/// commitment due by `to`, and the `failing` dependencies of live subjects. +fn motion_of( + state: &WorldState, + to: FictionalMinutes, + promisors: &std::collections::BTreeSet, + failing: impl Iterator, +) -> Motion { + let mut fulfilled = Vec::new(); + let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new(); + + for subject in promisors { + let held = &state.commitments[subject]; + for (key, commitment) in held { + if commitment.due > to { + continue; + } + match commitment.kind { + CommitmentKind::Routine => { + if let Some(next_due) = routine_rolls(state, *subject, commitment) { + fulfilled.push(RoutineFulfilled { + subject: *subject, + key: *key, + next_due, + }); + } + } + CommitmentKind::Obligation | CommitmentKind::Goal => { + let step = if commitment.kind == CommitmentKind::Obligation { + step::OBLIGATION_PAST_DUE + } else { + step::GOAL_PAST_DUE + }; + let source = PressureSource::Commitment { + subject: *subject, + key: *key, + }; + *pressed.entry((*subject, source)).or_default() += step; + } + } + } + } + + for (subject, target) in failing { + let source = PressureSource::Dependency(target); + *pressed.entry((subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE; + } + + Motion { + fulfilled, + pressed: pressed + .into_iter() + .map(|((target, source), step)| PressureWritten { + target, + source, + magnitude: PressureMagnitude( + state + .pressures + .get(&target) + .and_then(|held| held.get(&source)) + .map_or(0, |magnitude| magnitude.0) + .saturating_add(step), + ), + }) + .collect(), + } +} + +/// A routine fulfils when every one of its checks holds, and its `due` then +/// rolls forward by exactly one period per command. Catch-up arithmetic would +/// make the number of fulfilments a function of the operator's tick cadence in +/// a second place; one roll converges over subsequent ticks. +fn routine_rolls( + state: &WorldState, + subject: SubjectId, + commitment: &Commitment, +) -> Option { + if !action::preconditions_hold(state, subject, &commitment.checks).is_empty() { + return None; + } + commitment.due.checked_add(commitment.period?) +} + +/// Whether a subject's dependency is currently failing it. A closed route is a +/// supply failure; an unusable one is a permission question, and reading +/// authority here would drag `effective_authority` into every tick for every +/// dependency in the world. +pub(super) fn dependency_unavailable( + state: &WorldState, + subject: SubjectId, + target: DependencyTarget, +) -> bool { + match target { + DependencyTarget::Route(edge_id) => !state + .edges + .get(&edge_id) + .is_some_and(super::EdgeRecord::is_open), + // Absence is zero, per pass 3: the depender holds none of what it + // depends on. + DependencyTarget::Resource(entity_id) => !state + .holdings + .get(&subject) + .is_some_and(|held| held.contains_key(&entity_id)), + // The subject it depends on is nowhere in the world's topology. + DependencyTarget::Subject(other) => !state.positions.contains_key(&other), + } +} diff --git a/native/aetherlight/src/digest.rs b/native/aetherlight/src/digest.rs new file mode 100644 index 000000000..1cf891244 --- /dev/null +++ b/native/aetherlight/src/digest.rs @@ -0,0 +1,295 @@ +//! The state digest: a homomorphic set hash over per-document digests. +//! +//! Each document (one row of a partition, or the world header) has a digest +//! `sha256(len schema, schema, len key, key, rmp named value)`. The world's +//! accumulator is LtHash16 (Lewi et al. 2019): a document digest is expanded to +//! 2048 bytes and added lane-wise as 1024 wrapping `u16`; removing a document +//! subtracts it, and updating one subtracts the old and adds the new. So the +//! digest of a commit costs what the commit changed, not the size of the world, +//! and it depends on the set of documents alone, never on the order they were +//! written. `state_digest` seals the accumulator with the revision. + +use crate::docs::{DocKey, Docs, Tracked}; +use crate::{KernelError, STATE_SCHEMA}; +use serde::Serialize; +use sha2::{Digest, Sha256}; + +const LANES: usize = 1024; +/// 64 blocks of 32 bytes: 2048 bytes, 1024 lanes. +const BLOCKS: u8 = 64; + +pub(crate) type DocDigest = [u8; 32]; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct LtHash16(Box<[u16; LANES]>); + +impl Default for LtHash16 { + fn default() -> Self { + Self(Box::new([0; LANES])) + } +} + +impl LtHash16 { + fn lanes(doc: &DocDigest) -> impl Iterator + '_ { + (0..BLOCKS).flat_map(move |block| { + let mut hasher = Sha256::new(); + hasher.update(doc); + hasher.update([block]); + let expanded: [u8; 32] = hasher.finalize().into(); + (0..16).map(move |lane| u16::from_le_bytes([expanded[2 * lane], expanded[2 * lane + 1]])) + }) + } + + pub(crate) fn add(&mut self, doc: &DocDigest) { + for (slot, lane) in self.0.iter_mut().zip(Self::lanes(doc)) { + *slot = slot.wrapping_add(lane); + } + } + + pub(crate) fn subtract(&mut self, doc: &DocDigest) { + for (slot, lane) in self.0.iter_mut().zip(Self::lanes(doc)) { + *slot = slot.wrapping_sub(lane); + } + } + + /// The commit-facing digest: the accumulator sealed with the revision. + pub(crate) fn state_digest(&self, revision: u64) -> String { + let mut hasher = Sha256::new(); + hasher.update(STATE_SCHEMA.as_bytes()); + hasher.update(revision.to_be_bytes()); + for lane in self.0.iter() { + hasher.update(lane.to_le_bytes()); + } + format!("sha256:{:x}", hasher.finalize()) + } +} + +#[cfg(test)] +thread_local! { + /// Document digests computed on this thread, for the work-bound test. + pub(crate) static DOC_DIGESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +pub(crate) fn doc_digest( + schema: &str, + key: &str, + value: &V, +) -> Result { + #[cfg(test)] + DOC_DIGESTS.with(|count| count.set(count.get() + 1)); + let bytes = rmp_serde::to_vec_named(value) + .map_err(|error| KernelError::Serialization(error.to_string()))?; + let mut hasher = Sha256::new(); + hasher.update((schema.len() as u64).to_be_bytes()); + hasher.update(schema.as_bytes()); + hasher.update((key.len() as u64).to_be_bytes()); + hasher.update(key.as_bytes()); + hasher.update(bytes); + Ok(hasher.finalize().into()) +} + +/// One change of one document: subtract the old, add the new. +pub(crate) fn fold_change( + acc: &mut LtHash16, + schema: &str, + key: &str, + old: Option<&V>, + new: Option<&V>, +) -> Result<(), KernelError> { + if let Some(old) = old { + acc.subtract(&doc_digest(schema, key, old)?); + } + if let Some(new) = new { + acc.add(&doc_digest(schema, key, new)?); + } + Ok(()) +} + +/// What `WorldState` needs of a partition, whatever its key and value types. +pub(crate) trait Partition { + fn is_clean(&self) -> bool; + fn rollback(&mut self); + fn finish_log(&mut self); + /// Folds the open transaction's changes into `acc`. + fn fold_changes(&self, schema: &str, acc: &mut LtHash16) -> Result<(), KernelError>; + /// Every document's digest, by (schema, key): the full enumeration the + /// incremental digest is checked against. + #[cfg(test)] + fn documents( + &self, + schema: &str, + out: &mut std::collections::BTreeMap<(String, String), DocDigest>, + ) -> Result<(), KernelError>; + /// The partition as encoded: the bytes a test scans for what must never appear. + #[cfg(test)] + fn encoded(&self) -> Vec; + /// How many documents the partition holds. + #[cfg(test)] + fn rows(&self) -> usize; + /// Removes the first document, logged like any write; false when empty. + #[cfg(test)] + fn remove_first(&mut self) -> bool; + /// Whether the read index is exactly the projection of the documents. + #[cfg(test)] + fn index_is_derived(&self) -> bool; + /// Damages the read index in one place (a stray entry, else a missing one); + /// false when there is nothing to damage. + #[cfg(test)] + fn corrupt_index_first(&mut self, stray: bool) -> bool; +} + +impl Partition for Docs +where + K: Ord + Clone + DocKey + Serialize, + V: Clone + PartialEq + Serialize, + P: crate::docs::Projection, +{ + fn is_clean(&self) -> bool { + Docs::is_clean(self) + } + + fn rollback(&mut self) { + Docs::rollback(self); + } + + fn finish_log(&mut self) { + self.finish(); + } + + fn fold_changes(&self, schema: &str, acc: &mut LtHash16) -> Result<(), KernelError> { + for (key, old, new) in self.changes() { + fold_change(acc, schema, &key.key_text(), old, new)?; + } + Ok(()) + } + + #[cfg(test)] + fn documents( + &self, + schema: &str, + out: &mut std::collections::BTreeMap<(String, String), DocDigest>, + ) -> Result<(), KernelError> { + for (key, value) in self.iter() { + let key = key.key_text(); + let digest = doc_digest(schema, &key, value)?; + out.insert((schema.to_owned(), key), digest); + } + Ok(()) + } + + #[cfg(test)] + fn encoded(&self) -> Vec { + rmp_serde::to_vec_named(self).expect("a partition encodes") + } + + #[cfg(test)] + fn rows(&self) -> usize { + self.len() + } + + #[cfg(test)] + fn remove_first(&mut self) -> bool { + let Some(key) = self.keys().next().cloned() else { + return false; + }; + self.remove(&key).is_some() + } + + #[cfg(test)] + fn index_is_derived(&self) -> bool { + Docs::index_is_derived(self) + } + + #[cfg(test)] + fn corrupt_index_first(&mut self, stray: bool) -> bool { + self.corrupt_index_for_test(stray) + } +} + +/// The header's one change, keyed by its own world id. +pub(crate) fn fold_header( + acc: &mut LtHash16, + schema: &str, + key: &str, + header: &Tracked, +) -> Result<(), KernelError> { + if let Some((old, new)) = header.change() { + fold_change(acc, schema, key, old, Some(new))?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn documents(count: u32) -> Vec { + (0..count) + .map(|index| doc_digest("aetherlight.test.v1", &index.to_string(), &index).unwrap()) + .collect() + } + + /// Order never matters and a subtraction undoes an addition, so the digest + /// is a function of the set of documents alone. + #[test] + fn lthash_add_then_subtract_is_zero() { + let docs = documents(300); + let mut acc = LtHash16::default(); + for doc in &docs { + acc.add(doc); + } + assert_ne!(acc, LtHash16::default()); + + let mut backwards = LtHash16::default(); + for doc in docs.iter().rev() { + backwards.add(doc); + } + assert_eq!(acc, backwards, "equal sets in two orders differ"); + + let mut strided = LtHash16::default(); + for index in (0..docs.len()).map(|step| (step * 7) % docs.len()) { + strided.add(&docs[index]); + } + assert_eq!(acc, strided, "equal sets in a third order differ"); + + for index in (0..docs.len()).map(|step| (step * 11) % docs.len()) { + acc.subtract(&docs[index]); + } + assert_eq!(acc, LtHash16::default(), "add then subtract left a residue"); + } + + /// A lane that carries must wrap: 40 additions of one document overflow + /// nearly every lane of a `u16`, and the subtractions still return to zero. + #[test] + fn lanes_wrap_instead_of_saturating() { + let doc = documents(1)[0]; + let mut acc = LtHash16::default(); + for _ in 0..40 { + acc.add(&doc); + } + for _ in 0..40 { + acc.subtract(&doc); + } + assert_eq!(acc, LtHash16::default()); + } + + #[test] + fn the_state_digest_seals_the_revision_and_every_lane() { + let docs = documents(3); + let mut acc = LtHash16::default(); + docs.iter().for_each(|doc| acc.add(doc)); + assert_ne!(acc.state_digest(1), acc.state_digest(2), "the revision is not sealed"); + let mut other = acc.clone(); + other.0[1023] = other.0[1023].wrapping_add(1); + assert_ne!(acc.state_digest(1), other.state_digest(1), "the last lane is not hashed"); + } + + #[test] + fn a_document_digest_separates_schema_key_and_value() { + let one = doc_digest("ab", "c", &1u8).unwrap(); + assert_ne!(one, doc_digest("a", "bc", &1u8).unwrap(), "schema and key run together"); + assert_ne!(one, doc_digest("ab", "c", &2u8).unwrap()); + assert_ne!(one, doc_digest("ab", "d", &1u8).unwrap()); + assert_eq!(one, doc_digest("ab", "c", &1u8).unwrap()); + } +} diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs new file mode 100644 index 000000000..c9120754b --- /dev/null +++ b/native/aetherlight/src/docs.rs @@ -0,0 +1,766 @@ +//! Tracked documents: the one writer of a partition and the one recorder of +//! what a transaction changed. +//! +//! A `Docs` is a map whose every write goes through a method that remembers the +//! key's value as it stood before the transaction (first touch wins). `finish` +//! turns that record into the keys whose value really changed, with their old +//! values; `rollback` puts every touched key back. Reads see the plain map +//! through inherent methods, and no method hands out the map, so a write cannot skip the log. +//! The fields are private to this module for the same reason. + +use serde::{Serialize, Serializer}; +use std::collections::{BTreeMap, BTreeSet}; +use std::collections::btree_map::Entry; +use std::ops::Deref; + +#[cfg(test)] +thread_local! { + /// Rows any `Docs` iterator has yielded on this thread, and entries any + /// `indexed` read has returned: the work a read did, counted where the + /// reads are owned so no reader can skip it. + static ROWS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The rows read on this thread so far (test builds only). +#[cfg(test)] +pub(crate) fn rows_read() -> u64 { + ROWS_READ.with(|rows| rows.get()) +} + +/// Counts rows a view read, where the view is owned (test builds). +#[cfg(test)] +pub(crate) fn count_rows(rows: u64) { + ROWS_READ.with(|count| count.set(count.get() + rows)); +} + +/// A partition iterator that counts every row it yields (test builds); in a +/// shipped build it is the map's own iterator. +pub(crate) struct Counted(I); + +impl Iterator for Counted { + type Item = I::Item; + fn next(&mut self) -> Option { + let item = self.0.next(); + #[cfg(test)] + if item.is_some() { + count_rows(1); + } + item + } +} + +impl DoubleEndedIterator for Counted { + fn next_back(&mut self) -> Option { + let item = self.0.next_back(); + #[cfg(test)] + if item.is_some() { + count_rows(1); + } + item + } +} + +/// A key whose value changed in a transaction, with the value it had before +/// (`None` when the key was absent). The new value is whatever the map holds. +pub(crate) type Changed = (K, Option); + +/// Where a document sits in a partition's read index: a pure function of one +/// document's value, so the index can always be rebuilt from the map and never +/// disagrees with it. +pub(crate) trait Projection { + type Point: Ord + Clone + std::fmt::Debug; + /// Appends every point `value` sits at (duplicates allowed). + fn points(value: &V, out: &mut Vec); +} + +/// The projection of a partition nothing reads by value. +#[derive(Clone, Debug, Default)] +pub(crate) struct NoIndex; + +impl Projection for NoIndex { + type Point = (); + fn points(_: &V, _: &mut Vec<()>) {} +} + +/// A partition: its documents, the log of the open transaction, and the read +/// index (the projection of the documents as of the last `finish`). The index +/// is derived state: it is not digested, not encoded, and ignored by equality. +#[derive(Clone, Debug)] +pub(crate) struct Docs = NoIndex> { + map: BTreeMap, + touched: BTreeMap>, + index: BTreeMap>, +} + +impl> Default for Docs { + fn default() -> Self { + Self { + map: BTreeMap::new(), + touched: BTreeMap::new(), + index: BTreeMap::new(), + } + } +} + +/// Equality is the documents, never the log: two worlds with the same content +/// are equal whatever transaction state they are in. +impl> PartialEq for Docs { + fn eq(&self, other: &Self) -> bool { + self.map == other.map + } +} + +impl> Eq for Docs {} + +impl<'a, K: Ord + Clone, V: Clone + PartialEq, P: Projection> IntoIterator for &'a Docs { + type Item = (&'a K, &'a V); + type IntoIter = Counted>; + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +/// A partition encodes as its map, so the encoded world is what it was before +/// the partitions were tracked. +impl> Serialize for Docs { + fn serialize(&self, serializer: S) -> Result { + self.map.serialize(serializer) + } +} + +impl> std::ops::Index<&K> for Docs { + type Output = V; + fn index(&self, key: &K) -> &V { + &self.map[key] + } +} + +impl> Docs { + pub(crate) fn get(&self, key: &K) -> Option<&V> { + self.map.get(key) + } + + pub(crate) fn contains_key(&self, key: &K) -> bool { + self.map.contains_key(key) + } + + pub(crate) fn len(&self) -> usize { + self.map.len() + } + + pub(crate) fn is_empty(&self) -> bool { + self.map.is_empty() + } + + pub(crate) fn iter(&self) -> Counted> { + Counted(self.map.iter()) + } + + pub(crate) fn keys(&self) -> Counted> { + Counted(self.map.keys()) + } + + pub(crate) fn values(&self) -> Counted> { + Counted(self.map.values()) + } + + pub(crate) fn range>( + &self, + range: R, + ) -> Counted> { + Counted(self.map.range(range)) + } + + /// The plain map, for a test that compares a decoded partition to it. + #[cfg(test)] + pub(crate) fn as_map(&self) -> &BTreeMap { + &self.map + } + + fn touch(&mut self, key: &K) { + if !self.touched.contains_key(key) { + self.touched.insert(key.clone(), self.map.get(key).cloned()); + } + } + + pub(crate) fn insert(&mut self, key: K, value: V) -> Option { + self.touch(&key); + self.map.insert(key, value) + } + + pub(crate) fn remove(&mut self, key: &K) -> Option { + self.touch(key); + self.map.remove(key) + } + + /// Touches only a key that is present: a miss writes nothing. + pub(crate) fn get_mut(&mut self, key: &K) -> Option<&mut V> { + if self.map.contains_key(key) { + self.touch(key); + } + self.map.get_mut(key) + } + + pub(crate) fn entry(&mut self, key: K) -> Entry<'_, K, V> { + self.touch(&key); + self.map.entry(key) + } + + /// The open transaction's changed keys as (key, old, new), without closing it. + pub(crate) fn changes(&self) -> impl Iterator, Option<&V>)> + '_ { + self.touched.iter().filter_map(|(key, old)| { + let new = self.map.get(key); + (new != old.as_ref()).then_some((key, old.as_ref(), new)) + }) + } + + /// The keys whose value differs from the start of the transaction, with the + /// value they had then. A key written back to what it was is not reported. + /// The log is empty afterwards. + pub(crate) fn finish(&mut self) -> Vec> { + let changed: Vec> = std::mem::take(&mut self.touched) + .into_iter() + .filter(|(key, old)| self.map.get(key) != old.as_ref()) + .collect(); + for (key, old) in &changed { + self.fold_index(key, old.as_ref()); + } + changed + } + + /// Moves one changed key's entries: its old points out, its current points in. + fn fold_index(&mut self, key: &K, old: Option<&V>) { + let mut points = Vec::new(); + if let Some(old) = old { + P::points(old, &mut points); + for point in points.drain(..) { + if let Some(keys) = self.index.get_mut(&point) { + keys.remove(key); + if keys.is_empty() { + self.index.remove(&point); + } + } + } + } + if let Some(new) = self.map.get(key) { + P::points(new, &mut points); + for point in points { + self.index.entry(point).or_default().insert(key.clone()); + } + } + } + + /// Every (point, key) inside `range`, in order, true at this moment: the + /// committed index, corrected by the open log. A logged key's committed + /// entries are dropped and its current value's points are read from the + /// map, so a read inside a transaction sees what the transaction wrote and + /// the index itself never saw it (which is why `rollback` leaves it alone). + pub(crate) fn indexed>( + &self, + range: R, + ) -> Vec<(P::Point, K)> { + let mut found: Vec<(P::Point, K)> = self + .index + .range((range.start_bound(), range.end_bound())) + .flat_map(|(point, keys)| keys.iter().map(move |key| (point, key))) + .filter(|(_, key)| !self.touched.contains_key(*key)) + .map(|(point, key)| (point.clone(), key.clone())) + .collect(); + if !self.touched.is_empty() { + // Every logged key is walked whatever the range, so each is a row read. + #[cfg(test)] + count_rows(self.touched.len() as u64); + let mut points = Vec::new(); + for key in self.touched.keys() { + if let Some(value) = self.map.get(key) { + P::points(value, &mut points); + for point in points.drain(..) { + if range.contains(&point) { + found.push((point, key.clone())); + } + } + } + } + found.sort(); + found.dedup(); + } + #[cfg(test)] + count_rows(found.len() as u64); + found + } + + /// The committed index's (point, key) entries inside `range` for keys the + /// open log did not change: no walk of the log, so a bulk transaction pays + /// for the entries it returns and not for every key it touched. A key the + /// log changed is the caller's to judge from `changes()`. + pub(crate) fn indexed_unchanged>( + &self, + range: R, + ) -> Vec<(P::Point, K)> { + let found: Vec<(P::Point, K)> = self + .index + .range((range.start_bound(), range.end_bound())) + .flat_map(|(point, keys)| keys.iter().map(move |key| (point, key))) + .filter(|(_, key)| { + self.touched + .get(*key) + .is_none_or(|old| self.map.get(*key) == old.as_ref()) + }) + .map(|(point, key)| (point.clone(), key.clone())) + .collect(); + #[cfg(test)] + count_rows(found.len() as u64); + found + } + + /// Whether the index is exactly the projection of the map (test builds). + #[cfg(test)] + pub(crate) fn index_is_derived(&self) -> bool { + let mut rebuilt: BTreeMap> = BTreeMap::new(); + let mut points = Vec::new(); + for (key, value) in &self.map { + P::points(value, &mut points); + for point in points.drain(..) { + rebuilt.entry(point).or_default().insert(key.clone()); + } + } + rebuilt == self.index + } + + /// Makes the index disagree with the map in one place: a stray entry (a + /// document listed at a point it does not sit at) or a missing one. False + /// when this partition has no such place to damage (test builds). + #[cfg(test)] + pub(crate) fn corrupt_index_for_test(&mut self, stray: bool) -> bool { + if !stray { + let Some(point) = self.index.keys().next().cloned() else { + return false; + }; + let keys = self.index.get_mut(&point).expect("the point is present"); + let key = keys.iter().next().cloned().expect("a point holds a key"); + keys.remove(&key); + if keys.is_empty() { + self.index.remove(&point); + } + return true; + } + for keys in self.index.values_mut() { + if let Some(key) = self.map.keys().find(|key| !keys.contains(*key)) { + keys.insert(key.clone()); + return true; + } + } + false + } + + /// Puts every touched key back as it was and empties the log. + pub(crate) fn rollback(&mut self) { + for (key, old) in std::mem::take(&mut self.touched) { + match old { + Some(value) => { + self.map.insert(key, value); + } + None => { + self.map.remove(&key); + } + } + } + } + + pub(crate) fn is_clean(&self) -> bool { + self.touched.is_empty() + } +} + +/// One tracked value: the same first-touch rule as a `Docs` key, for the +/// world's own fields. +#[derive(Clone, Debug)] +pub(crate) struct Tracked { + value: T, + /// `None` untouched; `Some(None)` logged as absent (genesis), so `finish` + /// reports it as added. + old: Option>, +} + +impl PartialEq for Tracked { + fn eq(&self, other: &Self) -> bool { + self.value == other.value + } +} + +impl Eq for Tracked {} + +impl Deref for Tracked { + type Target = T; + fn deref(&self) -> &T { + &self.value + } +} + +impl Tracked { + /// A value that did not exist before this transaction. + pub(crate) fn absent(value: T) -> Self { + Self { + value, + old: Some(None), + } + } + + pub(crate) fn get_mut(&mut self) -> &mut T { + if self.old.is_none() { + self.old = Some(Some(self.value.clone())); + } + &mut self.value + } + + /// The old value when the value changed (`Some(None)`: it was absent). + pub(crate) fn finish(&mut self) -> Option> { + match self.old.take() { + Some(old) if old.as_ref() != Some(&self.value) => Some(old), + _ => None, + } + } + + /// (old, new) when the value changed in the open transaction. + pub(crate) fn change(&self) -> Option<(Option<&T>, &T)> { + match &self.old { + Some(old) if old.as_ref() != Some(&self.value) => Some((old.as_ref(), &self.value)), + _ => None, + } + } + + pub(crate) fn rollback(&mut self) { + if let Some(Some(old)) = self.old.take() { + self.value = old; + } + } + + pub(crate) fn is_clean(&self) -> bool { + self.old.is_none() + } +} + +/// The text a document is keyed by in its digest: stable, canonical, one per +/// key. An id is its uuid as `Display` prints it. +pub(crate) trait DocKey { + fn key_text(&self) -> String; +} + +impl DocKey for (A, B) { + fn key_text(&self) -> String { + format!("{}/{}", self.0.key_text(), self.1.key_text()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + type Rows = Docs; + + fn rows(held: &[(u8, u8)]) -> Rows { + let mut docs = Rows::default(); + for (key, value) in held { + docs.insert(*key, *value); + } + docs.finish(); + docs + } + + /// A value sits at its tens digit and its units digit (one point when they + /// agree), so a document has several points and two documents can share one. + #[derive(Clone, Debug)] + struct Digits; + + impl Projection for Digits { + type Point = u8; + fn points(value: &u8, out: &mut Vec) { + out.push(value / 10); + out.push(value % 10); + } + } + + type Spread = Docs; + + fn spread(held: &[(u8, u8)]) -> Spread { + let mut docs = Spread::default(); + for (key, value) in held { + docs.insert(*key, *value); + } + docs.finish(); + docs + } + + /// The projection of the map, computed from scratch: what `indexed(..)` must + /// return at every moment. + fn truth(docs: &Spread) -> Vec<(u8, u8)> { + let mut out = Vec::new(); + for (key, value) in docs.iter() { + out.push((value / 10, *key)); + out.push((value % 10, *key)); + } + out.sort(); + out.dedup(); + out + } + + #[test] + fn a_committed_index_is_the_projection_and_follows_every_finish() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + assert!(docs.index_is_derived()); + assert_eq!(docs.indexed(..), truth(&docs)); + assert_eq!(docs.indexed(1..=1), vec![(1, 1), (1, 2)]); + + docs.insert(1, 32); + docs.remove(&2); + docs.insert(4, 44); + docs.finish(); + assert!(docs.index_is_derived(), "old points leave, new points arrive"); + assert_eq!(docs.indexed(..), truth(&docs)); + assert!(docs.indexed(0..=0).is_empty() && docs.indexed(1..=1).is_empty()); + } + + #[test] + fn a_read_inside_a_transaction_sees_the_log_and_the_index_does_not() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + docs.insert(1, 55); + docs.remove(&2); + docs.insert(7, 12); + assert_eq!(docs.indexed(..), truth(&docs), "the read is true mid-transaction"); + assert!(!docs.indexed(0..=0).iter().any(|(_, key)| *key == 1), "an overwritten value leaves its old points"); + assert!(docs.indexed(5..=5).contains(&(5, 1)), "a new value is seen at once"); + assert!(docs.indexed(..).iter().all(|(_, key)| *key != 2), "a removed document is gone"); + for point in 0..=9 { + assert_eq!( + docs.indexed(point..=point), + truth(&docs).into_iter().filter(|(p, _)| *p == point).collect::>() + ); + } + assert!(!docs.index_is_derived(), "the open log has not reached the index"); + + docs.insert(1, 10); + docs.insert(7, 12); + docs.remove(&7); + assert_eq!(docs.indexed(..), truth(&docs), "a key written back or added and removed adds nothing"); + } + + #[test] + fn rollback_leaves_the_index_as_it_was_because_it_never_saw_the_transaction() { + let mut docs = spread(&[(1, 10), (2, 21)]); + let before = docs.indexed(..); + docs.insert(1, 99); + docs.insert(5, 35); + docs.remove(&2); + docs.rollback(); + assert!(docs.index_is_derived()); + assert_eq!(docs.indexed(..), before); + assert_eq!(docs.indexed(..), truth(&docs)); + } + + #[test] + fn an_index_read_counts_the_entries_it_returns() { + let docs = spread(&[(1, 10), (2, 21), (3, 33)]); + let before = rows_read(); + let found = docs.indexed(..); + assert_eq!(rows_read() - before, found.len() as u64); + let before = rows_read(); + assert_eq!(docs.indexed(1..=1).len(), 2); + assert_eq!(rows_read() - before, 2); + } + + /// Arbitrary interleavings of every write, finish and rollback, read back + /// over arbitrary ranges: `indexed` equals the projection computed from the + /// map at every step, and the index is the rebuild after each close. + #[test] + fn indexed_equals_truth_over_a_random_walk_of_writes_and_ranges() { + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut next = move |bound: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % bound + }; + let mut docs = spread(&[(0, 5), (1, 17), (2, 17)]); + for step in 0..4000 { + let key = next(12) as u8; + match next(8) { + 0 | 1 => { + docs.insert(key, next(100) as u8); + } + 2 => { + docs.remove(&key); + } + 3 => { + if let Some(value) = docs.get_mut(&key) { + *value = (next(100)) as u8; + } + } + 4 => { + let fresh = next(100) as u8; + docs.entry(key).or_insert(fresh); + } + 5 => { + docs.finish(); + assert!(docs.index_is_derived(), "step {step}: after finish"); + } + 6 => { + docs.rollback(); + assert!(docs.index_is_derived(), "step {step}: after rollback"); + } + _ => {} + } + let (a, b) = (next(11) as u8, next(11) as u8); + let (lo, hi) = (a.min(b), a.max(b)); + let all = truth(&docs); + assert_eq!(docs.indexed(..), all, "step {step}: full range"); + let within = |keep: &dyn Fn(u8) -> bool| -> Vec<(u8, u8)> { + all.iter().copied().filter(|(point, _)| keep(*point)).collect() + }; + assert_eq!(docs.indexed(lo..=hi), within(&|p| (lo..=hi).contains(&p)), "step {step}: {lo}..={hi}"); + assert_eq!(docs.indexed(..hi), within(&|p| p < hi), "step {step}: ..{hi}"); + } + } + + #[test] + fn indexed_unchanged_names_the_committed_entries_of_keys_the_log_did_not_change() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33), (4, 11)]); + docs.insert(1, 55); // changed + docs.remove(&2); // removed + docs.insert(3, 33); // touched, written back: unchanged + docs.insert(9, 11); // added: not in the committed index + let before = rows_read(); + let found = docs.indexed_unchanged(1..=1); + assert_eq!(found, vec![(1, 4)], "only the committed entries of unchanged keys"); + assert_eq!(rows_read() - before, 1, "no walk of the log, only the entries returned"); + assert_eq!(docs.indexed_unchanged(..), vec![(1, 4), (3, 3)], "key 3 written back counts as unchanged"); + } + + #[test] + fn walking_the_open_log_is_counted_even_when_nothing_matches() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + docs.insert(1, 11); + docs.insert(9, 99); + let before = rows_read(); + assert!(docs.indexed(5..=5).is_empty()); + assert_eq!(rows_read() - before, 2, "two logged keys were walked"); + } + + #[test] + fn a_damaged_index_is_seen_as_not_derived() { + for stray in [true, false] { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + assert!(docs.corrupt_index_for_test(stray)); + assert!(!docs.index_is_derived(), "stray={stray}"); + } + let mut empty = Spread::default(); + assert!(!empty.corrupt_index_for_test(true) && !empty.corrupt_index_for_test(false)); + } + + fn contents(docs: &Rows) -> Vec<(u8, u8)> { + docs.iter().map(|(key, value)| (*key, *value)).collect() + } + + #[test] + fn a_write_is_reported_with_the_value_the_transaction_began_with() { + let mut docs = rows(&[(1, 10), (2, 20)]); + docs.insert(1, 11); + docs.insert(1, 12); + docs.insert(3, 30); + docs.remove(&2); + let mut changed = docs.finish(); + changed.sort(); + assert_eq!(changed, vec![(1, Some(10)), (2, Some(20)), (3, None)]); + assert!(docs.finish().is_empty(), "finish empties the log"); + assert!(docs.is_clean()); + } + + #[test] + fn a_key_written_back_to_what_it_was_is_not_a_change() { + let mut docs = rows(&[(1, 10), (2, 20)]); + docs.insert(1, 11); + docs.insert(1, 10); + docs.insert(3, 30); + docs.remove(&3); + *docs.get_mut(&2).unwrap() = 20; + *docs.entry(2).or_insert(0) = 20; + assert!(docs.changes().next().is_none()); + assert!(docs.finish().is_empty()); + } + + #[test] + fn a_get_mut_that_misses_touches_nothing() { + let mut docs = rows(&[(1, 10)]); + assert!(docs.get_mut(&9).is_none()); + assert!(docs.is_clean()); + *docs.get_mut(&1).unwrap() += 1; + assert!(!docs.is_clean()); + assert_eq!(docs.finish(), vec![(1, Some(10))]); + } + + #[test] + fn an_entry_that_adds_a_row_is_a_change_and_one_that_finds_it_is_not() { + let mut docs = rows(&[(1, 10)]); + docs.entry(1).or_insert(99); + docs.entry(2).or_insert(20); + assert_eq!(docs.finish(), vec![(2, None)]); + assert_eq!(contents(&docs), vec![(1, 10), (2, 20)]); + } + + #[test] + fn rollback_restores_every_touched_key_and_empties_the_log() { + let mut docs = rows(&[(1, 10), (2, 20), (3, 30)]); + docs.insert(1, 11); + docs.insert(4, 40); + docs.remove(&2); + *docs.get_mut(&3).unwrap() = 31; + *docs.entry(5).or_insert(0) = 50; + docs.rollback(); + assert_eq!(contents(&docs), vec![(1, 10), (2, 20), (3, 30)]); + assert!(docs.is_clean()); + } + + #[test] + fn every_row_an_iterator_yields_is_counted_and_point_reads_are_not() { + let docs = rows(&[(1, 10), (2, 20), (3, 30), (4, 40)]); + let before = rows_read(); + assert_eq!(docs.iter().count(), 4); + assert_eq!(rows_read() - before, 4); + assert_eq!(docs.keys().count() + docs.values().count(), 8); + assert_eq!(docs.range(2..4).count(), 2); + assert_eq!((&docs).into_iter().rev().take(1).count(), 1); + assert_eq!(rows_read() - before, 4 + 8 + 2 + 1); + let before = rows_read(); + assert_eq!(docs.get(&2), Some(&20)); + assert!(docs.contains_key(&3) && docs[&4] == 40); + assert_eq!(docs.len(), 4); + assert_eq!(rows_read(), before); + } + + #[test] + fn equality_is_the_documents_and_not_the_log() { + let mut open = rows(&[(1, 10)]); + open.insert(1, 11); + open.insert(1, 10); + assert_eq!(open, rows(&[(1, 10)])); + } + + #[test] + fn the_header_is_logged_once_and_a_genesis_value_is_an_addition() { + let mut header = Tracked::absent(5u8); + assert_eq!(header.finish(), Some(None), "genesis adds the header"); + + *header.get_mut() = 6; + *header.get_mut() = 7; + assert_eq!(header.finish(), Some(Some(5))); + assert!(header.is_clean()); + + *header.get_mut() = 8; + *header.get_mut() = 7; + assert_eq!(header.finish(), None, "written back is not a change"); + + *header.get_mut() = 9; + header.rollback(); + assert_eq!(*header, 7); + assert!(header.is_clean()); + } +} diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs new file mode 100644 index 000000000..bba7e99a1 --- /dev/null +++ b/native/aetherlight/src/golden_tests.rs @@ -0,0 +1,2405 @@ +//! The pinned replay of one scripted session, and the commit-cost harness. +//! +//! The golden file is the determinism contract in its smallest form: every +//! committed revision's state digest and commit digest, and the digest of the +//! export, for a session that touches speech, display, a routine and a refusal. +//! A change to any id derivation, schema, encoding or reducer arm moves a line. + +use crate::tests::{ + affordance_named, auth_principal, command, creation, first_grant, operations, owner, + play_caller, play_command, speak, subject_by_label, submit_play, tick_body, +}; +use crate::patch::{ + AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, + OutcomeBand, Precondition, +}; +use crate::{ + AuthenticatedCaller, CommandBody, CommitmentKind, ComponentOp, DecisionInvocation, + FictionalMinutes, KernelError, KnowledgeSource, Ref, Statement, TickMinutes, WorldEffect, + WorldKernel, WorldPatch, +}; +use sha2::{Digest, Sha256}; +use std::time::Instant; + +/// The script: The Human speaks to The Witness, The Human shows a gesture, a +/// two-band `toss` is declared, granted to The Human and used three times (so +/// the band draw is recorded), a Routine is placed on The Witness, thirty minutes roll it, and The Human +/// invokes `convene`, which it does not hold. +pub(super) fn golden_session() -> (WorldKernel, String) { + let (mut kernel, _) = WorldKernel::create(creation("Golden"), &auth_principal(owner())) + .expect("the fixture world is created"); + let human = subject_by_label(&kernel.state, "The Human"); + let witness = subject_by_label(&kernel.state, "The Witness"); + + let snapshot = kernel.snapshot().unwrap(); + let speak_entry = first_grant(&snapshot, human); + submit_play( + &mut kernel, + &snapshot, + CommandBody::Act { + actor: human, + invocation: speak(speak_entry, "The vote carries."), + }, + ); + let heard = kernel.snapshot().unwrap(); + let witness_knowledge = &heard + .subjects + .iter() + .find(|subject| subject.id == witness) + .expect("the witness is a subject") + .knowledge; + assert!( + witness_knowledge.iter().any(|held| matches!( + held.source, + KnowledgeSource::Told { by, .. } if by == human + )), + "the witness holds what the human said as Told" + ); + + submit_play( + &mut kernel, + &heard, + CommandBody::Act { + actor: human, + invocation: DecisionInvocation { + affordance: speak_entry, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: Some(Statement::new("The Human raises one finger.").unwrap()), + }, + }, + ); + + // A two-band entry: the one place the golden records a band draw. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("toss"), + kind: AffordanceKindName("toss".into()), + roles: Vec::new(), + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![ + OutcomeBand { weight: 1, effects: Vec::new() }, + OutcomeBand { weight: 1, effects: Vec::new() }, + ], + carries_speech: true, + })], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(human), + affordance: Ref::Draft(DraftHandle::new("toss")), + }], + evidence: Vec::new(), + }, + }, + ); + for _ in 0..3 { + let snapshot = kernel.snapshot().unwrap(); + let toss = affordance_named(&snapshot, "toss"); + submit_play( + &mut kernel, + &snapshot, + CommandBody::Act { + actor: human, + invocation: DecisionInvocation { + affordance: toss, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Heads or tails.").unwrap()), + display: None, + }, + }, + ); + } + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(witness), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(10), + period: Some(TickMinutes::new(10).unwrap()), + checks: Vec::new(), + statement: Statement::new("The Witness keeps the lamp.").unwrap(), + }]), + ); + + let snapshot = kernel.snapshot().unwrap(); + submit_play(&mut kernel, &snapshot, tick_body(30)); + let ticked = kernel.journal.commits_for_test(); + let WorldEffect::TimeAdvanced { motion, .. } = + &ticked.last().expect("the tick committed").effect + else { + panic!("the last commit is the tick"); + }; + assert!(!motion.fulfilled.is_empty(), "the routine rolled"); + + // The refusal changes nothing: not the revision, not either digest. + let before = kernel.snapshot().unwrap(); + let convene = affordance_named(&before, "convene"); + let refused = kernel.submit( + command( + &before, + play_caller(), + CommandBody::Act { + actor: human, + invocation: speak(convene, "A meeting is called."), + }, + ), + &AuthenticatedCaller::verified_play(), + ); + assert!(matches!(refused, Err(KernelError::AffordanceDenied)), "{refused:?}"); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), 9); + + let mut file = String::new(); + for commit in kernel.journal.commits_for_test() { + file.push_str(&format!( + "{} {} {}\n", + commit.resulting_revision, commit.resulting_state_digest, commit.digest + )); + } + let export = kernel.export().unwrap(); + file.push_str(&format!("export sha256:{:x}\n", Sha256::digest(&export))); + (kernel, file) +} + +#[test] +fn golden_session_digests_are_fixed() { + let (_, computed) = golden_session(); + let (_, again) = golden_session(); + assert_eq!(computed, again, "one session, two runs, one file"); + let fixture: Vec<&str> = include_str!("../fixtures/golden.digests").lines().collect(); + let computed_lines: Vec<&str> = computed.lines().collect(); + assert!( + fixture == computed_lines, + "the golden digests moved; the computed file is:\n{computed}" + ); +} + +#[test] +fn export_open_round_trip_is_exact() { + let (mut original, _) = golden_session(); + let exported = original.export().unwrap(); + let mut reopened = WorldKernel::open(&exported).expect("the golden export opens"); + assert_eq!(reopened.state, original.state); + assert_eq!(reopened.snapshot().unwrap(), original.snapshot().unwrap()); + assert_eq!(reopened.export().unwrap(), exported); + + let human = subject_by_label(&original.state, "The Human"); + let snapshot = original.snapshot().unwrap(); + let next = play_command( + &snapshot, + CommandBody::Act { + actor: human, + invocation: speak(first_grant(&snapshot, human), "Order, please."), + }, + ); + let play = AuthenticatedCaller::verified_play(); + let original_receipt = original.submit(next.clone(), &play).unwrap(); + let reopened_receipt = reopened.submit(next, &play).unwrap(); + assert_eq!(original_receipt, reopened_receipt); + assert_eq!(original.export().unwrap(), reopened.export().unwrap()); +} + +/// The digest is what a replay or a fresh recompute would derive, at every +/// revision of the golden session and after reopening it, and also across a +/// removal, which the session itself never makes. +#[test] +fn incremental_digest_equals_full_recompute() { + let (mut kernel, _) = golden_session(); + let commits = kernel.journal.commits_for_test(); + for (index, commit) in commits.iter().enumerate() { + let replayed = crate::journal::verify_history(&commits[..=index]).unwrap(); + assert_eq!( + replayed.full_state_digest().unwrap(), + commit.resulting_state_digest, + "revision {index}: the incremental digest left the full recompute" + ); + } + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + + // A removal: the witness forgets what it was told. + let witness = subject_by_label(&kernel.state, "The Witness"); + let (fact, _) = kernel + .state + .knowledge_of(witness) + .next() + .expect("the witness knows something"); + let fact = *fact; + let rows = kernel.state.knowledge.len(); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(witness), + fact: Ref::Existing(fact), + }]), + ); + assert_eq!(kernel.state.knowledge.len(), rows - 1, "a row was removed"); + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + + let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap(); + assert_eq!(reopened.state.full_state_digest().unwrap(), reopened.state.state_digest); + assert_eq!(reopened.state.accumulator, kernel.state.accumulator); +} + +/// The clockwork world: `persons` persons, ten to a place, one Routine each +/// with period `persons / 2`, due `1 + i mod (persons / 2)`, so a one-minute +/// tick rolls two routines at every size and a speech reaches the same nine +/// listeners. Every partition a read index serves is populated, because an +/// empty one hides its scan: one route between consecutive places, one +/// `Reach::Place` channel per place controlled by its first person, one +/// institution per place with a warden office held by that person and a forum +/// for the place's grievances, and two Obligations past due from the first +/// minute, so a tick presses two sources at every size. +/// +/// Dependencies, retirement and checks grow with the world too, because +/// a partition that stays small hides the walk of it. Every person binds to the +/// previous live person (a satisfied dependency), and persons 0 and 1 also to +/// the last place's grain, which they do not hold: two failing dependencies at +/// every size. Every tenth person from the 35th retires (never a controller or +/// incumbent, who are place * 10), and every routine checks that its person +/// holds their place's grain. The clock then moves one period, so every +/// routine is past due: the live ones roll once, a retired person's stays due +/// for good, and a one-minute tick from there rolls two routines at every size. +fn clockwork_world(persons: usize) -> (WorldKernel, Vec, crate::AffordanceId) { + use crate::patch::kernel_speak_grant; + use crate::patch::{ + AccessKind, AuthoredSource, AuthorityGrantRef, AuthorityTargetRef, ChannelDeclaration, + DependencyRef, EntityDeclaration, EvidenceRef, FactDeclaration, FactStandingRef, + GrievanceKindName, PreconditionRef, Quantity, ReachRef, RouteDeclaration, + SubjectDeclaration, + }; + use crate::tests::{LEVY_KIND, TITHE_RECEIPT, WARDEN_OFFICE, authority_kind, office}; + use crate::Confidence; + use crate::{CallerId, CommandEnvelope, CreateWorld, Cost, EntityKind, SubjectKind}; + use std::collections::BTreeSet; + + let places = persons / 10; + let draft_place = |place: usize| Ref::Draft(DraftHandle::new(format!("place-{place}"))); + let draft_person = |person: usize| Ref::Draft(DraftHandle::new(format!("person-{person}"))); + let mut declarations = Vec::new(); + let mut offices = Vec::new(); + for place in 0..places { + declarations.push(Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(format!("place-{place}")), + label: format!("Place {place}"), + kind: EntityKind::Place, + container: None, + })); + if place + 1 < places { + declarations.push(Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(format!("route-{place}")), + label: format!("Route {place}"), + from: draft_place(place), + to: draft_place(place + 1), + access: AccessKind::Public, + cost: Cost(1), + })); + } + declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new(format!("channel-{place}")), + label: format!("Channel {place}"), + reach: ReachRef::Place(draft_place(place)), + controller: Some(draft_person(place * 10)), + })); + declarations.push(Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(format!("grain-{place}")), + label: format!("Grain {place}"), + kind: EntityKind::Resource, + container: None, + })); + declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(format!("fact-{place}")), + label: format!("Fact {place}"), + statement: Statement::new("The place keeps its hour.").unwrap(), + standing: FactStandingRef::Canonical { evidence: EvidenceRef::new(TITHE_RECEIPT) }, + })); + let institution = DraftHandle::new(format!("institution-{place}")); + declarations.push(Declaration::Subject(SubjectDeclaration { + handle: institution.clone(), + label: format!("Institution {place}"), + kind: SubjectKind::Institution, + affordances: BTreeSet::new(), + position: None, + import_key: None, + })); + offices.push(ComponentOp::GrantAuthority { + holder: Ref::Draft(institution.clone()), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::PlaceSubtree(draft_place(place)), + }, + }); + offices.push(ComponentOp::OpenOffice { + institution: Ref::Draft(institution.clone()), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }); + offices.push(ComponentOp::InstallIncumbent { + institution: Ref::Draft(institution.clone()), + office: office(WARDEN_OFFICE), + incumbent: draft_person(place * 10), + }); + offices.push(ComponentOp::OpenForum { + grievance: GrievanceKindName(format!("grievance_{place}")), + forum: Ref::Draft(institution), + standing: AuthorityTargetRef::PlaceSubtree(draft_place(place)), + }); + } + for person in 0..persons { + let place = person / 10; + // One holding and one known fact per person, so `holdings`, `facts` and + // `knowledge` grow with the world and a scan of them breaks the gate. + offices.push(ComponentOp::Admit { + holder: draft_person(person), + resource: Ref::Draft(DraftHandle::new(format!("grain-{place}"))), + qty: Quantity(1), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }); + offices.push(ComponentOp::AcquireKnowledge { + subject: draft_person(person), + fact: Ref::Draft(DraftHandle::new(format!("fact-{place}"))), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }); + declarations.push(Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(format!("person-{person}")), + label: format!("Person {person}"), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: Some(Ref::Draft(DraftHandle::new(format!("place-{}", person / 10)))), + import_key: None, + })); + } + let retires = |person: usize| person >= 35 && (person - 35) % 10 == 0; + for person in 0..persons { + if person > 0 { + // The previous person, or the one before when that one retires and + // so leaves the topology: the dependency stays satisfied. + let previous = if retires(person - 1) { person - 2 } else { person - 1 }; + offices.push(ComponentOp::Bind { + subject: draft_person(person), + target: DependencyRef::Subject(draft_person(previous)), + }); + } + if person < 2 { + offices.push(ComponentOp::Bind { + subject: draft_person(person), + target: DependencyRef::Resource(Ref::Draft(DraftHandle::new(format!( + "grain-{}", + places - 1 + )))), + }); + } + } + let (mut kernel, _) = WorldKernel::create( + CreateWorld { + owner: owner(), + title: "Clockwork".into(), + patch: WorldPatch { + declarations, + operations: offices, + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + grammar: None, + }, + &auth_principal(owner()), + ) + .expect("the clockwork world is created"); + let people: Vec<_> = (0..persons) + .map(|person| subject_by_label(&kernel.state, &format!("Person {person}"))) + .collect(); + let period = (persons / 2) as u64; + let grain_of_place: std::collections::BTreeMap = kernel + .state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Resource) + .map(|(id, record)| (record.label.clone(), *id)) + .collect(); + let mut routines: Vec = people + .iter() + .enumerate() + .map(|(index, subject)| ComponentOp::CreateCommitment { + subject: Ref::Existing(*subject), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(1 + index as u64 % period), + period: Some(TickMinutes::new(period as u32).unwrap()), + checks: vec![PreconditionRef::Holds { + resource: Ref::Existing(grain_of_place[&format!("Grain {}", index / 10)]), + at_least: Quantity(1), + }], + statement: Statement::new("Keeps the hour.").unwrap(), + }) + .collect(); + routines.extend(people[..2].iter().map(|subject| ComponentOp::CreateCommitment { + subject: Ref::Existing(*subject), + counterparty: Some(Ref::Existing(people[2])), + kind: CommitmentKind::Obligation, + due: FictionalMinutes(1), + period: None, + checks: Vec::new(), + statement: Statement::new("Owes the tithe.").unwrap(), + })); + let placing = CommandEnvelope { + world_id: kernel.state.header.world_id, + expected_revision: kernel.state.revision, + caller: CallerId::Play, + body: operations(routines), + }; + kernel + .submit(placing, &AuthenticatedCaller::verified_play()) + .expect("the routines are placed"); + let retired: Vec = (0..persons) + .filter(|person| retires(*person)) + .map(|person| ComponentOp::Retire { subject: Ref::Existing(people[person]) }) + .collect(); + if !retired.is_empty() { + let envelope = clockwork_envelope(&kernel, operations(retired)); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the retirements land"); + } + // One period on: every routine is past due, the live ones roll once. + let envelope = clockwork_envelope(&kernel, tick_body(period as u32)); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the clock moves one period"); + let speak_entry = *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "speak") + .map(|(id, _)| id) + .expect("genesis admits Speak"); + (kernel, people, speak_entry) +} + +fn clockwork_envelope(kernel: &WorldKernel, body: CommandBody) -> crate::CommandEnvelope { + crate::CommandEnvelope { + world_id: kernel.state.header.world_id, + expected_revision: kernel.state.revision, + caller: crate::CallerId::Play, + body, + } +} + +/// Submits and reports the document digests the commit computed beside the +/// ones its change set implies: added + removed + 2 x updated, counted by +/// enumerating every document before and after. +fn submit_counting_digests(kernel: &mut WorldKernel, body: CommandBody) -> (usize, usize) { + let before = kernel.state.documents().unwrap(); + let envelope = clockwork_envelope(kernel, body); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the commit lands"); + let computed = crate::digest::DOC_DIGESTS.with(|count| count.get()); + let after = kernel.state.documents().unwrap(); + let added = after.keys().filter(|key| !before.contains_key(*key)).count(); + let removed = before.keys().filter(|key| !after.contains_key(*key)).count(); + let updated = after + .iter() + .filter(|(key, digest)| before.get(*key).is_some_and(|old| old != *digest)) + .count(); + (computed, added + removed + 2 * updated) +} + +/// A commit's digest work is what it changed, not what the world holds: a tick +/// and a speech cost the same number of document digests at 100 persons and at +/// 1600, and exactly Added + Removed + 2 x Updated of that commit. +#[test] +fn digest_work_is_equal_at_100_and_1600() { + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, speak_entry) = clockwork_world(persons); + let mut counts = Vec::new(); + for _ in 0..3 { + counts.push(submit_counting_digests(&mut kernel, tick_body(1))); + } + for index in 0..3 { + let speech = CommandBody::Act { + actor: people[index], + invocation: speak(speak_entry, &format!("Speech {index}.")), + }; + counts.push(submit_counting_digests(&mut kernel, speech)); + } + for (computed, implied) in &counts { + assert!(*computed > 0, "a commit changed documents and digested none"); + assert_eq!( + computed, implied, + "{persons} persons: digests != Added + Removed + 2 x Updated" + ); + } + worked.push(counts); + } + assert_eq!(worked[0], worked[1], "digest work grew with the world"); +} + +/// The ways a failed apply is injected: the revision overflow a tick meets after +/// it has written its documents, and the failure after the digest is folded and +/// the commit sealed, the last point before the world is kept. +#[derive(Clone, Copy, Debug)] +enum Failure { + RevisionOverflow, + AfterDigest, +} + +/// One command to fail, and the world to fail it in. +struct FailureCase { + name: &'static str, + kernel: WorldKernel, + body: CommandBody, +} + +/// Each case writes what its name says: the two ticks are checked against the +/// motion the clock derives for them, so a case cannot quietly stop writing. +fn failure_cases() -> Vec { + let mut cases = Vec::new(); + + let (kernel, _, _) = clockwork_world(20); + let to = kernel.state.header.now.checked_add(TickMinutes::new(1).unwrap()).unwrap(); + assert!(!crate::clock::derive_motion(&kernel.state, to).fulfilled.is_empty()); + cases.push(FailureCase { name: "a tick that rolls routines", kernel, body: tick_body(1) }); + + let (kernel, _, _) = crate::clock_tests::clock_kernel("Pressure"); + let to = kernel.state.header.now.checked_add(TickMinutes::new(200).unwrap()).unwrap(); + assert!(!crate::clock::derive_motion(&kernel.state, to).pressed.is_empty()); + cases.push(FailureCase { name: "a tick that writes pressure rows", kernel, body: tick_body(200) }); + + let (kernel, _) = golden_session(); + let human = subject_by_label(&kernel.state, "The Human"); + let snapshot = kernel.snapshot().unwrap(); + let body = CommandBody::Act { + actor: human, + invocation: speak(first_grant(&snapshot, human), "Order, please."), + }; + cases.push(FailureCase { name: "a speech", kernel, body }); + + let (kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let (fact, _) = kernel.state.knowledge_of(witness).next().expect("the witness knows"); + let body = operations(vec![ComponentOp::Forget { + subject: Ref::Existing(witness), + fact: Ref::Existing(*fact), + }]); + cases.push(FailureCase { name: "a forget", kernel, body }); + cases +} + +/// A failed apply leaves nothing behind: state, accumulator, digest, every +/// partition's bytes, every log and the journal as before, and the next honest +/// command commits. Each case is failed twice: by the revision overflow a tick +/// meets after it has written its documents, and by a failure after the digest +/// is folded and the commit sealed, the last point before the world is kept. +#[test] +fn a_failed_apply_rolls_back() { + for failure in [Failure::RevisionOverflow, Failure::AfterDigest] { + for FailureCase { name, mut kernel, body } in failure_cases() { + let label = format!("{name}, {failure:?}"); + let honest_revision = kernel.state.revision; + let before = kernel.state.clone(); + let bytes = before.encoded_documents(); + let commits = kernel.journal.commit_count(); + match failure { + Failure::RevisionOverflow => kernel.state.revision = u64::MAX, + Failure::AfterDigest => crate::INJECT_FAILURE_AFTER_DIGEST.set(true), + } + let envelope = clockwork_envelope(&kernel, body.clone()); + let error = kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_err(); + crate::INJECT_FAILURE_AFTER_DIGEST.set(false); + match failure { + Failure::RevisionOverflow => { + assert!(matches!(error, KernelError::Serialization(_)), "{label}: {error:?}"); + } + Failure::AfterDigest => { + assert!(matches!(error, KernelError::Invariant(_)), "{label}: {error:?}"); + } + } + kernel.state.revision = honest_revision; + assert_eq!(kernel.state, before, "{label}: the failure left writes behind"); + assert_eq!(kernel.state.encoded_documents(), bytes, "{label}"); + assert_eq!(kernel.journal.commit_count(), commits, "{label}"); + assert!(kernel.state.header.is_clean(), "{label}: header log open"); + for (schema, docs) in kernel.state.partitions() { + assert!(docs.is_clean(), "{label}: {schema} log open"); + } + assert_eq!( + kernel.state.full_state_digest().unwrap(), + kernel.state.state_digest, + "{label}: the accumulator no longer matches the documents" + ); + assert_indexes_derived(&kernel.state, &format!("{label}, after the failure")); + assert!( + kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)), + "{label}: the failure left the views behind" + ); + + let envelope = clockwork_envelope(&kernel, body); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_or_else(|error| panic!("{label}: the next honest command: {error:?}")); + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + assert_indexes_derived(&kernel.state, &format!("{label}, after the honest command")); + assert!( + kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)), + "{label}: the views left their documents" + ); + } + } +} + +/// Worlds that between them hold a document in every partition: the golden +/// session, the civic, custody and speech benches and the ticked clock bench. +pub(crate) fn populated_worlds() -> Vec { + use crate::tests::{auth_principal, civic_world, creation, custody_world, owner, speech_world}; + let created = |title: &str| { + WorldKernel::create(creation(title), &auth_principal(owner())).unwrap().0 + }; + let mut worlds = vec![golden_session().0.state]; + // Two subjects holding import keys, so the subjects' `ByImportKey` index has + // points to read and to damage. + let mut keyed = crate::tests::creation("Keyed"); + for declaration in &mut keyed.patch.declarations { + if let Declaration::Subject(subject) = declaration { + let record = subject.label.clone(); + subject.import_key = Some(crate::ImportKey::new("aetherlight.fixture", record)); + } + } + worlds.push(WorldKernel::create(keyed, &auth_principal(owner())).unwrap().0.state); + let mut kernel = created("Civic"); + civic_world(&mut kernel); + worlds.push(kernel.state); + let mut kernel = created("Custody"); + custody_world(&mut kernel); + worlds.push(kernel.state); + let mut kernel = created("Speech"); + speech_world(&mut kernel); + worlds.push(kernel.state); + let (mut kernel, _, _) = crate::clock_tests::clock_kernel("Pressure"); + let tick = clockwork_envelope(&kernel, tick_body(200)); + kernel.submit(tick, &AuthenticatedCaller::verified_play()).unwrap(); + worlds.push(kernel.state); + worlds +} + +/// Membership of the partition table is behaviour: for every partition the +/// declaration names, one written document is in the folded digest and agrees +/// with the full recompute, is put back by a rollback, and leaves the log empty +/// and the accumulator at the full recompute when the transaction finishes. The +/// loop runs over the declaration, so a partition added to it is covered, and a +/// partition no fixture populates fails here rather than going untested. +#[test] +fn every_partition_is_digested_undone_and_finished() { + let worlds = populated_worlds(); + for index in 0..crate::WorldState::PARTITIONS { + let schema = worlds[0].partitions()[index].0; + let base = worlds + .iter() + .find(|world| world.partitions()[index].1.rows() > 0) + .unwrap_or_else(|| panic!("no fixture world holds a document in {schema}")); + let written = |state: &mut crate::WorldState| { + state.begin(); + assert!(state.partitions_mut()[index].1.remove_first(), "{schema}: nothing to write"); + let folded = state.folded().unwrap(); + assert_ne!(folded, state.accumulator, "{schema}: the write is not in the digest"); + assert_eq!( + folded.state_digest(state.revision), + state.full_state_digest().unwrap(), + "{schema}: the folded digest left the full recompute" + ); + folded + }; + let clean = |state: &crate::WorldState| { + state.header.is_clean() && state.partitions().iter().all(|(_, docs)| docs.is_clean()) + }; + + let mut state = base.clone(); + written(&mut state); + assert!(!state.partitions()[index].1.is_clean(), "{schema}: the write is not logged"); + state.rollback(); + assert_eq!(&state, base, "{schema}: rollback left the write behind"); + assert_eq!(state.encoded_documents(), base.encoded_documents(), "{schema}"); + assert!(clean(&state), "{schema}: rollback left a log open"); + + let mut state = base.clone(); + let folded = written(&mut state); + state.finish(folded); + assert!(clean(&state), "{schema}: finish left a log open"); + assert_ne!(&state, base, "{schema}: finish dropped the write"); + assert_eq!( + state.accumulator.state_digest(state.revision), + state.full_state_digest().unwrap(), + "{schema}: the finished accumulator left the full recompute" + ); + } +} + +/// What one tick and one speech cost to commit as the world grows, by the +/// clockwork world above: time, document digests and rows read (Docs rows plus +/// index entries) per commit, and the 1600/100 ratios. Run on its own, in +/// release, to read the numbers; nothing is asserted here. Wall time is noise +/// at this scale (a 30-sample mean ratio of speech ran 2.1 to 4.2 over runs +/// whose rows were flat), so each figure is the median of 200 commits, ticks +/// and speeches interleaved so drift and cache state fall on both, and the +/// gate is `read_work_is_equal_at_100_and_1600`, which counts the rows each +/// commit reads and fails when one grows with the world, and +/// `digest_work_is_equal_at_100_and_1600` for what a commit digests. +/// +/// `cargo test --release --lib clockwork_commit_cost -- --ignored --nocapture` +#[test] +#[ignore] +fn clockwork_commit_cost() { + const SAMPLES: usize = 200; + fn median(mut values: Vec) -> f64 { + values.sort_by(|a, b| a.partial_cmp(b).expect("a time")); + values[values.len() / 2] + } + println!( + "persons create_ms tick_ms tick_digests tick_rows speech_ms speech_digests speech_rows" + ); + let mut ticks_ms = Vec::new(); + let mut speeches_ms = Vec::new(); + for persons in [100usize, 400, 1600] { + let started = Instant::now(); + let (mut kernel, people, speak_entry) = clockwork_world(persons); + let create_ms = started.elapsed().as_secs_f64() * 1e3; + let play = AuthenticatedCaller::verified_play(); + + let (mut ticks, mut speeches) = (Vec::new(), Vec::new()); + let (mut tick_digests, mut tick_rows, mut speech_digests, mut speech_rows) = (0, 0, 0, 0); + for index in 0..SAMPLES { + let body = if index % 2 == 0 { + CommandBody::AdvanceTime { minutes: TickMinutes::new(1).unwrap() } + } else { + CommandBody::Act { + actor: people[index % 30], + invocation: speak(speak_entry, &format!("Speech {index}.")), + } + }; + let is_tick = index % 2 == 0; + let envelope = clockwork_envelope(&kernel, body); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + let rows = crate::docs::rows_read(); + let started = Instant::now(); + kernel.submit(envelope, &play).expect("the commit lands"); + let elapsed = started.elapsed().as_secs_f64() * 1e3; + let digests = crate::digest::DOC_DIGESTS.with(|count| count.get()); + let rows = crate::docs::rows_read() - rows; + if is_tick { + ticks.push(elapsed); + (tick_digests, tick_rows) = (digests, rows); + } else { + speeches.push(elapsed); + (speech_digests, speech_rows) = (digests, rows); + } + } + let (tick, speech) = (median(ticks), median(speeches)); + println!( + "{persons:>7} {create_ms:>9.1} {tick:>7.3} {tick_digests:>12} {tick_rows:>9} {speech:>9.3} {speech_digests:>14} {speech_rows:>11}", + ); + ticks_ms.push(tick); + speeches_ms.push(speech); + } + println!( + "ratio of medians 1600/100: tick {:.2} speech {:.2}", + ticks_ms[2] / ticks_ms[0], + speeches_ms[2] / speeches_ms[0] + ); +} + +/// What opening a world costs as it grows: `WorldKernel::open` of the clockwork +/// world's export replays genesis and every commit as bulk commits, which the +/// per-commit gate does not see. Median of five opens per size; nothing asserted +/// (rows are pinned by `folding_a_bulk_commit_reads_rows_in_proportion_to_the_change`). +/// +/// `cargo test --release --lib open_cost -- --ignored --nocapture` +#[test] +#[ignore] +fn open_cost() { + println!("persons open_ms"); + for persons in [200usize, 400, 800, 1600, 3200] { + let (kernel, _, _) = clockwork_world(persons); + let exported = kernel.export().unwrap(); + let mut times: Vec = (0..5) + .map(|_| { + let started = Instant::now(); + WorldKernel::open(&exported).expect("the world opens"); + started.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + times.sort_by(|a, b| a.partial_cmp(b).expect("a time")); + println!("{persons:>7} {:>7.1}", times[2]); + } +} + +/// A document written back to what it was costs no digest: the transaction +/// logged it, and folding finds nothing changed. A real change costs two (the +/// old, subtracted, and the new, added) and moves the accumulator. +#[test] +fn a_touched_document_written_back_costs_no_digest() { + let (mut kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let before = kernel.state.accumulator.clone(); + let digests = || crate::digest::DOC_DIGESTS.with(|count| count.get()); + + kernel.state.begin(); + let now = kernel.state.header.now; + kernel.state.header.get_mut().now = now; + kernel.state.commitments.get_mut(&witness).expect("the witness holds a routine"); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + assert_eq!(kernel.state.folded().unwrap(), before); + assert_eq!(digests(), 0, "an unchanged document was digested"); + + kernel.state.header.get_mut().now = FictionalMinutes(now.0 + 1); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + assert_ne!(kernel.state.folded().unwrap(), before); + assert_eq!(digests(), 2, "an updated document is its old digest and its new"); + kernel.state.rollback(); + assert_eq!(kernel.state.header.now, now); +} + +/// A transaction is never opened over an open one, nor over a stray write. +#[cfg(debug_assertions)] +#[test] +#[should_panic(expected = "a transaction is open")] +fn begin_refuses_an_open_header_log() { + let (mut kernel, _) = golden_session(); + kernel.state.header.get_mut(); + kernel.state.begin(); +} + +#[cfg(debug_assertions)] +#[test] +#[should_panic] +fn begin_refuses_an_open_partition_log() { + let (mut kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + kernel.state.commitments.get_mut(&witness); + kernel.state.begin(); +} + +/// The snapshot's `known_by` is the knowledge partition read the other way: +/// exactly the subjects holding a row for the fact. +#[test] +fn a_fact_is_known_by_exactly_the_subjects_holding_a_row() { + let (kernel, _) = golden_session(); + let snapshot = kernel.snapshot().unwrap(); + assert!(snapshot.facts.iter().any(|fact| !fact.known_by.is_empty())); + for fact in &snapshot.facts { + let holders: Vec<_> = kernel + .state + .subjects + .keys() + .filter(|subject| kernel.state.knowledge.contains_key(&(**subject, fact.id))) + .copied() + .collect(); + assert_eq!(fact.known_by, holders); + } +} + +/// A knowledge row names a live subject and a canonical fact, each judged on +/// its own. +#[test] +fn a_knowledge_row_without_a_subject_or_a_fact_is_corrupt() { + use crate::tests::subject_by_label; + let (kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let (fact, held) = kernel + .state + .knowledge_of(witness) + .next() + .map(|(fact, held)| (*fact, *held)) + .expect("the witness knows something"); + crate::journal::verify_state_shape(&kernel.state).expect("the honest state passes"); + + let mut no_subject = kernel.state.clone(); + no_subject.knowledge.insert((crate::SubjectId::issue(), fact), held); + assert!(crate::journal::verify_state_shape(&no_subject).is_err()); + + let mut no_fact = kernel.state.clone(); + no_fact.knowledge.insert((witness, crate::EntityId::issue()), held); + assert!(crate::journal::verify_state_shape(&no_fact).is_err()); +} + +/// The text a document is keyed by is the contract the digest hashes: an id's +/// uuid, a pair's two joined by a slash, a grievance kind's name. +#[test] +fn document_keys_are_canonical_text() { + use crate::docs::DocKey; + let subject = crate::SubjectId::issue(); + let fact = crate::EntityId::issue(); + assert_eq!(subject.key_text(), subject.0.to_string()); + assert_eq!((subject, fact).key_text(), format!("{}/{}", subject.0, fact.0)); + assert_eq!(crate::patch::GrievanceKindName("theft".into()).key_text(), "theft"); +} + +/// The snapshot says a commitment is past due exactly when its due minute has +/// been reached: the golden's routine rolled once by a thirty-minute tick and +/// is due again at or before the clock. +#[test] +fn a_commitment_due_at_or_before_the_clock_reads_past_due() { + let (kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let snapshot = kernel.snapshot().unwrap(); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == witness) + .expect("the witness is a subject"); + assert!(!subject.commitments.is_empty()); + for commitment in &subject.commitments { + assert_eq!(commitment.past_due, commitment.due <= kernel.state.header.now); + } + assert!( + subject.commitments.iter().any(|commitment| commitment.past_due), + "the routine fell due behind the clock" + ); +} + +/// Rows (Docs rows and index entries) one submit read. +fn submit_counting_rows(kernel: &mut WorldKernel, body: CommandBody) -> u64 { + let envelope = clockwork_envelope(kernel, body); + let before = crate::docs::rows_read(); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the commit lands"); + crate::docs::rows_read() - before +} + +/// A commit's read work is what it touches, not what the world holds: a tick +/// that rolls two routines and presses two obligations, and a colocated speech, +/// read the same number of rows at 100 persons and at 1600. The count is taken +/// where reads are owned (`Docs`), so a reader that scans a partition cannot +/// hide from it. Wall time is not asserted anywhere: it is noise at this scale. +#[test] +fn read_work_is_equal_at_100_and_1600() { + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, speak_entry) = clockwork_world(persons); + // The gate holds only if the partitions are populated at scale: an empty + // one hides a scan of it. + let state = &kernel.state; + assert!(state.holdings.len() >= persons && state.knowledge.len() >= persons); + assert!(state.facts.len() >= persons / 10 && state.channels.len() == persons / 10); + let retired: Vec<_> = + people.iter().copied().filter(|person| crate::is_retired(state, *person)).collect(); + assert!(retired.len() >= persons / 20, "{persons} persons: too few retired subjects"); + assert_eq!(state.positions.len() + retired.len(), persons, "a retired subject has no position"); + assert!(state.commitments.len() >= persons); + for person in &retired { + assert!( + state.commitments[person].values().any(|commitment| { + commitment.kind == CommitmentKind::Routine && commitment.due <= state.header.now + }), + "{persons} persons: a retired subject holds no past-due routine" + ); + } + for held in state.commitments.values() { + for commitment in held.values().filter(|c| c.kind == CommitmentKind::Routine) { + assert!( + matches!(commitment.checks.as_slice(), [crate::patch::BoundPrecondition::Holds { .. }]), + "{persons} persons: a routine without its Holds check" + ); + } + } + assert!(state.edges.len() + 1 == persons / 10 && state.selection.len() == persons / 10); + // A dependency per person and a forum per place, so a walk of either + // is seen; the clock reads only the two that fail. + assert!(state.dependencies.len() >= persons); + assert_eq!(state.redress.len(), persons / 10); + let mut counts = Vec::new(); + for _ in 0..3 { + counts.push(submit_counting_rows(&mut kernel, tick_body(1))); + } + for index in 0..3 { + let speech = CommandBody::Act { + actor: people[index], + invocation: speak(speak_entry, &format!("Speech {index}.")), + }; + counts.push(submit_counting_rows(&mut kernel, speech)); + } + assert!(counts.iter().all(|rows| *rows > 0), "{persons} persons: a commit read nothing"); + worked.push(counts); + } + assert_eq!(worked[0], worked[1], "read work grew with the world"); +} + +/// What a patch reads is what it touches, not what the world holds: ten patch +/// shapes, each submitted through `AdmitPatch` (resolution against the +/// candidate graph, the reducer, and the commit's own checks), read the same +/// number of rows at 100, 400 and 1600 persons (some read none: point reads are +/// not rows). The count is taken where reads +/// are owned (`Docs`), so a resolver arm that copies a partition, collects keys +/// from every subject, sums a resource over every holder, or judges every holder +/// for overlap cannot hide from it. The shapes run in order on one world, so +/// each leaves the world the next one reads. +#[test] +fn patch_read_work_is_equal_at_100_and_1600() { + use crate::patch::{ + AuthorityGrantRef, AuthorityTargetRef, AuthoredSource, DependencyRef, FactDeclaration, + FactStandingRef, PressureMagnitude, PressureSourceRef, Quantity, SubjectDeclaration, + }; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{Confidence, ImportKey, SubjectKind}; + use std::collections::BTreeSet; + + let mut shapes: Vec<&'static str> = Vec::new(); + let mut worked: Vec> = Vec::new(); + for persons in [100usize, 400, 1600] { + let (mut kernel, people, _) = clockwork_world(persons); + let label = |kernel: &WorldKernel, label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .unwrap_or_else(|| panic!("{label} is declared")) + .0 + }; + let (place_zero, grain, fact_one) = ( + label(&kernel, "Place 0"), + label(&kernel, "Grain 0"), + label(&kernel, "Fact 1"), + ); + let route = *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "Route 0") + .expect("the first route is declared") + .0; + let institution = subject_by_label(&kernel.state, "Institution 0"); + + // The tick presses the two obligations; then every other person is + // pressed by one source, so the pressure partition holds a row for each. + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick presses the obligations"); + let pressing: Vec = people[1..] + .iter() + .map(|person| ComponentOp::AdvancePressure { + source: PressureSourceRef::Subject(Ref::Existing(people[0])), + target: Ref::Existing(*person), + by: PressureMagnitude(1), + }) + .collect(); + kernel + .submit( + clockwork_envelope(&kernel, operations(pressing)), + &AuthenticatedCaller::verified_play(), + ) + .expect("the pressure rows land"); + assert!(kernel.state.pressures.len() >= persons, "the pressure partition is at scale"); + let obligation = kernel.state.commitments[&people[0]] + .iter() + .find(|(_, commitment)| commitment.kind == CommitmentKind::Obligation) + .map(|(key, _)| *key) + .expect("the first person owes an obligation"); + + let patch = |declarations: Vec, operations: Vec| { + CommandBody::AdmitPatch { + patch: WorldPatch { declarations, operations, evidence: Vec::new() }, + } + }; + let bodies: Vec<(&'static str, CommandBody)> = vec![ + ( + "discharge a past-due obligation", + patch( + Vec::new(), + vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(people[0]), + key: obligation, + }], + ), + ), + ( + "relocate along a route", + patch( + Vec::new(), + vec![ComponentOp::Relocate { subject: Ref::Existing(people[5]), via: Ref::Existing(route) }], + ), + ), + ( + "declare a subject with an import key", + patch( + vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("newcomer"), + label: "The Newcomer".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::new(), + position: Some(Ref::Existing(place_zero)), + import_key: Some(ImportKey::new("aetherlight.gate", "newcomer")), + })], + Vec::new(), + ), + ), + ( + "transfer grain", + patch( + Vec::new(), + vec![ComponentOp::Transfer { + from: Ref::Existing(people[0]), + to: Ref::Existing(people[1]), + resource: Ref::Existing(grain), + qty: Quantity(1), + }], + ), + ), + ( + "witness a fact declared in the same patch", + patch( + vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("omen"), + label: "The Omen".into(), + statement: Statement::new("The lamp gutters.").unwrap(), + standing: FactStandingRef::Ruled, + })], + vec![ComponentOp::Witness { + fact: Ref::Draft(DraftHandle::new("omen")), + place: Ref::Existing(place_zero), + confidence: Confidence::Believed, + }], + ), + ), + ( + "grant authority", + patch( + Vec::new(), + vec![ComponentOp::GrantAuthority { + holder: Ref::Existing(people[7]), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::Subject(Ref::Existing(people[8])), + }, + }], + ), + ), + ( + "install an incumbent", + patch( + Vec::new(), + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(institution), + office: office(WARDEN_OFFICE), + incumbent: Ref::Existing(people[3]), + }], + ), + ), + ( + "acquire knowledge", + patch( + Vec::new(), + vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(people[2]), + fact: Ref::Existing(fact_one), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }], + ), + ), + ( + "bind a dependency", + patch( + Vec::new(), + vec![ComponentOp::Bind { + subject: Ref::Existing(people[4]), + target: DependencyRef::Subject(Ref::Existing(people[2])), + }], + ), + ), + ( + "retire a subject", + patch(Vec::new(), vec![ComponentOp::Retire { subject: Ref::Existing(people[9]) }]), + ), + ]; + let mut counts = Vec::new(); + for (shape, body) in bodies { + let rows = submit_counting_rows(&mut kernel, body); + if persons == 100 { + shapes.push(shape); + } + counts.push(rows); + } + eprintln!("{persons:>5} persons, rows per shape: {counts:?}"); + worked.push(counts); + } + for (index, shape) in shapes.iter().enumerate() { + let rows: Vec = worked.iter().map(|counts| counts[index]).collect(); + assert!( + rows.windows(2).all(|pair| pair[0] == pair[1]), + "{shape}: rows read grew with the world (100, 400, 1600): {rows:?}" + ); + } + // A shape that is point reads all the way down reads no rows at all; the + // counter must still be live, or equality proves nothing. + assert!(worked[0].iter().sum::() > 0, "no shape read a row: the counter is dead"); +} + +/// The pure reads no submit shape isolates, inside one open transaction each: +/// who stands under a two-level subtree, one incumbent's delegated authority, and +/// a path of three routes. (What a patch reads is gated through `AdmitPatch` by +/// `patch_read_work_is_equal_at_100_and_1600`.) +#[test] +fn operation_reads_are_equal_at_100_and_1600() { + use crate::Cost; + use std::collections::BTreeSet; + + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, _) = clockwork_world(persons); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick presses the obligations"); + let place = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared place") + .0 + }; + let (zero, one, two, three) = + (place("Place 0"), place("Place 1"), place("Place 2"), place("Place 3")); + + let state = &mut kernel.state; + state.begin(); + // Place 1 inside place 0, place 2 inside place 1. + state.entities.get_mut(&one).unwrap().container = Some(zero); + state.entities.get_mut(&two).unwrap().container = Some(one); + + let mut counts = Vec::new(); + let mut measure = |read: &mut dyn FnMut()| { + let before = crate::docs::rows_read(); + read(); + let rows = crate::docs::rows_read() - before; + assert!(rows > 0, "a read counted nothing"); + counts.push(rows); + }; + let mut under = BTreeSet::new(); + measure(&mut || under = crate::under_place(state, zero)); + assert_eq!(under.len(), 30, "places 0, 1 and 2 hold ten persons each"); + let mut delegated = Default::default(); + measure(&mut || delegated = crate::delegated_authority(state, people[0])); + assert_eq!(delegated.len(), 1, "the first person holds one office"); + let authority = BTreeSet::new(); + let mut reached = false; + measure(&mut || reached = crate::action::reachable(state, people[0], &authority, three, Cost(3))); + assert!(reached, "three routes of cost one reach place 3"); + state.rollback(); + worked.push(counts); + } + assert_eq!(worked[0], worked[1], "an operation's read work grew with the world"); +} + +/// The commit lane's checks read what the transaction wrote, not the world: +/// conservation sums the holders that were written, disjointness judges the +/// holders whose authority was written, and both cost the same rows at 100 and +/// 1600 persons. Each shape also has to be answered right: a holder already +/// written when the operations begin is measured from where it stood then, and +/// an overlap made by installing an incumbent, or by a grant, is refused with +/// every other holder untouched. +#[test] +fn apply_checks_read_the_log() { + use crate::patch::{AuthorityGrant, AuthorityTarget, ResolvedOp}; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{Quantity, apply_operations}; + + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, _) = clockwork_world(persons); + let place = |label: &str| { + *kernel.state.entities.iter().find(|(_, record)| record.label == label).expect("declared").0 + }; + let (zero, one, grain) = (place("Place 0"), place("Place 1"), place("Grain 0")); + let institution = subject_by_label(&kernel.state, "Institution 0"); + let level = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(one), + }; + let revision = kernel.state.revision + 1; + let transfer = ResolvedOp::Transfer { from: people[0], to: people[1], resource: grain, qty: Quantity(1) }; + let mut counts = Vec::new(); + let state = &mut kernel.state; + + // A transfer between two of ten holders: nothing else is read. + state.begin(); + let before = crate::docs::rows_read(); + apply_operations(state, std::slice::from_ref(&transfer), &[], revision) + .expect("a conserving transfer applies"); + counts.push(crate::docs::rows_read() - before); + state.rollback(); + + // A holder written before the operations begin is measured from there. + state.begin(); + crate::set_held(state, people[0], grain, 5); + let before = crate::docs::rows_read(); + apply_operations(state, std::slice::from_ref(&transfer), &[], revision) + .expect("the entry value is the before, not the value the transaction began with"); + counts.push(crate::docs::rows_read() - before); + state.rollback(); + + // Place 1 inside place 0, committed, with person 5's own grant over place 1. + state.begin(); + state.entities.get_mut(&one).unwrap().container = Some(zero); + state.authority.insert(people[5], std::collections::BTreeSet::from([level.clone()])); + let folded = state.folded().unwrap(); + state.finish(folded); + crate::journal::verify_state_shape(state).expect("the world is still disjoint"); + + // A grant that overlaps the warden's lent ground is refused. + state.begin(); + let overlap = ResolvedOp::GrantAuthority { holder: people[0], grant: level.clone() }; + let before = crate::docs::rows_read(); + let refused = apply_operations(state, &[overlap], &[], revision).unwrap_err(); + counts.push(crate::docs::rows_read() - before); + assert!( + matches!(&refused, crate::KernelError::Invariant(m) if m.contains("overlapping")), + "{persons}: {refused:?}" + ); + state.rollback(); + + // Seating a holder of overlapping ground in the office is refused too. + state.begin(); + let install = ResolvedOp::InstallIncumbent { + institution, + office: office(WARDEN_OFFICE), + incumbent: people[5], + }; + let before = crate::docs::rows_read(); + let refused = apply_operations(state, &[install], &[], revision).unwrap_err(); + counts.push(crate::docs::rows_read() - before); + assert!( + matches!(&refused, crate::KernelError::Invariant(m) if m.contains("overlapping")), + "{persons}: {refused:?}" + ); + state.rollback(); + + // Custody is point reads, which are free; the disjointness judgments read + // the office index. A refusal stops at the first overlapping holder, and + // which holder that is depends on id order, so its reads are bounded + // rather than equal: a few rows, where a scan of the world reads thousands. + assert!(counts[2..].iter().all(|rows| (1..=8).contains(rows)), "{persons}: {counts:?}"); + worked.push(counts[..2].to_vec()); + } + assert_eq!(worked[0], worked[1], "a commit check's read work grew with the world"); +} + +fn assert_indexes_derived(state: &crate::WorldState, label: &str) { + for (schema, docs) in state.partitions() { + assert!(docs.index_is_derived(), "{label}: the read index of {schema} left its documents"); + } +} + +/// The states a test walks: every revision of the golden session as replay +/// derives it, the live and reopened golden world, each populated world, and +/// forty commits of the clockwork world. +fn walked_states() -> Vec<(String, crate::WorldState)> { + let mut states = Vec::new(); + let (kernel, _) = golden_session(); + let commits = kernel.journal.commits_for_test(); + for index in 0..commits.len() { + let replayed = crate::journal::verify_history(&commits[..=index]).unwrap(); + states.push((format!("golden revision {index}"), replayed)); + } + let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap(); + states.push(("golden reopened".into(), reopened.state)); + states.push(("golden live".into(), kernel.state)); + for (index, world) in populated_worlds().into_iter().enumerate() { + states.push((format!("populated world {index}"), world)); + } + let (mut kernel, people, speak_entry) = clockwork_world(100); + states.push(("clockwork created".into(), kernel.state.clone())); + for step in 0..40 { + let body = if step % 2 == 0 { + tick_body(1) + } else { + CommandBody::Act { + actor: people[step % 30], + invocation: speak(speak_entry, &format!("Speech {step}.")), + } + }; + let envelope = clockwork_envelope(&kernel, body); + kernel.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(); + states.push((format!("clockwork commit {step}"), kernel.state.clone())); + } + let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap(); + states.push(("clockwork reopened".into(), reopened.state)); + states.push(("multivalue world".into(), multivalue_world())); + states.extend(view_scenario()); + states +} + +/// The commands that move what the views join, one at a time, each state kept: +/// dependencies bound on a route, a resource and a subject; the route closed +/// and reopened; the resource's holding emptied and refilled; a depended-on +/// subject loses its position; a dependent released; and a subject that holds +/// past-due routines and a failing dependency retires. +fn view_scenario() -> Vec<(String, crate::WorldState)> { + use crate::patch::{DependencyRef, EvidenceRef, Quantity}; + use crate::tests::TITHE_RECEIPT; + let (mut kernel, people, _) = clockwork_world(20); + let route = *kernel.state.edges.keys().next().expect("a route"); + let grain = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared resource") + .0 + }; + let (grain_0, grain_1) = (grain("Grain 0"), grain("Grain 1")); + let bind = |subject: usize, target: DependencyRef| ComponentOp::Bind { + subject: Ref::Existing(people[subject]), + target, + }; + let steps: Vec<(&str, CommandBody)> = vec![ + ( + "binds", + operations(vec![ + bind(5, DependencyRef::Route(Ref::Existing(route))), + bind(6, DependencyRef::Resource(Ref::Existing(grain_1))), + bind(7, DependencyRef::Subject(Ref::Existing(people[8]))), + bind(7, DependencyRef::Resource(Ref::Existing(grain_0))), + bind(3, DependencyRef::Subject(Ref::Existing(people[4]))), + ]), + ), + ("the route closes", operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(route) }])), + ("the route reopens", operations(vec![ComponentOp::OpenRoute { route: Ref::Existing(route) }])), + ( + "a holding empties", + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(people[7]), + resource: Ref::Existing(grain_0), + qty: Quantity(1), + }]), + ), + ( + "the holding refills", + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(people[7]), + resource: Ref::Existing(grain_0), + qty: Quantity(1), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ), + // A retired dependent never fails: closing the route it names must leave no row. + ("a dependent on the route retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[5]) }])), + ("the route closes again", operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(route) }])), + ("a long tick", tick_body(30)), + ("a depended-on subject retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[8]) }])), + ( + "a dependent is released", + operations(vec![ComponentOp::Release { + subject: Ref::Existing(people[3]), + target: DependencyRef::Subject(Ref::Existing(people[4])), + }]), + ), + ("a failing, past-due subject retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[6]) }])), + ("the route reopens after the retirement", operations(vec![ComponentOp::OpenRoute { route: Ref::Existing(route) }])), + ("a last tick", tick_body(30)), + ]; + let mut states = vec![("scenario created".to_owned(), kernel.state.clone())]; + for (name, body) in steps { + let envelope = clockwork_envelope(&kernel, body); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_or_else(|error| panic!("{name}: {error:?}")); + states.push((format!("scenario: {name}"), kernel.state.clone())); + } + states +} + +/// A world where one document sits at several points: a pressure target fed by +/// three sources, and an institution whose offices have three distinct +/// incumbents, one of them in two offices. A projection that keeps only the +/// first or last of a document's points loses a row here and nowhere else. +fn multivalue_world() -> crate::WorldState { + use crate::patch::{Office, PressureMagnitude}; + use crate::tests::{LEVY_KIND, authority_kind, office}; + use crate::PressureSource; + let (mut kernel, people, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick commits"); + let mut state = kernel.state; + let institution = *state.selection.keys().next().expect("an institution holds offices"); + state.begin(); + for source in [people[1], people[2], people[3]] { + state + .pressures + .entry(people[5]) + .or_default() + .insert(PressureSource::Subject(source), PressureMagnitude(1)); + } + let delegated = std::collections::BTreeSet::from([authority_kind(LEVY_KIND)]); + let offices = state.selection.get_mut(&institution).unwrap(); + for (name, incumbent) in [("bailiff", people[3]), ("steward", people[3]), ("reeve", people[4])] { + offices.insert(office(name), Office { incumbent: Some(incumbent), delegated: delegated.clone() }); + } + let folded = state.folded().unwrap(); + state.finish(folded); + state +} + +/// Every read index is the projection of its partition and nothing else, after +/// every commit the walked worlds make, however the world was reached. +#[test] +fn indexes_are_derived() { + for (label, state) in walked_states() { + assert_indexes_derived(&state, &label); + // The rebuild above uses the projection itself, so a wrong projection + // agrees with its own index; the scans it replaced do not. + assert_eq!(reference_scan_disagreement(&state), None, "{label}"); + } +} + +/// The first place an index read and the scan it replaced disagree, if any. +fn reference_scan_disagreement(state: &crate::WorldState) -> Option { + use crate::{Audience, Cost, PressureSource}; + let subjects: Vec<_> = state.subjects.keys().copied().collect(); + let places: Vec<_> = state + .entities + .iter() + .filter(|(_, record)| record.kind == crate::EntityKind::Place) + .map(|(id, _)| *id) + .collect(); + for subject in &subjects { + if crate::audience(state, *subject, &Audience::Colocated) + != crate::audience_by_scan(state, *subject, &Audience::Colocated) + { + return Some(format!("colocated audience of {subject:?}")); + } + if crate::delegated_authority(state, *subject) + != crate::delegated_authority_by_scan(state, *subject) + { + return Some(format!("delegated authority of {subject:?}")); + } + if crate::channels_controlled_by(state, *subject) + != crate::channels_controlled_by_by_scan(state, *subject) + { + return Some(format!("channels controlled by {subject:?}")); + } + let authority = crate::subject_authority(state, *subject); + for place in &places { + if crate::action::reachable(state, *subject, &authority, *place, Cost(3)) + != crate::action::reachable_by_scan(state, *subject, &authority, *place, Cost(3)) + { + return Some(format!("reachable {place:?} from {subject:?}")); + } + } + } + let targets: std::collections::BTreeSet<_> = + state.dependencies.values().flat_map(|held| held.iter().copied()).collect(); + for target in targets { + let mut by_index = crate::views::Views::dependents_of(state, target); + by_index.sort(); + if by_index != crate::views::Views::dependents_by_scan(state, target) { + return Some(format!("dependents of {target:?}")); + } + } + let strange = crate::ImportKey::new("aetherlight.fixture", "held by nobody"); + for key in state + .subjects + .values() + .filter_map(|subject| subject.import_key.as_ref()) + .chain(std::iter::once(&strange)) + { + if state.import_key_held(key) != crate::import_key_held_by_scan(state, key) { + return Some(format!("import key {key:?} held")); + } + } + let unnamed = crate::patch::AffordanceKindName("no such kind".into()); + for kind in state + .affordance_catalog + .values() + .map(|entry| &entry.kind) + .chain(std::iter::once(&unnamed)) + { + if state.kind_taken(kind) != crate::kind_taken_by_scan(state, kind) { + return Some(format!("affordance kind {kind:?} taken")); + } + } + for place in &places { + if crate::under_place(state, *place) != crate::under_place_by_scan(state, *place) { + return Some(format!("under_place {place:?}")); + } + if crate::routes_at(state, *place) != crate::routes_at_by_scan(state, *place) { + return Some(format!("routes at {place:?}")); + } + } + for (channel, _) in state.channels.iter() { + let actor = subjects.first().copied()?; + if crate::audience(state, actor, &Audience::Channel(*channel)) + != crate::audience_by_scan(state, actor, &Audience::Channel(*channel)) + { + return Some(format!("audience of channel {channel:?}")); + } + } + let mut sources: Vec = state + .pressures + .iter() + .flat_map(|(_, held)| held.keys().copied()) + .collect(); + sources.extend(subjects.first().map(|first| PressureSource::Subject(*first))); + for source in sources { + if crate::pressure_holders(state, source) != crate::pressure_holders_by_scan(state, source) { + return Some(format!("holders of {source:?}")); + } + } + None +} + +/// Each read an index answers equals the scan it replaced, at every walked state. +#[test] +fn index_reads_equal_reference_scans() { + for (label, state) in walked_states() { + assert_eq!(reference_scan_disagreement(&state), None, "{label}"); + } +} + +/// A read inside an open transaction sees what the transaction wrote, though +/// the index has not: a subject moved through `positions` leaves its old room +/// and joins the new one, a removed pressure row no longer lists its source, and +/// after the rollback the reads are what they were. +#[test] +fn an_index_read_mid_transaction_sees_the_log() { + use crate::patch::Position; + use crate::{Audience, PressureSource}; + let (mut kernel, people, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick presses the obligations"); + let state = &mut kernel.state; + let (mover, in_old, in_new) = (people[1], people[2], people[11]); + let new_place = state.positions[&in_new].place; + assert_ne!(state.positions[&mover].place, new_place); + let obligation = state.commitments[&people[0]] + .iter() + .find(|(_, commitment)| commitment.kind == CommitmentKind::Obligation) + .map(|(key, _)| *key) + .expect("the first person owes an obligation"); + let source = PressureSource::Commitment { subject: people[0], key: obligation }; + let reads = |state: &crate::WorldState| { + ( + crate::audience(state, in_old, &Audience::Colocated), + crate::audience(state, in_new, &Audience::Colocated), + crate::pressure_holders(state, source), + ) + }; + let before = reads(state); + assert!(before.0.contains(&mover) && !before.1.contains(&mover)); + assert!(before.2.contains(&people[0])); + + state.begin(); + state.positions.insert(mover, Position { place: new_place }); + state.pressures.remove(&people[0]); + let during = reads(state); + assert!(!during.0.contains(&mover), "the old room still lists the mover"); + assert!(during.1.contains(&mover), "the new room does not list the mover"); + assert!(!during.2.contains(&people[0]), "a removed pressure row still lists its source"); + assert_eq!(reference_scan_disagreement(state), None, "mid-transaction reads equal the scans"); + state.rollback(); + + assert_indexes_derived(state, "after the rollback"); + assert_eq!(reads(state), before); +} + +/// The oracle can see an index that disagrees with its documents: damaged one +/// way (a document listed where it is not) or the other (a document left out), +/// every indexed partition reports it, and the reads the index serves then +/// differ from the scans they replaced. +#[test] +fn a_corrupted_index_is_detected() { + use std::collections::BTreeSet; + let mut worlds = populated_worlds(); + let (mut kernel, _, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .unwrap(); + worlds.push(kernel.state); + let mut reported = BTreeSet::new(); + let mut misread = BTreeSet::new(); + for world in &worlds { + for index in 0..crate::WorldState::PARTITIONS { + for stray in [true, false] { + let mut damaged = world.clone(); + if !damaged.partitions_mut()[index].1.corrupt_index_first(stray) { + continue; + } + let schema = damaged.partitions()[index].0; + assert!( + !damaged.partitions()[index].1.index_is_derived(), + "{schema}: damage (stray {stray}) went unseen" + ); + reported.insert(schema); + if reference_scan_disagreement(&damaged).is_some() { + misread.insert(schema); + } + } + } + } + let indexed: BTreeSet<&str> = [ + "aetherlight.subject.v1", + "aetherlight.affordance.v1", + "aetherlight.entity.v1", + "aetherlight.edge.v1", + "aetherlight.position.v1", + "aetherlight.channel.v1", + "aetherlight.selection.v1", + "aetherlight.dependencies.v1", + "aetherlight.pressures.v1", + ] + .into(); + assert_eq!(reported, indexed, "exactly the indexed partitions can be damaged"); + assert_eq!(misread, indexed, "a damaged index must change what a reader answers"); +} + +/// A view is derived from the documents and nothing else: after every commit of +/// the walked worlds, however each was reached, it is what a scan of the +/// committed documents builds. +#[test] +fn views_are_derived() { + for (label, state) in walked_states() { + assert!( + state.views.same_as(&crate::views::Views::rebuild(&state)), + "{label}: the views left their documents" + ); + } +} + +/// The motion the views derive is the motion the scans derive: every live +/// subject's due commitments and failing dependencies, over short and long +/// spans, in every walked state (which holds routes that close and reopen, +/// holdings that empty, subjects that lose a position, and subjects that retire +/// holding past-due routines and failing dependencies). +#[test] +fn view_reads_equal_reference_scans() { + let mut pressed_dependency = false; + for (label, state) in walked_states() { + for minutes in [1, 30, 5_000] { + let to = FictionalMinutes(state.header.now.0 + minutes); + let motion = crate::clock::derive_motion(&state, to); + assert_eq!(motion, crate::clock::derive_motion_by_scan(&state, to), "{label}, {minutes} minutes"); + pressed_dependency |= motion + .pressed + .iter() + .any(|written| matches!(written.source, crate::PressureSource::Dependency(_))); + } + } + assert!(pressed_dependency, "no walked state had a failing dependency to compare"); +} + +/// A damaged view is seen by the oracle and changes what the clock derives: a +/// stray failing row presses a dependency nobody holds, and a missing due +/// point leaves its subjects unmoved. +#[test] +fn a_corrupted_view_is_detected() { + let (mut kernel, _, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .unwrap(); + let state = kernel.state; + let to = FictionalMinutes(state.header.now.0 + 30); + assert!(state.views.same_as(&crate::views::Views::rebuild(&state))); + for stray in [true, false] { + let mut damaged = state.clone(); + assert!(damaged.views.corrupt_for_test(stray), "stray {stray}"); + assert!( + !damaged.views.same_as(&crate::views::Views::rebuild(&damaged)), + "stray {stray}: the oracle did not see the damage" + ); + assert_ne!( + crate::clock::derive_motion(&damaged, to), + crate::clock::derive_motion_by_scan(&damaged, to), + "stray {stray}: the damage changed no read" + ); + } +} + +/// A view is read only with clean logs: reading one while a partition it joins +/// has an open write is refused, not answered from a stale fold. +#[test] +#[should_panic(expected = "open log")] +fn a_view_read_with_an_open_log_is_refused() { + let (mut kernel, people, _) = clockwork_world(20); + kernel.state.begin(); + kernel.state.positions.remove(&people[3]); + crate::clock::derive_motion(&kernel.state, FictionalMinutes(1)); +} + +/// A dependency's pressure ends with the dependency: bind to a resource the +/// subject does not hold, let a tick press it, release it, and the row is gone +/// and the world still reopens from its export. +#[test] +fn releasing_a_dependency_removes_the_pressure_it_raised() { + use crate::patch::DependencyRef; + use crate::{DependencyTarget, PressureSource}; + let (mut kernel, people, _) = clockwork_world(20); + let grain_1 = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "Grain 1") + .expect("a declared resource") + .0; + let target = DependencyTarget::Resource(grain_1); + let pressed = PressureSource::Dependency(target); + let submit = |kernel: &mut WorldKernel, body| { + let envelope = clockwork_envelope(kernel, body); + kernel.submit(envelope, &AuthenticatedCaller::verified_play()).expect("the command lands"); + }; + submit( + &mut kernel, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(people[6]), + target: DependencyRef::Resource(Ref::Existing(grain_1)), + }]), + ); + submit(&mut kernel, tick_body(1)); + assert!( + kernel.state.pressures.get(&people[6]).is_some_and(|held| held.contains_key(&pressed)), + "the tick pressed the failing dependency" + ); + submit( + &mut kernel, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(people[6]), + target: DependencyRef::Resource(Ref::Existing(grain_1)), + }]), + ); + assert!( + kernel.state.pressures.get(&people[6]).is_none_or(|held| !held.contains_key(&pressed)), + "the released dependency's pressure row stayed" + ); + let reopened = WorldKernel::open(&kernel.export().unwrap()).expect("the world reopens"); + assert_eq!(reopened.state, kernel.state); +} + +/// A bulk commit (genesis, a large patch, every replayed commit at open) moves +/// many placements and touches many dependencies at once. Folding the views +/// for it reads rows in proportion to what the commit changed, not to changed +/// targets times touched dependencies: every person moves and binds a route in +/// one transaction, and 1600 persons read under six times the rows of 400. +#[test] +fn folding_a_bulk_commit_reads_rows_in_proportion_to_the_change() { + use crate::patch::Position; + use crate::DependencyTarget; + let mut rows = Vec::new(); + for persons in [400usize, 1600] { + let (kernel, people, _) = clockwork_world(persons); + let mut state = kernel.state; + let route = *state.edges.keys().next().expect("a route"); + let place = state.positions[&people[0]].place; + state.begin(); + for person in people.iter().filter(|person| state.positions.contains_key(person)).copied().collect::>() { + state.positions.insert(person, Position { place }); + state.dependencies.entry(person).or_default().insert(DependencyTarget::Route(route)); + } + let mut views = std::mem::take(&mut state.views); + let before = crate::docs::rows_read(); + views.fold(&state); + rows.push(crate::docs::rows_read() - before); + state.views = views; + state.rollback(); + } + assert!(rows[1] > rows[0], "{rows:?}: a bigger commit read no more"); + assert!(rows[1] < rows[0] * 6, "the fold read {} rows at 400 persons and {} at 1600", rows[0], rows[1]); +} + +/// Every kind of command that moves what the views join, drawn at random from a +/// seeded stream over the clockwork world (bind and release on a subject, a +/// route and a resource; routes closed and opened; holdings emptied and filled; +/// subjects relocated and retired; ticks and speech; refused commands), with the +/// world reopened from its export every 50 commits. After every commit, kept or +/// refused, the views are what a scan of the documents builds and the motion +/// they derive is the motion the scans derive, over short and long spans; each +/// reopened world holds the live views. Seeds are fixed, so a failure replays. +#[test] +fn views_equal_their_rebuild_and_the_scans_over_random_commands() { + use crate::patch::{DependencyRef, EvidenceRef, Quantity}; + use crate::tests::TITHE_RECEIPT; + use crate::DependencyTarget; + use std::collections::BTreeMap; + + let mut kept: BTreeMap<&'static str, usize> = BTreeMap::new(); + for seed in [1u64, 2, 3] { + let (mut kernel, people, speak_entry) = clockwork_world(40); + let routes: Vec<_> = kernel.state.edges.keys().copied().collect(); + let grains: Vec<_> = (0..4) + .map(|place| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == format!("Grain {place}")) + .expect("a declared resource") + .0 + }) + .collect(); + let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + let mut next = move |bound: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % bound as u64) as usize + }; + for step in 0..150 { + let person = people[next(people.len())]; + let route = routes[next(routes.len())]; + let grain = grains[next(grains.len())]; + let target = match next(3) { + 0 => DependencyRef::Subject(Ref::Existing(people[next(people.len())])), + 1 => DependencyRef::Route(Ref::Existing(route)), + _ => DependencyRef::Resource(Ref::Existing(grain)), + }; + let ops = |op| operations(vec![op]); + let (name, body) = match next(16) { + 0 | 1 => ("bind", ops(ComponentOp::Bind { subject: Ref::Existing(person), target })), + 2 | 3 => { + // Release something that is bound, so releases succeed. + let bound: Vec<_> = kernel + .state + .dependencies + .iter() + .flat_map(|(subject, held)| held.iter().map(|target| (*subject, *target))) + .collect(); + if bound.is_empty() { + ("tick", tick_body(1)) + } else { + let (subject, held) = bound[next(bound.len())]; + let target = match held { + DependencyTarget::Subject(other) => DependencyRef::Subject(Ref::Existing(other)), + DependencyTarget::Route(edge) => DependencyRef::Route(Ref::Existing(edge)), + DependencyTarget::Resource(entity) => DependencyRef::Resource(Ref::Existing(entity)), + }; + ("release", ops(ComponentOp::Release { subject: Ref::Existing(subject), target })) + } + } + 4 => ("close", ops(ComponentOp::CloseRoute { route: Ref::Existing(route) })), + 5 => ("open", ops(ComponentOp::OpenRoute { route: Ref::Existing(route) })), + 6 => ( + "consume", + ops(ComponentOp::Consume { + holder: Ref::Existing(person), + resource: Ref::Existing(grain), + qty: Quantity(1), + }), + ), + 7 => ( + "admit", + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(person), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ), + 8 => { + // Along a route that touches where the subject stands. + let here = kernel.state.positions.get(&person).map(|position| position.place); + let via = kernel + .state + .edges + .iter() + .find(|(_, edge)| { + let (from, to) = edge.endpoints(); + here.is_some_and(|place| place == from || place == to) + }) + .map(|(edge, _)| *edge) + .unwrap_or(route); + ("relocate", ops(ComponentOp::Relocate { subject: Ref::Existing(person), via: Ref::Existing(via) })) + } + 9 if next(5) == 0 => ("retire", ops(ComponentOp::Retire { subject: Ref::Existing(person) })), + 13 => ( + "speech", + CommandBody::Act { + actor: person, + invocation: speak(speak_entry, &format!("Speech {step}.")), + }, + ), + 14 => ( + "refused", + ops(ComponentOp::Bind { + subject: Ref::Existing(person), + target: DependencyRef::Subject(Ref::Existing(person)), + }), + ), + _ => ("tick", tick_body(1 + next(25) as u32)), + }; + let envelope = clockwork_envelope(&kernel, body); + if kernel.submit(envelope, &AuthenticatedCaller::verified_play()).is_ok() { + *kept.entry(name).or_default() += 1; + } + let label = format!("seed {seed}, commit {step} ({name})"); + assert!( + kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)), + "{label}: the views left their documents" + ); + for minutes in [1, 30, 5_000] { + let to = FictionalMinutes(kernel.state.header.now.0 + minutes); + assert_eq!( + crate::clock::derive_motion(&kernel.state, to), + crate::clock::derive_motion_by_scan(&kernel.state, to), + "{label}: motion over {minutes} minutes" + ); + } + if step % 50 == 49 { + let reopened = WorldKernel::open(&kernel.export().unwrap()) + .unwrap_or_else(|error| panic!("{label}: the world does not reopen: {error:?}")); + assert_eq!(reopened.state, kernel.state, "{label}: reopened state"); + assert!(reopened.state.views.same_as(&kernel.state.views), "{label}: reopened views"); + } + } + } + for name in ["bind", "release", "close", "open", "consume", "admit", "relocate", "retire", "speech", "tick"] { + assert!(kept.get(name).copied().unwrap_or(0) > 0, "no {name} ever landed: {kept:?}"); + } +} + +/// A holder written before the operations begin and returned by them to the +/// value it had when the transaction opened is no longer in the log, yet it +/// moved: conservation reads it from the entry record, so the transfer that +/// restores it is judged as conserving. +#[test] +fn apply_conserves_a_holder_restored_to_its_start_value() { + use crate::patch::ResolvedOp; + use crate::{Quantity, apply_operations}; + + let (mut kernel, people, _) = clockwork_world(20); + let grain = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "Grain 1") + .expect("declared") + .0; + let revision = kernel.state.revision + 1; + let state = &mut kernel.state; + state.begin(); + crate::set_held(state, people[0], grain, 5); + let transfer = ResolvedOp::Transfer { from: people[0], to: people[1], resource: grain, qty: Quantity(5) }; + apply_operations(state, std::slice::from_ref(&transfer), &[], revision) + .expect("moving the pre-written five on conserves it"); + state.rollback(); +} + +/// Patches whose later operations read what earlier ones wrote, judged by the +/// resolver and committed: each is a legal sequence and must be accepted, or, +/// where the sequence changes nothing, refused cleanly by the resolver with the +/// commit never reached. +mod within_one_patch { + use super::{clockwork_envelope, clockwork_world}; + use crate::patch::{ + AuthorityGrantRef, AuthorityTargetRef, Declaration, DraftHandle, Mismatch, + PressureMagnitude, PressureSourceRef, SubjectDeclaration, + }; + use crate::tests::{LEVY_KIND, authority_kind}; + use crate::{ + AuthenticatedCaller, CommandBody, ComponentOp, KernelError, Ref, SubjectKind, SubjectId, + WorldKernel, WorldPatch, + }; + use std::collections::BTreeSet; + + fn submit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<(), KernelError> { + let envelope = clockwork_envelope(kernel, CommandBody::AdmitPatch { patch }); + kernel.submit(envelope, &AuthenticatedCaller::verified_play()).map(|_| ()) + } + + fn ops(operations: Vec) -> WorldPatch { + WorldPatch { declarations: vec![], operations, evidence: vec![] } + } + + fn levy_over(holder: SubjectId, over: SubjectId) -> ComponentOp { + ComponentOp::GrantAuthority { + holder: Ref::Existing(holder), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::Subject(Ref::Existing(over)), + }, + } + } + + /// Two jurisdictions of one kind over different subjects are disjoint, so + /// one holder may hold both. + #[test] + fn one_holder_may_hold_one_kind_over_two_subjects() { + let (mut kernel, p, _) = clockwork_world(30); + submit(&mut kernel, ops(vec![levy_over(p[0], p[5]), levy_over(p[0], p[6])])) + .expect("levy over two different subjects does not overlap"); + } + + fn source(subject: SubjectId) -> PressureSourceRef { + PressureSourceRef::Subject(Ref::Existing(subject)) + } + + /// A pressure advanced by one operation is there for the next to resolve, + /// and one reduced to nothing is gone for the next to advance afresh. + #[test] + fn a_pressure_advanced_in_a_patch_is_read_by_the_next_operation() { + let (mut kernel, p, _) = clockwork_world(30); + submit(&mut kernel, ops(vec![ + ComponentOp::AdvancePressure { source: source(p[0]), target: Ref::Existing(p[12]), by: PressureMagnitude(2) }, + ComponentOp::ResolvePressure { source: source(p[0]), target: Ref::Existing(p[12]) }, + ])) + .expect("advance then resolve the same slot"); + + submit(&mut kernel, ops(vec![ + ComponentOp::AdvancePressure { source: source(p[0]), target: Ref::Existing(p[13]), by: PressureMagnitude(2) }, + ComponentOp::ReducePressure { source: source(p[0]), target: Ref::Existing(p[13]), by: PressureMagnitude(2) }, + ComponentOp::AdvancePressure { source: source(p[0]), target: Ref::Existing(p[13]), by: PressureMagnitude(1) }, + ])) + .expect("advance, reduce to nothing, advance again"); + } + + fn declared(name: &str, affordance: crate::AffordanceId) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(name), + label: name.into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([Ref::Existing(affordance)]), + position: None, + import_key: None, + }) + } + + /// A subject declared with an affordance already has it: granting it is no + /// change, and the resolver says so itself, rather than admitting what the + /// commit then refuses. Revoking it first makes the grant a change. + #[test] + fn a_declared_affordance_is_known_to_the_operations_that_follow() { + let (mut kernel, _, speak) = clockwork_world(30); + let draft = |name: &str| Ref::Draft(DraftHandle::new(name)); + + let refused = submit(&mut kernel, WorldPatch { + declarations: vec![declared("scribe", speak)], + operations: vec![ComponentOp::GrantAffordance { subject: draft("scribe"), affordance: Ref::Existing(speak) }], + evidence: vec![], + }) + .unwrap_err(); + assert!( + matches!(&refused, KernelError::PatchRejected(m) + if m == &[Mismatch::NoOperationEffect { operation: 0 }]), + "{refused:?}" + ); + + submit(&mut kernel, WorldPatch { + declarations: vec![declared("scribe2", speak)], + operations: vec![ + ComponentOp::RevokeAffordance { subject: draft("scribe2"), affordance: Ref::Existing(speak) }, + ComponentOp::GrantAffordance { subject: draft("scribe2"), affordance: Ref::Existing(speak) }, + ], + evidence: vec![], + }) + .expect("revoke then grant is a change"); + } +} + +/// Seeded random patch sequences through the real kernel. The resolver judges +/// each patch against its overlay, `apply_operations` re-derives conservation +/// and disjointness from the transaction log, and the full-scan references +/// judge the committed world: the three must agree after every step. +/// +/// Per step, in a world of grain holders, institutions with a warden office, +/// pressures and a speak affordance: +/// - the outcome is an accepted commit or a `PatchRejected` mismatch set, never +/// a kernel `Invariant` error (the resolver admitted what apply refuses); +/// - a refused patch changes no document, and the same patch refused again +/// gives the same mismatches; +/// - after an accepted one every index equals its scan, no subject holds two +/// overlapping jurisdictions of one kind, and the grain total is unchanged +/// (the generator transfers and never mints). +#[test] +fn random_patch_sequences_agree_with_the_scan_references() { + use crate::patch::{ + AuthorityGrantRef, AuthorityTargetRef, PressureMagnitude, PressureSourceRef, Quantity, + }; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{EntityKind, SubjectKind}; + + struct Rng(u64); + impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % n as u64) as usize + } + } + + let (mut accepted, mut refused, mut multi) = (0usize, 0usize, 0usize); + for seed in 1..=10u64 { + let (mut kernel, people, speak) = clockwork_world(30); + let labelled = |kernel: &WorldKernel, kind: EntityKind| -> Vec { + let mut found: Vec<_> = kernel + .state + .entities + .iter() + .filter(|(_, record)| record.kind == kind) + .map(|(id, record)| (record.label.clone(), *id)) + .collect(); + found.sort(); + found.into_iter().map(|(_, id)| id).collect() + }; + let places = labelled(&kernel, EntityKind::Place); + let grains = labelled(&kernel, EntityKind::Resource); + let institutions: Vec<_> = (0..places.len()) + .map(|place| subject_by_label(&kernel.state, &format!("Institution {place}"))) + .collect(); + let grain_total = |kernel: &WorldKernel| -> u128 { + grains.iter().map(|grain| crate::resource_total_by_scan(&kernel.state, *grain)).sum() + }; + let total = grain_total(&kernel); + let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + + for step in 0..30 { + // A small pool of subjects, so patches collide often. + let person = |rng: &mut Rng| Ref::Existing(people[rng.below(6)]); + let levy_target = |rng: &mut Rng| { + if rng.below(2) == 0 { + AuthorityTargetRef::Subject(Ref::Existing(people[rng.below(6)])) + } else { + AuthorityTargetRef::PlaceSubtree(Ref::Existing(places[rng.below(3)])) + } + }; + let mut declarations = Vec::new(); + let mut operations = Vec::new(); + for index in 0..1 + rng.below(4) { + let op = match rng.below(14) { + 0..=2 => { + let holder = if rng.below(4) == 0 { + Ref::Existing(institutions[rng.below(3)]) + } else { + person(&mut rng) + }; + ComponentOp::GrantAuthority { + holder, + grant: AuthorityGrantRef { kind: authority_kind(LEVY_KIND), over: levy_target(&mut rng) }, + } + } + 3 => ComponentOp::RevokeAuthority { + holder: person(&mut rng), + grant: AuthorityGrantRef { kind: authority_kind(LEVY_KIND), over: levy_target(&mut rng) }, + }, + 4 => ComponentOp::InstallIncumbent { + institution: Ref::Existing(institutions[rng.below(3)]), + office: office(WARDEN_OFFICE), + incumbent: person(&mut rng), + }, + 5 => ComponentOp::VacateOffice { + institution: Ref::Existing(institutions[rng.below(3)]), + office: office(WARDEN_OFFICE), + }, + 6 => ComponentOp::AdvancePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + by: PressureMagnitude(1 + rng.below(3) as u32), + }, + 7 => ComponentOp::ReducePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + by: PressureMagnitude(1 + rng.below(3) as u32), + }, + 8 => ComponentOp::ResolvePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + }, + 9 => ComponentOp::GrantAffordance { subject: person(&mut rng), affordance: Ref::Existing(speak) }, + 10 => ComponentOp::RevokeAffordance { subject: person(&mut rng), affordance: Ref::Existing(speak) }, + 11 => ComponentOp::Transfer { + from: person(&mut rng), + to: person(&mut rng), + resource: Ref::Existing(grains[rng.below(3)]), + qty: Quantity(1), + }, + 12 => { + let name = format!("s{step}-{index}"); + declarations.push(Declaration::Subject(crate::patch::SubjectDeclaration { + handle: DraftHandle::new(&name), + label: format!("Drafted {seed}-{name}"), + kind: SubjectKind::Person, + affordances: std::collections::BTreeSet::from([Ref::Existing(speak)]), + position: None, + import_key: None, + })); + ComponentOp::GrantAffordance { + subject: Ref::Draft(DraftHandle::new(&name)), + affordance: Ref::Existing(speak), + } + } + _ if rng.below(8) == 0 => ComponentOp::Retire { subject: person(&mut rng) }, + _ => ComponentOp::ResolvePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + }, + }; + operations.push(op); + } + let patch = WorldPatch { declarations, operations, evidence: vec![] }; + let documents = kernel.state.documents().unwrap(); + let again = clockwork_envelope(&kernel, CommandBody::AdmitPatch { patch: patch.clone() }); + let outcome = kernel.submit( + clockwork_envelope(&kernel, CommandBody::AdmitPatch { patch }), + &AuthenticatedCaller::verified_play(), + ); + match outcome { + Ok(_) => { + accepted += 1; + assert_eq!(reference_scan_disagreement(&kernel.state), None, "seed {seed} step {step}"); + assert_indexes_derived(&kernel.state, &format!("seed {seed} step {step}")); + for subject in kernel.state.subjects.keys() { + assert!( + !crate::holder_overlaps(&kernel.state, *subject), + "seed {seed} step {step}: {subject:?} holds overlapping jurisdictions" + ); + } + assert_eq!(grain_total(&kernel), total, "seed {seed} step {step}: custody"); + } + Err(KernelError::PatchRejected(mismatches)) => { + refused += 1; + multi += usize::from(mismatches.len() > 1); + assert_eq!(kernel.state.documents().unwrap(), documents, "seed {seed} step {step}: a refusal wrote"); + // The same patch against the same world: the same refusal. + let repeat = kernel.submit(again, &AuthenticatedCaller::verified_play()); + assert!( + matches!(&repeat, Err(KernelError::PatchRejected(m)) if *m == mismatches), + "seed {seed} step {step}: {repeat:?}" + ); + } + Err(other) => panic!("seed {seed} step {step}: resolver and apply disagree: {other:?}"), + } + } + } + // The generator must reach both sides, or the loop proves nothing. + assert!(accepted >= 40 && refused >= 40 && multi >= 1, "{accepted} accepted, {refused} refused, {multi} multi"); +} diff --git a/native/aetherlight/src/grammar.rs b/native/aetherlight/src/grammar.rs new file mode 100644 index 000000000..a11cd691a --- /dev/null +++ b/native/aetherlight/src/grammar.rs @@ -0,0 +1,209 @@ +//! The action grammar a world is bound to at creation. +//! +//! A grammar is the closed set of affordance kinds a world may declare, each +//! with its role signature and the one render path its acts take. The grammar's +//! home is the Aetheria repo; the kernel holds only this binding: the verbs it +//! enforces, and a content digest that names exactly which grammar that was. +//! The digest is derived here and nowhere else, so a binding cannot claim a +//! digest its verbs do not have. + +use crate::SubjectKind; +use crate::patch::{AffordanceKindName, EntityKind, RefKind, Role, RoleSpec, kernel_speak_entry}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; + +/// How an act of one verb reaches the player: filmed in the engine as a ship +/// action, or shown as Aetheria's portrait-and-choices conversation. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum RenderPath { + ShipAction, + Conversation, +} + +/// What a grammar role may be bound to, in the grammar's own vocabulary. Each +/// lowers to exactly one kernel `RefKind`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum GrammarReferentKind { + Person, + Faction, + Population, + Place, + Cargo, +} + +impl GrammarReferentKind { + fn ref_kind(self) -> RefKind { + match self { + Self::Person => RefKind::Subject(Some(SubjectKind::Person)), + Self::Faction => RefKind::Subject(Some(SubjectKind::Institution)), + Self::Population => RefKind::Subject(Some(SubjectKind::Population)), + Self::Place => RefKind::Entity(EntityKind::Place), + Self::Cargo => RefKind::Entity(EntityKind::Resource), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +pub struct GrammarRole { + pub role: String, + pub referent: GrammarReferentKind, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +pub struct GrammarVerb { + pub render_path: RenderPath, + /// In signature order: the order is part of the verb. + pub roles: Vec, +} + +impl GrammarVerb { + /// Whether a declared role list is this verb's signature: same names, same + /// referent kinds, same order. + pub(crate) fn admits_roles(&self, roles: &[RoleSpec]) -> bool { + self.role_specs() == roles + } + + /// This verb's signature as the kernel declares it: the one lowering of a + /// grammar role, so declaring a verb and admitting a declaration cannot + /// disagree. + pub(crate) fn role_specs(&self) -> Vec { + self.roles + .iter() + .map(|role| RoleSpec { + role: Role(role.role.clone()), + kind: role.referent.ref_kind(), + }) + .collect() + } +} + +/// Why a bound grammar refuses an affordance entry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GrammarRefusal { + KindNotInGrammar, + RolesDisagree, + SpeakNotConversation, +} + +#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)] +pub enum GrammarError { + #[error("grammar schema id is empty")] + EmptySchemaId, + #[error("grammar declares one verb kind twice")] + DuplicateVerb, + #[error("grammar digest does not match its verbs")] + DigestMismatch, +} + +/// Which grammar a world is bound to: its schema id, revision and content +/// digest. What a consumer reads; the verb table stays in the binding. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GrammarIdentity { + pub schema_id: String, + pub revision: u32, + pub digest: String, +} + +/// The grammar a world was created under. Immutable: the only constructor +/// derives the digest, and deserialisation re-derives it and refuses a mismatch. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(try_from = "RawBinding")] +pub struct GrammarBinding { + schema_id: String, + revision: u32, + digest: String, + verbs: BTreeMap, +} + +#[derive(Deserialize)] +struct RawBinding { + schema_id: String, + revision: u32, + digest: String, + verbs: BTreeMap, +} + +impl TryFrom for GrammarBinding { + type Error = GrammarError; + + fn try_from(raw: RawBinding) -> Result { + let bound = Self::new(raw.schema_id, raw.revision, raw.verbs)?; + if bound.digest != raw.digest { + return Err(GrammarError::DigestMismatch); + } + Ok(bound) + } +} + +impl GrammarBinding { + /// The one constructor. Verbs arrive in any order and are keyed by kind; + /// the digest is the sha256 of the canonical encoding of the kind-sorted + /// verbs, so the same verbs bind to the same digest however they were listed. + pub fn new( + schema_id: impl Into, + revision: u32, + verbs: impl IntoIterator, + ) -> Result { + let schema_id = schema_id.into(); + if schema_id.is_empty() { + return Err(GrammarError::EmptySchemaId); + } + let mut table = BTreeMap::new(); + for (kind, verb) in verbs { + if table.insert(kind, verb).is_some() { + return Err(GrammarError::DuplicateVerb); + } + } + let encoded = rmp_serde::to_vec_named(&table).expect("a verb table encodes"); + let digest = format!("sha256:{:x}", Sha256::digest(encoded)); + Ok(Self { + schema_id, + revision, + digest, + verbs: table, + }) + } + + pub fn identity(&self) -> GrammarIdentity { + GrammarIdentity { + schema_id: self.schema_id.clone(), + revision: self.revision, + digest: self.digest.clone(), + } + } + + /// Every verb, in kind order. + pub(crate) fn verbs(&self) -> impl Iterator { + self.verbs.iter().map(|(kind, verb)| (kind.as_str(), verb)) + } + + pub(crate) fn verb(&self, kind: &str) -> Option<&GrammarVerb> { + self.verbs.get(kind) + } + + /// The one grammar check. The resolver turns a refusal into a mismatch and + /// `admit_resolved`, the only writer of the affordance catalog, into an + /// invariant error, so no path adds an entry without passing it. + pub(crate) fn refusal( + &self, + kind: &AffordanceKindName, + roles: &[RoleSpec], + ) -> Option { + let Some(verb) = self.verb(&kind.0) else { + return Some(GrammarRefusal::KindNotInGrammar); + }; + if !verb.admits_roles(roles) { + return Some(GrammarRefusal::RolesDisagree); + } + if *kind == kernel_speak_entry().kind && verb.render_path != RenderPath::Conversation { + return Some(GrammarRefusal::SpeakNotConversation); + } + None + } +} + +#[cfg(test)] +mod tests; diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs new file mode 100644 index 000000000..817668d73 --- /dev/null +++ b/native/aetherlight/src/grammar/tests.rs @@ -0,0 +1,659 @@ +use super::*; +use crate::patch::{ + AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, EntityKind, + Mismatch, OutcomeBand, Precondition, Role, RoleSpec, +}; +use crate::tests::{auth_principal, command, creation, owner}; +use crate::{ + CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, CommitReceipt, + WorldKernel, WorldPatch, +}; + +fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb { + GrammarVerb { + render_path: path, + roles: roles + .iter() + .map(|(role, referent)| GrammarRole { + role: (*role).into(), + referent: *referent, + }) + .collect(), + } +} + +/// What the fixture world's genesis needs: the kernel speak entry and the +/// fixture's own `convene`. Anything else a test wants is added to it. +fn grammar_with(extra: &[(&str, GrammarVerb)]) -> GrammarBinding { + let mut verbs = vec![ + ("speak".to_owned(), verb(RenderPath::Conversation, &[])), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ]; + verbs.extend( + extra + .iter() + .map(|(kind, v)| ((*kind).to_owned(), v.clone())), + ); + GrammarBinding::new("aetheria.grammar", 3, verbs).unwrap() +} + +fn bound(grammar: Option, title: &str) -> CreateWorld { + let mut world = creation(title); + world.grammar = grammar; + world +} + +fn declare(handle: &str, kind: &str, roles: &[(&str, RefKind)]) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles: roles + .iter() + .map(|(role, kind)| RoleSpec { + role: Role((*role).into()), + kind: *kind, + }) + .collect(), + // Speech with one audience is the smallest entry the resolver does + // not refuse as inert; the grammar check does not read it. + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }) +} + +fn patch_of(declarations: Vec) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } +} + +fn rejected(result: Result) -> Vec { + match result { + Err(KernelError::PatchRejected(set)) => set, + Err(other) => panic!("expected a patch refusal, got {other:?}"), + Ok(_) => panic!("expected a patch refusal, the command was admitted"), + } +} + +fn create(world: CreateWorld) -> Result { + WorldKernel::create(world, &auth_principal(owner())).map(|(kernel, _)| kernel) +} + +fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CallerId::Play, + CommandBody::AdmitPatch { + patch, + }, + ), + &crate::AuthenticatedCaller::verified_play(), + ) +} + +fn person() -> RefKind { + RefKind::Subject(Some(SubjectKind::Person)) +} + +fn place() -> RefKind { + RefKind::Entity(EntityKind::Place) +} + +fn not_in_grammar(handle: &str) -> Vec { + vec![Mismatch::AffordanceKindNotInGrammar { + handle: DraftHandle::new(handle), + }] +} + +fn disagrees(handle: &str) -> Vec { + vec![Mismatch::AffordanceRolesDisagreeWithGrammar { + handle: DraftHandle::new(handle), + }] +} + +#[test] +fn grammar_world_refuses_an_affordance_kind_outside_the_grammar() { + // Genesis: a declared kind the binding lacks is refused. + let mut world = bound(Some(grammar_with(&[])), "Outside"); + world.patch.declarations.push(declare("wave", "wave", &[])); + assert_eq!(rejected(create(world)), not_in_grammar("wave")); + + // A later AdmitPatch: the same kind is refused, and a verb the grammar + // does carry is admitted by the same path. + let extra = [("hail", verb(RenderPath::Conversation, &[]))]; + let kernel = create(bound(Some(grammar_with(&extra)), "Outside")); + let mut kernel = kernel.unwrap(); + assert_eq!( + rejected(admit( + &mut kernel, + patch_of(vec![declare("wave", "wave", &[])]) + )), + not_in_grammar("wave") + ); + let receipt = admit(&mut kernel, patch_of(vec![declare("hail", "hail", &[])])).unwrap(); + assert!(receipt.resulting_revision > 0); +} + +#[test] +fn grammar_world_refuses_a_role_signature_the_grammar_does_not_carry() { + let extra = [ + ( + "meet", + verb( + RenderPath::ShipAction, + &[ + ("who", GrammarReferentKind::Person), + ("where_", GrammarReferentKind::Place), + ], + ), + ), + ("hail", verb(RenderPath::Conversation, &[])), + ]; + let kernel = create(bound(Some(grammar_with(&extra)), "Signatures")); + let mut kernel = kernel.unwrap(); + for (label, roles) in [ + ("renamed", vec![("whom", person()), ("where_", place())]), + ("rekinded", vec![("who", person()), ("where_", person())]), + ("swapped", vec![("where_", place()), ("who", person())]), + ("short", vec![("who", person())]), + ( + "long", + vec![("who", person()), ("where_", place()), ("why", person())], + ), + ] { + let set = rejected(admit( + &mut kernel, + patch_of(vec![declare(label, "meet", &roles)]), + )); + assert_eq!(set, disagrees(label), "{label}"); + } + // A role on a verb the grammar declares with none. + let set = rejected(admit( + &mut kernel, + patch_of(vec![declare("hail", "hail", &[("who", person())])]), + )); + assert_eq!(set, disagrees("hail")); + // The exact signature is admitted. + let receipt = admit( + &mut kernel, + patch_of(vec![declare( + "meet", + "meet", + &[("who", person()), ("where_", place())], + )]), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); +} + +#[test] +fn each_grammar_referent_kind_admits_exactly_its_own_kernel_kind() { + let kinds = [ + (GrammarReferentKind::Person, person()), + ( + GrammarReferentKind::Faction, + RefKind::Subject(Some(SubjectKind::Institution)), + ), + ( + GrammarReferentKind::Population, + RefKind::Subject(Some(SubjectKind::Population)), + ), + (GrammarReferentKind::Place, place()), + ( + GrammarReferentKind::Cargo, + RefKind::Entity(EntityKind::Resource), + ), + ]; + for (referent, own) in &kinds { + let extra = [("act", verb(RenderPath::ShipAction, &[("with", *referent)]))]; + for (_, offered) in &kinds { + let kernel = create(bound(Some(grammar_with(&extra)), "Referents")); + let mut kernel = kernel.unwrap(); + let result = admit( + &mut kernel, + patch_of(vec![declare("act", "act", &[("with", *offered)])]), + ); + if offered == own { + assert!( + matches!(result, Ok(_)), + "{referent:?} refused its own kind" + ); + } else { + assert_eq!( + rejected(result), + disagrees("act"), + "{referent:?} admitted {offered:?}" + ); + } + } + } +} + +#[test] +fn grammar_world_without_speak_refuses_the_kernel_speak_grant() { + let no_speak = GrammarBinding::new( + "aetheria.grammar", + 1, + [("convene".to_owned(), verb(RenderPath::Conversation, &[]))], + ) + .unwrap(); + assert_eq!( + rejected(create(bound(Some(no_speak), "Mute"))), + not_in_grammar(crate::patch::KERNEL_SPEAK_HANDLE) + ); + + // The kernel entry is held to the signature as well as the kind. + let loud = GrammarBinding::new( + "aetheria.grammar", + 1, + [ + ( + "speak".to_owned(), + verb( + RenderPath::Conversation, + &[("to", GrammarReferentKind::Person)], + ), + ), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ], + ) + .unwrap(); + assert_eq!( + rejected(create(bound(Some(loud), "Loud"))), + disagrees(crate::patch::KERNEL_SPEAK_HANDLE) + ); +} + +#[test] +fn unbound_world_keeps_the_open_catalog() { + let mut world = bound(None, "Open"); + world + .patch + .declarations + .push(declare("wave", "wave", &[("at", person())])); + let kernel = create(world); + let mut kernel = kernel.unwrap(); + let receipt = admit( + &mut kernel, + patch_of(vec![declare("beacon", "beacon", &[])]), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); + let snapshot = kernel.snapshot().unwrap(); + assert!(snapshot.grammar.is_none()); + assert!(snapshot.affordances.len() >= 4); + assert!(snapshot.affordances.iter().all(|a| a.render_path.is_none())); + + // The state row of a world with no grammar carries no grammar key, so its + // bytes and digests are those of a world written before grammars existed. + let encoded = rmp_serde::to_vec_named(&*kernel.state.header).unwrap(); + let keys: std::collections::BTreeMap = + rmp_serde::from_slice(&encoded).unwrap(); + assert!(!keys.contains_key("grammar")); + assert!(keys.contains_key("title")); +} + +#[test] +fn a_bound_world_reports_its_grammar_and_derives_render_paths_from_it() { + let extra = [("dock", verb(RenderPath::ShipAction, &[]))]; + let grammar = grammar_with(&extra); + let identity = grammar.identity(); + let kernel = create(bound(Some(grammar), "Reports")); + let mut kernel = kernel.unwrap(); + admit(&mut kernel, patch_of(vec![declare("dock", "dock", &[])])).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot.grammar, Some(identity)); + let path_of = |kind: &str| { + snapshot + .affordances + .iter() + .find(|a| a.entry.kind.0 == kind) + .unwrap_or_else(|| panic!("{kind} is in the catalog")) + .render_path + }; + assert_eq!(path_of("dock"), Some(RenderPath::ShipAction)); + assert_eq!(path_of("convene"), Some(RenderPath::Conversation)); + assert_eq!(path_of("speak"), Some(RenderPath::Conversation)); +} + +#[test] +fn a_reopened_grammar_world_still_holds_its_grammar() { + let grammar = grammar_with(&[]); + let identity = grammar.identity(); + let kernel = create(bound(Some(grammar), "Reopened")); + let kernel = kernel.unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap().grammar, Some(identity)); + assert_eq!( + rejected(admit( + &mut reopened, + patch_of(vec![declare("wave", "wave", &[])]) + )), + not_in_grammar("wave") + ); +} + +#[test] +fn the_bound_grammar_is_part_of_the_world_state_digest() { + let kernel = create(bound(Some(grammar_with(&[])), "Digested")); + let kernel = kernel.unwrap(); + let bound_digest = kernel.state.full_state_digest().unwrap(); + let mut state = kernel.state.clone(); + state.header.get_mut().grammar = None; + let open_digest = state.full_state_digest().unwrap(); + state.header.get_mut().grammar = Some(grammar_with(&[("dock", verb(RenderPath::ShipAction, &[]))])); + let other_digest = state.full_state_digest().unwrap(); + assert_ne!(bound_digest, open_digest); + assert_ne!(bound_digest, other_digest); +} + +#[test] +fn grammar_digest_is_derived_and_order_free() { + let forward = [ + ("alpha".to_owned(), verb(RenderPath::ShipAction, &[])), + ( + "beta".to_owned(), + verb( + RenderPath::Conversation, + &[("to", GrammarReferentKind::Person)], + ), + ), + ("gamma".to_owned(), verb(RenderPath::Conversation, &[])), + ]; + let mut reversed = forward.clone(); + reversed.reverse(); + let a = GrammarBinding::new("aetheria.grammar", 1, forward.clone()).unwrap(); + let b = GrammarBinding::new("aetheria.grammar", 1, reversed).unwrap(); + assert_eq!(a.digest, b.digest); + assert_eq!(a, b); + + // Content-derived: each part of a verb moves the digest. + let changed = |edit: &dyn Fn(&mut Vec<(String, GrammarVerb)>)| { + let mut verbs = forward.to_vec(); + edit(&mut verbs); + GrammarBinding::new("aetheria.grammar", 1, verbs) + .unwrap() + .digest + }; + assert_ne!( + a.digest, + changed(&|v| v[0].1.render_path = RenderPath::Conversation) + ); + assert_ne!(a.digest, changed(&|v| v[1].1.roles[0].role = "from".into())); + assert_ne!( + a.digest, + changed(&|v| v[1].1.roles[0].referent = GrammarReferentKind::Faction) + ); + assert_ne!(a.digest, changed(&|v| v[2].0 = "delta".into())); + assert_ne!( + a.digest, + changed(&|v| { + v.pop(); + }) + ); + // Role order is part of a verb. + let ordered = |roles: &[(&str, GrammarReferentKind)]| { + GrammarBinding::new( + "g", + 1, + [("meet".to_owned(), verb(RenderPath::ShipAction, roles))], + ) + .unwrap() + .digest + }; + assert_ne!( + ordered(&[ + ("a", GrammarReferentKind::Person), + ("b", GrammarReferentKind::Place) + ]), + ordered(&[ + ("b", GrammarReferentKind::Place), + ("a", GrammarReferentKind::Person) + ]) + ); + // The identity reads the same fields back. + let identity = a.identity(); + assert_eq!(identity.schema_id, "aetheria.grammar"); + assert_eq!(identity.revision, 1); + assert_eq!(identity.digest, a.digest); +} + +#[test] +fn a_tampered_grammar_digest_fails_to_deserialise() { + let binding = grammar_with(&[]); + let value = serde_json::to_value(&binding).unwrap(); + // Untouched: the round trip holds. + let back: GrammarBinding = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(back, binding); + + // A digest the verbs do not have. + let mut forged = value.clone(); + forged["digest"] = "sha256:00".into(); + assert!(serde_json::from_value::(forged.clone()).is_err()); + + // A verb edited under the digest it already had. + let mut edited = value; + edited["verbs"]["convene"]["render_path"] = "ship_action".into(); + assert!(serde_json::from_value::(edited).is_err()); + + // The named encoding a state row uses refuses it the same way. + let bytes = rmp_serde::to_vec_named(&forged).unwrap(); + assert!(rmp_serde::from_slice::(&bytes).is_err()); +} + +#[test] +fn a_grammar_names_each_verb_once_and_has_a_schema() { + assert_eq!( + GrammarBinding::new("", 1, Vec::new()).unwrap_err(), + GrammarError::EmptySchemaId + ); + assert_eq!( + GrammarBinding::new( + "g", + 1, + [ + ("hail".to_owned(), verb(RenderPath::Conversation, &[])), + ("hail".to_owned(), verb(RenderPath::ShipAction, &[])), + ] + ) + .unwrap_err(), + GrammarError::DuplicateVerb + ); +} + +fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + patch: WorldPatch, +) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + caller.clone(), + CommandBody::AdmitPatch { patch }, + ), + &crate::AuthenticatedCaller::fixture(caller), + ) +} + +/// A bound world whose revision has moved past genesis: one Play patch +/// that adds a dead-end place. +fn advanced_grammar_world() -> (WorldKernel, crate::EntityId) { + let extra = [("hail", verb(RenderPath::Conversation, &[]))]; + let kernel = create(bound(Some(grammar_with(&extra)), "Advanced")); + let mut kernel = kernel.unwrap(); + let commons = *kernel.state.entities.keys().next().unwrap(); + admit( + &mut kernel, + patch_of(vec![ + Declaration::Entity(crate::patch::EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(crate::patch::RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: crate::patch::Ref::Existing(commons), + to: crate::patch::Ref::Draft(DraftHandle::new("dead-end")), + access: crate::patch::AccessKind::Public, + cost: crate::patch::Cost(1), + }), + ]), + ) + .unwrap(); + let dead_end = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Unwalked Road") + .map(|(id, _)| id) + .unwrap(); + (kernel, dead_end) +} + +type Door = (&'static str, CallerId); + +/// Each door refuses an outside kind and a wrong role signature, typed, and the +/// refusal leaves the revision where it was. +fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec) { + for (door, caller) in doors { + let revision = kernel.state.revision; + let kind = submit_as( + kernel, + caller.clone(), + patch_of(vec![declare("wave", "wave", &[])]), + ); + assert_eq!(rejected(kind), not_in_grammar("wave"), "{door}"); + let roles = submit_as( + kernel, + caller, + patch_of(vec![declare("hail", "hail", &[("who", person())])]), + ); + assert_eq!(rejected(roles), disagrees("hail"), "{door}"); + assert_eq!( + kernel.state.revision, revision, + "{door} refusal moved the world" + ); + } +} + +#[test] +fn play_refuses_outside_the_grammar_after_the_revision_has_moved() { + let (mut kernel, _) = advanced_grammar_world(); + assert_eq!(kernel.state.revision, 1); + refuse_at_each_door(&mut kernel, vec![("play", CallerId::Play)]); + // The same path admits what the grammar carries, so the refusals above are + // the grammar's and not a closed door. + let receipt = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![declare("hail", "hail", &[])]), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); +} + +#[test] +fn a_grammar_that_binds_speak_as_anything_but_conversation_is_refused_at_bind() { + let ship = |roles: &[(&str, GrammarReferentKind)]| { + GrammarBinding::new( + "aetheria.grammar", + 1, + [ + ("speak".to_owned(), verb(RenderPath::ShipAction, roles)), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ], + ) + .unwrap() + }; + assert_eq!( + rejected(create(bound(Some(ship(&[])), "Filmed speech"))), + vec![Mismatch::SpeakRenderPathDisagreesWithGrammar { + handle: DraftHandle::new(crate::patch::KERNEL_SPEAK_HANDLE), + }] + ); + // A ShipAction speak with a role fails on the signature first and is still + // refused: no variant of speak but zero roles, Conversation, is admitted. + assert_eq!( + rejected( + create(bound( + Some(ship(&[("to", GrammarReferentKind::Person)])), + "Loud" + )) + ), + disagrees(crate::patch::KERNEL_SPEAK_HANDLE) + ); + // The control: Conversation speak binds. + assert!(create(bound(Some(grammar_with(&[])), "Spoken")).is_ok()); +} + +/// `apply_effect` re-decides an effect it is handed. An effect resolved against +/// a world with no grammar must not install an entry the bound grammar lacks: +/// the catalog's only writer holds the grammar check itself. +#[test] +fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { + let extra = [ + ( + "meet", + verb( + RenderPath::ShipAction, + &[("who", GrammarReferentKind::Person)], + ), + ), + ("hail", verb(RenderPath::Conversation, &[])), + ]; + let kernel = create(bound(Some(grammar_with(&extra)), "Forged")); + let kernel = kernel.unwrap(); + let mut twin = kernel.state.clone(); + twin.header.get_mut().grammar = None; + let resolve = |kind: &str, roles: &[(&str, RefKind)]| { + crate::patch::resolve_patch( + &twin, + CommandId::issue(), + &patch_of(vec![declare("probe", kind, roles)]), + ) + .expect("the unbound twin admits any canonical kind") + }; + for (label, resolved, admitted) in [ + ("outside kind", resolve("wave", &[]), false), + ("wrong roles", resolve("meet", &[("whom", person())]), false), + ("carried verb", resolve("hail", &[]), true), + ] { + let mut state = kernel.state.clone(); + let catalog = state.affordance_catalog.len(); + let result = crate::apply_effect( + &mut state, + CommandId::issue(), + &CallerId::Play, + &crate::WorldEffect::PatchAdmitted { + resolved, + }, + ); + if admitted { + result.unwrap_or_else(|error| panic!("{label}: {error:?}")); + assert_eq!(state.affordance_catalog.len(), catalog + 1, "{label}"); + } else { + assert!( + matches!(result, Err(KernelError::Invariant(_))), + "{label}: {result:?}" + ); + assert_eq!(state.affordance_catalog.len(), catalog, "{label}"); + } + } +} diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs new file mode 100644 index 000000000..150da6960 --- /dev/null +++ b/native/aetherlight/src/import_key_tests.rs @@ -0,0 +1,692 @@ +//! One record, one subject: admission keeps the import-key mapping injective at +//! every door and at every revision, and a world nobody imported into is +//! byte-for-byte what it was before keys existed. + +use crate::patch::{ + AccessKind, ComponentOp, Cost, Declaration, DraftHandle, EntityDeclaration, EntityKind, + ImportKey, Mismatch, Ref, RouteDeclaration, +}; +use crate::tests::{auth_principal, command, creation, owner}; +use crate::{ + CallerId, CommandBody, CommandId, CreateWorld, EntityId, KernelError, + SubjectDeclaration, SubjectKind, CommitReceipt, + WorldKernel, WorldPatch, +}; +use std::collections::BTreeSet; + +fn key(schema: &str, record: &str) -> ImportKey { + ImportKey::new(schema, record) +} + +fn alpha() -> ImportKey { + key("aetheria.ship", "Alpha") +} + +/// The fixture genesis with its witness imported from `alpha()`. +fn keyed_creation(title: &str) -> CreateWorld { + let mut world = creation(title); + for declaration in &mut world.patch.declarations { + if let Declaration::Subject(subject) = declaration + && subject.handle == DraftHandle::new("persona") + { + subject.import_key = Some(alpha()); + } + } + world +} + +fn create(world: CreateWorld) -> Result { + WorldKernel::create(world, &auth_principal(owner())).map(|(kernel, _)| kernel) +} + +fn keyed_world() -> WorldKernel { + create(keyed_creation("Keyed")).unwrap() +} + +fn rejected(result: Result) -> Vec { + match result { + Err(KernelError::PatchRejected(set)) => set, + Err(other) => panic!("expected a patch refusal, got {other:?}"), + Ok(_) => panic!("expected a patch refusal, the command was admitted"), + } +} + +fn patch_of(declarations: Vec) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } +} + +fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + patch: WorldPatch, +) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + caller.clone(), + CommandBody::AdmitPatch { patch }, + ), + &crate::AuthenticatedCaller::fixture(caller), + ) +} + +fn commons(kernel: &WorldKernel) -> EntityId { + *kernel.state.entities.keys().next().unwrap() +} + +/// A keyed subject that holds no verbs: legal, since a subject may be declared +/// with none, and the lightest declaration an import can make. +fn keyed(handle: &str, import_key: Option, place: EntityId) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: SubjectKind::Person, + affordances: BTreeSet::new(), + position: Some(Ref::Existing(place)), + import_key, + }) +} + +fn held(handle: &str) -> Mismatch { + Mismatch::ImportKeyHeld { + handle: DraftHandle::new(handle), + } +} + +fn duplicate(handle: &str) -> Mismatch { + Mismatch::DuplicateImportKey { + handle: DraftHandle::new(handle), + } +} + +fn malformed(handle: &str) -> Mismatch { + Mismatch::MalformedImportKey { + handle: DraftHandle::new(handle), + } +} + +fn keys_in(kernel: &WorldKernel) -> Vec { + kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .filter_map(|subject| subject.import_key) + .collect() +} + +#[test] +fn one_patch_cannot_declare_two_subjects_with_one_import_key() { + // At genesis. + let mut world = creation("Twins"); + for declaration in &mut world.patch.declarations { + if let Declaration::Subject(subject) = declaration + && (subject.handle == DraftHandle::new("persona") + || subject.handle == DraftHandle::new("operator")) + { + subject.import_key = Some(alpha()); + } + } + let result = create(world); + assert_eq!(rejected(result), vec![duplicate("operator")]); + + // In a later patch, with the key unheld. + let mut kernel = keyed_world(); + let place = commons(&kernel); + let revision = kernel.state.revision; + let beta = Some(key("aetheria.ship", "Beta")); + let error = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![ + keyed("first", beta.clone(), place), + keyed("second", beta, place), + ]), + ); + assert_eq!(rejected(error), vec![duplicate("second")]); + assert_eq!(kernel.state.revision, revision, "a refusal moved the world"); +} + +/// The fixture world past genesis: Play has added an unwalked place. +fn advanced_keyed_world() -> (WorldKernel, EntityId) { + let mut kernel = keyed_world(); + let place = commons(&kernel); + submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: Ref::Existing(place), + to: Ref::Draft(DraftHandle::new("dead-end")), + access: AccessKind::Public, + cost: Cost(1), + }), + ]), + ) + .unwrap(); + let dead_end = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Unwalked Road") + .map(|(id, _)| id) + .unwrap(); + (kernel, dead_end) +} + +/// Each door names the held key, typed, and the refusal leaves the revision +/// where it was. +fn refuse_held_key_at_each_door( + kernel: &mut WorldKernel, + place: EntityId, + doors: Vec<(&str, CallerId)>, +) { + for (door, caller) in doors { + let revision = kernel.state.revision; + let result = submit_as( + kernel, + caller, + patch_of(vec![keyed("copy", Some(alpha()), place)]), + ); + assert_eq!(rejected(result), vec![held("copy")], "{door}"); + assert_eq!( + kernel.state.revision, revision, + "{door} refusal moved the world" + ); + } +} + +#[test] +fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { + let (mut kernel, dead_end) = advanced_keyed_world(); + assert!(kernel.state.revision > 0, "the world has moved past genesis"); + refuse_held_key_at_each_door( + &mut kernel, + dead_end, + vec![("play", CallerId::Play)], + ); + // The same doors admit an unheld key, so the refusals are the key's; and + // what a door admitted is held against every later door. + let fresh = key("aetheria.ship", "Gamma"); + let receipt = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("fresh", Some(fresh.clone()), dead_end)]), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); + let again = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("fresh-again", Some(fresh), dead_end)]), + ); + assert_eq!(rejected(again), vec![held("fresh-again")]); +} + +#[test] +fn a_held_import_key_is_refused_in_a_later_patch() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("again", Some(alpha()), place)]), + ); + assert_eq!(rejected(error), vec![held("again")]); + assert_eq!(kernel.state.revision, revision); + assert_eq!(keys_in(&kernel), vec![alpha()]); +} + +#[test] +fn a_retired_subjects_import_key_is_never_reissued() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let witness = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.import_key.is_some()) + .unwrap() + .id; + submit_as( + &mut kernel, + CallerId::Play, + WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Retire { + subject: Ref::Existing(witness), + }], + evidence: Vec::new(), + }, + ) + .unwrap(); + let retired = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == witness) + .unwrap(); + assert!(retired.retired, "the witness is retired"); + assert_eq!( + retired.import_key, + Some(alpha()), + "a retired subject keeps its key" + ); + let error = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("reborn", Some(alpha()), place)]), + ); + assert_eq!(rejected(error), vec![held("reborn")]); +} + +#[test] +fn keys_that_differ_in_any_way_are_distinct_records() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + // Same length, case, prefix, the same concatenation split elsewhere, and + // the parts swapped: none is the held key. + let forgeries = [ + key("aetheria.ship", "Alphb"), + key("aetheria.ship", "alpha"), + key("aetheria.ship", "Alph"), + key("aetheria.ship", "Alpha2"), + key("aetheria.shipA", "lpha"), + key("aetheria.sh", "ipAlpha"), + key("Aetheria.ship", "Alpha"), + key("Alpha", "aetheria.ship"), + key("aetheria.ship2", "Alpha"), + ]; + let declarations = forgeries + .iter() + .enumerate() + .map(|(index, forged)| keyed(&format!("forged-{index}"), Some(forged.clone()), place)) + .collect(); + submit_as( + &mut kernel, + CallerId::Play, + patch_of(declarations), + ) + .expect("nine distinct keys beside the held one are admitted together"); + let held_now: BTreeSet = keys_in(&kernel).into_iter().collect(); + assert_eq!(held_now.len(), forgeries.len() + 1); + // And each is then held exactly: repeating any one is refused. + for (index, forged) in forgeries.iter().enumerate() { + let again = submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("repeat", Some(forged.clone()), place)]), + ); + assert_eq!(rejected(again), vec![held("repeat")], "forgery {index}"); + } +} + +#[test] +fn a_malformed_import_key_is_refused_without_echoing_it() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let long = "x".repeat(201); + let wide = "é".repeat(101); + let cases = [ + key("", "Delta"), + key("aetheria.ship", ""), + key("aetheria ship", "Delta"), + key("aetheria.ship", "Del\tta"), + key("aetheria.ship", "Del\u{a0}ta"), + key("aetheria.ship", " Delta"), + key("aetheria.ship", "Delta\n"), + key(&long, "Delta"), + key("aetheria.ship", &long), + key("aetheria.ship", &wide), + key(&wide, "Delta"), + ]; + for (index, bad) in cases.iter().enumerate() { + let set = rejected(submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed("bad", Some(bad.clone()), place)]), + )); + assert_eq!(set, vec![malformed("bad")], "case {index}"); + let spelled = format!("{set:?}"); + assert!( + !spelled.contains("Delta") && !spelled.contains("aetheria"), + "case {index} echoed the key" + ); + } + // The limit is 200 bytes per part, counted in bytes. + let edge = "é".repeat(100); + let at_limit = [ + key(&"x".repeat(200), &edge), + key("aetheria.ship", &"y".repeat(200)), + ]; + let declarations = at_limit + .iter() + .enumerate() + .map(|(index, limit)| keyed(&format!("edge-{index}"), Some(limit.clone()), place)) + .collect(); + submit_as( + &mut kernel, + CallerId::Play, + patch_of(declarations), + ) + .expect("keys of exactly 200 bytes per part are admitted"); +} + +#[test] +fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_elsewhere() { + let kernel = keyed_world(); + let place = commons(&kernel); + let resolve = |handle: &str| { + crate::patch::resolve_patch( + &kernel.state, + CommandId::issue(), + &patch_of(vec![keyed( + handle, + Some(key("aetheria.ship", "Omega")), + place, + )]), + ) + .expect("the key is unheld at the revision both were resolved against") + }; + let (first, second) = (resolve("first"), resolve("second")); + let mut state = kernel.state.clone(); + let before = state.subjects.len(); + let effect = |resolved| crate::WorldEffect::PatchAdmitted { + resolved, + }; + crate::apply_effect( + &mut state, + CommandId::issue(), + &CallerId::Play, + &effect(first), + ) + .unwrap(); + assert_eq!(state.subjects.len(), before + 1); + let result = crate::apply_effect( + &mut state, + CommandId::issue(), + &CallerId::Play, + &effect(second), + ); + assert!( + matches!(result, Err(KernelError::Invariant(_))), + "{result:?}" + ); + assert_eq!( + state.subjects.len(), + before + 1, + "the second subject was installed" + ); +} + +fn contains(haystack: &[u8], needle: &[u8]) -> bool { + haystack.windows(needle.len()).any(|window| window == needle) +} + +#[test] +fn keyless_world_digests_unchanged() { + // A subject nobody imported serialises without the field at all, so every + // digest written before keys existed is the digest of the same bytes. + let kernel = create(creation("Keyless")); + let kernel = kernel.unwrap(); + let state = kernel.state.encoded_documents(); + assert!( + !contains(&state, b"import_key"), + "a keyless world grew a field" + ); + // A keyed world carries it and digests differently. + let keyed = keyed_world(); + let keyed_state = keyed.state.encoded_documents(); + assert!(contains(&keyed_state, b"import_key")); + assert_ne!( + keyed.state.full_state_digest().unwrap(), + kernel.state.full_state_digest().unwrap() + ); + // And a world nobody imported into holds every key absent. + assert!(kernel.state.subjects.values().all(|s| s.import_key.is_none())); +} + +#[test] +fn a_keyed_world_reopens_with_its_keys_and_digests() { + let kernel = keyed_world(); + let snapshot = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + let again = reopened.snapshot().unwrap(); + assert_eq!(again.state_digest, snapshot.state_digest); + let keys = keys_in(&reopened); + assert_eq!(keys, vec![alpha()]); + // A reader of the snapshot gets both parts back, separately. + assert_eq!(keys[0].schema(), "aetheria.ship"); + assert_eq!(keys[0].record(), "Alpha"); +} + + +#[test] +fn a_record_key_is_one_canonical_spelling() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let nfc = "Caf\u{e9}"; + let nfd = "Cafe\u{301}"; + let submit = |kernel: &mut WorldKernel, handle: &str, record: &str| { + submit_as( + kernel, + CallerId::Play, + patch_of(vec![keyed( + handle, + Some(key("aetheria.ship", record)), + place, + )]), + ) + }; + submit(&mut kernel, "nfc", nfc).expect("the NFC spelling is admitted"); + let refused = [ + nfd, + "Alpha\u{200b}", + "Alpha\u{0}", + "\u{feff}Alpha", + "Alpha\u{202e}", + "Alpha\u{7}", + "Del ta", + "Del\tta", + "Del\u{a0}ta", + "Del\u{2003}ta", + "Del\nta", + // The violation sits deep in a long, real-shaped path, past any prefix. + "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Cafe\u{301}", + "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan\u{200b}Hart", + ]; + for (index, record) in refused.iter().enumerate() { + let set = rejected(submit(&mut kernel, "bad", record)); + assert_eq!(set, vec![malformed("bad")], "spelling {index}"); + assert!( + !format!("{set:?}").contains("Alpha"), + "spelling {index} echoed the key" + ); + } + assert_eq!( + keys_in(&kernel).len(), + 2, + "only the genesis key and the NFC key are held" + ); +} + +#[test] +fn a_lore_page_path_with_spaces_is_a_record_key() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let record = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart"; + let declare = |kernel: &mut WorldKernel, handle: &str| { + submit_as( + kernel, + CallerId::Play, + patch_of(vec![keyed( + handle, + Some(key("aetheria.lore", record)), + place, + )]), + ) + }; + declare(&mut kernel, "ewan").expect("a path with interior spaces is admitted"); + assert_eq!(rejected(declare(&mut kernel, "again")), vec![held("again")]); +} + +#[test] +fn a_loaded_state_with_a_bad_import_key_is_refused() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + submit_as( + &mut kernel, + CallerId::Play, + patch_of(vec![keyed( + "beta", + Some(key("aetheria.ship", "Beta")), + place, + )]), + ) + .unwrap(); + assert!(crate::journal::verify_state_shape(&kernel.state).is_ok()); + let corrupt = |edit: &dyn Fn(&mut ImportKey)| { + let mut state = kernel.state.clone(); + let ids: Vec<_> = state.subjects.keys().copied().collect(); + for id in ids { + if let Some(held) = state.subjects.get_mut(&id).and_then(|s| s.import_key.as_mut()) { + edit(held); + } + } + crate::journal::verify_state_shape(&state) + }; + let shared = corrupt(&|held| *held = alpha()); + assert!( + matches!(&shared, Err(crate::journal::JournalError::Corrupt(why)) if why.contains("import key")), + "two subjects sharing one key: {shared:?}" + ); + assert!( + corrupt(&|held| *held = key("aetheria.ship", " Beta ")).is_err(), + "a key with edge spaces must not load" + ); + assert!( + corrupt(&|held| *held = key("", "")).is_err(), + "an empty key must not load" + ); + assert!( + corrupt(&|held| *held = key("aetheria.ship", "Be\u{200b}ta")).is_err(), + "a key with a format character must not load" + ); +} + +/// The admission backstop, reached with an effect resolution never produced: a +/// resolved patch whose two subjects carry one key. The control is the same +/// effect with distinct keys, admitted by the same function. +#[test] +fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { + let kernel = keyed_world(); + let place = commons(&kernel); + let resolve = || { + crate::patch::resolve_patch( + &kernel.state, + CommandId::issue(), + &patch_of(vec![ + keyed("first", Some(key("aetheria.ship", "Beta")), place), + keyed("second", Some(key("aetheria.ship", "Gamma")), place), + ]), + ) + .expect("two distinct keys resolve") + }; + let resolves_to = crate::resolution_revision(&kernel.state).unwrap(); + let mut control = kernel.state.clone(); + crate::admit_resolved(&mut control, &resolve(), resolves_to) + .expect("distinct keys are admitted"); + + let mut twinned = resolve(); + assert_eq!(twinned.subjects.len(), 2); + twinned.subjects[1].subject.import_key = twinned.subjects[0].subject.import_key.clone(); + let mut state = kernel.state.clone(); + let error = crate::admit_resolved(&mut state, &twinned, resolves_to) + .expect_err("one key on two resolved subjects is refused"); + assert!( + matches!(&error, KernelError::Invariant(why) if why.contains("import key")), + "{error:?}" + ); + assert!(!format!("{error:?}").contains("Beta"), "the refusal echoed the key"); +} + +/// A decomposable character at every position of a real-shaped key: the NFD +/// spelling is refused wherever it sits, the NFC spelling is admitted, so the +/// rule cannot be a prefix, suffix or first-character check. +#[test] +fn a_decomposable_character_is_refused_in_nfd_at_every_position() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let template: Vec = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart" + .chars() + .collect(); + let submit = |kernel: &mut WorldKernel, handle: &str, record: String| { + submit_as( + kernel, + CallerId::Play, + patch_of(vec![keyed( + handle, + Some(key("aetheria.lore", &record)), + place, + )]), + ) + }; + let spelled = |position: usize, inserted: &str| { + let mut record: String = template[..position].iter().collect(); + record.push_str(inserted); + record.extend(&template[position..]); + record + }; + for position in 0..=template.len() { + let nfd = spelled(position, "e\u{301}"); + assert!( + !unicode_normalization::is_nfc(&nfd), + "position {position} is not NFD" + ); + let set = rejected(submit(&mut kernel, "bad", nfd)); + assert_eq!(set, vec![malformed("bad")], "NFD at position {position}"); + } + for position in 0..=template.len() { + let nfc = spelled(position, "\u{e9}"); + submit(&mut kernel, &format!("good{position}"), nfc) + .unwrap_or_else(|_| panic!("NFC at position {position} was refused")); + } + assert_eq!( + keys_in(&kernel).len(), + 1 + template.len() + 1, + "the genesis key and one NFC key per position are held, no NFD key" + ); +} + +#[test] +fn the_owner_door_is_closed_to_a_keyed_declaration() { + let mut kernel = keyed_world(); + let place = commons(&kernel); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + CallerId::Principal(owner()), + patch_of(vec![keyed("fresh", Some(key("aetheria.ship", "Gamma")), place)]), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.state.revision, revision); +} diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs new file mode 100644 index 000000000..929ce057c --- /dev/null +++ b/native/aetherlight/src/journal.rs @@ -0,0 +1,2329 @@ +use super::{ + COMMIT_SCHEMA, CommittedCommand, KernelError, WorldCommit, WorldEffect, + WorldId, WorldState, apply_effect, commit_digest, reduce, +}; +use crate::docs::Changed; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use std::collections::{BTreeMap, BTreeSet}; +use thiserror::Error; + +pub(super) const JOURNAL_SCHEMA: &str = "aetherlight.journal.v1"; + +#[derive(Debug, Error)] +pub(super) enum JournalError { + #[error("world journal is corrupt: {0}")] + Corrupt(String), + /// A well-formed commit of another schema generation: not damage, a world + /// this build cannot read. Named apart so a store can tell an old save from + /// a corrupt one. + #[error("commit schema {found} is not the supported {supported}")] + UnsupportedSchema { found: String, supported: &'static str }, +} + +/// The one judge of the schema generation, asked of every commit before any of +/// its other fields is believed. +fn require_commit_schema(commit: &WorldCommit) -> Result<(), JournalError> { + if commit.schema == COMMIT_SCHEMA { + return Ok(()); + } + Err(JournalError::UnsupportedSchema { + found: commit.schema.clone(), + supported: COMMIT_SCHEMA, + }) +} + +/// What an export carries: the schema that names the format, and the commits in +/// revision order. Nothing else is stored, because nothing else is truth: the +/// head state is the replay of these commits. +#[derive(Serialize)] +struct ExportRef<'a> { + schema: &'a str, + commits: &'a [WorldCommit], +} + +#[derive(Serialize, Deserialize)] +struct Export { + schema: String, + commits: Vec, +} + +/// The only record of a world: its commits in revision order, genesis first. +pub(super) struct WorldJournal { + commits: Vec, +} + +impl WorldJournal { + pub(super) fn genesis(genesis: WorldCommit) -> Self { + Self { + commits: vec![genesis], + } + } + + pub(super) fn append(&mut self, commit: WorldCommit) { + self.commits.push(commit); + } + + /// Every decision the world has acted on, oldest first: the one place an + /// event lives, in the commit that applied it. + pub(super) fn acted_events(&self) -> impl Iterator { + self.commits.iter().filter_map(|commit| match &commit.effect { + WorldEffect::Acted { event, .. } => Some(event), + _ => None, + }) + } + + pub(super) fn export(&self) -> Result, KernelError> { + rmp_serde::to_vec_named(&ExportRef { + schema: JOURNAL_SCHEMA, + commits: &self.commits, + }) + .map_err(|error| KernelError::Serialization(error.to_string())) + } + + /// Decode canonically, then replay: the head state is whatever the chain + /// derives, and a chain that does not verify is not a world. + /// + /// A chain verifies as a prefix, so an export with its tail dropped, or an + /// older export, opens as a valid shorter world. The holder of the bytes + /// owns the head: it keeps the revision and state digest from `snapshot()` + /// at export time and compares them after `open` (AL5's C# store). + pub(super) fn open(bytes: &[u8]) -> Result<(Self, WorldState), JournalError> { + let export: Export = decode(bytes)?; + if export.schema != JOURNAL_SCHEMA { + return Err(JournalError::Corrupt(format!( + "export schema {} is not {JOURNAL_SCHEMA}", + export.schema + ))); + } + let state = verify_history(&export.commits)?; + Ok(( + Self { + commits: export.commits, + }, + state, + )) + } + + #[cfg(test)] + pub(super) fn commit_count(&self) -> usize { + self.commits.len() + } + + #[cfg(test)] + pub(super) fn commits_for_test(&self) -> Vec { + self.commits.clone() + } +} + +/// The one judge of a stored chain, `pub(super)` so a forgery test outside this +/// module routes through the same function that `open` does. It replays the +/// commits in revision order from genesis and returns the head state they +/// derive; position `i` must hold resulting revision `i`. +pub(super) fn verify_history(commits: &[WorldCommit]) -> Result { + let genesis = commits + .first() + .ok_or_else(|| JournalError::Corrupt("world has no genesis commit".into()))?; + require_commit_schema(genesis)?; + let CommittedCommand::CreateWorld(genesis_command) = &genesis.command else { + return Err(JournalError::Corrupt( + "first commit does not contain the immutable creation command".into(), + )); + }; + let WorldEffect::WorldCreated { .. } = &genesis.effect else { + return Err(JournalError::Corrupt( + "first commit is not immutable world genesis".into(), + )); + }; + if genesis.previous_revision.is_some() + || genesis.resulting_revision != 0 + || genesis.world_id != WorldId::of(genesis_command.id()) + || genesis.previous_state_digest.is_some() + || genesis.previous_commit_digest.is_some() + || commit_digest(genesis).map_err(kernel_error)? != genesis.digest + { + return Err(JournalError::Corrupt( + "genesis commit is not canonical or verifiable".into(), + )); + } + let mut replay = WorldState::genesis(genesis.world_id, genesis_command, &genesis.effect) + .map_err(kernel_error)?; + verify_state_shape(&replay)?; + let born: Vec<_> = replay.commitments.keys().map(|subject| (*subject, None)).collect(); + verify_commitments_are_future(&replay, &born)?; + if replay.state_digest != genesis.resulting_state_digest { + return Err(JournalError::Corrupt( + "genesis resulting state digest is invalid".into(), + )); + } + replay.last_commit_digest = Some(genesis.digest.clone()); + + for commit in &commits[1..] { + require_commit_schema(commit)?; + if commit.world_id != replay.header.world_id + || commit.previous_revision != Some(replay.revision) + || commit.resulting_revision != replay.revision.saturating_add(1) + || commit.previous_state_digest.as_deref() != Some(replay.state_digest.as_str()) + || commit.previous_commit_digest != replay.last_commit_digest + || commit_digest(commit).map_err(kernel_error)? != commit.digest + { + return Err(JournalError::Corrupt( + "commit chain is not contiguous or verifiable".into(), + )); + } + // Authority is re-decided here for free: `apply_committed_command` + // re-runs `reduce` against the pre-commit state and requires effect + // equality, then `apply_effect`, and both of those call + // `require_play`. A forged commit recording the owner as the caller of + // a post-genesis command fails replay rather than being admitted by a + // reducer that trusts the recorded caller. A third statement of the same rule here would be a + // third owner of one decision. + replay.begin(); + apply_committed_command(&mut replay, commit)?; + // The clock needs no chain check of its own: only `TimeAdvanced` writes + // it, `apply_effect` re-derives `to` from a `TickMinutes` that cannot + // be read outside `1..=MAX_ROUTE_COST`, so every tick moves it forward + // and nothing else moves it. + replay.revision = commit.resulting_revision; + let accumulator = replay.folded().map_err(kernel_error)?; + replay.state_digest = accumulator.state_digest(replay.revision); + if replay.state_digest != commit.resulting_state_digest { + return Err(JournalError::Corrupt( + "commit resulting state digest is invalid".into(), + )); + } + let touched = replay.finish(accumulator); + verify_commitments_are_future(&replay, &touched)?; + replay.last_commit_digest = Some(commit.digest.clone()); + } + verify_state_shape(&replay)?; + Ok(replay) +} + +/// The replay-side twin of `Mismatch::CommitmentDueInThePast`: every commitment +/// key this commit introduced is due after the post-commit clock. Replay already +/// reconstructs both sides, and the transaction's change set names the only subjects +/// that can hold a new key, with what each held before. +fn verify_commitments_are_future( + state: &WorldState, + touched: &[Changed>], +) -> Result<(), JournalError> { + for (subject_id, before) in touched { + let Some(held) = state.commitments.get(subject_id) else { + continue; + }; + for (key, commitment) in held { + let existed = before + .as_ref() + .is_some_and(|previous| previous.contains_key(key)); + if !existed && commitment.due <= state.header.now { + return Err(JournalError::Corrupt( + "a commitment was born at or after its own due date".into(), + )); + } + } + } + Ok(()) +} + +pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { + if state.header.title.trim().is_empty() || state.header.title.trim() != state.header.title { + return Err(JournalError::Corrupt( + "world title is empty or noncanonical".into(), + )); + } + super::validate_principal(&state.header.owner).map_err(kernel_error)?; + if state.subjects.is_empty() { + return Err(JournalError::Corrupt("world ontology is empty".into())); + } + let is_place = |entity_id: &super::EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == super::EntityKind::Place) + }; + for (entity_id, entity) in &state.entities { + if !super::patch::is_canonical_text(&entity.label) { + return Err(JournalError::Corrupt( + "entity label is empty or noncanonical".into(), + )); + } + if let Some(container) = entity.container + && (entity.kind != super::EntityKind::Place || !is_place(&container)) + { + return Err(JournalError::Corrupt( + "entity container does not name a canonical place".into(), + )); + } + if !super::patch::containment_terminates(*entity_id, &state.entities) { + return Err(JournalError::Corrupt("place contains itself".into())); + } + } + for edge in state.edges.values() { + let (from, to) = edge.endpoints(); + if !is_place(&from) + || !is_place(&to) + || from == to + || !super::patch::is_valid_cost(edge.cost()) + { + return Err(JournalError::Corrupt( + "route does not join two distinct places at a valid cost".into(), + )); + } + } + for (subject_id, position) in &state.positions { + if !state.subjects.contains_key(subject_id) || !is_place(&position.place) { + return Err(JournalError::Corrupt( + "position does not name a canonical subject and place".into(), + )); + } + } + let is_resource = |entity_id: &super::EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == super::EntityKind::Resource) + }; + // Absence is zero and one slot holds one pair, so a store satisfying these + // clauses cannot carry a zero, an empty holder, a duplicate, or a dangling + // holding — with no scan for any of them. + for (subject_id, held) in &state.holdings { + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || held + .iter() + .any(|(resource, quantity)| !is_resource(resource) || quantity.0 == 0) + { + return Err(JournalError::Corrupt( + "holding does not name a canonical subject and resource at a nonzero quantity" + .into(), + )); + } + } + for (subject_id, targets) in &state.dependencies { + let target_is_canonical = |target: &super::DependencyTarget| match target { + super::DependencyTarget::Resource(entity_id) => is_resource(entity_id), + super::DependencyTarget::Route(edge_id) => state.edges.contains_key(edge_id), + super::DependencyTarget::Subject(other) => { + other != subject_id && state.subjects.contains_key(other) + } + }; + if !state.subjects.contains_key(subject_id) + || targets.is_empty() + || !targets.iter().all(target_is_canonical) + { + return Err(JournalError::Corrupt( + "dependency does not name a canonical subject and a distinct canonical target" + .into(), + )); + } + } + // Facts, channels, and knowledge. The `facts`/`channels` bijections run both + // ways: a payload row without its entity, or an entity of that kind without + // its payload, is a referenceable half-thing. + for (entity_id, record) in &state.facts { + let standing_is_live = match &record.standing { + super::FactStanding::Canonical { evidence } => { + super::patch::is_canonical_text(evidence.text()) + } + super::FactStanding::Claimed { by } => state.subjects.contains_key(by), + super::FactStanding::Ruled => true, + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Fact) + || !super::patch::is_canonical_text(record.statement.as_str()) + || !standing_is_live + { + return Err(JournalError::Corrupt( + "a fact names no canonical entity, statement, or standing".into(), + )); + } + } + for (entity_id, record) in &state.channels { + let reach_is_live = match &record.reach { + super::Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + super::Reach::Place(place) => is_place(place), + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Channel) + || !reach_is_live + || !record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) + { + return Err(JournalError::Corrupt( + "a channel names no canonical entity, reach, or controller".into(), + )); + } + } + for (entity_id, entity) in &state.entities { + let paired = match entity.kind { + super::EntityKind::Fact => state.facts.contains_key(entity_id), + super::EntityKind::Channel => state.channels.contains_key(entity_id), + super::EntityKind::Place | super::EntityKind::Resource => true, + }; + if !paired { + return Err(JournalError::Corrupt( + "a fact or channel entity carries no payload row".into(), + )); + } + } + for ((subject_id, fact), entry) in &state.knowledge { + let entry_is_live = |entry: &super::Knowledge| { + entry.acquired_at <= state.revision + && match entry.source { + super::KnowledgeSource::Told { by, via } => { + state.subjects.contains_key(&by) + && via.is_none_or(|channel| state.channels.contains_key(&channel)) + } + super::KnowledgeSource::Seen { by } => state.subjects.contains_key(&by), + super::KnowledgeSource::Witnessed | super::KnowledgeSource::Evidenced => true, + } + }; + if !state.subjects.contains_key(subject_id) + || !state.facts.contains_key(fact) + || !entry_is_live(entry) + { + return Err(JournalError::Corrupt( + "knowledge does not name a canonical subject, fact, and source, or was acquired ahead of the world's revision" + .into(), + )); + } + } + // Commitments, pressures, and the authored scale target. + // Absence is the only spelling of nothing at every level, so a store + // satisfying these clauses carries no empty inner map, no zero magnitude, + // and no dangling row — with no scan for any of them. + for (subject_id, held) in &state.commitments { + let commitment_is_canonical = |commitment: &super::Commitment| { + (commitment.kind == super::CommitmentKind::Routine) == commitment.period.is_some() + && (commitment.kind == super::CommitmentKind::Routine + || commitment.checks.is_empty()) + && match commitment.counterparty { + Some(counterparty) => { + counterparty != *subject_id + && state.subjects.contains_key(&counterparty) + && commitment.kind != super::CommitmentKind::Goal + } + None => true, + } + && commitment + .checks + .iter() + .all(|check| super::bound_precondition_is_live(state, check)) + }; + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || !held.values().all(commitment_is_canonical) + { + return Err(JournalError::Corrupt( + "a commitment does not name a canonical promisor, counterparty, shape, or check" + .into(), + )); + } + } + for (target, held) in &state.pressures { + let source_is_live = |source: &super::PressureSource| match source { + super::PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|commitments| commitments.contains_key(key)), + super::PressureSource::Dependency(dependency) => state + .dependencies + .get(target) + .is_some_and(|targets| targets.contains(dependency)), + super::PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + }; + if !state.subjects.contains_key(target) + || held.is_empty() + || held + .iter() + .any(|(source, magnitude)| magnitude.0 == 0 || !source_is_live(source)) + { + return Err(JournalError::Corrupt( + "a pressure row does not name a canonical target, live source, and nonzero \ + magnitude" + .into(), + )); + } + } + // The civic subgraph, in the slot the deleted `authority_scope` check + // occupied: a jurisdiction names live ground under a canonical kind, an + // office sits on an institution and lends something to a person who holds + // no other office there, and a forum names a live subject. + let target_is_canonical = |target: &super::AuthorityTarget| match target { + super::AuthorityTarget::Subject(subject_id) => state.subjects.contains_key(subject_id), + super::AuthorityTarget::PlaceSubtree(entity_id) => is_place(entity_id), + }; + for (subject_id, grants) in &state.authority { + if !state.subjects.contains_key(subject_id) + || grants.is_empty() + || !grants.iter().all(|grant| { + super::patch::is_civic_name(&grant.kind.0) && target_is_canonical(&grant.over) + }) + { + return Err(JournalError::Corrupt( + "authority does not name a canonical subject and live ground under a canonical kind" + .into(), + )); + } + } + for (institution, offices) in &state.selection { + let mut incumbents = BTreeSet::new(); + if state.subjects.get(institution).map(|subject| subject.kind) + != Some(super::SubjectKind::Institution) + || offices.is_empty() + { + return Err(JournalError::Corrupt( + "an office register does not name a canonical institution".into(), + )); + } + for (name, office) in offices { + let incumbent_is_person = office.incumbent.is_none_or(|incumbent| { + state.subjects.get(&incumbent).map(|subject| subject.kind) + == Some(super::SubjectKind::Person) + && incumbents.insert(incumbent) + }); + if !super::patch::is_civic_name(&name.0) + || office.delegated.is_empty() + || !office + .delegated + .iter() + .all(|kind| super::patch::is_civic_name(&kind.0)) + || !incumbent_is_person + { + return Err(JournalError::Corrupt( + "an office lends nothing, is misnamed, or is held twice or by a non-person" + .into(), + )); + } + } + } + for (grievance, forum) in &state.redress { + if !super::patch::is_civic_name(&grievance.0) + || !state.subjects.contains_key(&forum.forum) + || !target_is_canonical(&forum.standing) + { + return Err(JournalError::Corrupt( + "a forum does not name a canonical grievance, subject, and standing".into(), + )); + } + } + if super::overlapping_holder(state).is_some() { + return Err(JournalError::Corrupt( + "one subject holds two overlapping jurisdictions of one kind".into(), + )); + } + let mut declared_keys = BTreeSet::new(); + for subject in state.subjects.values() { + if let Some(key) = &subject.import_key + && super::patch::import_key_fault(key, |_| false, &mut declared_keys).is_some() + { + return Err(JournalError::Corrupt( + "subject import key is malformed or held by two subjects".into(), + )); + } + } + for subject in state.subjects.values() { + if !super::patch::is_canonical_text(&subject.label) { + return Err(JournalError::Corrupt( + "subject label is empty or noncanonical".into(), + )); + } + } + // A grant row is a verb list: non-empty, for a live subject, catalog + // entries only. A subject holding no verb holds no row. + for (subject_id, granted) in &state.affordance_grants { + if !state.subjects.contains_key(subject_id) + || super::is_retired(state, *subject_id) + || granted.is_empty() + || granted + .iter() + .any(|affordance_id| !state.affordance_catalog.contains_key(affordance_id)) + { + return Err(JournalError::Corrupt( + "affordance grant is empty, unscoped, retired, or names no catalog entry".into(), + )); + } + } + // Every stored entry still passes the declaration validator, so a forged + // catalog row cannot install an entry the resolver would have refused. + for entry in state.affordance_catalog.values() { + if !super::patch::entry_is_admissible(entry) { + return Err(JournalError::Corrupt( + "stored affordance entry is not admissible".into(), + )); + } + } + Ok(()) +} + +fn apply_committed_command( + state: &mut WorldState, + commit: &WorldCommit, +) -> Result<(), JournalError> { + let CommittedCommand::WorldCommand(command) = &commit.command else { + return Err(JournalError::Corrupt( + "creation command appears after world genesis".into(), + )); + }; + if command.world_id != state.header.world_id || command.expected_revision != state.revision { + return Err(JournalError::Corrupt( + "committed command does not target the exact replay state".into(), + )); + } + let expected_effect = reduce(state, command).map_err(kernel_error)?; + if expected_effect != commit.effect { + return Err(JournalError::Corrupt( + "committed effect is not the deterministic reduction of its command".into(), + )); + } + apply_effect( + state, + command.id(), + &commit.command.caller(), + &expected_effect, + ) + .map_err(kernel_error) +} + +fn decode(bytes: &[u8]) -> Result { + let value: T = rmp_serde::from_slice(bytes) + .map_err(|error| JournalError::Corrupt(format!("could not decode the export: {error}")))?; + let canonical = rmp_serde::to_vec_named(&value) + .map_err(|error| JournalError::Corrupt(error.to_string()))?; + if canonical != bytes { + return Err(JournalError::Corrupt("the export is not canonical".into())); + } + Ok(value) +} + +fn kernel_error(error: KernelError) -> JournalError { + JournalError::Corrupt(error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::patch::kernel_speak_grant; + use crate::tests::speak_entry; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CreateWorld, Declaration, + DraftHandle, EntityDeclaration, EntityId, EntityKind, Position, PrincipalId, + Ref, SubjectDeclaration, SubjectKind, WorldKernel, WorldPatch, + }; + + #[derive(serde::Serialize, serde::Deserialize)] + struct CanonicalFixture { + value: u8, + } + + /// The bytes an honest exporter writes for `commits`, whatever they claim. + pub(super) fn export_of(commits: &[WorldCommit]) -> Vec { + WorldJournal { + commits: commits.to_vec(), + } + .export() + .unwrap() + } + + /// Open a world from forged commits through the door a real export takes: + /// canonical decode, then the one replay judge. + pub(super) fn reopen(commits: &[WorldCommit]) -> Result { + WorldJournal::open(&export_of(commits)).map(|(_, state)| state) + } + + #[test] + fn decode_rejects_an_alternate_messagepack_shape() { + let bytes = rmp_serde::to_vec(&CanonicalFixture { value: 7 }).unwrap(); + assert!(decode::(&bytes).is_err()); + let canonical = rmp_serde::to_vec_named(&CanonicalFixture { value: 7 }).unwrap(); + assert!(decode::(&canonical).is_ok()); + } + + /// The commit a forgery test rewrites: the one the test just committed. + pub(super) fn last_commit(commits: &mut [WorldCommit]) -> &mut WorldCommit { + commits.iter_mut().max_by_key(|commit| commit.resulting_revision).unwrap() + } + + pub(super) fn genesis_commit(commits: &mut [WorldCommit]) -> &mut WorldCommit { + commits.iter_mut().min_by_key(|commit| commit.resulting_revision).unwrap() + } + + fn owner_patch(subject: SubjectDeclaration) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Subject(subject)], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + #[test] + fn replay_rejects_a_forged_command_or_effect_even_with_valid_hashes() { + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + owner: owner.clone(), + title: "Before".into(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + grammar: None, + }; + let (mut kernel, _) = WorldKernel::create(creation, &authenticated).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + CommandEnvelope { + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Play, + body: CommandBody::AdvanceTime { + minutes: crate::TickMinutes::new(1).unwrap(), + }, + }, + &AuthenticatedCaller::verified_play(), + ) + .unwrap(); + + let mut command_forged_commits = kernel.journal.commits.clone(); + let command_forged = last_commit(&mut command_forged_commits); + let CommittedCommand::WorldCommand(command) = &mut command_forged.command else { + panic!("expected a world command"); + }; + command.body = CommandBody::AdvanceTime { + minutes: crate::TickMinutes::new(2).unwrap(), + }; + command_forged.digest = commit_digest(command_forged).unwrap(); + + assert!(matches!( + reopen(&command_forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut caller_forged_commits = kernel.journal.commits.clone(); + let caller_forged = last_commit(&mut caller_forged_commits); + let CommittedCommand::WorldCommand(command) = &mut caller_forged.command else { + panic!("expected a world command"); + }; + command.caller = CallerId::Principal(PrincipalId::new("attacker@example.test")); + caller_forged.digest = commit_digest(caller_forged).unwrap(); + + assert!(matches!( + reopen(&caller_forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut effect_forged_commits = kernel.journal.commits.clone(); + let effect_forged = last_commit(&mut effect_forged_commits); + let WorldEffect::TimeAdvanced { to, .. } = &mut effect_forged.effect else { + panic!("expected a time effect"); + }; + *to = crate::FictionalMinutes(99); + effect_forged.digest = commit_digest(effect_forged).unwrap(); + + assert!(matches!( + reopen(&effect_forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + #[test] + fn a_forged_patch_effect_does_not_apply() { + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + owner: owner.clone(), + title: "Kharad".into(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + grammar: None, + }; + let (mut kernel, _) = WorldKernel::create(creation, &authenticated).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + CommandEnvelope { + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Play, + body: CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("rhythm-road"), + label: "The Rhythm Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("rhythm-authority"), + label: "The Rhythm Authority".into(), + kind: SubjectKind::Institution, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + }, + &AuthenticatedCaller::verified_play(), + ) + .unwrap(); + + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { + panic!("expected an admitted patch effect"); + }; + resolved.subjects[0].position = Some(Position { + place: EntityId::issue(), + }); + forged.digest = commit_digest(forged).unwrap(); + + assert!(matches!( + reopen(&forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// A world whose history includes a patch and a clock advance, both Play's, + /// reopened from its own export. + fn clock_history() -> WorldKernel { + use crate::tests::{auth_principal, creation, owner, submit_play}; + use crate::TickMinutes; + + let (mut kernel, _) = WorldKernel::create(creation("Clock History"), + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + patch: crate::WorldPatch { + declarations: vec![crate::patch::Declaration::Entity( + crate::patch::EntityDeclaration { + handle: crate::patch::DraftHandle::new("annex"), + label: "The Annex".into(), + kind: crate::patch::EntityKind::Place, + container: None, + }, + )], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ); + kernel + } + + /// Replay re-derives Play's patch and clock advance: the honest history + /// reopens to the same state digest and reading, and the exported bytes do too. + #[test] + fn a_history_with_a_patch_and_a_clock_advance_replays_exactly() { + let kernel = clock_history(); + let replayed = reopen(&kernel.journal.commits).expect("the honest history replays"); + assert_eq!(replayed.state_digest, kernel.state.state_digest); + assert_eq!(replayed.header.now, kernel.state.header.now); + + let (digest, now) = (kernel.state.state_digest.clone(), kernel.state.header.now); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.state.state_digest, digest); + assert_eq!(reopened.state.header.now, now); + } + + /// An export is a claim about a chain, and `open` believes none of it that + /// replay does not derive: a chain with a commit missing, repeated or out of + /// order, a Ghostlight commit or export schema, and a non-canonical + /// encoding of an honest chain are each refused. + #[test] + fn forged_exports_are_refused() { + let kernel = clock_history(); + let honest = kernel.journal.commits.clone(); + assert_eq!(honest.len(), 3, "genesis, a patch and a tick"); + reopen(&honest).expect("the honest chain opens"); + let refused = |what: &str, commits: &[WorldCommit]| { + assert!( + reopen(commits).is_err(), + "{what} was admitted" + ); + }; + + refused("a missing middle commit", &[honest[0].clone(), honest[2].clone()]); + refused("a world without genesis", &honest[1..]); + refused("a repeated commit", &[honest[0].clone(), honest[1].clone(), honest[1].clone(), honest[2].clone()]); + refused("reordered commits", &[honest[0].clone(), honest[2].clone(), honest[1].clone()]); + refused("no commits", &[]); + + // Re-sealed down the chain, so the schema is the only thing wrong. + let mut ghostlight = honest.clone(); + ghostlight[1].schema = "ghostlight.world_commit.consumer.v10".into(); + for index in 1..ghostlight.len() { + if index > 1 { + ghostlight[index].previous_commit_digest = Some(ghostlight[index - 1].digest.clone()); + } + ghostlight[index].digest = commit_digest(&ghostlight[index]).unwrap(); + } + refused("a ghostlight commit schema", &ghostlight); + + let foreign = rmp_serde::to_vec_named(&ExportRef { + schema: "ghostlight.world_state.consumer.v10", + commits: &honest, + }) + .unwrap(); + assert!(matches!( + WorldJournal::open(&foreign), + Err(JournalError::Corrupt(_)) + )); + + let positional = rmp_serde::to_vec(&ExportRef { + schema: JOURNAL_SCHEMA, + commits: &honest, + }) + .unwrap(); + assert!(matches!( + WorldJournal::open(&positional), + Err(JournalError::Corrupt(_)) + )); + assert!(matches!( + WorldJournal::open(&[0xc1]), + Err(JournalError::Corrupt(_)) + )); + } + + /// A chain written under the whole-state digest is refused: its commits carry + /// the v1 schema, re-sealed end to end so the schema is the only thing wrong. + #[test] + fn a_v1_commit_is_refused() { + let kernel = clock_history(); + let mut v1 = kernel.journal.commits.clone(); + reopen(&v1).expect("the honest chain opens"); + for index in 0..v1.len() { + v1[index].schema = "aetherlight.world_commit.v1".into(); + if index > 0 { + v1[index].previous_commit_digest = Some(v1[index - 1].digest.clone()); + } + v1[index].digest = commit_digest(&v1[index]).unwrap(); + } + match reopen(&v1) { + Err(JournalError::UnsupportedSchema { found, supported }) => { + assert_eq!(found, "aetherlight.world_commit.v1"); + assert_eq!(supported, COMMIT_SCHEMA); + } + other => panic!("a v1 chain must be refused by name, got {other:?}"), + } + // A later commit of another generation is refused the same way. + let mut mixed = kernel.journal.commits.clone(); + last_commit(&mut mixed).schema = "aetherlight.world_commit.v3".into(); + assert!(matches!( + reopen(&mixed), + Err(JournalError::UnsupportedSchema { .. }) + )); + } + + /// A stored tick whose span is zero or above the bound is not a world: the + /// export does not decode. This is the door the clock needs no check behind: + /// a zero-minute tick would be a commit that moves nothing, and an oversize + /// one a commit no `submit` could have built. + #[test] + fn a_stored_tick_with_a_span_outside_the_bound_does_not_open() { + let kernel = clock_history(); + let honest = export_of(&kernel.journal.commits); + // MessagePack names the span `minutes` and encodes the honest ones + // (1, 2, 30) as a single positive fixint byte, so each is rewritten in + // place, in the command and again in the effect. + let key = b"\xa7minutes"; + let at: Vec = (0..honest.len() - key.len()) + .filter(|&at| &honest[at..at + key.len()] == key) + .collect(); + assert!(at.len() >= 2, "a tick carries its span in the command and its effect"); + for forged_span in [vec![0x00], [&[0xce][..], &(crate::patch::MAX_ROUTE_COST + 1).to_be_bytes()].concat()] { + let mut bytes = honest.clone(); + for &start in at.iter().rev() { + let value = start + key.len(); + assert!(honest[value] < 0x80, "an honest span is a fixint"); + bytes.splice(value..=value, forged_span.iter().copied()); + } + let error = WorldJournal::open(&bytes).err().expect("a forged span opened"); + assert!( + error.to_string().contains("could not decode the export") + && error.to_string().contains("tick span"), + "{forged_span:?}: {error}" + ); + } + } + + /// The replay-side future check reads only the subjects the transaction + /// touched, and a key a subject already held is not newly born. + #[test] + fn a_commitment_born_due_is_corrupt_only_for_a_touched_new_key() { + use crate::tests::subject_by_label; + let (kernel, _) = crate::golden_tests::golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let held = kernel + .state + .commitments + .get(&witness) + .cloned() + .expect("the witness holds a routine"); + let mut early = kernel.state.clone(); + early.header.get_mut().now = crate::FictionalMinutes(0); + let mut late = kernel.state.clone(); + late.header.get_mut().now = crate::FictionalMinutes(u64::MAX); + + assert!(verify_commitments_are_future(&early, &[(witness, None)]).is_ok()); + assert!(matches!( + verify_commitments_are_future(&late, &[(witness, None)]), + Err(JournalError::Corrupt(_)) + )); + assert!(verify_commitments_are_future(&late, &[(witness, Some(held))]).is_ok()); + assert!(verify_commitments_are_future(&late, &[]).is_ok()); + } + + /// A committed command names the exact world and revision it applies to; + /// each is judged on its own. + #[test] + fn a_command_aimed_at_another_world_or_revision_is_corrupt() { + let kernel = clock_history(); + for aim_at_world in [true, false] { + let mut forged = kernel.journal.commits.clone(); + let last = forged.last_mut().unwrap(); + let CommittedCommand::WorldCommand(command) = &mut last.command else { + panic!("the last commit is a world command"); + }; + if aim_at_world { + command.world_id = WorldId::nil_for_test(); + } else { + command.expected_revision += 1; + } + last.digest = commit_digest(last).unwrap(); + assert!( + matches!(reopen(&forged), Err(JournalError::Corrupt(_))), + "a command aimed at another {} was admitted", + if aim_at_world { "world" } else { "revision" } + ); + } + } + + /// A stored digest is checked against the commit it seals, on its own: + /// flipping one character of any commit's digest, with nothing re-sealed, + /// leaves only the digest clause to refuse it (the last commit and a lone + /// genesis have no successor whose previous-digest could). + #[test] + fn a_stored_digest_flipped_without_resealing_is_refused() { + let kernel = clock_history(); + let honest = kernel.journal.commits.clone(); + let flip = |digest: &str| { + let mut flipped = digest.to_owned(); + let last = flipped.pop().unwrap(); + flipped.push(if last == '0' { '1' } else { '0' }); + flipped + }; + for upto in 1..=honest.len() { + let mut chain = honest[..upto].to_vec(); + let tail = chain.last_mut().unwrap(); + tail.digest = flip(&tail.digest); + assert!( + matches!(reopen(&chain), Err(JournalError::Corrupt(_))), + "a flipped digest on commit {} of {upto} was admitted", + upto - 1 + ); + } + } + + /// Each clause of the genesis condition refuses alone: a lone genesis, + /// re-sealed after one field is rewritten, so nothing else can object. + #[test] + fn each_genesis_clause_refuses_on_its_own() { + let kernel = clock_history(); + let genesis = kernel.journal.commits[0].clone(); + let forgeries: [(&str, &dyn Fn(&mut WorldCommit)); 5] = [ + ("schema", &|commit| commit.schema = "ghostlight.world_commit.consumer.v10".into()), + ("a previous revision", &|commit| commit.previous_revision = Some(0)), + ("a nonzero revision", &|commit| commit.resulting_revision = 1), + ("a previous state digest", &|commit| { + commit.previous_state_digest = Some("sha256:00".into()) + }), + ("a previous commit digest", &|commit| { + commit.previous_commit_digest = Some("sha256:00".into()) + }), + ]; + reopen(std::slice::from_ref(&genesis)).expect("a lone honest genesis opens"); + for (what, forge) in forgeries { + let mut forged = genesis.clone(); + forge(&mut forged); + forged.digest = commit_digest(&forged).unwrap(); + assert!( + reopen(&[forged]).is_err(), + "a genesis with {what} was admitted" + ); + } + } + + /// Position `i` holds resulting revision `i`: a commit that names a later + /// revision than its place, with a state digest honestly computed for that + /// revision, is still not the chain's next commit. + #[test] + fn a_chain_that_skips_a_revision_is_refused() { + let kernel = clock_history(); + let honest = kernel.journal.commits.clone(); + let mut state = reopen(&honest[..2]).expect("genesis and the patch open"); + state.revision = 7; + let mut forged = vec![honest[0].clone(), honest[1].clone()]; + forged[1].resulting_revision = 7; + forged[1].resulting_state_digest = state.full_state_digest().unwrap(); + forged[1].digest = commit_digest(&forged[1]).unwrap(); + assert!(matches!(reopen(&forged), Err(JournalError::Corrupt(_)))); + } + + /// A world is named by its creation: a genesis whose world id is any other + /// is refused, however consistently every id under it was derived. + #[test] + fn a_world_id_not_derived_from_its_creation_is_refused() { + use crate::patch::resolve_patch; + use crate::tests::{auth_principal, creation, owner}; + use crate::{CommandId, PreparedCreation}; + + let input = creation("Misnamed"); + let honest = crate::prepare_creation(input.clone(), &auth_principal(owner())).unwrap(); + let other = WorldId::of(CommandId::issue()); + assert_ne!(other, honest.world_id); + let resolved = resolve_patch( + &WorldState::empty(other, input.owner.clone(), honest.title.clone(), None), + input.id(), + &input.patch, + ) + .unwrap(); + let (kernel, _) = WorldKernel::initialize(PreparedCreation { + command: input, + world_id: other, + owner: honest.owner, + title: honest.title, + resolved, + }) + .unwrap(); + assert!(matches!( + reopen(&kernel.journal.commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// A stored command is not believed about who made it. The forgery re-seals + /// the commit around its rewrite and the head's last commit digest names the + /// re-sealed commit, so no digest can answer for the check; the control, the + /// same re-sealing around the honest caller, replays. Both Play's doors are + /// forged: a patch row and a clock row recorded as the owner's. + #[test] + fn a_commit_forged_to_the_owner_fails_replay() { + use crate::tests::owner; + + let kernel = clock_history(); + let honest: Vec = kernel.journal.commits.clone(); + // Re-seals the rewritten commit and every later one around it, so the + // chain of previous-commit digests agrees and only the caller check is + // left to refuse the history. + let forge = |is_row: &dyn Fn(&WorldEffect) -> bool, + rewrite: &dyn Fn(&mut WorldCommit)| + -> Vec { + let mut forged: Vec = honest.clone(); + forged.sort_by_key(|commit| commit.resulting_revision); + let rows: Vec = (0..forged.len()) + .filter(|index| is_row(&forged[*index].effect)) + .collect(); + let [at] = <[usize; 1]>::try_from(rows) + .expect("the history holds exactly one such row"); + rewrite(&mut forged[at]); + for index in at..forged.len() { + if index > at { + forged[index].previous_commit_digest = Some(forged[index - 1].digest.clone()); + } + forged[index].digest = commit_digest(&forged[index]).unwrap(); + } + forged + }; + let patch_row = |effect: &WorldEffect| matches!(effect, WorldEffect::PatchAdmitted { .. }); + let clock_row = |effect: &WorldEffect| matches!(effect, WorldEffect::TimeAdvanced { .. }); + + for is_row in [&patch_row as &dyn Fn(&WorldEffect) -> bool, &clock_row] { + let control = forge(is_row, &|_| {}); + reopen(&control) + .expect("a consistent re-sealed store replays"); + + let forged = forge(is_row, &|commit| { + if let CommittedCommand::WorldCommand(command) = &mut commit.command { + command.caller = CallerId::Principal(owner()); + } + }); + let error = reopen(&forged) + .expect_err("a commit forged to the owner replayed"); + assert!(matches!(error, JournalError::Corrupt(_)), "{error:?}"); + } + } + + /// The tick is re-derived at replay by the same function that produced it, + /// so a committed motion rewritten after the fact no longer reduces from + /// its command. The clock chain refuses a rewritten reading the same way. + #[test] + fn a_forged_motion_does_not_replay() { + use crate::tests::{auth_principal, command, owner}; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, FictionalMinutes, + TickMinutes, + }; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Chronicle"), + &authenticated, + ) + .unwrap(); + let active = kernel.snapshot().unwrap(); + let caller = CallerId::Play; + kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::TimeAdvanced { to, .. } = &mut forged.effect else { + panic!("expected a time-advanced effect"); + }; + *to = FictionalMinutes(31); + forged.digest = commit_digest(forged).unwrap(); + + assert!(matches!( + reopen(&forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Replay re-derives the operation half too: a committed relocation rewritten + /// to move a different subject no longer reduces from its command. + #[test] + fn a_forged_relocate_effect_does_not_apply() { + use crate::tests::{admit_topology, auth_principal, command, owner}; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Kharad"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &active, + CallerId::Play, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![crate::ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap(); + + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { + panic!("expected an admitted patch effect"); + }; + let crate::ResolvedOp::Relocate { subject_id, .. } = &mut resolved.operations[0] + else { + panic!("expected a lowered relocation"); + }; + *subject_id = crate::SubjectId::issue(); + forged.digest = commit_digest(forged).unwrap(); + + assert!(matches!( + reopen(&forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul: `a_forged_band_or_forged_effect_does_not_apply` proves the live + /// `apply_effect` arm re-derives. `verify_state_shape` does not re-derive a + /// band — it only bounds the index and refuses effects under an empty band — + /// so the layer that kills a persisted forgery is replay effect-equality. + /// This forges a committed decision inside the journal, re-digests it into a + /// contiguous chain, and asserts recovery refuses it. + #[test] + fn soul_a_forged_band_or_effect_in_the_journal_dies_at_replay() { + use crate::tests::{ + admit_custody, admit_topology, affordance_named, auth_principal, command, + owner, play_caller, + }; + use crate::{ + AuthenticatedCaller, DecisionInvocation, Magnitude, ProposedEffect, Quantity, + RoleBinding, Target, + }; + + let forge = |kind: &str, mutate: &dyn Fn(&mut crate::DecisionEvent)| { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("ForgedDecision"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = kernel.snapshot().unwrap(); + let entry = affordance_named(&active, kind); + let caller = play_caller(); + let role = |name: &str, target| RoleBinding { + role: crate::Role(name.into()), + target, + }; + kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::Act { + actor: custody.holder, + invocation: DecisionInvocation { + affordance: entry, + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + // The honest journal recovers. + assert!(reopen(&kernel.journal.commits).is_ok()); + + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::Acted { event, .. } = &mut forged.effect else { + panic!("expected an acted effect"); + }; + mutate(event); + forged.digest = commit_digest(forged).unwrap(); + forged_commits + }; + + // A band the seed did not draw, held inside a chain that verifies. + let commits = forge("carry_chance", &|event| { + event.band = (event.band + 1) % 3; + }); + assert!(matches!( + reopen(&commits), + Err(JournalError::Corrupt(_)) + )); + + // A magnitude the ceiling admitted but the lowering never produced. + let commits = forge("carry", &|event| { + let Some(crate::ResolvedOp::Transfer { qty, .. }) = event.effects.first_mut() + else { + panic!("expected a lowered transfer"); + }; + *qty = Quantity(1); + }); + assert!(matches!( + reopen(&commits), + Err(JournalError::Corrupt(_)) + )); + } + + #[test] + fn replay_rejects_genesis_that_does_not_derive_from_its_creation_command() { + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + owner: owner.clone(), + title: "Admitted".into(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + grammar: None, + }; + let (kernel, _) = WorldKernel::create(creation, &authenticated).unwrap(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = genesis_commit(&mut forged_commits); + let CommittedCommand::CreateWorld(command) = &mut forged.command else { + panic!("expected genesis creation command"); + }; + command.title = "Different command".into(); + forged.digest = commit_digest(forged).unwrap(); + + assert!(matches!( + reopen(&forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut binding_forged_commits = kernel.journal.commits.clone(); + let binding_forged = genesis_commit(&mut binding_forged_commits); + let WorldEffect::WorldCreated { resolved, .. } = &mut binding_forged.effect else { + panic!("expected genesis effect"); + }; + resolved.subjects[0].subject.label = "Not the creation subject".into(); + binding_forged.digest = commit_digest(binding_forged).unwrap(); + + assert!(matches!( + reopen(&binding_forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul falsification: the extended replay shape check is not decoration. + /// A forged state carrying a self-loop, a cost out of range, a + /// non-place endpoint, or a position on a non-place is refused by + /// `verify_state_shape`, which `WorldJournal::open` runs on the replayed head. + #[test] + fn soul_forged_topology_states_are_refused_by_the_shape_check() { + use crate::patch::{AccessKind, Cost, EdgeRecord, MAX_ROUTE_COST}; + use crate::tests::{admit_topology, auth_principal, owner}; + + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Forged Rows"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + // The honest state recovers. + assert!(verify_state_shape(&kernel.state).is_ok()); + assert!(reopen(&kernel.journal.commits).is_ok()); + + let self_loop = { + let mut state = kernel.state.clone(); + state.edges.insert( + topology.ramp, + EdgeRecord::Route { + label: "The Yard Ramp".into(), + from: topology.yard, + to: topology.yard, + access: AccessKind::Public, + cost: Cost(12), + open: true, + }, + ); + state + }; + let bad_cost = { + let mut state = kernel.state.clone(); + state + .edges + .get_mut(&topology.ramp) + .unwrap() + .set_cost(Cost(MAX_ROUTE_COST + 1)); + state + }; + let non_place_endpoint = { + let mut state = kernel.state.clone(); + state.entities.get_mut(&topology.road).unwrap().kind = + crate::EntityKind::Resource; + state + }; + let stray_position = { + let mut state = kernel.state.clone(); + state.positions.insert( + topology.walker, + Position { + place: EntityId::issue(), + }, + ); + state + }; + for forged in [self_loop, bad_cost, non_place_endpoint, stray_position] { + let error = verify_state_shape(&forged).unwrap_err(); + assert!( + matches!(error, JournalError::Corrupt(_)), + "a forged topology row recovered: {error:?}" + ); + } + } + + /// A committed levy survives a restart exactly: the snapshot, the band, the + /// lowered effects, and the re-derived authority verdict all come back, and + /// the same envelope is already applied. + #[test] + fn restart_replay_after_a_levy_is_exact() { + use crate::tests::{affordance_named, civic_world, command, owner, play_caller}; + use crate::{ + DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, + Target, + }; + + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Replayed Levy"), + &crate::tests::auth_principal(owner()), + ) + .unwrap(); + let (_, civic, active) = civic_world(&mut kernel); + let caller = play_caller(); + let envelope = command( + &active, + caller.clone(), + CommandBody::Act { + actor: civic.treasury, + invocation: DecisionInvocation { + affordance: affordance_named(&active, "levy"), + bindings: vec![ + RoleBinding { + role: Role("payer".into()), + target: Target::Subject(civic.farmer), + }, + RoleBinding { + role: Role("resource".into()), + target: Target::Entity(civic.grain), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(3)), + }], + speech: None, + display: None, + }, + }, + ); + kernel + .submit( + envelope.clone(), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let events = kernel.events(); + let event = events.last().expect("the levy event").clone(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + let events = reopened.events(); + let replayed = events.last().expect("the replayed event"); + assert_eq!(replayed.band, event.band); + assert_eq!(replayed.effects, event.effects); + assert!(matches!( + reopened.submit(envelope, &AuthenticatedCaller::fixture(caller)), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// Soul falsification: the civic shape checks are not decoration. A forged + /// state that widens a jurisdiction, doubles an incumbency, seats an + /// institution, or empties a delegation is refused by the shape check. + #[test] + fn a_forged_authority_or_incumbency_is_corrupt() { + use crate::tests::{ + BAILIFF_OFFICE, LEVY_KIND, WARDEN_OFFICE, auth_principal, authority_kind, civic_world, + office, owner, + }; + use crate::{AuthorityGrant, AuthorityTarget, Office}; + use std::collections::BTreeSet; + + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Forged Civics"), + &auth_principal(owner()), + ) + .unwrap(); + let (topology, civic, _) = civic_world(&mut kernel); + assert!(verify_state_shape(&kernel.state).is_ok()); + assert!(reopen(&kernel.journal.commits).is_ok()); + + let widened = { + let mut state = kernel.state.clone(); + state.authority.insert( + civic.reeve, + BTreeSet::from([AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.chamber), + }]), + ); + state + }; + let dangling = { + let mut state = kernel.state.clone(); + state.authority.insert( + civic.outsider, + BTreeSet::from([AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(EntityId::issue()), + }]), + ); + state + }; + let doubled = { + let mut state = kernel.state.clone(); + state + .selection + .get_mut(&civic.treasury) + .unwrap() + .get_mut(&office(BAILIFF_OFFICE)) + .unwrap() + .incumbent = Some(civic.reeve); + state + }; + let seated_institution = { + let mut state = kernel.state.clone(); + state + .selection + .get_mut(&civic.treasury) + .unwrap() + .get_mut(&office(WARDEN_OFFICE)) + .unwrap() + .incumbent = Some(civic.treasury); + state + }; + let inert_office = { + let mut state = kernel.state.clone(); + state.selection.get_mut(&civic.treasury).unwrap().insert( + office(WARDEN_OFFICE), + Office { + incumbent: Some(civic.reeve), + delegated: BTreeSet::new(), + }, + ); + state + }; + let office_on_person = { + let mut state = kernel.state.clone(); + state + .selection + .insert(topology.walker, state.selection[&civic.treasury].clone()); + state + }; + for forged in [ + widened, + dangling, + doubled, + seated_institution, + inert_office, + office_on_person, + ] { + let error = verify_state_shape(&forged).unwrap_err(); + assert!( + matches!(error, JournalError::Corrupt(_)), + "a forged civic row recovered: {error:?}" + ); + } + } + + /// Soul falsification of the structural-overlap decision, updated for the + /// admission-time covering check: a `Subject` grant naming ground a + /// `PlaceSubtree` grant already covers is refused on arrival, but nothing + /// re-derives that check off of live position. Once the farmer walks out + /// from under the hall, the identical grant is unremarkable, and no + /// `Relocate` — in either direction — is ever asked to keep a shape + /// decision current. + #[test] + fn a_relocation_never_corrupts_a_civic_store() { + use crate::tests::{ + LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_play, + submit_play, + }; + use crate::{ComponentOp, Mismatch}; + + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Moving Civics"), + &auth_principal(owner()), + ) + .unwrap(); + let (_, civic, _) = civic_world(&mut kernel); + + let admit = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + assert!(submit_play(kernel, &before, operations(ops)).resulting_revision > 0); + verify_state_shape(&kernel.state).expect("the committed store keeps its shape"); + assert!( + crate::overlapping_holder(&kernel.state).is_none(), + "a committed store never holds two overlapping jurisdictions" + ); + }; + let place_covers = |kernel: &WorldKernel| { + crate::covers( + &kernel.state, + crate::AuthorityTarget::PlaceSubtree(civic.hall), + crate::Target::Subject(civic.farmer), + ) + }; + let name_farmer = || { + vec![crate::tests::grant_to( + civic.treasury, + LEVY_KIND, + over_subject(civic.farmer), + )] + }; + + // The treasury's hall grant already covers the farmer standing in the + // chamber underneath it, so naming him directly is a second source + // for the same kind of act, and admission refuses it while he stands + // there. + assert!(place_covers(&kernel)); + let before = kernel.snapshot().unwrap(); + assert_eq!( + reject_play(&mut kernel, &before, operations(name_farmer())), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // Out of the subtree, one route at a time. + for edge in [civic.passage, civic.causeway] { + admit( + &mut kernel, + vec![ComponentOp::Relocate { + subject: Ref::Existing(civic.farmer), + via: Ref::Existing(edge), + }], + ); + } + // The move dissolved the cover without any operation naming it, which + // is why the disjointness rule cannot be occupancy-sensitive: nothing + // reruns the covering check on a `Relocate`, in or out. + assert!(!place_covers(&kernel)); + + // Now that he stands outside it, the identical grant is unremarkable. + admit(&mut kernel, name_farmer()); + assert!(kernel.state.authority[&civic.treasury].len() >= 3); + + // The whole history replays, and the reopened world is identical. + let committed = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + } +} + +#[cfg(test)] +mod custody_tests { + use super::*; + use super::tests::{last_commit, reopen}; + use crate::{ + CallerId, CommandBody, ComponentOp, DependencyRef, EntityKind, Quantity, Ref, + WorldKernel, WorldPatch, + tests::{admit_custody, admit_topology, auth_principal, command, creation, owner}, + }; + + /// Replay re-derives the custody partitions from the commit log alone: a + /// world reopened after a transfer is byte-identical, and the transfer's own + /// envelope is idempotent. + #[test] + fn restart_replay_after_a_transfer_is_exact() { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(creation("Replay"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = kernel.snapshot().unwrap(); + + let envelope = command( + &active, + CallerId::Play, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }], + evidence: Vec::new(), + }, + }, + ); + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap(); + let accepted = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert!(matches!( + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// Replay recomputes `reduce`, so the band and the lowered operations are + /// re-derived rather than trusted: a stored event whose band or effects the + /// seed does not reproduce fails effect equality on the way back in. + #[test] + fn restart_replay_after_an_action_is_exact() { + use crate::tests::{affordance_named, play_caller}; + use crate::{AuthenticatedCaller, Magnitude, ProposedEffect, RoleBinding, Target}; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(creation("ActionReplay"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = kernel.snapshot().unwrap(); + let carry = affordance_named(&active, "carry"); + let caller = play_caller(); + + let role = |name: &str, target| RoleBinding { + role: crate::Role(name.into()), + target, + }; + let envelope = command( + &active, + caller.clone(), + CommandBody::Act { + actor: custody.holder, + invocation: crate::DecisionInvocation { + affordance: carry, + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }], + speech: None, + display: None, + }, + }, + ); + let authenticated_controller = AuthenticatedCaller::fixture(caller); + kernel + .submit(envelope.clone(), &authenticated_controller) + .unwrap(); + let accepted = kernel.snapshot().unwrap(); + let committed = kernel + .events() + .last() + .expect("the committed event") + .clone(); + assert!(!committed.effects.is_empty()); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!( + reopened.events().last().expect("the replayed event"), + &committed + ); + assert!(matches!( + reopened.submit(envelope, &authenticated_controller), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// The title clause of the shape check refuses an empty title and a + /// noncanonical one, each on its own. + #[test] + fn a_forged_empty_or_padded_title_is_corrupt() { + use crate::tests::{auth_principal, creation, owner}; + + let (kernel, _) = WorldKernel::create(creation("Titled"), + &auth_principal(owner()), + ) + .unwrap(); + verify_state_shape(&kernel.state).expect("a canonical title passes"); + for title in ["", " ", " Titled", "Titled "] { + let mut forged = kernel.state.clone(); + forged.header.get_mut().title = title.into(); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "title {title:?} passed the shape check" + ); + } + } + + /// A grant row is a verb list for a live subject: each clause of the shape + /// check is pinned on `verify_state_shape` directly, one forged state per + /// clause, so deleting any one of them fails a case. + #[test] + fn a_malformed_grant_row_is_corrupt() { + use crate::tests::{auth_principal, creation, owner}; + use crate::{AffordanceId, SubjectId}; + + let (kernel, _) = WorldKernel::create(creation("GrantRows"), + &auth_principal(owner()), + ) + .unwrap(); + verify_state_shape(&kernel.state).expect("a fresh world has canonical grant rows"); + let held = *kernel.state.affordance_grants.keys().next().unwrap(); + + let corrupt = |name: &str, forge: &dyn Fn(&mut WorldState)| { + let mut forged = kernel.state.clone(); + forge(&mut forged); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "{name} passed the shape check" + ); + }; + corrupt("a grant row for a retired subject", &|state| { + state.subjects.get_mut(&held).unwrap().retired = true; + }); + corrupt("an empty grant row", &|state| { + state.affordance_grants.get_mut(&held).unwrap().clear(); + }); + corrupt("a grant row for no subject", &|state| { + let verbs = state.affordance_grants[&held].clone(); + state.affordance_grants.insert(SubjectId::issue(), verbs); + }); + corrupt("a grant row naming an uncataloged verb", &|state| { + state + .affordance_grants + .get_mut(&held) + .unwrap() + .insert(AffordanceId::issue()); + }); + } + + /// A chain holding `Acted` commits recovers and verifies on reopen. + #[test] + fn an_acted_chain_reopens() { + use crate::tests::{ + act, auth_principal, creation, first_grant, owner, speak, + }; + + let (mut kernel, _) = WorldKernel::create(creation("ActedChain"), + &auth_principal(owner()), + ) + .unwrap(); + let active = kernel.snapshot().unwrap(); + let actor = *active.subjects.first().map(|subject| &subject.id).unwrap(); + act( + &mut kernel, + actor, + speak(first_grant(&active, actor), "The chain holds."), + ) + .unwrap(); + act( + &mut kernel, + actor, + speak(first_grant(&active, actor), "And again."), + ) + .unwrap(); + let accepted = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).expect("the acted chain recovers"); + assert_eq!(reopened.snapshot().unwrap(), accepted); + verify_state_shape(&reopened.state).expect("an honest event passes the shape check"); + } + + /// Absence is zero and one slot holds one pair, so a stored zero, an empty + /// holder, and a holding on something that is not a resource are each + /// corrupt at replay. + /// + /// Deviation from the spec's wording, decided here: the assertion is against + /// `verify_state_shape`, which owns these clauses. Routing through + /// `verify_history` would also fail on replay-equality, so it would pass + /// even if the shape clauses were deleted — which is the opposite of a + /// falsification. + #[test] + fn a_zero_or_dangling_holding_is_corrupt() { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(creation("Shape"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); + + let mut zero = kernel.state.clone(); + zero.holdings + .get_mut(&custody.holder) + .unwrap() + .insert(custody.tithe, Quantity(0)); + assert!(matches!( + verify_state_shape(&zero), + Err(JournalError::Corrupt(_)) + )); + + let mut emptied = kernel.state.clone(); + emptied.holdings.get_mut(&custody.holder).unwrap().clear(); + assert!(matches!( + verify_state_shape(&emptied), + Err(JournalError::Corrupt(_)) + )); + + let mut not_a_resource = kernel.state.clone(); + assert_eq!( + not_a_resource.entities[&topology.yard].kind, + EntityKind::Place + ); + not_a_resource + .holdings + .get_mut(&custody.holder) + .unwrap() + .insert(topology.yard, Quantity(1)); + assert!(matches!( + verify_state_shape(¬_a_resource), + Err(JournalError::Corrupt(_)) + )); + + let mut dangling = kernel.state.clone(); + dangling.dependencies.insert( + custody.holder, + BTreeSet::from([crate::DependencyTarget::Subject(custody.holder)]), + ); + assert!(matches!( + verify_state_shape(&dangling), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul: replay is exact after *every* custody and dependency operation, not + /// only after a transfer. The reopened world is byte-identical, the last + /// envelope is idempotent, and the whole chain still verifies. + #[test] + fn soul_replay_is_exact_after_every_custody_operation() { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(creation("EveryOperation"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + // `Admit` and its evidence are Draft-only, so the opening balance is + // already on the log before activation. + let custody = admit_custody(&mut kernel, &topology); + let active = kernel.snapshot().unwrap(); + + let envelope = command( + &active, + CallerId::Play, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(2), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }, + ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Route(Ref::Existing(topology.shutter)), + }, + ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Subject(Ref::Existing(custody.counterparty)), + }, + ], + evidence: Vec::new(), + }, + }, + ); + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap(); + let accepted = kernel.snapshot().unwrap(); + let holdings = kernel.state.holdings.clone(); + let dependencies = kernel.state.dependencies.clone(); + let digest = kernel.state.state_digest.clone(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!(reopened.state.holdings, holdings); + assert_eq!(reopened.state.dependencies, dependencies); + assert_eq!(reopened.state.state_digest, digest); + assert!(matches!( + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// Soul: a dependency naming a target of the wrong kind, or no canonical + /// target at all, is refused at replay. The shape clauses carry the + /// referential integrity the operation arm enforces at admission. + #[test] + fn soul_a_dependency_on_an_absent_or_wrong_kind_target_is_corrupt() { + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create(creation("DependencyShape"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); + + // A place is not a resource, so a resource dependency naming one dangles. + let mut wrong_kind = kernel.state.clone(); + wrong_kind.dependencies.insert( + custody.holder, + BTreeSet::from([crate::DependencyTarget::Resource(topology.yard)]), + ); + assert!(matches!( + verify_state_shape(&wrong_kind), + Err(JournalError::Corrupt(_)) + )); + + // An empty target set is the second representation of nothing, and there + // is only supposed to be one. + let mut emptied = kernel.state.clone(); + emptied.dependencies.insert(custody.holder, BTreeSet::new()); + assert!(matches!( + verify_state_shape(&emptied), + Err(JournalError::Corrupt(_)) + )); + + // A holder key that names no canonical subject. + let mut orphan = kernel.state.clone(); + let absent = *orphan.subjects.keys().next().unwrap(); + orphan.dependencies.insert( + absent, + BTreeSet::from([crate::DependencyTarget::Resource(custody.tithe)]), + ); + orphan.subjects.remove(&absent); + assert!(matches!( + verify_state_shape(&orphan), + Err(JournalError::Corrupt(_)) + )); + } + + /// A world with one routine, one past-due goal, and a commit chain that + /// reaches them: the fixture the two clock-forgery checks below need. + fn ticking_world() -> (WorldKernel, super::super::SubjectId) { + use crate::tests::{auth_principal, command, operations, owner}; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommitmentKind, ComponentOp, + FictionalMinutes, Ref, TickMinutes, + }; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + crate::tests::creation("Ticking"), + &authenticated, + ) + .unwrap(); + let active = kernel.snapshot().unwrap(); + let subject = active.subjects.first().expect("a seeded subject").id; + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CallerId::Play, + operations(vec![ + ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(10), + period: Some(TickMinutes::new(10).unwrap()), + checks: Vec::new(), + statement: crate::Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(20), + period: None, + checks: Vec::new(), + statement: crate::Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ]), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap(); + + let caller = CallerId::Play; + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + caller.clone(), + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + (kernel, subject) + } + + /// Soul falsification: the replay gate and the `apply_effect` gate are two + /// independent re-derivations. This one exercises the replay side over a + /// motion that actually moved commitments and pressure — a rewritten + /// magnitude, a rewritten roll, and a fabricated row each stop replaying. + #[test] + fn soul_a_forged_tick_motion_does_not_replay() { + use crate::{FictionalMinutes, PressureMagnitude, PressureSource}; + + let (kernel, subject) = ticking_world(); + let WorldEffect::TimeAdvanced { motion, .. } = &kernel + .journal + .commits + .iter() + .max_by_key(|commit| commit.resulting_revision) + .expect("the tick's commit") + .effect + else { + panic!("expected a time-advanced effect"); + }; + assert!(!motion.fulfilled.is_empty(), "the routine rolled"); + assert!(!motion.pressed.is_empty(), "the past-due goal pressed"); + + let forge = |rewrite: fn(&mut crate::Motion)| { + let mut forged_commits = kernel.journal.commits.clone(); + let forged = last_commit(&mut forged_commits); + let WorldEffect::TimeAdvanced { motion, .. } = &mut forged.effect else { + panic!("expected a time-advanced effect"); + }; + rewrite(motion); + forged.digest = commit_digest(forged).unwrap(); + reopen(&forged_commits) + }; + + let rewrites: [fn(&mut crate::Motion); 4] = [ + // A magnitude the tick never wrote. + |motion| motion.pressed[0].magnitude = PressureMagnitude(42), + // A roll to a date the period does not reach. + |motion| motion.fulfilled[0].next_due = FictionalMinutes(9_999), + // A row for a source nothing derived. + |motion| { + let mut row = motion.pressed[0].clone(); + row.source = PressureSource::Subject(row.target); + motion.pressed.push(row); + }, + // A fulfilment dropped on the floor. + |motion| motion.fulfilled.clear(), + ]; + for rewrite in rewrites { + assert!( + matches!(forge(rewrite), Err(JournalError::Corrupt(_))), + "a forged motion replayed" + ); + } + let _ = subject; + } + + /// A commitment that is not a Routine and carries a check is not canonical: + /// nothing would ever evaluate the check. The check is a live one, taken + /// from a Routine, so no other clause can be what refuses it; the control + /// is the honest world. + #[test] + fn a_non_routine_commitment_carrying_a_check_is_corrupt() { + let (kernel, _, _) = crate::clock_tests::clock_kernel("Checks"); + verify_state_shape(&kernel.state).expect("the honest world is canonical"); + let check = kernel + .state + .commitments + .values() + .flat_map(|held| held.values()) + .find_map(|commitment| commitment.checks.first().cloned()) + .expect("the clock bench's routine carries a check"); + let (subject, key) = kernel + .state + .commitments + .iter() + .flat_map(|(subject, held)| held.iter().map(move |(key, c)| (*subject, *key, c))) + .find(|(_, _, commitment)| commitment.kind != crate::CommitmentKind::Routine) + .map(|(subject, key, _)| (subject, key)) + .expect("the clock bench holds an obligation or a goal"); + + let mut forged = kernel.state.clone(); + forged + .commitments + .get_mut(&subject) + .unwrap() + .get_mut(&key) + .unwrap() + .checks = vec![check]; + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "a non-routine commitment with a check was admitted" + ); + } + + /// `TickMinutes` owns its bound at decode, so a span outside + /// `1..=MAX_ROUTE_COST` cannot be read in any position: a routine's period, + /// a command, or a tick's own effect. + #[test] + fn a_span_outside_the_bound_cannot_be_decoded() { + for minutes in [0u32, crate::patch::MAX_ROUTE_COST + 1, u32::MAX] { + let raw = rmp_serde::to_vec(&minutes).unwrap(); + assert!( + rmp_serde::from_slice::(&raw).is_err(), + "{minutes} decoded as a span" + ); + assert!(serde_json::from_value::(minutes.into()).is_err()); + } + for minutes in [1u32, crate::patch::MAX_ROUTE_COST] { + let raw = rmp_serde::to_vec(&minutes).unwrap(); + assert_eq!( + rmp_serde::from_slice::(&raw).unwrap().minutes(), + minutes + ); + } + } + +} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs new file mode 100644 index 000000000..892a8e34f --- /dev/null +++ b/native/aetherlight/src/lib.rs @@ -0,0 +1,12840 @@ +//! The Aetherlight world library, a fork of Ghostlight c43eb54 (see `PROVENANCE.md`). +//! +//! The world owner is one deterministic authority: authenticated commands enter, +//! one reducer decides, and the journal, an in-memory list of commits, records +//! each result. The journal exports as bytes, and opening those bytes replays +//! the chain from genesis: the head state is whatever the replay derives. +//! The fork keeps only that single-threaded kernel: no async runtime, no network, no +//! model controllers and no ports. A decision arrives as an invocation the caller +//! built, a player or a brain; nothing in this crate composes one. +//! +//! The crate has no entry point yet: the ABI that creates, opens and drives a +//! world arrives in AL4. Until then the kernel itself is sealed: there is no +//! mutable state, no canonical ID allocator, no reducer entry, no journal writer, +//! and no authenticated-caller constructor on the public surface, under every +//! configuration. This crate declares no cargo features, so no build can lift +//! the seal. +//! +//! The negative proofs are doc-tests, which compile as an external crate and so +//! stand exactly where a consumer stands. Stable rustdoc does not check the error +//! code of a `compile_fail` test, so none is claimed: each test passes only +//! because its item is not public, and fails once the item is made public. +//! +//! ```compile_fail +//! use aetherlight::WorldKernel; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::reduce; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::WorldState; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::CommandEnvelope; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::AuthenticatedCaller; +//! ``` +//! +//! ```compile_fail +//! use aetherlight::journal::WorldJournal; +//! ``` +//! +//! ```compile_fail +//! let _ = aetherlight::SubjectId::issue(); +//! ``` +//! +//! ```compile_fail +//! use aetherlight::DecisionEvent; +//! ``` + +// The kernel has no entry point until AL4 adds the ABI, so most of it is unreachable +// from the public surface. AL4 removes this attribute. +#![allow(dead_code)] + +mod action; +mod clock; +mod digest; +mod docs; +#[cfg(test)] +mod golden_tests; +mod grammar; +#[cfg(test)] +mod import_key_tests; +mod journal; +mod patch; +mod views; + +pub(crate) use action::ActionMismatch; +pub(crate) use clock::Motion; +pub use clock::{FictionalMinutes, TickMinutes}; +pub use grammar::{ + GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb, + RenderPath, +}; +pub use patch::{ + CommitmentKey, DraftHandle, Mismatch, Ref, RefKind, RefName, Role, Site, Statement, WorldPatch, +}; +pub(crate) use patch::{ + AccessKind, Affordance, Audience, AuthoredSource, AuthorityGrant, AuthorityTarget, + BoundPrecondition, ChannelRecord, Commitment, CommitmentKind, Confidence, Cost, + DependencyTarget, EntityKind, EvidenceRef, FactRecord, + FactStanding, Forum, GrievanceKindName, Knowledge, KnowledgeSource, Office, OfficeName, + Position, PressureMagnitude, PressureSource, Quantity, Reach, +}; +pub use patch::ImportKey; +#[cfg(test)] +pub(crate) use patch::{Bounds, Declaration, EntityDeclaration, SubjectDeclaration}; +#[cfg(test)] +use patch::{ + AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp, + DependencyRef, FactDeclaration, FactStandingRef, ReachRef, RouteDeclaration, +}; +#[cfg(test)] +pub(crate) use patch::{ + AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind, + EffectSlot, OutcomeBand, Precondition, RoleSpec, +}; +use patch::{ + AffordanceKindName, EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch, +}; + +use digest::{LtHash16, Partition}; +use docs::{Changed, DocKey, Docs, Tracked}; +use views::Views; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use thiserror::Error; +use uuid::Uuid; + +pub const STATE_SCHEMA: &str = "aetherlight.world_state.v2"; +pub(crate) const COMMIT_SCHEMA: &str = "aetherlight.world_commit.v2"; + +/// Domain strings of the three content-derived identities. A command is named +/// by what it says, so no caller draws an id and no retry needs one. +const COMMAND_DOMAIN: &[u8] = b"aetherlight.command.v1"; +const CREATE_DOMAIN: &[u8] = b"aetherlight.create.v1"; +const WORLD_DOMAIN: &[u8] = b"aetherlight.world.v1"; + +/// The first 16 bytes of a digest as a `Uuid`, as `patch::derive_id` truncates. +fn truncated_uuid(hasher: Sha256) -> Uuid { + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&hasher.finalize()[..16]); + Uuid::from_bytes(bytes) +} + +/// The visibility argument is the whole boundary decision for an ID type: the +/// ones a consumer names by value are `pub`, the rest stay `pub(crate)`, and no +/// `issue()` impl is emitted here at all — issuance is private in every case. +macro_rules! opaque_uuid { + ($name:ident, $vis:vis) => { + #[derive( + Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, + )] + #[serde(transparent)] + $vis struct $name(Uuid); + + impl DocKey for $name { + fn key_text(&self) -> String { + self.0.to_string() + } + } + }; + ($name:ident) => { + opaque_uuid!($name, pub(crate)); + }; +} + +opaque_uuid!(WorldId, pub); +opaque_uuid!(CommandId, pub); +opaque_uuid!(SubjectId, pub); +opaque_uuid!(EntityId, pub); +opaque_uuid!(EdgeId, pub); +opaque_uuid!(AffordanceId, pub); +opaque_uuid!(EventId); + +impl CommandId { + fn key(self) -> String { + self.0.to_string() + } + + /// A named random id for tests that need a command id and no command. + #[cfg(test)] + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +impl WorldId { + /// Canonical text, for the key derivations that hash a world identity. + pub(crate) fn text(self) -> String { + self.0.to_string() + } + + /// A named zero for tests that need a world identity and no world. + #[cfg(test)] + pub(crate) fn nil_for_test() -> Self { + Self(Uuid::nil()) + } + + /// The world is named by the creation that made it. + fn of(creation: CommandId) -> Self { + let mut hasher = Sha256::new(); + hasher.update(WORLD_DOMAIN); + hasher.update(creation.0.as_bytes()); + Self(truncated_uuid(hasher)) + } + + fn key(self) -> String { + self.0.to_string() + } +} + +// Subject, entity, controller, and affordance IDs are derived, never drawn. +// `patch::derive_id` is the only allocator, and it is called from exactly two +// sites: `patch::resolve_patch` and `action::exercise`. The action lane mints +// exactly one referent per invocation — always an `EntityKind::Fact`, always +// `Claimed` by the acting subject, never caller-named, never any other kind. +// These fixtures exist so tests can name an ID that no partition holds. +#[cfg(test)] +impl SubjectId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl EntityId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl AffordanceId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +impl EventId { + fn for_command(command_id: CommandId) -> Self { + Self(command_id.0) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct PrincipalId(String); + +impl PrincipalId { + pub fn new(value: impl Into) -> Self { + Self(value.into()) + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum SubjectKind { + Person, + Institution, + Population, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct CreateWorld { + owner: PrincipalId, + title: String, + patch: WorldPatch, + /// The grammar the world is bound to for its whole life, or none for an + /// open-catalog world. Authored here and nowhere else: genesis installs it. + #[serde(default, skip_serializing_if = "Option::is_none")] + grammar: Option, +} + +impl CreateWorld { + /// The creation is named by its own bytes: equal creations are one command. + /// Host contract: two byte-equal creations share a `WorldId` and every id + /// derived under it, so a host that wants distinct worlds salts each run or + /// profile into the creation (for example a run seed in the patch). + fn id(&self) -> CommandId { + let mut hasher = Sha256::new(); + hasher.update(CREATE_DOMAIN); + hasher.update(rmp_serde::to_vec_named(self).expect("a creation command serializes")); + CommandId(truncated_uuid(hasher)) + } +} + +/// Who wrote a command. The owner principal authors genesis and nothing after +/// it; after genesis `Play` is the only caller any command body admits. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", content = "id", rename_all = "snake_case")] +enum CallerId { + Principal(PrincipalId), + /// The play table, minted only by `PlayPort`. + Play, +} + +#[derive(Clone, Debug)] +struct AuthenticatedCaller { + caller: CallerId, +} + +impl AuthenticatedCaller { + fn verified_principal(principal: PrincipalId) -> Self { + Self { + caller: CallerId::Principal(principal), + } + } + + /// Visible only inside the `world` subtree. Runtime ingress cannot reach it. + fn verified_play() -> Self { + Self { + caller: CallerId::Play, + } + } + + #[cfg(test)] + fn fixture(caller: CallerId) -> Self { + Self { caller } + } +} + +/// The referent a role is bound to. Canonical IDs only: an invocation happens +/// in Active, where no declaration exists, so a draft reference is +/// unrepresentable here and the action lane runs no draft resolution. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum Target { + Subject(SubjectId), + Entity(EntityId), + Edge(EdgeId), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct RoleBinding { + pub(crate) role: Role, + pub(crate) target: Target, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "magnitude", content = "value", rename_all = "snake_case")] +pub(crate) enum Magnitude { + None, + Quantity(Quantity), + Cost(Cost), +} + +/// One proposal against one effect slot. It carries no referents: they all come +/// from the slot's roles resolved through the invocation's bindings, so an +/// invocation cannot name a target its affordance declared no role for and the +/// ceiling check is a comparison rather than a graph walk. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ProposedEffect { + pub(crate) slot: usize, + pub(crate) magnitude: Magnitude, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct DecisionInvocation { + pub affordance: AffordanceId, + pub bindings: Vec, + /// Exactly one entry per slot in the entry, in any order. + pub proposed: Vec, + /// Command input, and the only place an utterance's text enters the kernel. + /// The committed home of those bytes is `facts[fact].statement`. + pub speech: Option, + /// A visible act in the actor's own words, and the only place it enters + /// the kernel. It accompanies any invocation: a body is visible whatever + /// it is doing. Its audience is the actor's place, never the entry's. + pub display: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct CommandEnvelope { + world_id: WorldId, + expected_revision: u64, + caller: CallerId, + body: CommandBody, +} + +impl CommandEnvelope { + /// A command is named by the world, revision, caller and body it carries. + /// The revision is in the preimage so the same body at two revisions is + /// two commands, and every id derived from it is distinct. + fn id(&self) -> CommandId { + let mut hasher = Sha256::new(); + hasher.update(COMMAND_DOMAIN); + hasher.update(self.world_id.0.as_bytes()); + hasher.update(self.expected_revision.to_be_bytes()); + hasher.update(rmp_serde::to_vec_named(&self.caller).expect("a caller serializes")); + hasher.update(rmp_serde::to_vec_named(&self.body).expect("a command body serializes")); + CommandId(truncated_uuid(hasher)) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum CommandBody { + /// One subject's act. Play's alone: the actor's grants decide whether the + /// affordance is its to use. + Act { + actor: SubjectId, + invocation: DecisionInvocation, + }, + /// A patch to the world. Play's alone. + AdmitPatch { + patch: WorldPatch, + }, + /// The world's only clock advance. Play's alone. + AdvanceTime { + minutes: TickMinutes, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct SubjectState { + label: String, + kind: SubjectKind, + /// Written only when a subject declaration is resolved; absent from a + /// subject nobody imported, so its digests are unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + import_key: Option, + /// Set once by `Retire`; the one place retirement is stored. A live + /// subject's row serializes without it. + #[serde(default, skip_serializing_if = "is_false")] + retired: bool, +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct DecisionEvent { + pub(crate) id: EventId, + pub(crate) revision: u64, + pub(crate) actor: SubjectId, + /// The entry exercised. The invocation itself lives on the effect: the + /// invocation is what the caller said, the event is what the world recorded. + pub(crate) affordance: AffordanceId, + /// The claim this act asserted, if it carried speech. Never the text: the + /// event is the world's record and every reader reads it, so it carries the + /// fact id and the statement lives in `facts` alone. + pub(crate) speech: Option, + /// The claim this act displayed, if it carried a visible act. Same rule. + pub(crate) display: Option, + /// Index into the entry's `outcome_bands`. Re-derived and compared at apply + /// and at replay, never trusted. + pub(crate) band: usize, + /// The selected band's slots, lowered through the invocation's bindings. + /// Empty when the selected band names no effects. + pub(crate) effects: Vec, +} + +/// The world's own fields: the one document that is not a map row. Tracked like +/// a partition key, so a tick that advances the clock is one changed document. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +struct WorldHeader { + world_id: WorldId, + owner: PrincipalId, + title: String, + /// Bound by genesis and never written again; absent from a world with no + /// grammar, so such a world's state and digests are what they were before + /// grammars existed. + #[serde(skip_serializing_if = "Option::is_none")] + grammar: Option, + /// Minutes since genesis. The world's only clock, advanced by exactly one + /// command body and read by no wall clock. It is world truth, and it is + /// read by no precondition. + now: FictionalMinutes, +} + +/// The world's partitions, declared once. Each row names a partition, its +/// key and value types and the schema its documents are digested with; the +/// struct, the table `begin`, `folded`, `finish`, `rollback` and the test +/// oracle walk, and the empty world are all generated from these rows, so a +/// partition is in the digest and under the undo log because it exists, and +/// there is no second list to forget it from. +/// +/// Every partition is a `Docs`: reads see the map, every write is logged, and +/// `submit` applies in place and either finishes or rolls the log back. A row +/// may name a [`docs::Projection`] as a third type: that partition then keeps a +/// read index, and the projections sit just above this macro. +macro_rules! world_state { + ($($(#[$meta:meta])* $field:ident: Docs<$key:ty, $value:ty $(, $proj:ty)?> = $schema:literal;)*) => { + #[derive(Clone, Debug, PartialEq, Eq)] + struct WorldState { + header: Tracked, + revision: u64, + $($(#[$meta])* $field: Docs<$key, $value $(, $proj)?>,)* + /// Derived from the partitions at every `finish`: outside every + /// document, so neither digested nor encoded, and equal whatever + /// it holds (see `views`). + views: Views, + // The chain head: outside every document. + accumulator: LtHash16, + state_digest: String, + last_commit_digest: Option, + } + + impl WorldState { + /// The number of partitions. + const PARTITIONS: usize = [$($schema),*].len(); + + /// Every partition under the schema its documents are digested with. + fn partitions(&self) -> [(&'static str, &dyn Partition); Self::PARTITIONS] { + [$(($schema, &self.$field as &dyn Partition)),*] + } + + fn partitions_mut(&mut self) -> [(&'static str, &mut dyn Partition); Self::PARTITIONS] { + [$(($schema, &mut self.$field as &mut dyn Partition)),*] + } + + /// A world with this header, revision 0 and no documents. + fn with_header(header: Tracked) -> Self { + Self { + header, + revision: 0, + $($field: Docs::default(),)* + views: Views::default(), + accumulator: LtHash16::default(), + state_digest: String::new(), + last_commit_digest: None, + } + } + } + }; +} + +/// The read indexes. Each is a pure function of one document's value, held by +/// its partition's `Docs` and read only through `Docs::indexed`; none is state +/// of its own, so none is digested or encoded. +/// +/// `ChildOf`: the places directly inside a place. +#[derive(Clone, Debug)] +struct ChildOf; + +impl docs::Projection for ChildOf { + type Point = EntityId; + fn points(value: &EntityRecord, out: &mut Vec) { + out.extend(value.container); + } +} + +/// `StandsAt`: who stands in a place. A position holds only its place, so two +/// positions are equal exactly when their places are. +#[derive(Clone, Debug)] +struct StandsAt; + +impl docs::Projection for StandsAt { + type Point = EntityId; + fn points(value: &Position, out: &mut Vec) { + out.push(value.place); + } +} + +/// `DependsOn`: who depends on a target. `Views` reads it to re-judge the +/// dependents of a route or a placement that changed. +#[derive(Clone, Debug)] +struct DependsOn; + +impl docs::Projection> for DependsOn { + type Point = DependencyTarget; + fn points(value: &BTreeSet, out: &mut Vec) { + out.extend(value.iter().copied()); + } +} + +/// `BySource`: which pressure sources press on a subject. +#[derive(Clone, Debug)] +struct BySource; + +impl docs::Projection> for BySource { + type Point = PressureSource; + fn points( + value: &BTreeMap, + out: &mut Vec, + ) { + out.extend(value.keys().copied()); + } +} + +/// `ByEndpoint`: the routes touching a place, at either end. +#[derive(Clone, Debug)] +struct ByEndpoint; + +impl docs::Projection for ByEndpoint { + type Point = EntityId; + fn points(value: &EdgeRecord, out: &mut Vec) { + let (from, to) = value.endpoints(); + out.push(from); + if to != from { + out.push(to); + } + } +} + +/// `ByController`: the channels a subject controls. +#[derive(Clone, Debug)] +struct ByController; + +impl docs::Projection for ByController { + type Point = SubjectId; + fn points(value: &ChannelRecord, out: &mut Vec) { + out.extend(value.controller); + } +} + +/// `ByIncumbent`: the institutions in which a subject holds an office. +#[derive(Clone, Debug)] +struct ByIncumbent; + +impl docs::Projection> for ByIncumbent { + type Point = SubjectId; + fn points(value: &BTreeMap, out: &mut Vec) { + let first = out.len(); + out.extend(value.values().filter_map(|office| office.incumbent)); + out[first..].sort(); + out.dedup(); + } +} + +/// `ByImportKey`: the subject that holds an import key. Retired subjects keep +/// theirs, so a key is never reissued. +#[derive(Clone, Debug)] +struct ByImportKey; + +impl docs::Projection for ByImportKey { + type Point = ImportKey; + fn points(value: &SubjectState, out: &mut Vec) { + out.extend(value.import_key.clone()); + } +} + +/// `ByKind`: the catalog entry that names an affordance kind, so a kind is +/// taken exactly when a point holds an entry. +#[derive(Clone, Debug)] +struct ByKind; + +impl docs::Projection for ByKind { + type Point = AffordanceKindName; + fn points(value: &Affordance, out: &mut Vec) { + out.push(value.kind.clone()); + } +} + +world_state! { + subjects: Docs = "aetherlight.subject.v1"; + entities: Docs = "aetherlight.entity.v1"; + edges: Docs = "aetherlight.edge.v1"; + positions: Docs = "aetherlight.position.v1"; + /// What each subject holds. Absence is zero at both levels: no stored + /// `Quantity(0)` and no empty inner map, so a duplicate holding is + /// unrepresentable and "nothing" has one shape. + holdings: Docs> = "aetherlight.holdings.v1"; + /// What each subject depends on. Never empty for a present key. + dependencies: Docs, DependsOn> = "aetherlight.dependencies.v1"; + /// One row per `EntityKind::Fact` entity, and no orphan either way. Facts + /// are write-once: declaration and `AssertClaim` are the only writers, and + /// standing never changes after admission. + facts: Docs = "aetherlight.fact.v1"; + /// One row per `EntityKind::Channel` entity, and no orphan either way. + channels: Docs = "aetherlight.channel.v1"; + /// What each subject knows. The sole owner of who-heard-what: `events` + /// records what was done, and this decides what a subject may act on and + /// what its projection may contain. One document per (subject, fact), and + /// absence is "knows nothing of it" — forgetting removes the key. + knowledge: Docs<(SubjectId, EntityId), Knowledge> = "aetherlight.knowledge.v1"; + /// What ground each subject has jurisdiction over, and under which + /// world-declared kind. Never empty for a present key. No subject holds two + /// grants of one kind over overlapping ground, so nothing ever arbitrates + /// between two sources of one permission. + authority: Docs> = "aetherlight.authority.v1"; + /// The offices each institution constitutes, and who sits in them. An + /// incumbent never acts as its institution: an office answers what its + /// incumbent has jurisdiction over, not who the actor is. + selection: Docs, ByIncumbent> = "aetherlight.selection.v1"; + /// Where each kind of grievance goes, and who may bring it. Keyed by + /// neither a subject nor a referent, so it enters no scope components and + /// is admission-only state. + redress: Docs = "aetherlight.redress.v1"; + /// What each subject has promised. Never empty for a present key. + commitments: Docs> = "aetherlight.commitments.v1"; + /// Pressure *on* each subject, keyed target-major then source. Never empty + /// for a present key; no stored zero magnitude. Lived meaning: read by + /// projection and by nothing that decides. + pressures: Docs, BySource> = "aetherlight.pressures.v1"; + /// What an affordance *is*. World-authored and written by `admit_resolved` + /// alone. + affordance_catalog: Docs = "aetherlight.affordance.v1"; + /// Who may exercise which entry: a row exists if and only if the subject + /// holds at least one verb. A grant carries no payload, so a duplicate + /// grant is unrepresentable rather than checked. + affordance_grants: Docs> = "aetherlight.affordance_grants.v1"; +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +enum WorldEffect { + WorldCreated { + owner: PrincipalId, + title: String, + resolved: ResolvedPatch, + }, + PatchAdmitted { + resolved: ResolvedPatch, + }, + Acted { + /// The command's own input, kept beside the event rather than inside it: + /// the invocation is what the caller said, the event is what the world + /// recorded, and only the first carries text. + invocation: DecisionInvocation, + event: DecisionEvent, + }, + /// The first effect that mutates state for subjects other than one scope. + /// Play's alone, and `apply_effect` + /// re-derives the whole motion, so a forged fulfilment, magnitude, row, or + /// target is one comparison rather than a clause apiece. + TimeAdvanced { + minutes: TickMinutes, + to: FictionalMinutes, + motion: Motion, + }, +} + +/// The exact raw command admitted by the kernel. This is the sole +/// persistent command authority: IDs, callers, and effects are +/// derived from this value rather than copied into independently forgeable +/// commit fields. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", content = "command", rename_all = "snake_case")] +enum CommittedCommand { + CreateWorld(CreateWorld), + WorldCommand(CommandEnvelope), +} + +impl CommittedCommand { + fn id(&self) -> CommandId { + match self { + Self::CreateWorld(command) => command.id(), + Self::WorldCommand(command) => command.id(), + } + } + + fn caller(&self) -> CallerId { + match self { + Self::CreateWorld(command) => CallerId::Principal(command.owner.clone()), + Self::WorldCommand(command) => command.caller.clone(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct WorldCommit { + schema: String, + world_id: WorldId, + command: CommittedCommand, + previous_revision: Option, + resulting_revision: u64, + previous_state_digest: Option, + resulting_state_digest: String, + previous_commit_digest: Option, + effect: WorldEffect, + digest: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SubjectSnapshot { + pub id: SubjectId, + pub label: String, + pub kind: SubjectKind, + /// The Aetheria record this subject was imported from, if it was. + pub import_key: Option, + pub affordances: BTreeSet, + pub(crate) position: Option, + /// Set for a subject `Retire` ended: no grants, no position, no + /// audience, its history kept. The agent's view and the surface read this + /// rather than inferring retirement from an absent position, which a + /// merely unplaced live subject also has. + pub retired: bool, + /// Exactly what a verification reads for this subject, carried whole + /// rather than lowered into projections that then have to be diffed back + /// together: its own position, incident routes, holdings, dependencies, + /// grants, delegated offices, known fact keys, controlled channels, and + /// commitments. A counterparty's components never enter. The narrative lane + /// persists this as the "before" an interruption is measured against. + pub(crate) components: ScopeComponents, + pub(crate) offices_held: Vec, + /// View-only, and covered by no digest: an institution's own offices, so + /// its controller can see what it lends and to whom. No precondition reads + /// it, and installing a warden therefore does not reject the institution's + /// in-flight proposals — what an institution lends is not what it may do. + pub(crate) offices_granted: Vec, + /// View-only: the forums whose standing covers this subject, through the + /// same covering predicate `HasStanding` uses. + pub(crate) redress: Vec, + /// Every fact this subject holds, with the statement resolved. The sole + /// perception surface: a subject perceives a speech act if and only if it + /// holds `Knowledge` of that act's fact. Ordered by `minted_at` then `fact`. + pub(crate) knowledge: Vec, + /// Digest-bound, lowered from the one `scope_components` call `snapshot` + /// already makes, so view and digest cannot drift. Carries `past_due`, + /// which the components do not. + pub(crate) commitments: Vec, + /// Pressure on self. View-only: read by no precondition, so covered by no + /// digest. Pressure this subject *sources* is excluded — it is another + /// subject's state, and the actor already sees the commitment that produced + /// it. + pub(crate) pressures: Vec, + /// This subject's own dependencies, lowered from `components.dependencies` + /// (private to this module) so the play table's omniscient view can print + /// what a `release` may name without reaching into `ScopeComponents` + /// itself. View-only: it is already carried by `components`. + pub(crate) dependencies: Vec, + /// The greatest `DecisionEvent.revision` whose actor is this subject, or + /// `None` if the subject never acted. Derived from the journal's acted events alone: + /// no new state, no schema change. The recency marker `projector_knowledge` + /// stamps onto each knowledge row is `acquired_at > last_acted_at`. + pub(crate) last_acted_at: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct CommitmentSnapshot { + pub(crate) key: CommitmentKey, + pub(crate) kind: CommitmentKind, + pub(crate) counterparty: Option, + pub(crate) due: FictionalMinutes, + pub(crate) period: Option, + pub(crate) statement: Statement, + /// Derived in `snapshot` so a controller does not recompute it against a + /// clock it must be handed anyway. + pub(crate) past_due: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PressureSnapshot { + pub(crate) source: PressureSource, + pub(crate) magnitude: PressureMagnitude, +} + +/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a +/// receipt is non-fictional provenance and never enters a subject-facing +/// surface, so a subject learns *that* a fact is canonical and never which +/// receipt admitted it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct KnowledgeSnapshot { + pub(crate) fact: EntityId, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingView, + pub(crate) confidence: Confidence, + /// The speaker a subject sees is `Told { by }`. A subject holding a fact it + /// was never told sees the statement with no speaker, which is correct: it + /// knows the thing, not the telling. + pub(crate) source: KnowledgeSource, + /// The revision of the act that minted this claim, spoken or displayed, + /// when some committed event asserted it. + pub(crate) minted_at: Option, + /// The revision at which this subject acquired this row, from `Knowledge` + /// directly: always present, unlike `minted_at`, so the recency marker can + /// see a row a patch, a seed, or a ruling landed with no minting event. + pub(crate) acquired_at: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FactStandingView { + Canonical, + Claimed { by: SubjectId }, + /// Stated by the play table. Never produced for a subject-facing knowledge + /// row (`snapshot`'s per-subject projection still collapses it into + /// `Canonical`, because a subject's own perception cannot tell a ruled + /// fact from an ordinarily canonical one); produced only for the + /// omniscient `WorldSnapshot::facts` row the play table's own `table_view` + /// reads. + Ruled, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct OfficeSnapshot { + pub(crate) institution: SubjectId, + pub(crate) office: OfficeName, + pub(crate) incumbent: Option, + /// What the office actually lends: the institution's live grants whose kind + /// the office delegates. + pub(crate) authority: BTreeSet, +} + +/// A forum a subject may petition. It carries no standing: a subject learns +/// that it may bring a grievance, not the boundary of everyone else's standing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ForumSnapshot { + pub(crate) grievance: GrievanceKindName, + pub(crate) forum: SubjectId, +} + +/// One catalog entry as consumers read it. The whole entry, because every +/// derived surface — tool schemas, signature prose, the typed view's permission +/// block — is a projection of it and a narrower snapshot would be a second +/// vocabulary to keep in step. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct AffordanceSnapshot { + pub id: AffordanceId, + pub entry: Affordance, + /// Derived from the world's grammar by this entry's kind; none when the + /// world has no grammar. + pub render_path: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ResourceSnapshot { + pub(crate) id: EntityId, + pub(crate) label: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PlaceSnapshot { + pub id: EntityId, + pub label: String, + pub(crate) container: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct RouteSnapshot { + pub(crate) id: EdgeId, + pub(crate) label: String, + pub(crate) from: EntityId, + pub(crate) to: EntityId, + pub(crate) access: AccessKind, + pub(crate) cost: Cost, + pub(crate) open: bool, +} + +/// A declared channel, standing rather than per-subject: `ChannelRecord` +/// carries no label (only `reach` and `controller`), so this is exactly that +/// record plus the canonical id, an omniscient row for the play table's own +/// view. No subject-facing surface reads it; a subject sees only the channels +/// it controls, through its own `components`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ChannelSnapshot { + pub(crate) id: EntityId, + pub(crate) reach: Reach, + pub(crate) controller: Option, +} + +/// Every fact the world holds, canonical or not, with its real standing — +/// including `Ruled`, which every subject-facing knowledge row collapses to +/// `Canonical` — and who currently holds it. Built straight from +/// `state.facts` and `state.knowledge`, not from any subject's own knowledge +/// projection, so a fact nobody has been told or shown is still a row here: +/// `mint`, `transfer`, `witness`, and `acquire_knowledge` all take a fact id, +/// and the play table's omniscient view must be able to name one nobody +/// perceives yet. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct FactSnapshot { + pub(crate) id: EntityId, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingView, + pub(crate) known_by: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WorldSnapshot { + pub world_id: WorldId, + pub revision: u64, + pub owner: PrincipalId, + pub title: String, + /// The bound grammar's identity; none for a world with an open catalog. + pub grammar: Option, + pub subjects: Vec, + pub affordances: Vec, + pub places: Vec, + pub(crate) resources: Vec, + pub(crate) routes: Vec, + /// Every declared channel, omniscient: no subject-facing surface reads + /// this field. `communicate`'s audience may name one by id. + pub(crate) channels: Vec, + /// Every fact the world holds, omniscient and including facts nobody + /// currently perceives: no subject-facing surface reads this field, which + /// exists for the play table's own `table_view` alone. + pub(crate) facts: Vec, + /// Everyone in a world shares the clock, and no controller can read a `due` + /// without it. + pub now: FictionalMinutes, + pub state_digest: String, + pub last_commit_digest: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CommitReceipt { + pub command_id: CommandId, + pub resulting_revision: u64, + pub resulting_state_digest: String, + pub commit_digest: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CreationReceipt { + pub command_id: CommandId, + pub world_id: WorldId, + pub resulting_state_digest: String, + pub commit_digest: String, +} + +impl CreationReceipt { + fn from_commit(commit: &WorldCommit) -> Result { + let CommittedCommand::CreateWorld(command) = &commit.command else { + return Err(KernelError::Invariant( + "world genesis receipt does not point to a creation command".into(), + )); + }; + let WorldEffect::WorldCreated { .. } = &commit.effect else { + return Err(KernelError::Invariant( + "world genesis receipt does not point to genesis".into(), + )); + }; + Ok(Self { + command_id: command.id(), + world_id: commit.world_id, + resulting_state_digest: commit.resulting_state_digest.clone(), + commit_digest: commit.digest.clone(), + }) + } +} + +impl From<&WorldCommit> for CommitReceipt { + fn from(commit: &WorldCommit) -> Self { + Self { + command_id: commit.command.id(), + resulting_revision: commit.resulting_revision, + resulting_state_digest: commit.resulting_state_digest.clone(), + commit_digest: commit.digest.clone(), + } + } +} + +#[derive(Debug, Error)] +pub enum KernelError { + #[error("world title must not be empty")] + EmptyTitle, + #[error("world owner principal must be canonical and nonempty")] + EmptyPrincipal, + #[error("patch rejected: {0:?}")] + PatchRejected(Vec), + #[error("action rejected: {0:?}")] + ActionRejected(Vec), + #[error("command targets another world")] + WorldMismatch, + #[error("authenticated caller does not match the command")] + AuthenticationMismatch, + #[error("caller does not own this world")] + Unauthorized, + #[error("decision affordance is not granted to the actor")] + AffordanceDenied, + #[error("expected revision {expected}, current revision {actual}")] + RevisionMismatch { expected: u64, actual: u64 }, + #[error("canonical serialization failed: {0}")] + Serialization(String), + #[error("world journal is corrupt: {0}")] + CorruptJournal(String), + /// A well-formed export written under another commit schema generation + /// (a v1 save): not corrupt, but not readable by this build. + #[error("export commit schema {found} is not the supported {supported}")] + UnsupportedSchema { found: String, supported: &'static str }, + #[error("private reducer invariant failed: {0}")] + Invariant(String), +} + +impl From for KernelError { + fn from(error: journal::JournalError) -> Self { + match error { + journal::JournalError::Corrupt(detail) => Self::CorruptJournal(detail), + journal::JournalError::UnsupportedSchema { found, supported } => { + Self::UnsupportedSchema { found, supported } + } + } + } +} + +// Test seam: when set on this thread, `submit` fails after it has folded the +// digest and sealed the commit, the last point before the world is kept. +#[cfg(test)] +thread_local! { + static INJECT_FAILURE_AFTER_DIGEST: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +struct WorldKernel { + state: WorldState, + journal: journal::WorldJournal, +} + +struct PreparedCreation { + command: CreateWorld, + world_id: WorldId, + owner: PrincipalId, + title: String, + resolved: ResolvedPatch, +} + +fn prepare_creation( + input: CreateWorld, + authenticated: &AuthenticatedCaller, +) -> Result { + let CallerId::Principal(authenticated_principal) = &authenticated.caller else { + return Err(KernelError::AuthenticationMismatch); + }; + validate_principal(&input.owner)?; + if &input.owner != authenticated_principal { + return Err(KernelError::AuthenticationMismatch); + } + let title = normalize_title(&input.title)?; + // The world's own identity is not world structure, and it feeds every + // derived ID, so it is minted before resolution rather than by it. + let world_id = WorldId::of(input.id()); + let resolved = patch::resolve_patch( + &WorldState::empty( + world_id, + input.owner.clone(), + title.clone(), + input.grammar.clone(), + ), + input.id(), + &input.patch, + ) + .map_err(KernelError::PatchRejected)?; + forbid_rulings_at_genesis(&resolved).map_err(KernelError::PatchRejected)?; + Ok(PreparedCreation { + world_id, + owner: input.owner.clone(), + title, + resolved, + command: input, + }) +} + +impl WorldKernel { + fn initialize(prepared: PreparedCreation) -> Result<(Self, CreationReceipt), KernelError> { + let world_id = prepared.world_id; + let effect = WorldEffect::WorldCreated { + owner: prepared.owner, + title: prepared.title, + resolved: prepared.resolved, + }; + let mut state = WorldState::genesis(world_id, &prepared.command, &effect)?; + let mut genesis = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id, + command: CommittedCommand::CreateWorld(prepared.command), + previous_revision: None, + resulting_revision: 0, + previous_state_digest: None, + resulting_state_digest: state.state_digest.clone(), + previous_commit_digest: None, + effect, + digest: String::new(), + }; + genesis.digest = commit_digest(&genesis)?; + state.last_commit_digest = Some(genesis.digest.clone()); + let receipt = CreationReceipt::from_commit(&genesis)?; + let journal = journal::WorldJournal::genesis(genesis); + Ok((Self { state, journal }, receipt)) + } + + fn create( + input: CreateWorld, + authenticated: &AuthenticatedCaller, + ) -> Result<(Self, CreationReceipt), KernelError> { + Self::initialize(prepare_creation(input, authenticated)?) + } + + /// The world an export derives: its head state is the replay of its commits. + fn open(bytes: &[u8]) -> Result { + let (journal, state) = journal::WorldJournal::open(bytes)?; + Ok(Self { state, journal }) + } + + fn export(&self) -> Result, KernelError> { + self.journal.export() + } + + fn snapshot(&self) -> Result { + snapshot(&self.state, &self.journal) + } + + /// The decisions the world has acted on, for the tests that read them. + #[cfg(test)] + fn events(&self) -> Vec { + self.journal.acted_events().cloned().collect() + } + + fn submit( + &mut self, + command: CommandEnvelope, + authenticated: &AuthenticatedCaller, + ) -> Result { + let command_id = command.id(); + if command.world_id != self.state.header.world_id { + return Err(KernelError::WorldMismatch); + } + if command.caller != authenticated.caller { + return Err(KernelError::AuthenticationMismatch); + } + if command.expected_revision != self.state.revision { + return Err(KernelError::RevisionMismatch { + expected: command.expected_revision, + actual: self.state.revision, + }); + } + + let effect = reduce(&self.state, &command)?; + let previous_revision = self.state.revision; + let previous_state_digest = self.state.state_digest.clone(); + let previous_commit_digest = self.state.last_commit_digest.clone(); + // Applied in place under the partitions' undo logs: the world is never + // cloned, and any failure up to the sealed commit puts it back. + self.state.begin(); + let sealed = (|| -> Result<(WorldCommit, LtHash16), KernelError> { + apply_effect(&mut self.state, command_id, &command.caller, &effect)?; + self.state.revision = previous_revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into()))?; + let accumulator = self.state.folded()?; + self.state.state_digest = accumulator.state_digest(self.state.revision); + let mut commit = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id: self.state.header.world_id, + command: CommittedCommand::WorldCommand(command), + previous_revision: Some(previous_revision), + resulting_revision: self.state.revision, + previous_state_digest: Some(previous_state_digest.clone()), + resulting_state_digest: self.state.state_digest.clone(), + previous_commit_digest, + effect, + digest: String::new(), + }; + commit.digest = commit_digest(&commit)?; + #[cfg(test)] + if INJECT_FAILURE_AFTER_DIGEST.get() { + return Err(KernelError::Invariant("injected failure after the digest".into())); + } + Ok((commit, accumulator)) + })(); + let (commit, accumulator) = match sealed { + Ok(sealed) => sealed, + Err(error) => { + self.state.rollback(); + self.state.revision = previous_revision; + self.state.state_digest = previous_state_digest; + return Err(error); + } + }; + self.state.finish(accumulator); + self.state.last_commit_digest = Some(commit.digest.clone()); + + let receipt = CommitReceipt::from(&commit); + self.journal.append(commit); + Ok(receipt) + } + +} + +fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { + // The one admission rule, stated here and again at the top of + // `apply_effect`: `reduce` decides and `apply_effect` re-decides, which is + // how every gate in this file is written. + require_play(&command.caller)?; + let command_id = command.id(); + match &command.body { + CommandBody::Act { actor, invocation } => { + let granted = require_granted(state, *actor, invocation.affordance)?; + let event = action::exercise(state, command_id, *actor, &granted, invocation)?; + Ok(WorldEffect::Acted { + invocation: invocation.clone(), + event, + }) + } + CommandBody::AdvanceTime { minutes } => { + let to = state + .header.now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // A tick with an empty motion is still a commit: the clock moved, + // which is a canonical change. That is why the clock is a state + // field rather than a patch operation. + Ok(WorldEffect::TimeAdvanced { + minutes: *minutes, + to, + motion: clock::derive_motion(state, to), + }) + } + CommandBody::AdmitPatch { patch } => { + let resolved = patch::resolve_patch(state, command_id, patch) + .map_err(KernelError::PatchRejected)?; + Ok(WorldEffect::PatchAdmitted { resolved }) + } + } +} + +/// The one admission rule: after genesis Play is the only caller any command +/// body admits. Stated once here, reached by `reduce` and by `apply_effect`. +fn require_play(caller: &CallerId) -> Result<(), KernelError> { + match caller { + CallerId::Play => Ok(()), + CallerId::Principal(_) => Err(KernelError::Unauthorized), + } +} + +/// The genesis predicate: the world is being built from nothing, so the one +/// lane that builds revision 0 may build the kernel Speak entry and the first +/// subjects. It reads state, never the caller. It takes the two fields it inspects rather than a whole +/// `WorldState` so the genesis lane, which resolves declarations before any +/// `WorldState` exists, can call the same owner instead of hand-copying the +/// literal it would otherwise always evaluate to. +fn is_genesis(revision: u64, subjects: &Docs) -> bool { + revision == 0 && subjects.is_empty() +} + +const WORLD_DOC_SCHEMA: &str = "aetherlight.world.v1"; + +impl WorldState { + /// Opens a transaction. Every log must be empty: a write outside a + /// transaction, or a transaction left open, is a bug here and not state. + fn begin(&self) { + debug_assert!(self.header.is_clean(), "a transaction is open"); + debug_assert!(self.partitions().iter().all(|(_, docs)| docs.is_clean())); + } + + /// What `subject` knows: its rows of the flat knowledge partition, by fact. + fn knowledge_of(&self, subject: SubjectId) -> impl Iterator { + self.knowledge + .range((subject, EntityId(Uuid::nil()))..=(subject, EntityId(Uuid::max()))) + .map(|((_, fact), held)| (fact, held)) + } + + /// The accumulator the open transaction's writes lead to. Reads the logs and + /// changes nothing, so a failure after it can still roll back. + fn folded(&self) -> Result { + let mut acc = self.accumulator.clone(); + digest::fold_header(&mut acc, WORLD_DOC_SCHEMA, &self.header.world_id.key(), &self.header)?; + for (schema, docs) in self.partitions() { + docs.fold_changes(schema, &mut acc)?; + } + Ok(acc) + } + + /// Closes the transaction, keeping its writes and the accumulator `folded` + /// computed for them. Returns the commitments subjects that changed, with + /// their old promises, for replay's check that every commitment stays in the + /// future. + fn finish( + &mut self, + accumulator: LtHash16, + ) -> Vec>> { + self.accumulator = accumulator; + self.header.finish(); + // The views fold from the open logs, so they come before the logs close. + let mut views = std::mem::take(&mut self.views); + views.fold(self); + self.views = views; + let commitments = self.commitments.finish(); + for (_, docs) in self.partitions_mut() { + docs.finish_log(); + } + commitments + } + + /// Closes the transaction, undoing every write in it. + fn rollback(&mut self) { + self.header.rollback(); + for (_, docs) in self.partitions_mut() { + docs.rollback(); + } + } + + /// Every document's digest by (schema, key), enumerated from the maps and + /// ignoring the logs. + #[cfg(test)] + fn documents( + &self, + ) -> Result, KernelError> { + let mut out = std::collections::BTreeMap::new(); + let header = &*self.header; + let key = header.world_id.key(); + out.insert( + (WORLD_DOC_SCHEMA.to_owned(), key.clone()), + digest::doc_digest(WORLD_DOC_SCHEMA, &key, header)?, + ); + for (schema, docs) in self.partitions() { + docs.documents(schema, &mut out)?; + } + Ok(out) + } + + /// The accumulator recomputed from every document: the oracle the + /// incremental digest is checked against. + #[cfg(test)] + fn full_state_digest(&self) -> Result { + let mut acc = LtHash16::default(); + for doc in self.documents()?.values() { + acc.add(doc); + } + Ok(acc.state_digest(self.revision)) + } + + /// Every document as encoded, header first: the bytes a test scans. + #[cfg(test)] + fn encoded_documents(&self) -> Vec { + let mut bytes = rmp_serde::to_vec_named(&*self.header).expect("the header encodes"); + for (_, docs) in self.partitions() { + bytes.extend(docs.encoded()); + } + bytes + } +} + +impl WorldState { + /// The world before any structure. Genesis resolves its own patch against + /// this value, so the genesis lane and `AdmitPatch` share one resolver + /// signature instead of hand-passing empty partitions. + fn empty( + world_id: WorldId, + owner: PrincipalId, + title: String, + grammar: Option, + ) -> Self { + Self::with_header(Tracked::absent(WorldHeader { + world_id, + owner, + title, + grammar, + now: FictionalMinutes::default(), + })) + } + + fn genesis( + world_id: WorldId, + command: &CreateWorld, + effect: &WorldEffect, + ) -> Result { + let WorldEffect::WorldCreated { + owner, + title, + resolved, + } = effect + else { + return Err(KernelError::Invariant( + "genesis state requires a world-created effect".into(), + )); + }; + validate_principal(&command.owner)?; + let expected_title = normalize_title(&command.title)?; + if owner != &command.owner || title != &expected_title { + return Err(KernelError::Invariant( + "genesis effect does not match the admitted creation command".into(), + )); + } + // The same re-derive-and-compare that `apply_committed_command` runs for + // every other command. Deterministic allocation is what lets one + // equality replace a field-by-field binding zip. + let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone()); + let expected = patch::resolve_patch( + &state, + command.id(), + &command.patch, + ) + .map_err(KernelError::PatchRejected)?; + if &expected != resolved { + return Err(KernelError::Invariant( + "genesis effect does not derive from its creation command".into(), + )); + } + forbid_rulings_at_genesis(resolved).map_err(|_| { + KernelError::Invariant("genesis effect rules or mints without the play authority".into()) + })?; + // Genesis resolves to revision 0 itself: `state.revision` never + // advances past 0 for the creating commit (`resulting_revision: 0`), + // unlike every later commit, which resolves to `state.revision + 1`. + let genesis_revision = state.revision; + admit_resolved(&mut state, resolved, genesis_revision)?; + let accumulator = state.folded()?; + state.state_digest = accumulator.state_digest(state.revision); + state.finish(accumulator); + Ok(state) + } +} + +/// The only writer of every ontology partition. Both admission lanes mutate +/// through it in one fixed order — entities, routes, subjects, operations — so a +/// patch may relocate along a route it declares. It re-derives every structural +/// claim from `state`, so an effect that skipped resolution dies here. +fn admit_resolved( + state: &mut WorldState, + resolved: &ResolvedPatch, + resolves_to: u64, +) -> Result<(), KernelError> { + if resolved.declares_nothing() && resolved.operations.is_empty() { + return Err(KernelError::Invariant( + "admitted patch carries no canonical change".into(), + )); + } + for entity in &resolved.entities { + if !patch::is_canonical_text(&entity.entity.label) { + return Err(KernelError::Invariant( + "admitted entity label is not canonical".into(), + )); + } + if let Some(container) = entity.entity.container + && (entity.entity.kind != EntityKind::Place + || state + .entities + .get(&container) + .is_none_or(|record| record.kind != EntityKind::Place)) + { + return Err(KernelError::Invariant( + "admitted container does not name a canonical place".into(), + )); + } + if state + .entities + .insert(entity.entity_id, entity.entity.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted entity ID collision".into(), + )); + } + if !patch::containment_terminates(entity.entity_id, &state.entities) { + return Err(KernelError::Invariant( + "admitted place contains itself".into(), + )); + } + } + for route in &resolved.routes { + let (from, to) = route.edge.endpoints(); + let endpoint_is_place = |entity_id: &EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == EntityKind::Place) + }; + if !patch::is_canonical_text(route.edge.label()) + || !endpoint_is_place(&from) + || !endpoint_is_place(&to) + || from == to + || !patch::is_valid_cost(route.edge.cost()) + { + return Err(KernelError::Invariant( + "admitted route is noncanonical or does not join two places".into(), + )); + } + if state + .edges + .insert(route.edge_id, route.edge.clone()) + .is_some() + { + return Err(KernelError::Invariant("admitted route ID collision".into())); + } + } + for entry in &resolved.affordances { + // The catalog's only writer holds the same grammar check the resolver + // runs, so an effect resolved elsewhere cannot install an entry the + // bound grammar refuses. + if state.header.grammar.as_ref().is_some_and(|grammar| { + grammar + .refusal(&entry.affordance.kind, &entry.affordance.roles) + .is_some() + }) { + return Err(KernelError::Invariant( + "admitted affordance is outside the bound grammar".into(), + )); + } + if state + .affordance_catalog + .insert(entry.affordance_id, entry.affordance.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted affordance ID collision".into(), + )); + } + } + // The subjects map's only writer holds the same injectivity the resolver + // checks, decided by the same function. + { + let mut declared = BTreeSet::new(); + for subject in &resolved.subjects { + if let Some(key) = &subject.subject.import_key + && patch::import_key_fault(key, |key| state.import_key_held(key), &mut declared) + .is_some() + { + return Err(KernelError::Invariant( + "admitted subject's import key is malformed, held or repeated".into(), + )); + } + } + } + for subject in &resolved.subjects { + if !patch::is_canonical_text(&subject.subject.label) { + return Err(KernelError::Invariant( + "admitted subject label is not canonical".into(), + )); + } + if let Some(position) = subject.position + && state + .entities + .get(&position.place) + .is_none_or(|entity| entity.kind != EntityKind::Place) + { + return Err(KernelError::Invariant( + "admitted position does not name a canonical place".into(), + )); + } + if state + .subjects + .insert(subject.subject_id, subject.subject.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted subject ID collision".into(), + )); + } + if let Some(position) = subject.position + && state + .positions + .insert(subject.subject_id, position) + .is_some() + { + return Err(KernelError::Invariant( + "admitted position collides with an existing one".into(), + )); + } + for affordance_id in &subject.affordances { + if !state.affordance_catalog.contains_key(affordance_id) { + return Err(KernelError::Invariant( + "admitted grant names no catalog entry".into(), + )); + } + state + .affordance_grants + .entry(subject.subject_id) + .or_default() + .insert(*affordance_id); + } + } + // Facts and channels: one `entities` row and one payload row per + // declaration, written together so the bijection has one writer. + for declared in &resolved.facts { + let claimed_by_a_stranger = match &declared.fact.standing { + FactStanding::Canonical { evidence } => { + !(patch::is_canonical_text(evidence.text()) && resolved.evidence.contains(evidence)) + } + FactStanding::Claimed { by } => !state.subjects.contains_key(by), + FactStanding::Ruled => false, + }; + if !patch::is_canonical_text(&declared.entity.label) + || !patch::is_canonical_text(declared.fact.statement.as_str()) + || declared.entity.kind != EntityKind::Fact + || claimed_by_a_stranger + { + return Err(KernelError::Invariant( + "admitted fact is noncanonical, unevidenced, or asserted by no live subject".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .facts + .insert(declared.entity_id, declared.fact.clone()) + .is_some() + { + return Err(KernelError::Invariant("admitted fact ID collision".into())); + } + } + for declared in &resolved.channels { + if !patch::is_canonical_text(&declared.entity.label) + || declared.entity.kind != EntityKind::Channel + || !channel_referents_exist(state, &declared.channel) + { + return Err(KernelError::Invariant( + "admitted channel is noncanonical or names no live reach".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .channels + .insert(declared.entity_id, declared.channel.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted channel ID collision".into(), + )); + } + } + apply_operations(state, &resolved.operations, &resolved.evidence, resolves_to) +} + +/// The component writer for every lane: apply each operation, accumulate the +/// ledger deltas, and prove conservation once. Declaration admission calls it +/// after its declaration loops; an exercised affordance's lowered effects call +/// it directly. One writer, one conservation statement. +/// +/// A forged effect reaches this function without ever passing the resolver, so +/// conservation and disjointness are re-derived here, from the transaction's own +/// log: only a holder the operations wrote can change either answer, because +/// every other holder appears on both sides of the equation and no other +/// jurisdiction moved. `before` is what each written holder held when this +/// function was entered, never anything the effect asserts. +fn apply_operations( + state: &mut WorldState, + operations: &[ResolvedOp], + evidence: &[EvidenceRef], + resolves_to: u64, +) -> Result<(), KernelError> { + let mut deltas: BTreeMap = BTreeMap::new(); + for operation in operations { + for resource in operation_resources(operation) { + deltas.entry(resource).or_default(); + } + } + // Holders already written when the operations begin (the declarations + // above, normally none): what they hold now is their `before`. + let at_entry: BTreeMap>> = state + .holdings + .changes() + .map(|(holder, _, now)| (*holder, now.cloned())) + .collect(); + for operation in operations { + apply_operation(state, operation, evidence, resolves_to)?; + match operation { + ResolvedOp::Transform { + from_resource, + into_resource, + qty, + .. + } => { + deltas.entry(*from_resource).or_default().spent += u128::from(qty.0); + deltas.entry(*into_resource).or_default().gained += u128::from(qty.0); + } + ResolvedOp::Consume { resource, qty, .. } => { + deltas.entry(*resource).or_default().consumed += u128::from(qty.0); + } + ResolvedOp::Admit { resource, qty, .. } => { + deltas.entry(*resource).or_default().admitted += u128::from(qty.0); + } + ResolvedOp::Mint { resource, qty, .. } => { + deltas.entry(*resource).or_default().admitted += u128::from(qty.0); + } + _ => {} + } + } + let held_of = |held: Option<&BTreeMap>, resource: &EntityId| { + held.and_then(|held| held.get(resource)).map_or(0, |quantity| u128::from(quantity.0)) + }; + // The holders judged are the union of those written at entry and those the + // log now reports: a holder written before the operations and returned to + // its transaction-start value is absent from `changes()` but still moved. + type Held<'a> = Option<&'a BTreeMap>; + let mut judged: BTreeMap, Held<'_>)> = BTreeMap::new(); + for (holder, logged, now) in state.holdings.changes() { + let before = match at_entry.get(holder) { + Some(recorded) => recorded.as_ref(), + None => logged, + }; + judged.insert(*holder, (before, now)); + } + for (holder, recorded) in &at_entry { + judged + .entry(*holder) + .or_insert_with(|| (recorded.as_ref(), state.holdings.get(holder))); + } + for (before, now) in judged.values() { + for (resource, delta) in &mut deltas { + delta.before += held_of(*before, resource); + delta.after += held_of(*now, resource); + } + } + if patch::check_ledger(&deltas).is_some() { + return Err(KernelError::Invariant("custody does not conserve".into())); + } + // Disjointness, re-derived for the same reason conservation is: a forged + // effect reaches this function without passing the resolver. Only a holder + // the transaction touched can have gained an overlap. + if operations.iter().any(|operation| { + matches!( + operation, + ResolvedOp::GrantAuthority { .. } + | ResolvedOp::OpenOffice { .. } + | ResolvedOp::InstallIncumbent { .. } + ) + }) && touched_holders(state).into_iter().any(|holder| holder_overlaps(state, holder)) + { + return Err(KernelError::Invariant( + "one subject holds two overlapping jurisdictions of one kind".into(), + )); + } + Ok(()) +} + +/// Every subject whose effective authority the open transaction may have +/// changed: whose own grants were written, whose offices were written (old +/// incumbent and new), and the incumbents of an institution whose grants were +/// written, because an office lends what its institution holds. A retirement +/// only removes lent authority, so it cannot add an overlap and is not read. +fn touched_holders(state: &WorldState) -> BTreeSet { + let mut touched = BTreeSet::new(); + let mut institutions = BTreeSet::new(); + for (holder, _, _) in state.authority.changes() { + touched.insert(*holder); + institutions.insert(*holder); + } + for (institution, old, new) in state.selection.changes() { + for offices in [old, new].into_iter().flatten() { + touched.extend(offices.values().filter_map(|office| office.incumbent)); + } + institutions.insert(*institution); + } + for institution in institutions { + if let Some(offices) = state.selection.get(&institution) { + touched.extend(offices.values().filter_map(|office| office.incumbent)); + } + } + touched +} + +/// Every resource an operation names, so `admit_resolved` can read its committed +/// total before touching it. +fn operation_resources(operation: &ResolvedOp) -> Vec { + match operation { + ResolvedOp::Transfer { resource, .. } + | ResolvedOp::Consume { resource, .. } + | ResolvedOp::Admit { resource, .. } + | ResolvedOp::Mint { resource, .. } => vec![*resource], + ResolvedOp::Transform { + from_resource, + into_resource, + .. + } => vec![*from_resource, *into_resource], + _ => Vec::new(), + } +} + +/// What `apply_operations` sums before and after: every holder. Conservation +/// reads only the holders a transaction wrote, and this is the reference. +#[cfg(test)] +fn resource_total_by_scan(state: &WorldState, resource: EntityId) -> u128 { + state + .holdings + .values() + .filter_map(|held| held.get(&resource)) + .map(|quantity| u128::from(quantity.0)) + .sum() +} + +/// What a holder holds. Absence is zero. +fn held(state: &WorldState, holder: SubjectId, resource: EntityId) -> u64 { + state + .holdings + .get(&holder) + .and_then(|held| held.get(&resource)) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the resource key, and an emptied holder removes the holder key, +/// so `holdings` has exactly one representation of nothing. +fn set_held(state: &mut WorldState, holder: SubjectId, resource: EntityId, value: u64) { + if value == 0 { + let empty = if let Some(held) = state.holdings.get_mut(&holder) { + held.remove(&resource); + held.is_empty() + } else { + false + }; + if empty { + state.holdings.remove(&holder); + } + } else { + state + .holdings + .entry(holder) + .or_default() + .insert(resource, Quantity(value)); + } +} + +/// Whether a subject and a resource are both canonical and of the right kind. +fn custody_referents_exist(state: &WorldState, holder: SubjectId, resource: EntityId) -> bool { + state.subjects.contains_key(&holder) + && state + .entities + .get(&resource) + .is_some_and(|record| record.kind == EntityKind::Resource) +} + +fn dependency_target_exists(state: &WorldState, target: DependencyTarget) -> bool { + match target { + DependencyTarget::Resource(entity_id) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Resource), + DependencyTarget::Route(edge_id) => state.edges.contains_key(&edge_id), + DependencyTarget::Subject(subject_id) => state.subjects.contains_key(&subject_id), + } +} + +/// The component half of admission. Every precondition is re-derived from the +/// partitions, so a forged operation cannot assert a move the topology refuses. +fn apply_operation( + state: &mut WorldState, + operation: &ResolvedOp, + evidence: &[EvidenceRef], + resolves_to: u64, +) -> Result<(), KernelError> { + let insufficient = || KernelError::Invariant("holder does not hold enough".into()); + let overflow = || KernelError::Invariant("holding would overflow".into()); + let unknown = || KernelError::Invariant("custody operation names no canonical referent".into()); + let zero = || KernelError::Invariant("custody operation moves nothing".into()); + match operation { + ResolvedOp::Relocate { + subject_id, + edge_id, + } => { + let route = state + .edges + .get(edge_id) + .ok_or_else(|| KernelError::Invariant("relocation names no route".into()))?; + let (from, to) = route.endpoints(); + let open = route.is_open(); + let access = route.access().clone(); + if !open + || state.positions.get(subject_id) != Some(&Position { place: from }) + || !patch::route_admits(state, &subject_authority(state, *subject_id), &access, to) + { + return Err(KernelError::Invariant( + "relocation does not traverse an open route the subject may take from its place" + .into(), + )); + } + state.positions.insert(*subject_id, Position { place: to }); + } + ResolvedOp::OpenRoute { edge_id } | ResolvedOp::CloseRoute { edge_id } => { + let open = matches!(operation, ResolvedOp::OpenRoute { .. }); + let route = state + .edges + .get_mut(edge_id) + .ok_or_else(|| KernelError::Invariant("route operation names no route".into()))?; + if route.is_open() == open { + return Err(KernelError::Invariant( + "route operation changes nothing".into(), + )); + } + route.set_open(open); + } + ResolvedOp::AlterCost { edge_id, cost } => { + if !patch::is_valid_cost(*cost) { + return Err(KernelError::Invariant( + "admitted cost is out of range".into(), + )); + } + let route = state + .edges + .get_mut(edge_id) + .ok_or_else(|| KernelError::Invariant("route operation names no route".into()))?; + if route.cost() == *cost { + return Err(KernelError::Invariant( + "route operation changes nothing".into(), + )); + } + route.set_cost(*cost); + } + ResolvedOp::Transfer { + from, + to, + resource, + qty, + } => { + if !custody_referents_exist(state, *from, *resource) || !state.subjects.contains_key(to) + { + return Err(unknown()); + } + if qty.0 == 0 || from == to { + return Err(zero()); + } + let remaining = held(state, *from, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let credited = held(state, *to, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *from, *resource, remaining); + set_held(state, *to, *resource, credited); + } + ResolvedOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *from_resource) + || !custody_referents_exist(state, *holder, *into_resource) + { + return Err(unknown()); + } + if qty.0 == 0 || from_resource == into_resource { + return Err(zero()); + } + let remaining = held(state, *holder, *from_resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let gained = held(state, *holder, *into_resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *from_resource, remaining); + set_held(state, *holder, *into_resource, gained); + } + ResolvedOp::Consume { + holder, + resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + let remaining = held(state, *holder, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + set_held(state, *holder, *resource, remaining); + } + ResolvedOp::Admit { + holder, + resource, + qty, + evidence: cited, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + if !evidence.contains(cited) { + return Err(KernelError::Invariant( + "admitted quantity cites no evidence in its patch".into(), + )); + } + let admitted = held(state, *holder, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *resource, admitted); + } + ResolvedOp::Mint { + holder, + resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + let minted = held(state, *holder, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *resource, minted); + } + ResolvedOp::Bind { subject, target } | ResolvedOp::Release { subject, target } => { + let bind = matches!(operation, ResolvedOp::Bind { .. }); + if !state.subjects.contains_key(subject) || !dependency_target_exists(state, *target) { + return Err(unknown()); + } + if *target == DependencyTarget::Subject(*subject) { + return Err(KernelError::Invariant( + "a subject cannot depend on itself".into(), + )); + } + let bound = state + .dependencies + .get(subject) + .is_some_and(|targets| targets.contains(target)); + if bound == bind { + return Err(KernelError::Invariant( + "dependency operation changes nothing".into(), + )); + } + if bind { + state + .dependencies + .entry(*subject) + .or_default() + .insert(*target); + } else { + let empty = if let Some(targets) = state.dependencies.get_mut(subject) { + targets.remove(target); + targets.is_empty() + } else { + false + }; + if empty { + state.dependencies.remove(subject); + } + // The pressure a failing dependency raised is that dependency's + // own: it ends with it, or the world fails its shape check at open. + set_pressure(state, *subject, PressureSource::Dependency(*target), 0); + } + } + ResolvedOp::GrantAuthority { holder, grant } + | ResolvedOp::RevokeAuthority { holder, grant } => { + let granting = matches!(operation, ResolvedOp::GrantAuthority { .. }); + if !state.subjects.contains_key(holder) + || !authority_referent_exists(state, grant.over) + || !patch::is_civic_name(&grant.kind.0) + { + return Err(unknown()); + } + let held = state + .authority + .get(holder) + .is_some_and(|grants| grants.contains(grant)); + if held == granting { + return Err(KernelError::Invariant( + "authority operation changes nothing".into(), + )); + } + if granting { + state + .authority + .entry(*holder) + .or_default() + .insert(grant.clone()); + } else { + let empty = if let Some(grants) = state.authority.get_mut(holder) { + grants.remove(grant); + grants.is_empty() + } else { + false + }; + if empty { + state.authority.remove(holder); + } + } + } + ResolvedOp::OpenOffice { + institution, + office, + delegated, + } => { + require_institution(state, *institution, office)?; + if delegated.is_empty() || delegated.iter().any(|kind| !patch::is_civic_name(&kind.0)) { + return Err(KernelError::Invariant( + "an office lends no canonical authority kind".into(), + )); + } + let current = state + .selection + .get(institution) + .and_then(|offices| offices.get(office)); + if current.is_some_and(|seat| &seat.delegated == delegated) { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } + // A sitting incumbent survives a reconstitution: clipping an + // office's powers under its holder is a political act, not a + // vacancy. + let incumbent = current.and_then(|seat| seat.incumbent); + state.selection.entry(*institution).or_default().insert( + office.clone(), + Office { + incumbent, + delegated: delegated.clone(), + }, + ); + } + ResolvedOp::CloseOffice { + institution, + office, + } + | ResolvedOp::VacateOffice { + institution, + office, + } => { + let closing = matches!(operation, ResolvedOp::CloseOffice { .. }); + require_institution(state, *institution, office)?; + let no_office = || KernelError::Invariant("office operation names no office".into()); + let offices = state.selection.get_mut(institution).ok_or_else(no_office)?; + let occupied = offices + .get(office) + .map(|seat| seat.incumbent.is_some()) + .ok_or_else(no_office)?; + if closing { + offices.remove(office); + let empty = offices.is_empty(); + if empty { + state.selection.remove(institution); + } + } else if !occupied { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } else { + offices.get_mut(office).ok_or_else(no_office)?.incumbent = None; + } + } + ResolvedOp::InstallIncumbent { + institution, + office, + incumbent, + } => { + require_institution(state, *institution, office)?; + if state.subjects.get(incumbent).map(|subject| subject.kind) + != Some(SubjectKind::Person) + { + return Err(KernelError::Invariant( + "an office holder is not a person subject".into(), + )); + } + let offices = state + .selection + .get_mut(institution) + .ok_or_else(|| KernelError::Invariant("office operation names no office".into()))?; + if offices + .iter() + .any(|(name, seat)| name != office && seat.incumbent == Some(*incumbent)) + { + return Err(KernelError::Invariant( + "one person holds two offices of one institution".into(), + )); + } + let seat = offices + .get_mut(office) + .ok_or_else(|| KernelError::Invariant("office operation names no office".into()))?; + if seat.incumbent == Some(*incumbent) { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } + seat.incumbent = Some(*incumbent); + } + ResolvedOp::OpenForum { + grievance, + forum, + standing, + } => { + if !state.subjects.contains_key(forum) + || !authority_referent_exists(state, *standing) + || !patch::is_civic_name(&grievance.0) + { + return Err(unknown()); + } + let seat = Forum { + forum: *forum, + standing: *standing, + }; + if state.redress.get(grievance) == Some(&seat) { + return Err(KernelError::Invariant( + "forum operation changes nothing".into(), + )); + } + state.redress.insert(grievance.clone(), seat); + } + ResolvedOp::CloseForum { grievance } => { + if state.redress.remove(grievance).is_none() { + return Err(KernelError::Invariant( + "forum operation names no forum".into(), + )); + } + } + ResolvedOp::AssertClaim { + fact, + statement, + by, + } => { + if !state.subjects.contains_key(by) || !patch::is_canonical_text(statement.as_str()) { + return Err(KernelError::Invariant( + "a claim names no live asserter or no canonical statement".into(), + )); + } + if state + .entities + .insert( + *fact, + EntityRecord { + label: CLAIM_LABEL.into(), + kind: EntityKind::Fact, + container: None, + }, + ) + .is_some() + || state + .facts + .insert( + *fact, + FactRecord { + statement: statement.clone(), + standing: FactStanding::Claimed { by: *by }, + }, + ) + .is_some() + { + return Err(KernelError::Invariant("minted claim ID collision".into())); + } + } + ResolvedOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let Some(record) = state.facts.get(fact) else { + return Err(KernelError::Invariant( + "knowledge operation names no canonical fact".into(), + )); + }; + if !state.subjects.contains_key(subject) + || (*source == AuthoredSource::Evidenced + && !matches!(record.standing, FactStanding::Canonical { .. })) + { + return Err(KernelError::Invariant( + "knowledge operation names no live subject, or evidences a claim".into(), + )); + } + let source = match source { + AuthoredSource::Witnessed => KnowledgeSource::Witnessed, + AuthoredSource::Evidenced => KnowledgeSource::Evidenced, + }; + // Compared on `confidence` and `source` alone: `acquired_at` is + // this write's own revision, not part of what the author asserts, + // so a re-assertion identical in everything the author controls + // still refuses as a no-op even though it would land a later + // `acquired_at`. + if state + .knowledge + .get(&(*subject, *fact)) + .is_some_and(|held| held.confidence == *confidence && held.source == source) + { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + // Matches `DecisionEvent.revision` and the `minted_at` scan built + // from it (`action::exercise`, `snapshot`): both name the revision + // this commit resolves to. `resolves_to` is `state.revision` itself + // at genesis, which never advances past 0, and `state.revision + 1` + // everywhere else, since `state` still holds the *previous* + // revision until `submit` bumps it. One value, one caller-computed + // source, so a genesis-seeded row cannot land one revision ahead of + // the state it was written into. + let acquired_at = resolves_to; + let entry = Knowledge { + confidence: *confidence, + source, + acquired_at, + }; + state.knowledge.insert((*subject, *fact), entry); + } + ResolvedOp::Forget { subject, fact } => { + if state.knowledge.remove(&(*subject, *fact)).is_none() { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + } + ResolvedOp::Communicate { speaker, fact, to } => { + if !state.subjects.contains_key(speaker) || !state.facts.contains_key(fact) { + return Err(KernelError::Invariant( + "a telling names no live speaker or fact".into(), + )); + } + if !can_broadcast(state, *speaker, to) { + return Err(KernelError::Invariant( + "a speaker is outside its own audience".into(), + )); + } + // An empty fan-out is legal: the delta of a telling is a property of + // the world — an empty room, a silenced channel — not a defect in + // the proposal. Speaking alone commits the claim and lands nothing. + // `acquired_at` matches `minted_at` (PA.f44): both name the + // revision this commit resolves to, `resolves_to` (PA.f49) — + // `state.revision` itself at genesis, `state.revision + 1` + // otherwise. + let acquired_at = resolves_to; + for listener in fan_out(state, *speaker, *fact, to) { + state.knowledge.insert( + (listener, *fact), + Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: *speaker, + via: to.channel(), + }, + acquired_at, + }, + ); + } + } + ResolvedOp::Display { actor, fact } => { + if !state.subjects.contains_key(actor) || !state.facts.contains_key(fact) { + return Err(KernelError::Invariant( + "a display names no live actor or fact".into(), + )); + } + // The room is the audience, re-derived here: the same derivation + // co-located speech uses, so a body and a voice cannot disagree + // about who is in the room. A placeless actor is refused as a + // placeless speaker is; an empty room is a legal no-op, as + // speaking alone is. `Believed` is fixed by the kernel: a + // displayer cannot choose how much a viewer believes its body. + let room = Audience::Colocated; + if !can_broadcast(state, *actor, &room) { + return Err(KernelError::Invariant( + "an actor displays from no place".into(), + )); + } + // The revision the caller's own commit resolves to: `state.revision` + // itself at genesis, which never advances past 0, and + // `state.revision + 1` everywhere else, since `state` still holds + // the *previous* revision until `submit` bumps it. One value, one + // caller-computed source, so a genesis-seeded row cannot land one + // revision ahead of the state it was written into. + let acquired_at = resolves_to; + for viewer in fan_out(state, *actor, *fact, &room) { + state.knowledge.insert( + (viewer, *fact), + Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Seen { by: *actor }, + acquired_at, + }, + ); + } + } + ResolvedOp::Witness { + fact, + place, + confidence, + } => { + if !state.facts.contains_key(fact) + || !state + .entities + .get(place) + .is_some_and(|record| record.kind == EntityKind::Place) + { + return Err(KernelError::Invariant( + "a witness names no live fact or place".into(), + )); + } + // Recipients are derived here and never stored: everyone standing + // under the place, less everyone who already holds the fact. A + // witness that reaches nobody is refused, because a witnessed event + // is only its reception — `resolve_patch` refuses the same case over + // the candidate graph, so the two layers cannot disagree. + let recipients = unheld(state, *fact, under_place(state, *place)); + if recipients.is_empty() { + return Err(KernelError::Invariant( + "a witness reaches nobody who does not already hold the fact".into(), + )); + } + // The revision the caller's own commit resolves to: `state.revision` + // itself at genesis, which never advances past 0, and + // `state.revision + 1` everywhere else, since `state` still holds + // the *previous* revision until `submit` bumps it. One value, one + // caller-computed source, so a genesis-seeded row cannot land one + // revision ahead of the state it was written into. + let acquired_at = resolves_to; + for witness in recipients { + state.knowledge.insert( + (witness, *fact), + Knowledge { + confidence: *confidence, + source: KnowledgeSource::Witnessed, + acquired_at, + }, + ); + } + } + ResolvedOp::SetReach { channel, reach } => { + let current = state + .channels + .get(channel) + .ok_or_else(|| KernelError::Invariant("channel operation names no channel".into()))? + .clone(); + let record = ChannelRecord { + reach: reach.clone(), + controller: current.controller, + }; + if !channel_referents_exist(state, &record) { + return Err(KernelError::Invariant( + "a reach names no live subject or place".into(), + )); + } + if current.reach == *reach { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + state.channels.insert(*channel, record); + } + ResolvedOp::SetController { + channel, + controller, + } => { + if controller.is_some_and(|subject_id| !state.subjects.contains_key(&subject_id)) { + return Err(unknown()); + } + let seat = state.channels.get_mut(channel).ok_or_else(|| { + KernelError::Invariant("channel operation names no channel".into()) + })?; + if seat.controller == *controller { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + seat.controller = *controller; + } + ResolvedOp::CreateCommitment { + subject, + key, + commitment, + } => { + if !state.subjects.contains_key(subject) + || !commitment_is_live(state, *subject, commitment) + { + return Err(KernelError::Invariant( + "a commitment names no live promisor, counterparty, or check".into(), + )); + } + if state + .commitments + .entry(*subject) + .or_default() + .insert(*key, commitment.clone()) + .is_some() + { + return Err(KernelError::Invariant("commitment key collision".into())); + } + } + ResolvedOp::DischargeCommitment { subject, key } => { + // One removal, two writes, one owner: the commitment and every + // pressure row it sourced. + let discharged = || KernelError::Invariant("discharge names no live commitment".into()); + let held = state.commitments.get_mut(subject).ok_or_else(discharged)?; + held.remove(key).ok_or_else(discharged)?; + let empty = held.is_empty(); + if empty { + state.commitments.remove(subject); + } + let sourced = PressureSource::Commitment { + subject: *subject, + key: *key, + }; + for target in pressure_holders(state, sourced) { + let emptied = state.pressures.get_mut(&target).is_some_and(|held| { + held.remove(&sourced); + held.is_empty() + }); + if emptied { + state.pressures.remove(&target); + } + } + } + ResolvedOp::AdvancePressure { source, target, by } + | ResolvedOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ResolvedOp::AdvancePressure { .. }); + if !state.subjects.contains_key(target) || !pressure_source_is_live(state, source) { + return Err(unknown()); + } + let current = state + .pressures + .get(target) + .and_then(|held| held.get(source)) + .map_or(0, |magnitude| magnitude.0); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + if next == current { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, next); + } + ResolvedOp::ResolvePressure { source, target } => { + if state + .pressures + .get(target) + .is_none_or(|held| !held.contains_key(source)) + { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, 0); + } + ResolvedOp::Retire { subject } => { + let held = state.subjects.get_mut(subject).ok_or_else(unknown)?; + if held.retired { + return Err(KernelError::Invariant( + "retire operation names an already retired subject".into(), + )); + } + held.retired = true; + state.positions.remove(subject); + state.affordance_grants.remove(subject); + } + ResolvedOp::GrantAffordance { subject, affordance } + | ResolvedOp::RevokeAffordance { subject, affordance } => { + let granting = matches!(operation, ResolvedOp::GrantAffordance { .. }); + if !state.subjects.contains_key(subject) + || is_retired(state, *subject) + || !state.affordance_catalog.contains_key(affordance) + { + return Err(unknown()); + } + if granting { + if !state + .affordance_grants + .entry(*subject) + .or_default() + .insert(*affordance) + { + return Err(KernelError::Invariant( + "affordance grant operation changes nothing".into(), + )); + } + } else { + let granted = state + .affordance_grants + .get_mut(subject) + .ok_or_else(unknown)?; + if !granted.remove(affordance) { + return Err(KernelError::Invariant( + "affordance grant operation changes nothing".into(), + )); + } + if granted.is_empty() { + state.affordance_grants.remove(subject); + } + } + } + } + Ok(()) +} + +/// Zero removes the source key, and an emptied target removes the target key, +/// so `pressures` has exactly one representation of nothing. +fn set_pressure(state: &mut WorldState, target: SubjectId, source: PressureSource, value: u32) { + if value == 0 { + let empty = if let Some(held) = state.pressures.get_mut(&target) { + held.remove(&source); + held.is_empty() + } else { + false + }; + if empty { + state.pressures.remove(&target); + } + } else { + state + .pressures + .entry(target) + .or_default() + .insert(source, PressureMagnitude(value)); + } +} + +/// Whether every referent a commitment names is live and its shape holds. +/// Re-derived over the committed partitions, because a forged effect reaches +/// `apply_operation` without ever passing the resolver. +fn commitment_is_live(state: &WorldState, subject: SubjectId, commitment: &Commitment) -> bool { + let counterparty_is_live = match commitment.counterparty { + Some(counterparty) => { + counterparty != subject + && state.subjects.contains_key(&counterparty) + && commitment.kind != CommitmentKind::Goal + } + None => true, + }; + counterparty_is_live + && (commitment.kind == CommitmentKind::Routine) == commitment.period.is_some() + && (commitment.kind == CommitmentKind::Routine || commitment.checks.is_empty()) + && commitment.due > state.header.now + && commitment + .checks + .iter() + .all(|check| bound_precondition_is_live(state, check)) +} + +fn bound_precondition_is_live(state: &WorldState, check: &BoundPrecondition) -> bool { + let is_kind = |entity_id: &EntityId, kind: EntityKind| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == kind) + }; + let audience_is_live = |via: &Audience| match via { + Audience::Colocated => true, + Audience::Channel(entity_id) => state.channels.contains_key(entity_id), + }; + match check { + BoundPrecondition::Present { at } => is_kind(at, EntityKind::Place), + BoundPrecondition::Reachable { to, within } => { + is_kind(to, EntityKind::Place) && patch::is_valid_cost(*within) + } + BoundPrecondition::Holds { resource, .. } => is_kind(resource, EntityKind::Resource), + BoundPrecondition::Authorized { over, kind } => { + patch::is_civic_name(&kind.0) + && match over { + Target::Subject(subject_id) => state.subjects.contains_key(subject_id), + Target::Entity(entity_id) => is_kind(entity_id, EntityKind::Place), + Target::Edge(edge_id) => state.edges.contains_key(edge_id), + } + } + BoundPrecondition::HasStanding { grievance } => patch::is_civic_name(&grievance.0), + BoundPrecondition::Knows { fact, .. } => is_kind(fact, EntityKind::Fact), + BoundPrecondition::CanBroadcast { via } => audience_is_live(via), + BoundPrecondition::CanReach { subject, via } => { + state.subjects.contains_key(subject) && audience_is_live(via) + } + BoundPrecondition::Committed { to, .. } => state.subjects.contains_key(to), + } +} + +fn pressure_source_is_live(state: &WorldState, source: &PressureSource) -> bool { + match source { + PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|held| held.contains_key(key)), + PressureSource::Dependency(target) => dependency_target_exists(state, *target), + PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + } +} + +/// The label every minted claim carries. A label is a name, not a transcript: +/// the statement is never copied into it and the label is never derived from +/// it. Labels resolve no references, so identical labels across every claim +/// are unremarkable. The statement itself lives in `facts[fact].statement` +/// and is also carried inside the committed `AssertClaim` effect on the +/// event that minted it; `facts` is the one readable home a projection may +/// consult, and the event copy is the replay witness, never a second read +/// surface. +const CLAIM_LABEL: &str = "claim"; + +/// Whether a channel's reach and controller name live structure. +fn channel_referents_exist(state: &WorldState, record: &ChannelRecord) -> bool { + let reach = match &record.reach { + Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + Reach::Place(place) => state + .entities + .get(place) + .is_some_and(|entity| entity.kind == EntityKind::Place), + }; + reach + && record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) +} + +impl WorldState { + /// Whether a subject, retired or not, holds this import key. One point read + /// of `ByImportKey`. + fn import_key_held(&self, key: &ImportKey) -> bool { + !self.subjects.indexed(key.clone()..=key.clone()).is_empty() + } + + /// Whether a catalog entry already names this affordance kind. + fn kind_taken(&self, kind: &AffordanceKindName) -> bool { + !self.affordance_catalog.indexed(kind.clone()..=kind.clone()).is_empty() + } +} + +/// What `import_key_held` and `kind_taken` were before their indexes: every +/// subject, every catalog entry. The index reads must equal them. +#[cfg(test)] +fn import_key_held_by_scan(state: &WorldState, key: &ImportKey) -> bool { + state.subjects.values().any(|subject| subject.import_key.as_ref() == Some(key)) +} + +#[cfg(test)] +fn kind_taken_by_scan(state: &WorldState, kind: &AffordanceKindName) -> bool { + state.affordance_catalog.values().any(|entry| &entry.kind == kind) +} + +/// Whether a subject is retired: the one statement of retirement, read by +/// audience derivation, preconditions and resolvers. Only an actual `Retire` +/// sets `SubjectState.retired`. +pub(crate) fn is_retired(state: &WorldState, subject_id: SubjectId) -> bool { + state + .subjects + .get(&subject_id) + .is_some_and(|subject| subject.retired) +} + +/// Everyone standing anywhere under one place. The one downward-facing read of +/// `positions`: `audience`'s `Reach::Place` arm and `ResolvedOp::Witness` are +/// its two callers, so what "under a place" means cannot drift between a +/// declared broadcast area and a witnessed event. A subject with no position is +/// under nothing. +fn under_place(state: &WorldState, root: EntityId) -> BTreeSet { + // The subtree by `ChildOf`, collecting who stands in each place. Containment + // is acyclic (`admit_resolved` refuses a chain that does not terminate); the + // visited set keeps the walk total regardless. + let mut under = BTreeSet::new(); + let mut seen = BTreeSet::new(); + let mut frontier = vec![root]; + while let Some(place) = frontier.pop() { + if !seen.insert(place) { + continue; + } + under.extend( + state + .positions + .indexed(place..=place) + .into_iter() + .map(|(_, subject_id)| subject_id), + ); + frontier.extend( + state + .entities + .indexed(place..=place) + .into_iter() + .map(|(_, child)| child), + ); + } + under +} + +/// What `under_place` was before the index: every position, asked whether its +/// place is covered. The index read must equal it. +#[cfg(test)] +fn under_place_by_scan(state: &WorldState, root: EntityId) -> BTreeSet { + state + .positions + .iter() + .filter(|(_, position)| patch::covers_place(&state.entities, root, position.place)) + .map(|(subject_id, _)| *subject_id) + .collect() +} + +/// The one statement of reach. Called by both speech preconditions, by a +/// `Communicate`'s admission, and by its apply. Nothing else computes an +/// audience. +/// +/// Co-location is the actor's exact place, not its subtree: a voice fills a +/// room, not the district containing it. A channel's `Reach::Place` is +/// deliberately wider, because a declared broadcast area is a declared choice. +fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet { + match of { + Audience::Colocated => { + let Some(here) = state.positions.get(&actor).copied() else { + return BTreeSet::new(); + }; + state + .positions + .indexed(here.place..=here.place) + .into_iter() + .map(|(_, subject_id)| subject_id) + .collect() + } + Audience::Channel(channel) => { + let Some(record) = state.channels.get(channel) else { + return BTreeSet::new(); + }; + match &record.reach { + // Audience derivation is the one owner of who is reachable, so + // a channel may still *declare* a retired member (PA.f33); + // retirement is filtered here, at the single read site, not at + // declaration time. + Reach::Subjects(members) => members + .iter() + .copied() + .filter(|member| !is_retired(state, *member)) + .collect(), + Reach::Place(root) => under_place(state, *root), + } + } + } +} + +/// What `audience` was before the index: every position compared with the +/// actor's, and `under_place_by_scan` for a channel's place. The index read +/// must equal it. +#[cfg(test)] +fn audience_by_scan(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet { + match of { + Audience::Colocated => { + let Some(here) = state.positions.get(&actor).copied() else { + return BTreeSet::new(); + }; + state + .positions + .iter() + .filter(|(_, position)| **position == here) + .map(|(subject_id, _)| *subject_id) + .collect() + } + Audience::Channel(channel) => match state.channels.get(channel).map(|record| &record.reach) { + Some(Reach::Place(root)) => under_place_by_scan(state, *root), + _ => audience(state, actor, of), + }, + } +} + +/// Whether an actor may broadcast into an audience: either the actor stands +/// inside the declared reach, or — for a channel — the actor is that +/// channel's controller. The controller's privilege is narrow: it lets the +/// horn sound from outside the room, but it does not admit the controller to +/// the audience itself. A controller outside its channel's reach gains no +/// knowledge from its own telling and is not a target another actor can +/// reach through that channel; `audience()` stays the one statement of who is +/// inside, and this is the one statement of who may speak. +fn can_broadcast(state: &WorldState, actor: SubjectId, of: &Audience) -> bool { + if audience(state, actor, of).contains(&actor) { + return true; + } + match of { + Audience::Channel(channel) => state + .channels + .get(channel) + .is_some_and(|record| record.controller == Some(actor)), + Audience::Colocated => false, + } +} + +/// A knowledge landing never overwrites and never downgrades a holder: whoever +/// already holds the fact is dropped, whatever it holds and however it came by +/// it. The knower owns its own credence, and a landing that could reset it by +/// repeating itself would own another subject's mind through an effect nobody +/// checked. `fan_out` and `ResolvedOp::Witness` are the two callers, so a +/// telling and a witnessed event cannot disagree about who is already a knower. +fn unheld( + state: &WorldState, + fact: EntityId, + listeners: BTreeSet, +) -> BTreeSet { + listeners + .into_iter() + .filter(|listener| { + !state.knowledge.contains_key(&(*listener, fact)) + }) + .collect() +} + +/// Who gains knowledge from one telling: the audience, less the speaker, less +/// anyone who already holds the fact. `Believed` is fixed by the kernel and is +/// not a field on the operation, so a speaker cannot choose how much a listener +/// believes it. +fn fan_out( + state: &WorldState, + speaker: SubjectId, + fact: EntityId, + to: &Audience, +) -> BTreeSet { + let mut listeners = audience(state, speaker, to); + listeners.remove(&speaker); + unheld(state, fact, listeners) +} + +/// Whether an authority target names a live subject or a live place. +fn authority_referent_exists(state: &WorldState, target: AuthorityTarget) -> bool { + match target { + AuthorityTarget::Subject(subject_id) => state.subjects.contains_key(&subject_id), + AuthorityTarget::PlaceSubtree(entity_id) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Place), + } +} + +/// The shared half of every office operation: a canonical office name on a live +/// institution subject. +fn require_institution( + state: &WorldState, + institution: SubjectId, + office: &OfficeName, +) -> Result<(), KernelError> { + if !patch::is_civic_name(&office.0) { + return Err(KernelError::Invariant( + "office name is not canonical".into(), + )); + } + if state.subjects.get(&institution).map(|subject| subject.kind) + != Some(SubjectKind::Institution) + { + return Err(KernelError::Invariant( + "an office was opened on a subject that is not an institution".into(), + )); + } + Ok(()) +} + +/// The subject, if any, whose effective authority holds two grants of one kind +/// over overlapping ground. Re-derived over the committed partitions after every +/// batch that could widen a jurisdiction, so a forged effect cannot install the +/// split-brained state the resolver refuses. +fn overlapping_holder(state: &WorldState) -> Option { + let holders: BTreeSet = state + .authority + .keys() + .copied() + .chain( + state + .selection + .values() + .flat_map(|offices| offices.values()) + .filter_map(|office| office.incumbent), + ) + .collect(); + holders.into_iter().find(|holder| holder_overlaps(state, *holder)) +} + +/// Whether one subject's effective authority holds two grants of one kind over +/// overlapping ground. The pairwise check `overlapping_holder` runs over every +/// holder, and `apply_operations` over the holders a transaction touched. +fn holder_overlaps(state: &WorldState, holder: SubjectId) -> bool { + let effective: Vec = subject_authority(state, holder).into_iter().collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind && patch::targets_overlap(&state.entities, one.over, other.over) + }) + }) +} + +/// Exactly the components a subject's verification reads. One owner, consumed by +/// `action::exercise` and by the snapshot, so the two cannot drift. `routes` is +/// every edge whose `from` or `to` is the subject's place: an inbound route +/// decides who can arrive, and reading too little is a correctness hole while +/// reading too much only costs an extra rejection. `holdings` and `dependencies` +/// are the acting subject's own; a counterparty's holdings do not enter, because +/// a transfer changes both subjects' components. +/// It also holds what the actor *is* authorized over, and nothing about the +/// world the actor reaches: the target's position, the target's container +/// chain, the forum's state, and any subordinate's components stay out. A +/// target that walks out of a jurisdiction mid-flight fails at `Authorized` +/// at commit, and a revoked grant fails the same way. +/// +/// `Deserialize` is here so the narrative lane can persist a subject's own +/// components as the "before" an interruption is measured against. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ScopeComponents { + position: Option, + routes: BTreeMap, + holdings: BTreeMap, + dependencies: BTreeSet, + /// This subject's own grants. + authority: BTreeSet, + /// What each held office lends: for every office whose incumbent is this + /// subject, the institution's live grants whose kind that office delegates. + /// The institution's authority is copied in through the office link, so one + /// scope covers the grant, the office, and the institution's jurisdiction, + /// and only delegated kinds enter — an institution's `judge` jurisdiction + /// never reaches a `levy`-only incumbent. + delegated: BTreeMap>>, + /// The keys of this subject's own knowledge. Keys, not payloads: a statement + /// is immutable, so it cannot change without the key changing, and + /// confidence is admission-only — a re-appraisal that lowers a subject's own + /// confidence does not reject its own in-flight proposal, because `Knows` + /// re-checks at commit and fails closed with `FactUnknown`. + knows: BTreeSet, + /// The channels this subject controls, with their records. Membership of a + /// channel it merely hears never enters: a 1,000-member channel would churn + /// a thousand scopes per membership change. + controls: BTreeMap, + /// This subject's own commitments. `Precondition::Committed` reads them, so + /// they are in scope. Pressure and the clock stay out: no precondition reads + /// either. + commitments: BTreeMap, +} + +/// Whether an authority target covers a referent. The one statement of +/// jurisdictional membership, reached by `Authorized`, `HasStanding`, +/// `route_admits`, the delegation monotonicity rule, and the snapshot's redress +/// projection. +/// +/// A place subtree covers a subject standing anywhere under it, a place under +/// it, and a route with either endpoint under it — a city must be able to close +/// its own gate, and a gate's far end is outside the city by construction. A +/// resource, fact, or channel is covered by nothing; `RoleKindUnfit` refuses an +/// `Authorized` over such a role at declaration. +fn covers(state: &WorldState, target: AuthorityTarget, of: Target) -> bool { + let under = |place: EntityId, root: EntityId| patch::covers_place(&state.entities, root, place); + match (target, of) { + (AuthorityTarget::Subject(holder), Target::Subject(subject_id)) => holder == subject_id, + (AuthorityTarget::Subject(_), _) => false, + (AuthorityTarget::PlaceSubtree(root), Target::Subject(subject_id)) => state + .positions + .get(&subject_id) + .is_some_and(|position| under(position.place, root)), + (AuthorityTarget::PlaceSubtree(root), Target::Entity(entity_id)) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Place && under(entity_id, root)), + (AuthorityTarget::PlaceSubtree(root), Target::Edge(edge_id)) => { + state.edges.get(&edge_id).is_some_and(|record| { + let (from, to) = record.endpoints(); + under(from, root) || under(to, root) + }) + } + } +} + +/// Own grants plus what every held office lends. The single statement of what a +/// subject may invoke authority over. There is no precedence between a direct +/// grant and a delegated one, because `OverlappingJurisdiction` makes it +/// impossible for both to answer for one kind over overlapping ground. +fn effective_authority( + own: &BTreeSet, + delegated: &BTreeMap>>, +) -> BTreeSet { + let mut effective = own.clone(); + for lent in delegated.values().flat_map(|offices| offices.values()) { + effective.extend(lent.iter().cloned()); + } + effective +} + +/// Every office this subject occupies, keyed by institution, with what each one +/// lends of that institution's live grants. +fn delegated_authority( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap>> { + let mut held: BTreeMap>> = + BTreeMap::new(); + for (_, institution) in state.selection.indexed(subject_id..=subject_id) { + lend_offices(state, subject_id, institution, &state.selection[&institution], &mut held); + } + held +} + +/// What one institution's offices lend `subject_id`, added to `held`. +fn lend_offices( + state: &WorldState, + subject_id: SubjectId, + institution: SubjectId, + offices: &BTreeMap, + held: &mut BTreeMap>>, +) { + // A retired institution lends nothing: `Retire` does not vacate + // offices, so the incumbency stays on record, but a dissolved + // institution's grants stop reaching its office-holders here, the one + // site that turns an office into effective authority. + if is_retired(state, institution) { + return; + } + for (name, office) in offices { + if office.incumbent != Some(subject_id) { + continue; + } + let lent: BTreeSet = state + .authority + .get(&institution) + .into_iter() + .flatten() + .filter(|grant| office.delegated.contains(&grant.kind)) + .cloned() + .collect(); + held.entry(institution) + .or_default() + .insert(name.clone(), lent); + } +} + +/// What `delegated_authority` was before the index: every institution. +#[cfg(test)] +fn delegated_authority_by_scan( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap>> { + let mut held = BTreeMap::new(); + for (institution, offices) in &state.selection { + lend_offices(state, subject_id, *institution, offices, &mut held); + } + held +} + +/// The effective authority of one subject read straight from the partitions, +/// for the reducer paths that do not already hold a `ScopeComponents`. +fn subject_authority(state: &WorldState, subject_id: SubjectId) -> BTreeSet { + let empty = BTreeSet::new(); + effective_authority( + state.authority.get(&subject_id).unwrap_or(&empty), + &delegated_authority(state, subject_id), + ) +} + +/// The routes with an end at `place`, keyed by edge. +fn routes_at(state: &WorldState, place: EntityId) -> BTreeMap { + state + .edges + .indexed(place..=place) + .into_iter() + .map(|(_, edge_id)| (edge_id, state.edges[&edge_id].clone())) + .collect() +} + +#[cfg(test)] +fn routes_at_by_scan(state: &WorldState, place: EntityId) -> BTreeMap { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == place || to == place + }) + .map(|(edge_id, record)| (*edge_id, record.clone())) + .collect() +} + +/// The channels `subject_id` controls, with their records. +fn channels_controlled_by( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap { + state + .channels + .indexed(subject_id..=subject_id) + .into_iter() + .map(|(_, entity_id)| (entity_id, state.channels[&entity_id].clone())) + .collect() +} + +#[cfg(test)] +fn channels_controlled_by_by_scan( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap { + state + .channels + .iter() + .filter(|(_, record)| record.controller == Some(subject_id)) + .map(|(entity_id, record)| (*entity_id, record.clone())) + .collect() +} + +/// The subjects with a pressure row from `source`. +fn pressure_holders(state: &WorldState, source: PressureSource) -> Vec { + state + .pressures + .indexed(source..=source) + .into_iter() + .map(|(_, target)| target) + .collect() +} + +#[cfg(test)] +fn pressure_holders_by_scan(state: &WorldState, source: PressureSource) -> Vec { + state + .pressures + .iter() + .filter(|(_, held)| held.contains_key(&source)) + .map(|(target, _)| *target) + .collect() +} + +fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponents { + let position = state.positions.get(&subject_id).copied(); + let routes = position + .map(|position| routes_at(state, position.place)) + .unwrap_or_default(); + ScopeComponents { + position, + routes, + holdings: state.holdings.get(&subject_id).cloned().unwrap_or_default(), + dependencies: state + .dependencies + .get(&subject_id) + .cloned() + .unwrap_or_default(), + authority: state + .authority + .get(&subject_id) + .cloned() + .unwrap_or_default(), + delegated: delegated_authority(state, subject_id), + knows: state + .knowledge_of(subject_id) + .map(|(fact, _)| *fact) + .collect(), + controls: channels_controlled_by(state, subject_id), + commitments: state + .commitments + .get(&subject_id) + .cloned() + .unwrap_or_default(), + } +} + +fn snapshot( + state: &WorldState, + journal: &journal::WorldJournal, +) -> Result { + // One pass over the causal record so each subject's own knowledge map can be + // stamped with the revision that minted each claim it holds. + let minted_at: BTreeMap = journal + .acted_events() + .flat_map(|event| { + event + .speech + .into_iter() + .chain(event.display) + .map(move |fact| (fact, event.revision)) + }) + .collect(); + // One pass over the causal record so each subject can be stamped with the + // revision of its own last exercised decision. `None` for a subject that + // never acted. + let last_acted_at: BTreeMap = + journal + .acted_events() + .fold(BTreeMap::new(), |mut acc, event| { + let entry = acc.entry(event.actor).or_insert(event.revision); + if event.revision > *entry { + *entry = event.revision; + } + acc + }); + let subjects = state + .subjects + .iter() + .map(|(subject_id, subject)| { + let affordances = state + .affordance_grants + .get(subject_id) + .cloned() + .unwrap_or_default(); + let components = scope_components(state, *subject_id); + let offices_held = components + .delegated + .iter() + .flat_map(|(institution, offices)| { + offices + .iter() + .map(move |(office, authority)| OfficeSnapshot { + institution: *institution, + office: office.clone(), + incumbent: Some(*subject_id), + authority: authority.clone(), + }) + }) + .collect(); + let offices_granted = state + .selection + .get(subject_id) + .into_iter() + .flatten() + .map(|(office, seat)| OfficeSnapshot { + institution: *subject_id, + office: office.clone(), + incumbent: seat.incumbent, + authority: state + .authority + .get(subject_id) + .into_iter() + .flatten() + .filter(|grant| seat.delegated.contains(&grant.kind)) + .cloned() + .collect(), + }) + .collect(); + let redress = state + .redress + .iter() + .filter(|(_, forum)| covers(state, forum.standing, Target::Subject(*subject_id))) + .map(|(grievance, forum)| ForumSnapshot { + grievance: grievance.clone(), + forum: forum.forum, + }) + .collect(); + // The sole perception surface, derived here rather than in a + // controller: a controller that recomputed perception would be a + // second answer to who heard what. + let mut knowledge: Vec = state + .knowledge_of(*subject_id) + .map(|(fact, held)| { + let record = state.facts.get(fact).ok_or_else(|| { + KernelError::Invariant("knowledge names no canonical fact".into()) + })?; + Ok(KnowledgeSnapshot { + fact: *fact, + statement: record.statement.clone(), + standing: match &record.standing { + FactStanding::Canonical { .. } => FactStandingView::Canonical, + FactStanding::Claimed { by } => FactStandingView::Claimed { by: *by }, + FactStanding::Ruled => FactStandingView::Canonical, + }, + confidence: held.confidence, + source: held.source, + minted_at: minted_at.get(fact).copied(), + acquired_at: held.acquired_at, + }) + }) + .collect::, KernelError>>()?; + knowledge.sort_by_key(|entry| (entry.minted_at, entry.fact)); + Ok(SubjectSnapshot { + id: *subject_id, + label: subject.label.clone(), + kind: subject.kind, + import_key: subject.import_key.clone(), + affordances, + position: components.position.map(|position| position.place), + retired: subject.retired, + offices_held, + offices_granted, + redress, + knowledge, + commitments: components + .commitments + .iter() + .map(|(key, commitment)| CommitmentSnapshot { + key: *key, + kind: commitment.kind, + counterparty: commitment.counterparty, + due: commitment.due, + period: commitment.period, + statement: commitment.statement.clone(), + past_due: commitment.due <= state.header.now, + }) + .collect(), + dependencies: components.dependencies.iter().copied().collect(), + components, + pressures: state + .pressures + .get(subject_id) + .into_iter() + .flatten() + .map(|(source, magnitude)| PressureSnapshot { + source: *source, + magnitude: *magnitude, + }) + .collect(), + last_acted_at: last_acted_at.get(subject_id).copied(), + }) + }) + .collect::, KernelError>>()?; + let places = state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Place) + .map(|(entity_id, record)| PlaceSnapshot { + id: *entity_id, + label: record.label.clone(), + container: record.container, + }) + .collect(); + let resources = state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Resource) + .map(|(entity_id, record)| ResourceSnapshot { + id: *entity_id, + label: record.label.clone(), + }) + .collect(); + let routes = state + .edges + .iter() + .map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + RouteSnapshot { + id: *edge_id, + label: record.label().to_owned(), + from, + to, + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + } + }) + .collect(); + let channels = state + .channels + .iter() + .map(|(entity_id, record)| ChannelSnapshot { + id: *entity_id, + reach: record.reach.clone(), + controller: record.controller, + }) + .collect(); + // Omniscient and independent of any subject's own knowledge projection: + // a fact nobody has been told or shown is still a row here, and a + // `Ruled` fact keeps its real standing rather than the `Canonical` + // collapse every subject-facing knowledge row applies. + let facts = state + .facts + .iter() + .map(|(fact_id, record)| FactSnapshot { + id: *fact_id, + statement: record.statement.clone(), + standing: match &record.standing { + FactStanding::Canonical { .. } => FactStandingView::Canonical, + FactStanding::Claimed { by } => FactStandingView::Claimed { by: *by }, + FactStanding::Ruled => FactStandingView::Ruled, + }, + known_by: state + .knowledge + .keys() + .filter(|(_, fact)| fact == fact_id) + .map(|(subject_id, _)| *subject_id) + .collect(), + }) + .collect(); + Ok(WorldSnapshot { + world_id: state.header.world_id, + revision: state.revision, + owner: state.header.owner.clone(), + title: state.header.title.clone(), + grammar: state.header.grammar.as_ref().map(GrammarBinding::identity), + subjects, + affordances: state + .affordance_catalog + .iter() + .map(|(affordance_id, entry)| AffordanceSnapshot { + id: *affordance_id, + entry: entry.clone(), + render_path: state + .header.grammar + .as_ref() + .and_then(|grammar| grammar.verb(&entry.kind.0)) + .map(|verb| verb.render_path), + }) + .collect(), + places, + resources, + routes, + channels, + facts, + now: state.header.now, + state_digest: state.state_digest.clone(), + last_commit_digest: state.last_commit_digest.clone(), + }) +} + +/// One affordance the kernel has already gated: the actor holds this entry, and `entry` is its catalog definition. It is the +/// only way to name an affordance to `action::exercise`, so a caller cannot +/// reach the invocation pipeline without passing the grant check first. +pub(crate) struct GrantedAffordance<'a> { + pub(crate) id: AffordanceId, + pub(crate) entry: &'a Affordance, +} + +/// The grant check, shared by `reduce` and `apply_effect`: the actor's own +/// entry set holds the affordance and the catalog defines it. It returns the +/// entry rather than a unit, so the gate and the lookup are one act, and it is +/// the only constructor of `GrantedAffordance`. Retire removes a subject's +/// grants, so a retired actor holds nothing. +fn require_granted<'a>( + state: &'a WorldState, + actor: SubjectId, + affordance: AffordanceId, +) -> Result, KernelError> { + if !state + .affordance_grants + .get(&actor) + .is_some_and(|granted| granted.contains(&affordance)) + { + return Err(KernelError::AffordanceDenied); + } + let entry = state + .affordance_catalog + .get(&affordance) + .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into()))?; + Ok(GrantedAffordance { + id: affordance, + entry, + }) +} + +/// Genesis may not rule or mint: only Play authors a `Ruled` fact or a `Mint`, +/// and Play only writes after genesis. One `Mismatch::RuledWithoutAuthority` +/// per `Ruled` fact and per `Mint`, and `Ok` if there are none. Called by +/// `prepare_creation` and by `WorldState::genesis` at replay. The resolver +/// stays actor-blind: this runs after resolution, never inside it. +fn forbid_rulings_at_genesis(resolved: &ResolvedPatch) -> Result<(), Vec> { + let mut mismatches = Vec::new(); + for declared in &resolved.facts { + if matches!(declared.fact.standing, FactStanding::Ruled) { + mismatches.push(Mismatch::RuledWithoutAuthority { + site: Site::Declaration(declared.handle.clone()), + }); + } + } + for (index, operation) in resolved.operations.iter().enumerate() { + if matches!(operation, ResolvedOp::Mint { .. }) { + mismatches.push(Mismatch::RuledWithoutAuthority { + site: Site::Operation(index), + }); + } + } + if mismatches.is_empty() { + Ok(()) + } else { + Err(mismatches) + } +} + +fn normalize_title(value: &str) -> Result { + let value = value.trim(); + if value.is_empty() { + Err(KernelError::EmptyTitle) + } else { + Ok(value.to_owned()) + } +} + +fn validate_principal(value: &PrincipalId) -> Result<(), KernelError> { + if value.0.trim().is_empty() || value.0.trim() != value.0 { + Err(KernelError::EmptyPrincipal) + } else { + Ok(()) + } +} + +/// The revision a non-genesis commit resolves to: one past `state.revision`, +/// which still holds the *previous* revision here, since `submit` only bumps +/// it after `apply_effect` returns. Genesis is not a caller: it resolves to +/// `state.revision` itself and computes that directly (PA.f49). +fn resolution_revision(state: &WorldState) -> Result { + state + .revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into())) +} + +/// `command_id` is the band draw's only per-command term, so the arm that +/// re-derives an exercised decision needs the same one `reduce` drew from. +fn apply_effect( + state: &mut WorldState, + command_id: CommandId, + caller: &CallerId, + effect: &WorldEffect, +) -> Result<(), KernelError> { + // The admission rule `reduce` decided, re-decided here. + require_play(caller)?; + match effect { + WorldEffect::WorldCreated { .. } => { + return Err(KernelError::Invariant( + "world genesis cannot be applied as a mutable effect".into(), + )); + } + WorldEffect::PatchAdmitted { resolved } => { + let resolves_to = resolution_revision(state)?; + admit_resolved(state, resolved, resolves_to)?; + } + WorldEffect::Acted { invocation, event } => { + let granted = require_granted(state, event.actor, invocation.affordance)?; + // The whole event is re-derived by the function that produced the + // honest one, so a forged band, operation, magnitude, minted claim, + // or utterance is one comparison rather than a clause apiece. + let derived = + action::exercise(state, command_id, event.actor, &granted, invocation)?; + if derived != *event { + return Err(KernelError::Invariant( + "acted effect does not derive from the actor's grants".into(), + )); + } + if !event.effects.is_empty() { + // `derived != *event` above already proved `event.revision` is + // exactly what `resolution_revision(state)` would compute right + // now; read it back rather than computing it a second time. + apply_operations(state, &event.effects, &[], event.revision)?; + } + } + WorldEffect::TimeAdvanced { + minutes, + to, + motion, + } => { + let derived_to = state + .header.now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // The whole motion is re-derived rather than trusted field by + // field, so a forged fulfilment, magnitude, row, and target are one + // comparison. + if derived_to != *to || clock::derive_motion(state, derived_to) != *motion { + return Err(KernelError::Invariant( + "time effect does not derive from the world clock".into(), + )); + } + state.header.get_mut().now = *to; + for rolled in &motion.fulfilled { + let commitment = state + .commitments + .get_mut(&rolled.subject) + .and_then(|held| held.get_mut(&rolled.key)) + .ok_or_else(|| { + KernelError::Invariant("a fulfilled routine has no commitment".into()) + })?; + commitment.due = rolled.next_due; + } + // No inner map is ever left empty, because `derive_motion` emits no + // zero magnitude. + for written in &motion.pressed { + state + .pressures + .entry(written.target) + .or_default() + .insert(written.source, written.magnitude); + } + } + } + Ok(()) +} + +fn digest(value: &T) -> Result { + let bytes = rmp_serde::to_vec_named(value) + .map_err(|error| KernelError::Serialization(error.to_string()))?; + Ok(format!("sha256:{:x}", Sha256::digest(bytes))) +} + +fn commit_digest(commit: &WorldCommit) -> Result { + let mut value = commit.clone(); + value.digest.clear(); + digest(&value) +} + +#[cfg(test)] +mod tests { + use super::patch::kernel_speak_grant; + use super::*; + + /// What a committed event actually asserted, read from the one readable + /// home of an utterance: `facts[fact].statement`. The committed event's + /// own `AssertClaim` effect carries the same bytes as the replay witness, + /// but no projection reads that copy; `facts` is the surface. + pub(crate) fn spoken<'a>(state: &'a WorldState, event: &DecisionEvent) -> Option<&'a str> { + event + .speech + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.as_str()) + } + + pub(crate) fn owner() -> PrincipalId { + PrincipalId::new("owner@example.test") + } + + pub(crate) fn human_principal() -> PrincipalId { + PrincipalId::new("human@example.test") + } + + pub(crate) fn auth_principal(principal: PrincipalId) -> AuthenticatedCaller { + AuthenticatedCaller::fixture(CallerId::Principal(principal)) + } + + pub(crate) fn subject( + handle: &str, + label: &str, + kind: SubjectKind, + ) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + affordances: kernel_speak_grant(), + // The fixture world is one room. Co-located speech needs a place to + // fill, so every fixture subject stands in the commons. + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), + import_key: None, + }) + } + + /// The one place the base fixture world declares. + pub(crate) const COMMONS: &str = "commons"; + + /// How many entities the base fixture world admits at genesis: the commons + /// and nothing else. A patch-lane test that proves a rejection allocated + /// nothing compares against this rather than against zero. + pub(crate) const FIXTURE_ENTITIES: usize = 1; + + /// The committed Speak entry. A post-genesis declaration grants it by + /// canonical reference, like every other structure a previous commit + /// allocated: the kernel synthesizes the entry once, at genesis. + pub(crate) fn speak_entry(kernel: &WorldKernel) -> Ref { + Ref::Existing( + *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "speak") + .map(|(affordance_id, _)| affordance_id) + .expect("genesis admits the kernel Speak entry"), + ) + } + + /// A catalog entry by kind name. An affordance id names an entry, not a + /// subject's copy of one, so a test that needs an entry a scope does not + /// hold asks for it by name rather than by list position. + pub(crate) fn affordance_named(snapshot: &WorldSnapshot, kind: &str) -> AffordanceId { + snapshot + .affordances + .iter() + .find(|entry| entry.entry.kind.0 == kind) + .map(|entry| entry.id) + .expect("the fixture world declares this affordance") + } + + pub(crate) fn creation(title: &str) -> CreateWorld { + CreateWorld { + owner: owner(), + title: title.into(), + patch: WorldPatch { + operations: Vec::new(), + evidence: Vec::new(), + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(COMMONS), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), + // A second, world-declared entry granted to exactly one + // subject, so the fixture world has more than one verb and + // grant sets differ between scopes. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("convene"), + kind: AffordanceKindName("convene".into()), + roles: Vec::new(), + // A speech-carrying entry must name exactly one + // audience for the lowering to read. + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + subject( + "human", + "The Human", + SubjectKind::Person, + ), + subject( + "persona", + "The Witness", + SubjectKind::Person, + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("operator"), + label: "The Council".into(), + kind: SubjectKind::Institution, + affordances: kernel_speak_grant() + .into_iter() + .chain(std::iter::once(Ref::Draft(DraftHandle::new("convene")))) + .collect(), + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), + import_key: None, + }), + ], + }, + grammar: None, + } + } + + pub(crate) fn command( + snapshot: &WorldSnapshot, + caller: CallerId, + body: CommandBody, + ) -> CommandEnvelope { + CommandEnvelope { + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller, + body, + } + } + + /// The smallest Play command that commits: a one-minute clock advance. + pub(crate) fn tick_body(minutes: u32) -> CommandBody { + CommandBody::AdvanceTime { + minutes: TickMinutes::new(minutes).expect("a valid span"), + } + } + + pub(crate) fn play_command(snapshot: &WorldSnapshot, body: CommandBody) -> CommandEnvelope { + command(snapshot, CallerId::Play, body) + } + + pub(crate) fn submit_play( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + body: CommandBody, + ) -> CommitReceipt { + kernel + .submit( + command( + snapshot, + CallerId::Play, + body, + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap() + } + + /// The canonical IDs of the shared topology fixture: three places, four + /// routes with every access and open combination the operations read, and one + /// subject standing in the yard. + pub(crate) struct Topology { + pub(crate) yard: EntityId, + pub(crate) road: EntityId, + pub(crate) gate: EntityId, + pub(crate) ramp: EdgeId, + pub(crate) shutter: EdgeId, + pub(crate) toll: EdgeId, + pub(crate) span: EdgeId, + pub(crate) walker: SubjectId, + } + + fn place(handle: &str, label: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: None, + }) + } + + fn way( + handle: &str, + label: &str, + from: &str, + to: &str, + access: AccessKind, + cost: u32, + ) -> Declaration { + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + from: Ref::Draft(DraftHandle::new(from)), + to: Ref::Draft(DraftHandle::new(to)), + access, + cost: Cost(cost), + }) + } + + pub(crate) fn topology_patch(speak: Ref) -> WorldPatch { + WorldPatch { + declarations: vec![ + place("yard", "The Cavity Yard"), + place("road", "The Rhythm Road"), + place("gate", "The Rain Gate"), + way( + "ramp", + "The Yard Ramp", + "yard", + "road", + AccessKind::Public, + 12, + ), + way( + "shutter", + "The Yard Shutter", + "yard", + "gate", + AccessKind::Public, + 5, + ), + way( + "toll", + "The Toll Stair", + "yard", + "gate", + AccessKind::Restricted { + requires: AuthorityKindName(ADMIT_KIND.into()), + }, + 4, + ), + way( + "span", + "The Western Span", + "road", + "gate", + AccessKind::Public, + 7, + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("walker"), + label: "The Walker".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Draft(DraftHandle::new("yard"))), + import_key: None, + }), + ], + // A route that should start closed is declared and closed in one + // patch, so `open` keeps a single writer family. + operations: vec![ComponentOp::CloseRoute { + route: Ref::Draft(DraftHandle::new("shutter")), + }], + evidence: Vec::new(), + } + } + + pub(crate) fn admit_topology(kernel: &mut WorldKernel) -> Topology { + let before = kernel.snapshot().unwrap(); + let receipt = submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: topology_patch(speak_entry(kernel)), + }, + ); + assert!(receipt.resulting_revision > 0); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared place") + .0 + }; + let edge = |label: &str| { + *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == label) + .expect("a declared route") + .0 + }; + Topology { + yard: entity("The Cavity Yard"), + road: entity("The Rhythm Road"), + gate: entity("The Rain Gate"), + ramp: edge("The Yard Ramp"), + shutter: edge("The Yard Shutter"), + toll: edge("The Toll Stair"), + span: edge("The Western Span"), + walker: *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Walker") + .expect("the walker is admitted") + .0, + } + } + + /// The canonical IDs of the custody fixture: two resources and two holder + /// subjects standing in the topology, with the first holder carrying an + /// evidenced opening balance. + pub(crate) struct Custody { + pub(crate) tithe: EntityId, + pub(crate) ingot: EntityId, + pub(crate) holder: SubjectId, + pub(crate) counterparty: SubjectId, + } + + /// The seed world's authority kinds, offices, and grievance. They are world + /// data: the kernel compares these strings and reads them no other way. + pub(crate) const LEVY_KIND: &str = "levy"; + pub(crate) const ADMIT_KIND: &str = "admit"; + pub(crate) const COMMAND_KIND: &str = "command"; + pub(crate) const JUDGE_KIND: &str = "judge"; + pub(crate) const WARDEN_OFFICE: &str = "warden"; + pub(crate) const BAILIFF_OFFICE: &str = "bailiff"; + pub(crate) const SEIZURE_GRIEVANCE: &str = "seizure"; + + pub(crate) const TITHE_RECEIPT: &str = "receipt:rhythm-tithe-census"; + pub(crate) const OPENING_BALANCE: u64 = 7; + + pub(crate) fn resource(handle: &str, label: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Resource, + container: None, + }) + } + + fn holder(handle: &str, label: &str, place: EntityId, speak: Ref) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Institution, + affordances: std::iter::once(speak) + .chain(carry_affordances().into_iter().map(|declaration| { + let Declaration::Affordance(entry) = declaration else { + unreachable!("carry_affordances declares only affordances") + }; + Ref::Draft(entry.handle) + })) + .collect(), + position: Some(Ref::Existing(place)), + import_key: None, + }) + } + + pub(crate) const CARRY_HANDLE: &str = "carry"; + + /// The worked affordances for the action lane. Every one carries the same + /// four roles and the same bounded `Transfer` slot, so a test varies exactly + /// one thing — a precondition or a band table — by naming a different entry + /// rather than by reaching into a committed catalog. The catalog is + /// Draft-only, so authoring it is how a world gets a verb. + fn carry_roles() -> Vec { + vec![ + RoleSpec { + role: Role("from".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("recipient".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("place".into()), + kind: RefKind::Entity(EntityKind::Place), + }, + RoleSpec { + role: Role("resource".into()), + kind: RefKind::Entity(EntityKind::Resource), + }, + ] + } + + /// Two slots on disjoint bands: band 0 names only the transfer, band 1 only + /// the consume. Both slots are proposed on every invocation, so the entry + /// separates what a proposer offered from what a draw admitted. + fn split_variant() -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("carry-split"), + kind: AffordanceKindName("carry_split".into()), + roles: carry_roles(), + preconditions: Vec::new(), + effect_slots: vec![ + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }, + EffectSlot { + op_kind: ComponentOpKind::Consume, + roles: vec![Role("from".into()), Role("resource".into())], + bounds: Bounds::Quantity(Quantity(3)), + }, + ], + outcome_bands: vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: vec![1], + }, + ], + carries_speech: false, + }) + } + + fn carry_variant( + handle: &str, + kind: &str, + preconditions: Vec, + outcome_bands: Vec, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles: carry_roles(), + preconditions, + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }], + outcome_bands, + carries_speech: false, + }) + } + + fn certain_band() -> Vec { + vec![OutcomeBand { + weight: 1, + effects: vec![0], + }] + } + + fn place_role() -> Role { + Role("place".into()) + } + + /// Carry, and five variants that each move one dial: a holding demand above + /// the opening balance, a reach budget short of the two-hop path, one that + /// covers it, a band that names no effect, and three equally weighted bands. + pub(crate) fn carry_affordances() -> Vec { + vec![ + carry_variant( + CARRY_HANDLE, + "carry", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-greedy", + "carry_greedy", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(OPENING_BALANCE + 1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-holds", + "carry_holds", + vec![Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }], + certain_band(), + ), + carry_variant( + "carry-near", + "carry_near", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(NEAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-far", + "carry_far", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(FAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-idle", + "carry_idle", + Vec::new(), + vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + ), + carry_variant( + "carry-chance", + "carry_chance", + Vec::new(), + vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + ], + ), + split_variant(), + ] + } + + /// Yard to gate over the open shutter alone. + pub(crate) const NEAR_REACH: u32 = 5; + /// Yard to gate over the ramp and the span, which is the only open public + /// path while the shutter is closed. + pub(crate) const FAR_REACH: u32 = 19; + + /// Declarations and evidence are Draft-only, so the resources, the holders, + /// and the one evidenced `Admit` that creates the opening balance all land + /// before activation. There is no holdings declaration field: quantity is + /// created by `Admit` and by nothing else, in this lane as in every other. + pub(crate) fn custody_patch(topology: &Topology, speak: Ref) -> WorldPatch { + WorldPatch { + declarations: carry_affordances() + .into_iter() + .chain([ + resource("tithe", "The Rhythm Tithe"), + resource("ingot", "The Cut Ingot"), + holder("clerk", "The Ledger Clerk", topology.yard, speak.clone()), + holder("keeper", "The Gate Keeper", topology.gate, speak), + ]) + .collect(), + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + } + } + + pub(crate) fn admit_custody(kernel: &mut WorldKernel, topology: &Topology) -> Custody { + let before = kernel.snapshot().unwrap(); + let receipt = submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: custody_patch(topology, speak_entry(kernel)), + }, + ); + assert!(receipt.resulting_revision > 0); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared resource") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared holder") + .0 + }; + Custody { + tithe: entity("The Rhythm Tithe"), + ingot: entity("The Cut Ingot"), + holder: subject("The Ledger Clerk"), + counterparty: subject("The Gate Keeper"), + } + } + + /// Topology, custody, then activation: everything a custody test needs, in + /// the one order the phase rules allow. + pub(crate) fn custody_world(kernel: &mut WorldKernel) -> (Topology, Custody, WorldSnapshot) { + let topology = admit_topology(kernel); + let custody = admit_custody(kernel, &topology); + let active = kernel.snapshot().unwrap(); + (topology, custody, active) + } + + /// The canonical IDs of the civic fixture: a hall containing a chamber, an + /// institution holding jurisdiction over the hall, a person who holds that + /// jurisdiction only through an office, a person and a resource inside the + /// hall, and a person standing outside it. + pub(crate) struct Civic { + pub(crate) hall: EntityId, + pub(crate) chamber: EntityId, + pub(crate) passage: EdgeId, + pub(crate) causeway: EdgeId, + pub(crate) postern: EdgeId, + pub(crate) treasury: SubjectId, + pub(crate) reeve: SubjectId, + pub(crate) farmer: SubjectId, + pub(crate) outsider: SubjectId, + pub(crate) grain: EntityId, + } + + pub(crate) fn authority_kind(name: &str) -> AuthorityKindName { + AuthorityKindName(name.into()) + } + + pub(crate) fn office(name: &str) -> OfficeName { + OfficeName(name.into()) + } + + pub(crate) fn grievance(name: &str) -> GrievanceKindName { + GrievanceKindName(name.into()) + } + + pub(crate) fn over_place(place: EntityId) -> AuthorityTargetRef { + AuthorityTargetRef::PlaceSubtree(Ref::Existing(place)) + } + + pub(crate) fn over_subject(subject_id: SubjectId) -> AuthorityTargetRef { + AuthorityTargetRef::Subject(Ref::Existing(subject_id)) + } + + pub(crate) fn grant_of(kind: &str, over: AuthorityTargetRef) -> AuthorityGrantRef { + AuthorityGrantRef { + kind: authority_kind(kind), + over, + } + } + + pub(crate) fn grant_to(holder: SubjectId, kind: &str, over: AuthorityTargetRef) -> ComponentOp { + ComponentOp::GrantAuthority { + holder: Ref::Existing(holder), + grant: grant_of(kind, over), + } + } + + /// Seven world-authored civic entries. The kernel builds none of them; + /// each is a worked example of what a seed author writes to make the + /// political layer playable rather than administratively imposed. + fn civic_affordances() -> Vec { + let entry = |handle: &str, + kind: &str, + roles: Vec, + preconditions: Vec, + effect_slots: Vec, + outcome_bands: Vec, + carries_speech: bool| { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles, + preconditions, + effect_slots, + outcome_bands, + carries_speech, + }) + }; + let role = |name: &str, kind: RefKind| RoleSpec { + role: Role(name.into()), + kind, + }; + let slot = |op_kind: ComponentOpKind, roles: Vec<&str>, bounds: Bounds| EffectSlot { + op_kind, + roles: roles.into_iter().map(|name| Role(name.into())).collect(), + bounds, + }; + let authorized = |over: &str, kind: &str| Precondition::Authorized { + over: Role(over.into()), + kind: authority_kind(kind), + }; + vec![ + // The payee is the reserved `actor` role, so an authorized + // collector cannot lawfully take a tax and send it to a friend. + entry( + "levy", + "levy", + vec![ + role("payer", RefKind::Subject(None)), + role("resource", RefKind::Entity(EntityKind::Resource)), + ], + vec![authorized("payer", LEVY_KIND)], + vec![slot( + ComponentOpKind::Transfer, + vec!["payer", "actor", "resource"], + Bounds::Quantity(Quantity(10)), + )], + certain_band(), + false, + ), + entry( + "delegate", + "delegate", + vec![ + role("deputy", RefKind::Subject(None)), + role("ground", RefKind::Entity(EntityKind::Place)), + ], + // The precondition names one kind and the slot grants another, + // so the monotonicity rule is the check that decides whether + // the granted authority is one the granter holds. + vec![authorized("ground", COMMAND_KIND)], + vec![slot( + ComponentOpKind::GrantAuthority { + kind: authority_kind(LEVY_KIND), + }, + vec!["deputy", "ground"], + Bounds::None, + )], + certain_band(), + false, + ), + // Isolates the action-lane's revocation envelope: no separate + // precondition, so a rejection here can only be + // `DelegationNotMonotone`. + entry( + "revoke", + "revoke", + vec![ + role("holder", RefKind::Subject(None)), + role("ground", RefKind::Entity(EntityKind::Place)), + ], + Vec::new(), + vec![slot( + ComponentOpKind::RevokeAuthority { + kind: authority_kind(LEVY_KIND), + }, + vec!["holder", "ground"], + Bounds::None, + )], + certain_band(), + false, + ), + entry( + "deploy", + "deploy", + vec![ + role("subordinate", RefKind::Subject(None)), + role("via", RefKind::Edge(patch::EdgeKind::Route)), + ], + vec![authorized("subordinate", COMMAND_KIND)], + vec![slot( + ComponentOpKind::Relocate, + vec!["subordinate", "via"], + Bounds::None, + )], + certain_band(), + false, + ), + // The first affordance whose effect changes shared topology under a + // legitimacy check; the second band is the interdiction that fails. + entry( + "sanction", + "sanction", + vec![role("road", RefKind::Edge(patch::EdgeKind::Route))], + vec![authorized("road", COMMAND_KIND)], + vec![slot( + ComponentOpKind::CloseRoute, + vec!["road"], + Bounds::None, + )], + vec![ + OutcomeBand { + weight: 3, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + ], + false, + ), + // Succession is an act someone performs under authority, not a + // declared method string. + entry( + "appoint", + "appoint", + vec![ + role("institution", RefKind::Subject(None)), + role("candidate", RefKind::Subject(None)), + ], + vec![authorized("institution", COMMAND_KIND)], + vec![slot( + ComponentOpKind::InstallIncumbent { + office: office(BAILIFF_OFFICE), + }, + vec!["institution", "candidate"], + Bounds::None, + )], + certain_band(), + false, + ), + // The reader that keeps `Redress` from being decorative. + entry( + "petition", + "petition", + Vec::new(), + vec![ + Precondition::HasStanding { + grievance: grievance(SEIZURE_GRIEVANCE), + }, + // A petition is spoken, so the entry names where it lands. + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ], + Vec::new(), + vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + true, + ), + ] + } + + fn civic_grants(handles: &[&str], speak: &Ref) -> BTreeSet> { + std::iter::once(speak.clone()) + .chain( + handles + .iter() + .map(|handle| Ref::Draft(DraftHandle::new(*handle))), + ) + .collect() + } + + pub(crate) fn civic_patch(topology: &Topology, speak: Ref) -> WorldPatch { + let person = |handle: &str, label: &str, place: Ref, handles: &[&str]| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + affordances: civic_grants(handles, &speak), + position: Some(place), + import_key: None, + }) + }; + let declarations = civic_affordances() + .into_iter() + .chain([ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Tithe Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("chamber"), + label: "The Counting Chamber".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + resource("grain", "The Winter Grain"), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("passage"), + label: "The Hall Passage".into(), + from: Ref::Draft(DraftHandle::new("chamber")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(3), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("causeway"), + label: "The Hall Causeway".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Existing(topology.road), + access: AccessKind::Public, + cost: Cost(6), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("postern"), + label: "The Hall Postern".into(), + from: Ref::Existing(topology.yard), + to: Ref::Draft(DraftHandle::new("chamber")), + access: AccessKind::Restricted { + requires: authority_kind(ADMIT_KIND), + }, + cost: Cost(2), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("treasury"), + label: "The Tithe Treasury".into(), + kind: SubjectKind::Institution, + affordances: civic_grants( + &[ + "levy", "delegate", "deploy", "sanction", "appoint", "revoke", + ], + &speak, + ), + position: Some(Ref::Draft(DraftHandle::new("hall"))), + import_key: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("reeve"), + label: "The Hall Reeve".into(), + kind: SubjectKind::Person, + affordances: civic_grants( + &["levy", "delegate", "petition", "sanction"], + &speak, + ), + position: Some(Ref::Draft(DraftHandle::new("chamber"))), + import_key: None, + }), + person( + "farmer", + "The Winter Farmer", + Ref::Draft(DraftHandle::new("chamber")), + &["levy", "petition", "revoke"], + ), + person( + "outsider", + "The Road Pedlar", + Ref::Existing(topology.road), + &["levy", "petition"], + ), + // Deliberately unplaced: a place-subtree jurisdiction covers a + // subject through its position, so a subject with none is + // covered by nothing. + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("nowhere"), + label: "The Unhoused".into(), + kind: SubjectKind::Person, + affordances: civic_grants(&["levy", "petition"], &speak), + position: None, + import_key: None, + }), + ]) + .collect(); + WorldPatch { + declarations, + operations: vec![ + ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("farmer")), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }, + ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("outsider")), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }, + ComponentOp::GrantAuthority { + holder: Ref::Draft(DraftHandle::new("treasury")), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "hall", + ))), + }, + }, + ComponentOp::GrantAuthority { + holder: Ref::Draft(DraftHandle::new("treasury")), + grant: AuthorityGrantRef { + kind: authority_kind(COMMAND_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "hall", + ))), + }, + }, + ComponentOp::OpenOffice { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }, + ComponentOp::OpenOffice { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(BAILIFF_OFFICE), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(WARDEN_OFFICE), + incumbent: Ref::Draft(DraftHandle::new("reeve")), + }, + ComponentOp::OpenForum { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: Ref::Draft(DraftHandle::new("treasury")), + standing: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "chamber", + ))), + }, + ], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + } + } + + pub(crate) fn admit_civic(kernel: &mut WorldKernel, topology: &Topology) -> Civic { + let before = kernel.snapshot().unwrap(); + let receipt = submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: civic_patch(topology, speak_entry(kernel)), + }, + ); + assert!(receipt.resulting_revision > 0); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared entity") + .0 + }; + let edge = |label: &str| { + *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == label) + .expect("a declared route") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared subject") + .0 + }; + Civic { + hall: entity("The Tithe Hall"), + chamber: entity("The Counting Chamber"), + grain: entity("The Winter Grain"), + passage: edge("The Hall Passage"), + causeway: edge("The Hall Causeway"), + postern: edge("The Hall Postern"), + treasury: subject("The Tithe Treasury"), + reeve: subject("The Hall Reeve"), + farmer: subject("The Winter Farmer"), + outsider: subject("The Road Pedlar"), + } + } + + /// Topology, the civic subgraph, then activation. + pub(crate) fn civic_world(kernel: &mut WorldKernel) -> (Topology, Civic, WorldSnapshot) { + let topology = admit_topology(kernel); + let civic = admit_civic(kernel, &topology); + let active = kernel.snapshot().unwrap(); + (topology, civic, active) + } + + /// The speech bench: a hall containing a yard, a speaker and a listener in + /// the hall, a bystander in the yard, a stranger nowhere, one evidenced + /// canonical fact, and a horn that carries over the hall subtree. + pub(crate) struct Speech { + pub(crate) hall: EntityId, + pub(crate) yard: EntityId, + pub(crate) speaker: SubjectId, + pub(crate) listener: SubjectId, + pub(crate) bystander: SubjectId, + pub(crate) stranger: SubjectId, + pub(crate) flood: EntityId, + pub(crate) horn: EntityId, + pub(crate) whisper: AffordanceId, + pub(crate) proclaim: AffordanceId, + pub(crate) recant: AffordanceId, + pub(crate) stair: EdgeId, + } + + pub(crate) const FLOOD_STATEMENT: &str = "The lower hinge is flooding."; + pub(crate) const FLOOD_EVIDENCE: &str = "vault:flood-survey"; + + /// A world with one room inside another, four subjects, a fact, and a + /// channel. Two world-declared speaking entries exercise both audiences: an + /// addressed co-located `whisper` and a channel-bound `proclaim`. + pub(crate) fn speech_world(kernel: &mut WorldKernel) -> (Speech, WorldSnapshot) { + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(kernel); + let person = |handle: &str, label: &str, place: Option<&str>| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Draft(DraftHandle::new("whisper")), + Ref::Draft(DraftHandle::new("proclaim")), + Ref::Draft(DraftHandle::new("recant")), + ]), + position: place.map(|place| Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + }; + submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + evidence: vec![EvidenceRef::new(FLOOD_EVIDENCE)], + operations: Vec::new(), + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Long Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("yard"), + label: "The Cavity Yard".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("stair"), + label: "The Yard Stair".into(), + from: Ref::Draft(DraftHandle::new("yard")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("flood"), + label: "the flooding of the lower hinge".into(), + statement: Statement::new(FLOOD_STATEMENT).unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + }, + }), + // Addressed speech: the audience is still the room. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("whisper"), + kind: AffordanceKindName("whisper".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::CanReach { + subject: Role("target".into()), + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("proclaim"), + kind: AffordanceKindName("proclaim".into()), + roles: vec![RoleSpec { + role: Role("channel".into()), + kind: RefKind::Entity(EntityKind::Channel), + }], + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Channel(Role("channel".into())), + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + // `Knows` plus the one knowledge operation an affordance + // may propose: a subject may only unremember what it + // holds with certainty. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("recant"), + kind: AffordanceKindName("recant".into()), + roles: vec![RoleSpec { + role: Role("fact".into()), + kind: RefKind::Entity(EntityKind::Fact), + }], + preconditions: vec![Precondition::Knows { + fact: Role("fact".into()), + at_least: Confidence::Certain, + }], + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Forget, + roles: vec![Role("actor".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + person("speaker", "The Hall Speaker", Some("hall")), + person("listener", "The Hall Listener", Some("hall")), + person("bystander", "The Yard Bystander", Some("yard")), + person("stranger", "The Placeless Stranger", None), + Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("horn"), + label: "The Temple Horn".into(), + reach: ReachRef::Place(Ref::Draft(DraftHandle::new("hall"))), + controller: Some(Ref::Draft(DraftHandle::new("speaker"))), + }), + ], + }, + }, + ); + let active = kernel.snapshot().unwrap(); + let place = |label: &str| { + active + .places + .iter() + .find(|place| place.label == label) + .expect("the declared place") + .id + }; + let who = |label: &str| { + active + .subjects + .iter() + .find(|subject| subject.label == label) + .expect("the declared subject") + .id + }; + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == FLOOD_STATEMENT) + .expect("the declared fact") + .0; + let horn = *kernel + .state + .channels + .keys() + .next() + .expect("the declared channel"); + ( + Speech { + hall: place("The Long Hall"), + yard: place("The Cavity Yard"), + speaker: who("The Hall Speaker"), + listener: who("The Hall Listener"), + bystander: who("The Yard Bystander"), + stranger: who("The Placeless Stranger"), + flood: fact, + horn, + whisper: affordance_named(&active, "whisper"), + proclaim: affordance_named(&active, "proclaim"), + recant: affordance_named(&active, "recant"), + stair: active.routes[0].id, + }, + active, + ) + } + + /// Submits as Play and returns the complete mismatch set. + pub(crate) fn reject_play( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + body: CommandBody, + ) -> Vec { + let error = kernel + .submit( + command( + snapshot, + CallerId::Play, + body, + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + mismatches + } + + pub(crate) fn operations(operations: Vec) -> CommandBody { + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + } + } + + /// The first entry the subject holds, in id order. + pub(crate) fn first_grant(snapshot: &WorldSnapshot, subject_id: SubjectId) -> AffordanceId { + *snapshot + .subjects + .iter() + .find(|subject| subject.id == subject_id) + .expect("the subject exists") + .affordances + .first() + .expect("the subject holds an affordance") + } + + /// The one subject with this label; the fixture's three are The Human, + /// The Witness and The Council. + pub(crate) fn subject_by_label(state: &WorldState, label: &str) -> SubjectId { + state + .subjects + .iter() + .find(|(_, subject)| subject.label == label) + .map(|(subject_id, _)| *subject_id) + .expect("a subject has this label") + } + + pub(crate) fn speak(affordance: AffordanceId, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + /// The one door for an act in tests: Play submits `Act` for the actor. + pub(crate) fn act_as( + kernel: &mut WorldKernel, + caller: CallerId, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + caller.clone(), + CommandBody::Act { actor, invocation }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + pub(crate) fn play_caller() -> CallerId { + CallerId::Play + } + + pub(crate) fn act( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + act_as( + kernel, + CallerId::Play, + actor, + invocation, + ) + } + + #[test] + fn create_submit_restart_and_replay_are_exact() { + let creation = creation("First"); + let (mut kernel, creation_receipt) = + WorldKernel::create(creation.clone(), &auth_principal(owner())).unwrap(); + let active = kernel.snapshot().unwrap(); + let operator = subject_by_label(&kernel.state, "The Council"); + let command = command( + &active, + play_caller(), + CommandBody::Act { + actor: operator, + invocation: speak(first_grant(&active, operator), "The vote carries."), + }, + ); + kernel + .submit(command.clone(), &AuthenticatedCaller::verified_play()) + .unwrap(); + let accepted = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + + // The same creation names the same world, with the same receipt. + let (_, retried) = WorldKernel::create(creation, &auth_principal(owner())).unwrap(); + assert_eq!(retried, creation_receipt); + + // The export is the whole world: its reopening is equal, re-exports + // byte for byte, and the applied command is stale in it. + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!(reopened.export().unwrap(), exported); + assert!(matches!( + reopened.submit(command, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + + // The next command gives equal receipts and equal worlds on both. + let next = play_command(&accepted, tick_body(1)); + let original_receipt = kernel + .submit(next.clone(), &AuthenticatedCaller::verified_play()) + .unwrap(); + let reopened_receipt = reopened + .submit(next, &AuthenticatedCaller::verified_play()) + .unwrap(); + assert_eq!(original_receipt, reopened_receipt); + assert_eq!(kernel.snapshot().unwrap(), reopened.snapshot().unwrap()); + assert_eq!(kernel.export().unwrap(), reopened.export().unwrap()); + } + + #[test] + fn a_stale_command_is_a_revision_mismatch() { + let (mut kernel, _) = WorldKernel::create(creation("Still"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + assert!(submit_play(&mut kernel, &genesis, tick_body(1)).resulting_revision > 0); + let after = kernel.snapshot().unwrap(); + // The very command that was applied, resubmitted: there is no retry + // identity, so it is stale like any other. + let stale = play_command(&genesis, tick_body(1)); + assert!(matches!( + kernel.submit(stale, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + assert_eq!(kernel.snapshot().unwrap(), after); + assert_eq!(kernel.journal.commit_count(), 2); + } + + #[test] + fn ids_are_derived_from_the_command() { + let create = |title: &str| { + WorldKernel::create(creation(title), &auth_principal(owner())).unwrap() + }; + let (mut kernel, receipt) = create("Same"); + let (twin, twin_receipt) = create("Same"); + assert_eq!(receipt, twin_receipt); + assert_eq!(kernel.state.header.world_id, twin.state.header.world_id); + assert_eq!(receipt.world_id, WorldId::of(receipt.command_id)); + let (other, _) = create("Other"); + assert_ne!(kernel.state.header.world_id, other.state.header.world_id); + + // The same patch at two revisions is two commands, so the entity it + // declares is minted twice under two ids. + let patch = WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cairn"), + label: "A Cairn".into(), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }; + let mut ids = BTreeSet::new(); + for _ in 0..2 { + let snapshot = kernel.snapshot().unwrap(); + let envelope = play_command(&snapshot, CommandBody::AdmitPatch { patch: patch.clone() }); + let expected = envelope.id(); + let receipt = kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap(); + assert_eq!(receipt.command_id, expected); + assert!(ids.insert(receipt.command_id), "two commands share an id"); + } + let cairns = kernel + .state + .entities + .values() + .filter(|entity| entity.label == "A Cairn") + .count(); + assert_eq!(cairns, 2); + } + + #[test] + fn invalid_seed_never_allocates_a_world() { + let mut invalid = creation("Nope"); + invalid.patch.declarations[3] = invalid.patch.declarations[2].clone(); + let Err(KernelError::PatchRejected(rejected)) = + WorldKernel::create(invalid, &auth_principal(owner())) + else { + panic!("expected a rejected creation patch"); + }; + assert_eq!( + rejected, + vec![Mismatch::DuplicateHandle { + handle: DraftHandle::new("human") + }] + ); + assert!( + WorldKernel::create(creation("Valid"), + &auth_principal(owner()) + ) + .is_ok() + ); + } + + #[test] + fn sealed_authentication_cannot_be_replaced_by_a_command_claim() { + let (mut kernel, _) = WorldKernel::create(creation("Owned"), + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let forged = command( + &snapshot, + CallerId::Principal(human_principal()), + tick_body(1), + ); + assert!(matches!( + kernel.submit(forged, &auth_principal(owner())), + Err(KernelError::AuthenticationMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), snapshot); + } + + /// Soul falsification: the preimage must exclude the revision + /// and every component outside the scope. Each step below is a real commit + /// that moves the world, not a hand-edited state. + #[test] + fn soul_scope_components_exclude_revision_and_everything_outside_the_scope() { + let (mut kernel, _) = WorldKernel::create(creation("Preimage"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let scope = topology.walker; + let base = scope_components(&kernel.state, scope); + let start_revision = kernel.state.revision; + + // A new place elsewhere, a route that touches neither the walker's + // place nor it, and a second placed subject: all outside the scope. + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("annex"), + label: "The Annex".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("annexway"), + label: "The Annex Way".into(), + from: Ref::Existing(topology.road), + to: Ref::Draft(DraftHandle::new("annex")), + access: AccessKind::Public, + cost: Cost(3), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("runner"), + label: "The Runner".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.road)), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert_ne!(kernel.state.revision, start_revision); + assert_eq!(scope_components(&kernel.state, scope), base); + + // Another subject's Position moving is not this scope's business. + let annexway = *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Annex Way") + .expect("the declared route") + .0; + let runner = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Runner") + .expect("the declared subject") + .0; + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Relocate { + subject: Ref::Existing(runner), + via: Ref::Existing(annexway), + }], + evidence: Vec::new(), + }, + }, + ); + assert_eq!( + kernel.state.positions.get(&runner), + Some(&Position { + place: kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Annex") + .map(|(id, _)| *id) + .unwrap() + }) + ); + assert_eq!(scope_components(&kernel.state, scope), base); + + // A route incident to the walker's own place is inside the scope. + let moved = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &moved, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ); + assert_ne!(scope_components(&kernel.state, scope), base); + } + + /// Soul: an `AffordanceId` now names a catalog entry, not a subject's copy + /// of one — the three genesis subjects share Speak's single id. So the id + /// cannot be what gates: grant membership for the invoking scope is. The + /// same `convene` id commits for the scope that holds it and is denied for + /// one that does not. + #[test] + fn act_needs_the_actors_grant() { + let (mut kernel, _) = WorldKernel::create(creation("SharedCatalogIds"), + &auth_principal(owner()), + ) + .unwrap(); + let active = kernel.snapshot().unwrap(); + let speak = affordance_named(&active, "speak"); + let convened = affordance_named(&active, "convene"); + + // One entry, one id, every genesis subject a grantee. + assert_eq!(active.subjects.len(), 3); + assert!( + active + .subjects + .iter() + .all(|subject| subject.affordances.contains(&speak)) + ); + let holders: Vec = active + .subjects + .iter() + .filter(|subject| subject.affordances.contains(&convened)) + .map(|subject| subject.id) + .collect(); + assert_eq!(holders.len(), 1); + + let invoke = |kernel: &mut WorldKernel, subject: SubjectId| { + act( + kernel, + subject, + DecisionInvocation { + affordance: convened, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("The council convenes.").unwrap()), + display: None, + }, + ) + }; + + // The grantee's scope commits with that id. + assert!(invoke(&mut kernel, holders[0]).unwrap().resulting_revision > 0); + + // A scope that does not hold the entry is denied the very same id, and + // nothing commits. + let after = kernel.snapshot().unwrap(); + let stranger = after + .subjects + .iter() + .find(|subject| !subject.affordances.contains(&convened)) + .expect("a subject without the grant") + .id; + assert!(matches!( + invoke(&mut kernel, stranger).unwrap_err(), + KernelError::AffordanceDenied + )); + assert_eq!(kernel.snapshot().unwrap(), after); + } + + #[test] + fn a_distant_route_closing_leaves_the_actors_scope_alone_and_its_act_commits() { + let (mut kernel, _) = WorldKernel::create(creation("BindingAndAdmission"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + let speak = affordance_named(&active, "speak"); + + // A route the actor does not stand beside is outside its scope. + // Admission re-reads the live graph at commit, so nothing commits on + // stale topology. + let before_components = scope_components(&kernel.state, topology.walker); + let before = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.span), + }]), + ); + assert_eq!( + scope_components(&kernel.state, topology.walker), + before_components, + "a route outside the actor's incident set is not in its scope" + ); + + let receipt = act( + &mut kernel, + topology.walker, + DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Still here.").unwrap()), + display: None, + }, + ) + .expect("a distant route closing does not stop this act"); + assert!(receipt.resulting_revision > 0); + } + + /// The mvp doc's disjointness requirement: an institution with an + /// operational organ and a person-shaped voice is two subjects joined by an + /// office, not one subject with two controllers. + #[test] + fn an_institution_and_its_voice_are_two_subjects_joined_by_an_office() { + let mut kernel = crate::custody_tests::custody_kernel("Two"); + let (_, civic, _) = civic_world(&mut kernel); + + + // Both are authorized over the hall — one directly, one by delegation — + // and neither appears in the other's components. + let over_hall = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }; + assert!(subject_authority(&kernel.state, civic.treasury).contains(&over_hall)); + assert!(subject_authority(&kernel.state, civic.reeve).contains(&over_hall)); + assert!(kernel.state.authority.get(&civic.reeve).is_none()); + assert!( + scope_components(&kernel.state, civic.treasury) + .delegated + .is_empty() + ); + assert!( + scope_components(&kernel.state, civic.reeve) + .authority + .is_empty() + ); + } + + /// A levy from catalog to conservation: one lowered `Transfer`, the ledger + /// total unchanged, and no other partition touched. + #[test] + fn a_levy_round_trips_from_catalog_to_conservation() { + let mut kernel = crate::custody_tests::custody_kernel("Levy"); + let (_, civic, active) = civic_world(&mut kernel); + let before_total: u64 = kernel + .state + .holdings + .values() + .filter_map(|held| held.get(&civic.grain)) + .map(|quantity| quantity.0) + .sum(); + let positions = kernel.state.positions.clone(); + let edges = kernel.state.edges.clone(); + let entities = kernel.state.entities.clone(); + + let caller = play_caller(); + let receipt = kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::Act { + actor: civic.treasury, + invocation: DecisionInvocation { + affordance: affordance_named(&active, "levy"), + bindings: vec![ + RoleBinding { + role: Role("payer".into()), + target: Target::Subject(civic.farmer), + }, + RoleBinding { + role: Role("resource".into()), + target: Target::Entity(civic.grain), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(3)), + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + assert!(receipt.resulting_revision > 0); + + let held = |holder: SubjectId| { + kernel + .state + .holdings + .get(&holder) + .and_then(|held| held.get(&civic.grain)) + .map_or(0, |quantity| quantity.0) + }; + assert_eq!(held(civic.farmer), OPENING_BALANCE - 3); + assert_eq!(held(civic.treasury), 3); + let after_total: u64 = kernel + .state + .holdings + .values() + .filter_map(|held| held.get(&civic.grain)) + .map(|quantity| quantity.0) + .sum(); + assert_eq!(before_total, after_total); + assert_eq!( + kernel.events().last().unwrap().effects, + vec![ResolvedOp::Transfer { + from: civic.farmer, + to: civic.treasury, + resource: civic.grain, + qty: Quantity(3), + }] + ); + assert_eq!(kernel.state.positions, positions); + assert_eq!(kernel.state.edges, edges); + assert_eq!(kernel.state.entities, entities); + } + + /// Representation is person-and-institution shaped, and that is the check + /// that stops the two-subject shape from collapsing back into one. + #[test] + fn office_admission_is_person_and_institution_shaped() { + let mut kernel = crate::custody_tests::custody_kernel("Offices"); + let (_, civic, _) = civic_world(&mut kernel); + let refuse = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + reject_play(kernel, &before, operations(ops)) + }; + + // An institution cannot occupy its own office. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.treasury), + }] + ), + vec![Mismatch::OfficeHolderNotPerson { operation: 0 }] + ); + // An office cannot be opened on a person. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::OpenOffice { + institution: Ref::Existing(civic.reeve), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }] + ), + vec![Mismatch::OfficeOnNonInstitution { operation: 0 }] + ); + // One person, at most one office per institution. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.reeve), + }] + ), + vec![Mismatch::DuplicateIncumbency { operation: 0 }] + ); + } + + /// Disjointness in both directions: overlap inside one subject's effective + /// authority is refused, overlap between subjects is layered government. + #[test] + fn overlapping_jurisdiction_within_one_subject_is_rejected() { + let mut kernel = crate::custody_tests::custody_kernel("Overlap"); + let (_, civic, _) = civic_world(&mut kernel); + let refuse = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + reject_play(kernel, &before, operations(ops)) + }; + let admit = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + submit_play(kernel, &before, operations(ops)) + }; + + // A direct grant under what the reeve's office already lends. + assert_eq!( + refuse( + &mut kernel, + vec![grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber))] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + // Two direct grants of one kind, nested, in one patch. + assert_eq!( + refuse( + &mut kernel, + vec![ + grant_to(civic.farmer, LEVY_KIND, over_place(civic.hall)), + grant_to(civic.farmer, LEVY_KIND, over_place(civic.chamber)), + ] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 1 }] + ); + // An incumbency that would lend the farmer ground it already holds. + admit( + &mut kernel, + vec![grant_to(civic.farmer, LEVY_KIND, over_place(civic.chamber))], + ); + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + incumbent: Ref::Existing(civic.farmer), + }] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // A different kind over the same ground commits, and so does the same + // kind held by a different subject: two holders authorized over one + // target is not a contradiction, because nothing arbitrates. + assert!(admit( &mut kernel, vec![ grant_to(civic.reeve, JUDGE_KIND, over_place(civic.chamber)), grant_to(civic.outsider, LEVY_KIND, over_place(civic.chamber)), ] ).resulting_revision > 0); + } + + /// Contract 6 on the civic surface: one patch, the complete sorted set, no + /// allocation, and repairing exactly those failures commits. + #[test] + fn civic_operations_are_rejected_with_the_complete_set() { + let mut kernel = crate::custody_tests::custody_kernel("CivicSet"); + let (_, civic, _) = civic_world(&mut kernel); + let before = kernel.snapshot().unwrap(); + let broken = vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + delegated: BTreeSet::new(), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("provost"), + incumbent: Ref::Existing(civic.farmer), + }, + ComponentOp::CloseForum { + grievance: grievance("eviction"), + }, + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("Chief Steward"), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.treasury), + }, + grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber)), + ]; + let mut expected = vec![ + Mismatch::EmptyDelegation { operation: 0 }, + Mismatch::UnknownOffice { operation: 1 }, + Mismatch::UnknownForum { operation: 2 }, + Mismatch::InvalidCivicName { + site: patch::Site::Operation(3), + }, + Mismatch::OfficeHolderNotPerson { operation: 4 }, + Mismatch::OverlappingJurisdiction { operation: 5 }, + ]; + expected.sort(); + assert_eq!( + reject_play(&mut kernel, &before, operations(broken)), + expected + ); + assert_eq!(kernel.snapshot().unwrap(), before); + + let repaired = vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + incumbent: Ref::Existing(civic.farmer), + }, + ComponentOp::OpenForum { + grievance: grievance("eviction"), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.hall), + }, + ]; + assert!(submit_play(&mut kernel, &before, operations(repaired)).resulting_revision > 0); + } + + /// A civic operation that changes nothing is not a canonical change. + #[test] + fn an_idempotent_civic_operation_is_no_change() { + let mut kernel = + crate::custody_tests::custody_kernel("Idempotent"); + let (_, civic, _) = civic_world(&mut kernel); + for operation in [ + grant_to(civic.treasury, LEVY_KIND, over_place(civic.hall)), + ComponentOp::RevokeAuthority { + holder: Ref::Existing(civic.treasury), + grant: grant_of(JUDGE_KIND, over_place(civic.hall)), + }, + ComponentOp::VacateOffice { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + }, + ComponentOp::OpenForum { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.chamber), + }, + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }, + ] { + let before = kernel.snapshot().unwrap(); + assert_eq!( + reject_play(&mut kernel, &before, operations(vec![operation])), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + } + + /// The digest reads what the actor is authorized over and nothing about the + /// world the actor reaches. + #[test] + fn scope_components_read_authority_and_delegation_but_not_occupancy() { + let mut kernel = crate::custody_tests::custody_kernel("Digest"); + let (topology, civic, _) = civic_world(&mut kernel); + let digest_of = |kernel: &WorldKernel, subject_id| { + scope_components(&kernel.state, subject_id) + }; + let admit = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + submit_play(kernel, &before, operations(ops)); + }; + + // Moving an unrelated subject into and out of the jurisdiction, and + // opening a forum, leave every digest alone. + let reeve_before = digest_of(&kernel, civic.reeve); + let treasury_before = digest_of(&kernel, civic.treasury); + admit( + &mut kernel, + vec![ + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }, + ComponentOp::OpenForum { + grievance: grievance("eviction"), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.hall), + }, + ], + ); + assert_eq!(digest_of(&kernel, civic.reeve), reeve_before); + assert_eq!(digest_of(&kernel, civic.treasury), treasury_before); + + // Installing an office the subject does not hold leaves it alone too. + admit( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.farmer), + }], + ); + assert_eq!(digest_of(&kernel, civic.reeve), reeve_before); + assert_eq!(digest_of(&kernel, civic.treasury), treasury_before); + + // Revoking the institution's grant for a lent kind moves the + // incumbent's digest, because the office copies it in. + admit( + &mut kernel, + vec![ComponentOp::RevokeAuthority { + holder: Ref::Existing(civic.treasury), + grant: grant_of(LEVY_KIND, over_place(civic.hall)), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + assert_ne!(digest_of(&kernel, civic.treasury), treasury_before); + + // Granting the actor's own, and narrowing a held office, move it too. + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber))], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(COMMAND_KIND)]), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![ComponentOp::VacateOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + } + + /// The snapshot carries a subject's own civic state and no gazetteer: a + /// forum is visible only to its standing, and no subject sees another's + /// grants. + #[test] + fn a_forum_is_visible_only_to_its_standing() { + let mut kernel = crate::custody_tests::custody_kernel("Redress"); + let (_, civic, active) = civic_world(&mut kernel); + let of = |subject_id: SubjectId| { + active + .subjects + .iter() + .find(|subject| subject.id == subject_id) + .expect("a declared subject") + }; + + // The farmer stands in the chamber, which is the forum's standing. + assert_eq!( + of(civic.farmer).redress, + vec![ForumSnapshot { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: civic.treasury, + }] + ); + assert!(of(civic.outsider).redress.is_empty()); + + // Grants are the subject's own; offices held and offices granted are + // the two ends of one link and never merge. + assert!(of(civic.reeve).components.authority.is_empty()); + assert_eq!(of(civic.reeve).offices_held.len(), 1); + assert!(of(civic.reeve).offices_granted.is_empty()); + assert_eq!(of(civic.treasury).offices_granted.len(), 2); + assert!(of(civic.treasury).offices_held.is_empty()); + assert!(of(civic.farmer).components.authority.is_empty()); + assert_eq!( + of(civic.treasury).components.authority, + BTreeSet::from([ + AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }, + AuthorityGrant { + kind: authority_kind(COMMAND_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }, + ]) + ); + } + + /// Soul falsification of the candidate authority shadow's reach: a grant + /// minted in the same patch resolves, but a *destination* declared in the + /// same patch does not, because the shadow is projected to canonical + /// referents before the covering predicate runs. A genesis patch therefore + /// cannot declare a restricted room and walk anyone into it in one batch. + #[test] + fn a_same_patch_destination_is_covered_by_no_grant() { + let mut kernel = crate::custody_tests::custody_kernel("DraftDoor"); + let topology = admit_topology(&mut kernel); + let before = kernel.snapshot().unwrap(); + let patch = WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("keep"), + label: "The Inner Keep".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("keepgate"), + label: "The Keep Gate".into(), + from: Ref::Existing(topology.yard), + to: Ref::Draft(DraftHandle::new("keep")), + access: AccessKind::Restricted { + requires: authority_kind(ADMIT_KIND), + }, + cost: Cost(2), + }), + ], + operations: vec![ + ComponentOp::GrantAuthority { + holder: Ref::Existing(topology.walker), + grant: AuthorityGrantRef { + kind: authority_kind(ADMIT_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "keep", + ))), + }, + }, + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Draft(DraftHandle::new("keepgate")), + }, + ], + evidence: Vec::new(), + }; + assert_eq!( + reject_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch + } + ), + vec![Mismatch::RouteAccessRestricted { operation: 1 }], + "the key covers the door, but the door's far side is still a draft" + ); + } + + /// PA.f38: a retired institution lends nothing. `Retire` does not vacate + /// the office the reeve holds — the incumbency stays on the ledger — but + /// `delegated_authority` stops reading a dissolved institution's grants, + /// the one site that turns an office into effective authority. + #[test] + fn a_retired_institution_lends_no_authority_to_its_office_holder() { + let mut kernel = crate::custody_tests::custody_kernel("RetiredLends"); + let (_, civic, before) = civic_world(&mut kernel); + let over_hall = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }; + assert!( + subject_authority(&kernel.state, civic.reeve).contains(&over_hall), + "the reeve holds levy only through the warden office before retirement" + ); + + submit_play( + &mut kernel, + &before, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }]), + ); + + let warden = kernel + .state + .selection + .get(&civic.treasury) + .and_then(|offices| offices.get(&office(WARDEN_OFFICE))) + .expect("retire did not vacate the office"); + assert_eq!( + warden.incumbent, + Some(civic.reeve), + "the reeve still holds the office after the institution retires" + ); + assert!( + !subject_authority(&kernel.state, civic.reeve).contains(&over_hall), + "a retired institution still lent authority through its office" + ); + } +} + +#[cfg(test)] +mod custody_tests { + use super::tests::{ + OPENING_BALANCE, TITHE_RECEIPT, act, admit_custody, admit_topology, + auth_principal, creation, custody_world, first_grant, operations, owner, reject_play, + speak, speak_entry, submit_play, + }; + use super::*; + + pub(crate) fn custody_kernel(title: &str) -> WorldKernel { + WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0 + } + + fn holding(kernel: &WorldKernel, holder: SubjectId, resource: EntityId) -> u64 { + held(&kernel.state, holder, resource) + } + + /// A forged `PatchAdmitted` never passes the resolver, so `admit_resolved` + /// re-derives every custody precondition from the committed partitions and + /// commits nothing when one fails. + /// + /// Deviation from the spec's wording, decided here: `ResolvedOp::Transfer` + /// carries one `qty`, so "a transfer whose debit and credit differ" is + /// unrepresentable — which is the stronger outcome that shape was chosen + /// for. The reachable forgery is a transfer the holder cannot cover, and + /// the conservation equation itself is falsified directly beside it. + #[test] + fn a_non_conserving_transfer_effect_does_not_apply() { + let mut kernel = custody_kernel("Forged"); + let (_, custody, _) = custody_world(&mut kernel); + let before = kernel.state.holdings.clone(); + + let mut candidate = kernel.state.clone(); + let forged = WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::Transfer { + from: custody.holder, + to: custody.counterparty, + resource: custody.tithe, + qty: Quantity(OPENING_BALANCE + 1), + }], + evidence: Vec::new(), + }, + }; + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &forged, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate.holdings, before); + + // The conservation equation is the one owner, and it refuses a ledger + // that does not balance regardless of which operation produced it. + let unbalanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 9, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&unbalanced), Some(custody.tithe)); + let balanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 8, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&balanced), None); + } + + /// Creation of quantity is attributable: an `Admit` whose ref is not in the + /// patch's own evidence list mints nothing and allocates no ID. + #[test] + fn an_admit_without_evidence_is_rejected() { + let mut kernel = custody_kernel("Unevidenced"); + let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + + let mismatches = reject_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("tithe"), + label: "The Rhythm Tithe".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("clerk"), + label: "The Ledger Clerk".into(), + kind: SubjectKind::Institution, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.yard)), + import_key: None, + }), + ], + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(4), + evidence: EvidenceRef::new("receipt:never-listed"), + }], + evidence: Vec::new(), + }, + }, + ); + + assert_eq!( + mismatches, + vec![Mismatch::AdmitWithoutEvidence { operation: 0 }] + ); + assert!(kernel.state.holdings.is_empty()); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + #[test] + fn a_transfer_moves_the_exact_quantity_and_nothing_else() { + let mut kernel = custody_kernel("Transfer"); + let (_, custody, active) = custody_world(&mut kernel); + let entities = kernel.state.entities.clone(); + let edges = kernel.state.edges.clone(); + let positions = kernel.state.positions.clone(); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 3); + assert_eq!(resource_total_by_scan(&kernel.state, custody.tithe), 7); + assert_eq!(kernel.state.entities, entities); + assert_eq!(kernel.state.edges, edges); + assert_eq!(kernel.state.positions, positions); + } + + /// Absence is zero at both levels, so emptying a holding removes the + /// resource key and emptying a holder removes the holder key. + #[test] + fn consume_reduces_the_holding_and_emptying_removes_the_key() { + let mut kernel = custody_kernel("Consume"); + let (_, custody, active) = custody_world(&mut kernel); + + let after_three = submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + assert!(after_three.resulting_revision > 0); + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(4), + }]), + ); + assert!(!kernel.state.holdings.contains_key(&custody.holder)); + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert!(subject.components.holdings.is_empty()); + } + + #[test] + fn a_transform_conserves_one_for_one() { + let mut kernel = custody_kernel("Transform"); + let (_, custody, active) = custody_world(&mut kernel); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(5), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); + assert_eq!(holding(&kernel, custody.holder, custody.ingot), 5); + assert_eq!(resource_total_by_scan(&kernel.state, custody.tithe), 2); + assert_eq!(resource_total_by_scan(&kernel.state, custody.ingot), 5); + } + + #[test] + fn spending_more_than_held_is_rejected_with_insufficient_custody() { + let mut kernel = custody_kernel("Insufficient"); + let (_, custody, _) = custody_world(&mut kernel); + let too_much = Quantity(OPENING_BALANCE + 1); + let attempts = [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: too_much, + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ]; + + for attempt in attempts { + let snapshot = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + let mismatches = reject_play(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), snapshot); + } + } + + /// A holder with no entry holds zero: there is no second name for it and no + /// zero entry anywhere in the snapshot. + #[test] + fn an_absent_holding_is_zero() { + let mut kernel = custody_kernel("Absent"); + let (_, custody, active) = custody_world(&mut kernel); + + let mismatches = reject_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }]), + ); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + let counterparty = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.counterparty) + .expect("the counterparty is in the snapshot"); + assert!(counterparty.components.holdings.is_empty()); + } + + #[test] + fn a_zero_quantity_operation_is_rejected() { + let mut kernel = custody_kernel("Zero"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + + // `Admit` is Draft-only, because Active refuses a patch carrying + // evidence, so its zero case is proven before activation. + let draft = kernel.snapshot().unwrap(); + let mismatches = reject_play( + &mut kernel, + &draft, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + + let active = kernel.snapshot().unwrap(); + for attempt in [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ] { + let snapshot = kernel.snapshot().unwrap(); + let mismatches = reject_play(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + } + assert_eq!(kernel.snapshot().unwrap(), active); + } + + #[test] + fn dependency_bind_and_release_round_trip() { + let mut kernel = custody_kernel("Dependency"); + let (_, custody, active) = custody_world(&mut kernel); + let before = kernel.state.dependencies.clone(); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!( + kernel.state.dependencies.get(&custody.holder), + Some(&BTreeSet::from([DependencyTarget::Resource(custody.tithe)])) + ); + + let bound = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!(kernel.state.dependencies, before); + assert!(!kernel.state.dependencies.contains_key(&custody.holder)); + } + + /// A bind that changes nothing is `NoOperationEffect`, the name pass 2 + /// already owns; a subject bound to itself is `SelfDependency`. + #[test] + fn a_duplicate_dependency_bind_is_rejected_as_no_effect() { + let mut kernel = custody_kernel("Duplicate"); + let (_, custody, active) = custody_world(&mut kernel); + + let bind = ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }; + submit_play(&mut kernel, &active, operations(vec![bind.clone()])); + + let bound = kernel.snapshot().unwrap(); + assert_eq!( + reject_play(&mut kernel, &bound, operations(vec![bind])), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_play( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.ingot)), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_play( + &mut kernel, + &bound, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Subject(Ref::Existing(custody.holder)), + }]), + ), + vec![Mismatch::SelfDependency { operation: 0 }] + ); + } + + /// Pass 3 owns the representation of a dependency, not its consequence. A + /// dependency on a closed route commits and shows up in the subject's + /// components; nothing rejects it and nothing fires from it. + #[test] + fn a_dependency_on_a_closed_route_is_representable_and_visible() { + let mut kernel = custody_kernel("Closed"); + let (topology, custody, active) = custody_world(&mut kernel); + assert!(!kernel.state.edges[&topology.shutter].is_open()); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Route(Ref::Existing(topology.shutter)), + }]), + ); + + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert_eq!( + subject.components.dependencies, + BTreeSet::from([DependencyTarget::Route(topology.shutter)]) + ); + } + + /// The digest reads the acting subject's own holdings and dependencies, and + /// only its own: a counterparty's churn does not move it. + #[test] + fn scope_components_read_holdings_and_dependencies() { + let mut kernel = custody_kernel("ScopeCustody"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let scope = custody.holder; + let base = scope_components(&kernel.state, scope); + + let mut spent = kernel.state.clone(); + set_held(&mut spent, custody.holder, custody.tithe, 1); + assert_ne!(scope_components(&spent, scope), base); + + let mut gained = kernel.state.clone(); + set_held(&mut gained, custody.holder, custody.ingot, 1); + assert_ne!(scope_components(&gained, scope), base); + + let mut bound = kernel.state.clone(); + bound + .dependencies + .entry(custody.holder) + .or_default() + .insert(DependencyTarget::Resource(custody.tithe)); + assert_ne!(scope_components(&bound, scope), base); + + let mut elsewhere = kernel.state.clone(); + set_held(&mut elsewhere, custody.counterparty, custody.tithe, 9); + elsewhere + .dependencies + .entry(custody.counterparty) + .or_default() + .insert(DependencyTarget::Resource(custody.ingot)); + assert_eq!(scope_components(&elsewhere, scope), base); + } + + /// Soul, proof 4: the ledger equation stated as arithmetic over the + /// committed partitions, across one patch that exercises every conserving + /// operation at once. Per resource, `after == before + admitted + gained - + /// consumed - spent`, and no third resource moves. + #[test] + fn soul_a_mixed_patch_conserves_every_resource_it_touches() { + let mut kernel = custody_kernel("MixedLedger"); + let (_, custody, active) = custody_world(&mut kernel); + + // The opening balance was created by `Admit` alone: before is zero, + // admitted is the balance, and the total equals the sum of the two. + assert_eq!( + resource_total_by_scan(&kernel.state, custody.tithe), + u128::from(OPENING_BALANCE) + ); + assert_eq!(resource_total_by_scan(&kernel.state, custody.ingot), 0); + + let tithe_before = resource_total_by_scan(&kernel.state, custody.tithe); + let ingot_before = resource_total_by_scan(&kernel.state, custody.ingot); + + let receipt = submit_play( + &mut kernel, + &active, + operations(vec![ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(2), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }, + ]), + ); + assert!(receipt.resulting_revision > 0); + + // Transfer contributes to no term; transform contributes one spent and + // one gained; consume contributes one consumed. Nothing was admitted. + assert_eq!( + resource_total_by_scan(&kernel.state, custody.tithe), + tithe_before - 1 - 2 + ); + assert_eq!( + resource_total_by_scan(&kernel.state, custody.ingot), + ingot_before + 2 + ); + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); + assert_eq!(holding(&kernel, custody.holder, custody.ingot), 2); + assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 2); + // Absence is zero: the counterparty never held an ingot, so there is no + // row for one rather than a row holding nothing. + assert!(!kernel.state.holdings[&custody.counterparty].contains_key(&custody.ingot)); + } + + /// Soul: is the apply-side `check_ledger` reachable? + /// + /// A forged `PatchAdmitted` can carry a *sequence* whose second operation + /// exceeds what the first left. It dies at `apply_operation`'s own + /// re-derived precondition, one operation early, so the ledger never speaks. + /// A sequence in which every operation applies cannot break the equation, + /// because every `ResolvedOp` arm debits and credits the same `qty` it + /// records: the apply-side call is unreachable from the current closed set. + #[test] + fn soul_a_forged_sequence_dies_at_the_per_operation_check_not_the_ledger() { + let mut kernel = custody_kernel("ForgedSequence"); + let (_, custody, _) = custody_world(&mut kernel); + let before = kernel.state.holdings.clone(); + + let forge = |operations: Vec| WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations, + evidence: Vec::new(), + }, + }; + let transfer = |qty: u64| ResolvedOp::Transfer { + from: custody.holder, + to: custody.counterparty, + resource: custody.tithe, + qty: Quantity(qty), + }; + + // Two transfers of five out of a balance of seven: the first leaves two, + // the second cannot cover five. + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &forge(vec![transfer(5), transfer(5)]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "holder does not hold enough"), + "the per-operation precondition speaks first, not the ledger: {error:?}" + ); + // The candidate is a throwaway clone; the live state never moved. + assert_eq!(kernel.state.holdings, before); + + // Every operation applying means the equation balances, so the same + // forged lane commits a conserving sequence with no ledger complaint. + let mut conserving = kernel.state.clone(); + apply_effect( + &mut conserving, + CommandId::issue(), + &CallerId::Play, + &forge(vec![ + transfer(5), + ResolvedOp::Transfer { + from: custody.counterparty, + to: custody.holder, + resource: custody.tithe, + qty: Quantity(5), + }, + ]), + ) + .expect("a conserving forged sequence applies"); + assert_eq!(conserving.holdings, before); + + // The degenerate shapes a forgery could otherwise use to mint or burn + // are refused by the arms themselves, not by the equation. + for degenerate in [ + ResolvedOp::Transfer { + from: custody.holder, + to: custody.holder, + resource: custody.tithe, + qty: Quantity(1), + }, + ResolvedOp::Transform { + holder: custody.holder, + from_resource: custody.tithe, + into_resource: custody.tithe, + qty: Quantity(1), + }, + ] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &forge(vec![degenerate]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "custody operation moves nothing"), + "unexpected refusal: {error:?}" + ); + } + + // An `Admit` in a forged effect still needs its receipt in the same + // patch, so the apply lane mints no unattributable quantity either. + let mut unevidenced = kernel.state.clone(); + let error = apply_effect( + &mut unevidenced, + CommandId::issue(), + &CallerId::Play, + &forge(vec![ResolvedOp::Admit { + holder: custody.holder, + resource: custody.tithe, + qty: Quantity(4), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "admitted quantity cites no evidence in its patch"), + "unexpected refusal: {error:?}" + ); + assert_eq!(kernel.state.holdings, before); + } + + /// Soul: `QuantityOverflow` is reachable, and the arithmetic that reaches it + /// is `checked_add` rather than a silent clamp. Two admissions in one patch + /// whose sum exceeds `u64::MAX` mint nothing and allocate no ID. + #[test] + fn soul_a_holding_cannot_overflow_silently() { + let mut kernel = custody_kernel("Overflow"); + let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + + let admit = |qty: u64| ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(qty), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }; + let mismatches = reject_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("tithe"), + label: "The Rhythm Tithe".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("clerk"), + label: "The Ledger Clerk".into(), + kind: SubjectKind::Institution, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.yard)), + import_key: None, + }), + ], + operations: vec![admit(u64::MAX), admit(1)], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ); + + assert_eq!( + mismatches, + vec![Mismatch::QuantityOverflow { operation: 1 }], + "the overflow is the complete verdict: no clamp, no second name" + ); + assert!(kernel.state.holdings.is_empty()); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Soul, scope: a transfer changes the *receiver's* components too, and + /// no unrelated subject's, whose act still commits at the later revision. + #[test] + fn soul_an_incoming_transfer_changes_only_the_counterpartys_scope() { + let mut kernel = custody_kernel("IncomingScope"); + let (topology, custody, active) = custody_world(&mut kernel); + let receiver_before = scope_components(&kernel.state, custody.counterparty); + let bystander_before = scope_components(&kernel.state, topology.walker); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + let moved = kernel.snapshot().unwrap(); + + assert_ne!( + scope_components(&kernel.state, custody.counterparty), + receiver_before, + "the receiver's holdings moved" + ); + assert_eq!( + scope_components(&kernel.state, topology.walker), + bystander_before, + "an unrelated subject's scope is untouched by the transfer" + ); + + let receipt = act( + &mut kernel, + topology.walker, + speak(first_grant(&moved, topology.walker), "Unmoved."), + ) + .expect("an unrelated subject acts at the later revision"); + assert!(receipt.resulting_revision > 0); + } +} + +/// Pass 6: `Knowledge`, `Channel`, `Fact` standing, and the non-leakage rule. +/// A subject perceives a speech act if and only if it holds `Knowledge` of that +/// act's fact — the knowledge partition is the sole owner of who-heard-what. +#[cfg(test)] +mod knowledge_tests { + use super::patch::{RefName, Site}; + use super::tests::{ + act, play_caller, affordance_named, + FLOOD_EVIDENCE, FLOOD_STATEMENT, Speech, auth_principal, command, creation, operations, + owner, reject_play, speech_world, spoken, submit_play, + }; + use super::*; + + fn speech_kernel(title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + (kernel, speech, active) + } + + fn utter( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + act(kernel, actor, invocation) + } + + fn say(affordance: AffordanceId, bindings: Vec, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn rejected(result: Result) -> Vec { + match result { + Err(KernelError::ActionRejected(mismatches)) => mismatches, + other => panic!("expected a rejected invocation, got {other:?}"), + } + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&(subject, fact)) + .copied() + } + + fn acquire(subject: SubjectId, fact: EntityId, source: AuthoredSource) -> ComponentOp { + ComponentOp::AcquireKnowledge { + subject: Ref::Existing(subject), + fact: Ref::Existing(fact), + source, + confidence: Confidence::Certain, + } + } + + fn minted_claim(kernel: &WorldKernel) -> EntityId { + kernel + .events() + .last() + .expect("the committed event") + .speech + .expect("a speech act names its claim") + } + + /// Verification 5, first half: a patch adds knowledge only by citing an + /// accessible fact, and a rejected citation allocates nothing. + #[test] + fn knowledge_citing_an_inaccessible_fact_is_rejected() { + let (mut kernel, speech, active) = speech_kernel("Inaccessible"); + let before = kernel.state.clone(); + + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + EntityId::issue(), + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::UnknownCanonical { + site: Site::Operation(0), + expected: RefKind::Entity(EntityKind::Fact), + }] + ); + // A live referent of the wrong kind names the kind it actually is. + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.hall, + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::WrongKind { + site: Site::Operation(0), + referent: RefName::Entity(Ref::Existing(speech.hall)), + expected: RefKind::Entity(EntityKind::Fact), + actual: RefKind::Entity(EntityKind::Place), + }] + ); + assert_eq!(kernel.state, before); + + submit_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + assert_eq!( + knows(&kernel, speech.listener, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Witnessed) + ); + } + + /// Standing is what a fact *is*, so both halves are checked at declaration: + /// canon needs its receipt in the same patch, a claim needs a live asserter. + #[test] + fn a_canonical_fact_needs_evidence_and_a_claim_needs_an_asserter() { + let mut draft = WorldKernel::create(creation("Standing"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let start = draft.snapshot().unwrap(); + let declare = + |standing: FactStandingRef, evidence: Vec| CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rumour"), + label: "a rumour".into(), + statement: Statement::new("The reeve took two tithes.").unwrap(), + standing, + })], + operations: Vec::new(), + evidence, + }, + }; + + assert_eq!( + reject_play( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:absent"), + }, + Vec::new(), + ), + ), + vec![Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("rumour"), + }] + ); + assert_eq!( + reject_play( + &mut draft, + &start, + declare( + FactStandingRef::Claimed { + by: Ref::Draft(DraftHandle::new("nobody")), + }, + Vec::new(), + ), + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("rumour")), + referent: DraftHandle::new("nobody"), + expected: RefKind::Subject(None), + }] + ); + assert!(draft.state.facts.is_empty()); + + submit_play( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:rumour"), + }, + vec![EvidenceRef::new("vault:rumour")], + ), + ); + assert_eq!(draft.state.facts.len(), 1); + // The bijection holds in both directions. + let fact = *draft.state.facts.keys().next().unwrap(); + assert_eq!(draft.state.entities[&fact].kind, EntityKind::Fact); + } + + /// A receipt vouches for canon. It cannot vouch for an assertion the kernel + /// never evaluated. + #[test] + fn evidenced_knowledge_of_a_claim_is_rejected() { + let (mut kernel, speech, _) = speech_kernel("Evidenced"); + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The gate was left open.", + ), + ) + .expect("the proclamation commits"); + let claim = minted_claim(&kernel); + let active = kernel.snapshot().unwrap(); + + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + claim, + AuthoredSource::Evidenced + )]), + ), + vec![Mismatch::EvidencedKnowledgeOfClaim { operation: 0 }] + ); + submit_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + speech.flood, + AuthoredSource::Evidenced, + )]), + ); + assert_eq!( + knows(&kernel, speech.stranger, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Evidenced) + ); + assert_eq!( + kernel.state.facts[&speech.flood].standing, + FactStanding::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + } + ); + } + + /// The fan-out is the audience, less the speaker: co-located speech fills + /// the exact room, and the utterance lands in `facts` and nowhere else. + #[test] + fn speak_fans_out_to_the_audience_and_not_beyond() { + let (mut kernel, speech, active) = speech_kernel("FanOut"); + utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Mind the hinge.", + ), + ) + .expect("the whisper commits"); + + let events = kernel.events(); + let event = events.last().expect("the committed event"); + let claim = event.speech.expect("a speech act names its claim"); + assert_eq!(spoken(&kernel.state, event), Some("Mind the hinge.")); + assert_eq!( + knows(&kernel, speech.listener, claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: None, + }, + acquired_at: active.revision + 1, + }) + ); + // The yard is inside the hall, but a voice fills a room and not the + // district containing it. The speaker's own claim is not implied. + for outside in [speech.bystander, speech.stranger, speech.speaker] { + assert_eq!(knows(&kernel, outside, claim), None); + } + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + // The utterance has exactly one home: a label is a name, not a + // transcript. + assert_ne!(kernel.state.entities[&claim].label, "Mind the hinge."); + } + + /// Co-location is the exact place; a channel's `Reach::Place` is the + /// subtree, through the same containment walk a jurisdiction uses. + #[test] + fn co_location_reach_is_the_exact_place_and_a_channel_place_is_the_subtree() { + let (mut kernel, speech, _) = speech_kernel("Reach"); + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn carries.", + ), + ) + .expect("the proclamation commits"); + let broadcast = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, broadcast).is_some()); + assert!(knows(&kernel, speech.bystander, broadcast).is_some()); + assert_eq!(knows(&kernel, speech.stranger, broadcast), None); + + // The same speaker's voice reaches only the hall. + utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "A voice does not.", + ), + ) + .expect("the whisper commits"); + let voiced = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, voiced).is_some()); + assert_eq!(knows(&kernel, speech.bystander, voiced), None); + + // Moving the bystander up the stair puts it in both audiences. + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Now you hear it.", + ), + ) + .expect("the whisper commits"); + assert!(knows(&kernel, speech.bystander, minted_claim(&kernel)).is_some()); + } + + /// The delta of a telling is a property of the world, not a defect in the + /// proposal: speaking alone commits the claim and the event and lands + /// nothing. + #[test] + fn speaking_into_an_empty_room_commits_the_claim_and_lands_nothing() { + let (mut kernel, speech, _) = speech_kernel("EmptyRoom"); + let knowledge_before = kernel.state.knowledge.clone(); + utter(&mut kernel, speech.bystander, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Nobody is here.", + ), + ) + .expect("speech into an empty room commits"); + + assert_eq!(kernel.state.knowledge, knowledge_before); + assert_eq!(kernel.events().len(), 1); + assert_eq!( + spoken(&kernel.state, kernel.events().last().unwrap()), + Some("Nobody is here.") + ); + assert_eq!( + kernel + .state + .facts + .values() + .filter(|record| matches!(record.standing, FactStanding::Claimed { .. })) + .count(), + 1 + ); + } + + + fn show( + affordance: AffordanceId, + bindings: Vec, + speech: Option<&str>, + display: &str, + ) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: speech.map(|text| Statement::new(text).unwrap()), + display: Some(Statement::new(display).unwrap()), + } + } + + /// A visible act is the room's to see and nobody else's: everyone standing + /// in the actor's place holds it as `Seen { by }`; the actor, the yard + /// below, and the placeless hold nothing. The entry's own audience is not + /// consulted: a proclamation down the horn carries its words to the yard + /// and still folds its arms only before the hall. + #[test] + fn a_display_is_seen_by_the_room_and_by_no_one_else() { + let (mut kernel, speech, active) = speech_kernel("Display"); + utter(&mut kernel, speech.speaker, + show( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + Some("The horn carries."), + "I fold my arms.", + ), + ) + .expect("the proclamation with a display commits"); + + let events = kernel.events(); + let event = events.last().expect("the committed event"); + let said = event.speech.expect("the utterance names its claim"); + let seen = event.display.expect("the display names its claim"); + assert_ne!(said, seen); + assert_eq!(kernel.state.facts[&seen].statement.as_str(), "I fold my arms."); + assert_eq!( + kernel.state.facts[&seen].standing, + FactStanding::Claimed { by: speech.speaker } + ); + assert!(knows(&kernel, speech.bystander, said).is_some()); + assert_eq!( + knows(&kernel, speech.listener, seen), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Seen { by: speech.speaker }, + acquired_at: active.revision + 1, + }) + ); + for blind in [speech.bystander, speech.stranger, speech.speaker] { + assert_eq!(knows(&kernel, blind, seen), None); + } + // One act minted both claims, so the listener's snapshot stamps both + // rows with the one revision. + let snapshot = kernel.snapshot().unwrap(); + let listener = snapshot + .subjects + .iter() + .find(|subject| subject.id == speech.listener) + .unwrap(); + let stamps: BTreeSet> = listener + .knowledge + .iter() + .filter(|row| row.fact == said || row.fact == seen) + .map(|row| row.minted_at) + .collect(); + assert_eq!(stamps, BTreeSet::from([Some(event.revision)])); + } + + /// A silent turn: the kernel `speak` entry invoked with no utterance and a + /// display is an address, not `SpeechRequired`. The act lands, no speech + /// claim is minted, and alone in the yard the same act commits its claim + /// and lands nothing, as speaking alone does. + #[test] + fn a_silent_display_addresses_the_room_through_the_speak_entry() { + let (mut kernel, speech, active) = speech_kernel("Silent"); + let speak = affordance_named(&active, "speak"); + utter(&mut kernel, speech.speaker, + show(speak, Vec::new(), None, "I nod toward the stair."), + ) + .expect("a silent act commits"); + let events = kernel.events(); + let event = events.last().unwrap(); + assert!(event.speech.is_none()); + let seen = event.display.expect("the display names its claim"); + assert_eq!( + knows(&kernel, speech.listener, seen).map(|held| held.source), + Some(KnowledgeSource::Seen { by: speech.speaker }) + ); + assert_eq!(claimed(&kernel), 1); + + let knowledge_before = kernel.state.knowledge.clone(); + utter(&mut kernel, speech.bystander, + show(speak, Vec::new(), None, "I sit on the step."), + ) + .expect("a display into an empty room commits"); + assert_eq!(kernel.state.knowledge, knowledge_before); + assert_eq!(kernel.events().len(), 2); + assert_eq!(claimed(&kernel), 2); + } + + /// The refusals, each at its own layer: a padded act is `EmptyDisplay` at + /// the check; a speech-carrying entry given neither words nor act is + /// `SpeechRequired`; the placeless stranger has no room to be seen in and + /// fails the entry's own `NoAudience`. None of them mints anything. + #[test] + fn a_display_is_refused_when_empty_placeless_or_when_nothing_is_addressed() { + let (mut kernel, speech, active) = speech_kernel("Refused"); + let speak = affordance_named(&active, "speak"); + let mut padded = show(speak, Vec::new(), None, "placeholder"); + padded.display = Some(serde_json::from_str::("\" \"").unwrap()); + assert_eq!( + rejected(utter(&mut kernel, speech.speaker, padded)), + vec![ActionMismatch::EmptyDisplay] + ); + let mute = DecisionInvocation { + affordance: speech.whisper, + bindings: vec![binding("target", Target::Subject(speech.listener))], + proposed: Vec::new(), + speech: None, + display: None, + }; + assert_eq!( + rejected(utter(&mut kernel, speech.speaker, mute)), + vec![ActionMismatch::SpeechRequired] + ); + assert_eq!( + rejected(utter(&mut kernel, speech.stranger, + show(speak, Vec::new(), None, "I shrug."), + )), + vec![ActionMismatch::NoAudience { precondition: 0 }] + ); + assert!(kernel.events().is_empty()); + assert_eq!(claimed(&kernel), 0); + } + + /// The claims a display minted, its `Seen` rows, and its event replay from + /// the journal exactly, through the same path as speech. + #[test] + fn restart_replay_after_a_display_is_exact() { + let (speech, exported, expected) = { + let mut kernel = WorldKernel::create(creation("ReplayDisplay"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + let speak = affordance_named(&active, "speak"); + utter(&mut kernel, speech.speaker, + show(speak, Vec::new(), Some("One."), "I raise one finger."), + ) + .expect("the act commits"); + utter(&mut kernel, speech.listener, + show(speak, Vec::new(), None, "I look away."), + ) + .expect("the silent act commits"); + (speech, kernel.export().unwrap(), kernel.state.clone()) + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(reopened.state, expected); + assert!(reopened + .state + .knowledge_of(speech.listener) + .any(|(_, held)| held.source == KnowledgeSource::Seen { by: speech.speaker })); + assert!(reopened + .state + .knowledge_of(speech.speaker) + .any(|(_, held)| held.source == KnowledgeSource::Seen { by: speech.listener })); + } + + fn claimed(kernel: &WorldKernel) -> usize { + kernel + .state + .facts + .values() + .filter(|record| matches!(record.standing, FactStanding::Claimed { .. })) + .count() + } + + /// The horn belongs to the temple: its controller may speak on it whether + /// or not it stands inside its reach, and removing the controller flips the + /// same invocation to exactly one named failure. + #[test] + fn a_channel_controller_may_speak_outside_its_own_reach() { + let (mut kernel, speech, active) = speech_kernel("Controller"); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.listener)])), + }]), + ); + let proclaim = || { + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn still carries.", + ) + }; + utter(&mut kernel, speech.speaker, proclaim()) + .expect("the controller may speak on its own channel"); + + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::SetController { + channel: Ref::Existing(speech.horn), + controller: None, + }]), + ); + assert_eq!( + rejected(utter(&mut kernel, speech.speaker, proclaim())), + vec![ActionMismatch::NoAudience { precondition: 0 }] + ); + } + + /// Addressing does not narrow the audience, and a target outside it names + /// itself. A target that walked in mid-flight commits, and the whole + /// audience receives the telling, not only the addressed subject. + #[test] + fn an_addressed_subject_outside_the_audience_names_itself() { + let (mut kernel, speech, active) = speech_kernel("Addressing"); + let whisper = || { + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Come inside.", + ) + }; + assert_eq!( + rejected(utter(&mut kernel, speech.speaker, whisper())), + vec![ActionMismatch::CannotReach { precondition: 0 }] + ); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + utter(&mut kernel, speech.speaker, whisper()) + .expect("the addressed subject is now in the room"); + let claim = minted_claim(&kernel); + assert!(knows(&kernel, speech.bystander, claim).is_some()); + assert!( + knows(&kernel, speech.listener, claim).is_some(), + "speaking to someone in a room is heard by the room" + ); + } + + /// `Knows` compares confidence with one `>=`, and `Forget` removes the key + /// rather than storing a zero. + #[test] + fn knows_fails_below_its_confidence_and_forget_removes() { + let (mut kernel, speech, active) = speech_kernel("Knows"); + let recant = || DecisionInvocation { + affordance: speech.recant, + bindings: vec![binding("fact", Target::Entity(speech.flood))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + assert_eq!( + rejected(utter(&mut kernel, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }] + ); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + rejected(utter(&mut kernel, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }], + "Believed falls short of Certain" + ); + + submit_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + utter(&mut kernel, speech.listener, recant()) + .expect("certainty admits the recant"); + // Absence is the one shape of knowing nothing: no row. + assert!(kernel.state.knowledge_of(speech.listener).next().is_none()); + + let active = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + + /// A telling never overwrites and never downgrades: the knower owns its own + /// credence. + #[test] + fn a_telling_never_overwrites_a_holder() { + let (mut kernel, speech, active) = speech_kernel("NoOverwrite"); + submit_play( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + let before = knows(&kernel, speech.listener, speech.flood); + let active = kernel.snapshot().unwrap(); + + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + assert_eq!(knows(&kernel, speech.listener, speech.flood), before); + assert_eq!( + knows(&kernel, speech.bystander, speech.flood), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + acquired_at: active.revision + 1, + }) + ); + } + + /// Ontology admission: communication reaches only subjects inside the + /// channel's reach, and a speaker outside it is not speaking. + #[test] + fn communicating_from_outside_the_audience_is_rejected() { + let (mut kernel, speech, active) = speech_kernel("OutsideAudience"); + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert!(kernel.state.knowledge.is_empty()); + } + + /// The two allocation sites, asserted: only `derive_id` allocates, and the + /// action lane's one referent per invocation is reproduced by calling it + /// directly with the recorded world, command, handle, and discriminator. + #[test] + fn every_canonical_id_comes_from_one_of_two_sites() { + let (mut kernel, speech, active) = speech_kernel("Allocation"); + let world_id = kernel.state.header.world_id; + let caller = play_caller(); + let entities_before = kernel.state.entities.len(); + let whisper = command( + &active, + caller.clone(), + CommandBody::Act { + actor: speech.speaker, + invocation: say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Counted.", + ), + }, + ); + let command_id = whisper.id(); + kernel + .submit(whisper, &AuthenticatedCaller::fixture(caller)) + .expect("the whisper commits"); + + let claim = minted_claim(&kernel); + assert_eq!( + claim, + EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ghostlight.speech"), + Some("0"), + )) + ); + // Exactly one referent, always a fact, always claimed by the actor. + assert_eq!(kernel.state.entities.len(), entities_before + 1); + assert_eq!(kernel.state.entities[&claim].kind, EntityKind::Fact); + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + } + + /// Replay is exact because every allocation derives from committed inputs + /// and every fan-out is re-derived at apply from the audience plus live + /// state. + #[test] + fn restart_replay_after_speech_is_exact() { + let (speech, exported, expected, expected_events) = { + let mut kernel = WorldKernel::create(creation("ReplaySpeech"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, _) = speech_world(&mut kernel); + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "One.", + ), + ) + .expect("the first proclamation commits"); + utter(&mut kernel, speech.listener, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.speaker))], + "Two.", + ), + ) + .expect("the whisper commits"); + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + let exported = kernel.export().unwrap(); + (speech, exported, kernel.state.clone(), kernel.events()) + }; + + let reopened = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(reopened.state.facts, expected.facts); + assert_eq!(reopened.state.channels, expected.channels); + assert_eq!(reopened.state.knowledge, expected.knowledge); + assert_eq!(reopened.events(), expected_events); + assert_eq!(reopened.state, expected); + assert!(reopened.state.knowledge_of(speech.bystander).next().is_some()); + } + + /// A forged claim does not apply, and a forged recipient list is + /// unrepresentable: `ResolvedOp::Communicate` stores an audience, never + /// recipients. + #[test] + fn a_forged_claim_or_forged_recipient_does_not_apply() { + let (kernel, speech, _) = speech_kernel("Forgery"); + let command_id = CommandId::issue(); + let caller = play_caller(); + let invocation = say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "Honest.", + ); + let granted = require_granted(&kernel.state, speech.speaker, invocation.affordance).unwrap(); + let honest = action::exercise( + &kernel.state, + command_id, + speech.speaker, + &granted, + &invocation, + ) + .expect("the honest event derives"); + let fact = honest.speech.expect("the honest claim"); + + let mut forged_claim = honest.clone(); + forged_claim.speech = Some(speech.flood); + let mut forged_statement = honest.clone(); + forged_statement.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Forged.").unwrap(), + by: speech.speaker, + }; + let mut forged_asserter = honest.clone(); + forged_asserter.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Honest.").unwrap(), + by: speech.listener, + }; + for forged in [forged_claim, forged_statement, forged_asserter] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + + // A recipient list cannot be forged because none is stored. + assert!(matches!( + honest.effects[1], + ResolvedOp::Communicate { + to: Audience::Channel(_), + .. + } + )); + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation, + event: honest, + }, + ) + .expect("the honest event applies"); + assert!(candidate.knowledge_of(speech.listener).next().is_some()); + } + + /// The scope table: a telling moves its listener's scope and leaves a bystander + /// alone, and a reach change moves only the controller's scope. + #[test] + fn a_telling_moves_only_the_listeners_scope() { + let (mut kernel, speech, _) = speech_kernel("ScopeMove"); + let digest = |kernel: &WorldKernel, subject: SubjectId| { + scope_components(&kernel.state, subject) + }; + let listener_before = digest(&kernel, speech.listener); + let bystander_before = digest(&kernel, speech.bystander); + + utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Only you.", + ), + ) + .expect("the whisper commits"); + assert_ne!(digest(&kernel, speech.listener), listener_before); + assert_eq!(digest(&kernel, speech.bystander), bystander_before); + + // Reach membership is admission-only: adding a hearer moves the + // controller's digest and nobody else's. + let active = kernel.snapshot().unwrap(); + let hearer_before = digest(&kernel, speech.listener); + let speaker_before = digest(&kernel, speech.speaker); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.stranger)])), + }]), + ); + assert_eq!(digest(&kernel, speech.listener), hearer_before); + assert_ne!(digest(&kernel, speech.speaker), speaker_before); + } + + /// A speech-carrying entry names exactly one audience: none is unlowerable + /// and two is unchoosable. Each rejection allocates no `AffordanceId`. + #[test] + fn a_speech_carrying_entry_must_declare_exactly_one_audience() { + let mut kernel = WorldKernel::create(creation("SpeechAudience"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let before = kernel.snapshot().unwrap(); + let catalog_before = kernel.state.affordance_catalog.len(); + let declare = |preconditions: Vec| CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("herald"), + kind: AffordanceKindName("herald".into()), + roles: Vec::new(), + preconditions, + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }; + assert_eq!( + reject_play(&mut kernel, &before, declare(Vec::new())), + vec![Mismatch::SpeechWithoutAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!( + reject_play( + &mut kernel, + &before, + declare(vec![ + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ]), + ), + vec![Mismatch::AmbiguousSpeechAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), catalog_before); + } + + /// The kernel does not compare two statements: no dedup, no interning, no + /// contradiction check, no similarity. A claim byte-identical to a + /// canonical fact and one that plainly negates it commit identically. + #[test] + fn the_kernel_never_compares_two_statements() { + let run = |name: &str, text: &str| { + let (mut kernel, speech, _) = speech_kernel(name); + let receipt = utter(&mut kernel, speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + text, + ), + ) + .expect("both statements commit identically"); + assert!(receipt.resulting_revision > 0); + let events = kernel.events(); + let event = events.last().unwrap().clone(); + (kernel, speech, event) + }; + let (agreeing, agreeing_speech, agreeing_event) = run("agree", FLOOD_STATEMENT); + let (negating, _, negating_event) = run("negate", "The lower hinge is dry."); + + assert_eq!(agreeing_event.band, negating_event.band); + assert_eq!(agreeing_event.effects.len(), negating_event.effects.len()); + assert_eq!(agreeing.state.facts.len(), negating.state.facts.len()); + // Two facts with byte-identical statements are two facts: the claim is + // not the canonical fact it repeats, and neither run learned anything + // about the other's meaning. + let claim = agreeing_event.speech.unwrap(); + assert_ne!(claim, agreeing_speech.flood); + assert_eq!( + agreeing.state.facts[&claim].statement, + agreeing.state.facts[&agreeing_speech.flood].statement + ); + assert_ne!( + agreeing.state.facts[&claim].standing, + agreeing.state.facts[&agreeing_speech.flood].standing + ); + } +} + +/// Soul's pass-6 falsification set. Each test names the claim it attacks and, +/// where the landed behaviour differs from the specified one, pins the actual +/// behaviour so the difference is visible rather than assumed. +#[cfg(test)] +mod soul_knowledge_tests { + use super::tests::{ + act, play_caller, FLOOD_STATEMENT, Speech, affordance_named, auth_principal, command, creation, operations, + owner, speech_world, submit_play, + }; + use super::*; + + fn speech_kernel(title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + (kernel, speech, active) + } + + fn say(affordance: AffordanceId, bindings: Vec, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn utter( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + act(kernel, actor, invocation) + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&(subject, fact)) + .copied() + } + + fn digest_of(kernel: &WorldKernel, subject_id: SubjectId) -> ScopeComponents { + scope_components(&kernel.state, subject_id) + } + + fn minted_claim(kernel: &WorldKernel) -> EntityId { + kernel + .events() + .last() + .expect("the committed event") + .speech + .expect("a speech act names its claim") + } + + /// A channel's controller carries exactly one privilege: `can_broadcast` + /// lets it sound the horn from outside the declared reach. `audience` + /// itself never folds the controller in, so the controller is not a + /// recipient of a telling it did not stand inside, whether the telling is + /// its own or another subject's. + #[test] + fn soul_a_channel_controller_hears_what_it_is_out_of_reach_of() { + let (mut kernel, speech, active) = speech_kernel("ControllerHears"); + // The horn now reaches exactly one subject. The speaker controls it and + // is not in that set. + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.listener)])), + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + kernel.state.channels[&speech.horn].reach, + Reach::Subjects(BTreeSet::from([speech.listener])) + ); + + // The controller may still speak from outside its own reach — the horn + // belongs to the temple — and the listener, who stands inside the + // reach, hears it. + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn is mine to sound.", + ), + ) + .expect("the controller may speak on its own channel"); + let controllers_claim = minted_claim(&kernel); + assert_eq!( + knows(&kernel, speech.listener, controllers_claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + acquired_at: active.revision + 1, + }) + ); + // The controller gains no knowledge of its own claim: it is outside + // the reach, and speaking privilege is not audience membership. + assert_eq!(knows(&kernel, speech.speaker, controllers_claim), None); + + // Now the listener speaks on the same channel. + utter(&mut kernel, speech.listener, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn is mine tonight.", + ), + ) + .expect("a subject inside the reach may broadcast"); + let claim = minted_claim(&kernel); + + // The declared reach names the listener alone, and the listener spoke, + // so the declared fan-out is empty. The controller — outside the + // reach, and not the speaker this time either — learns nothing. + assert_eq!( + knows(&kernel, speech.speaker, claim), + None, + "the controller does not gain knowledge through fan-out" + ); + assert_eq!(knows(&kernel, speech.bystander, claim), None); + assert_eq!(knows(&kernel, speech.stranger, claim), None); + assert_eq!(knows(&kernel, speech.listener, claim), None); + } + + /// Every speech precondition fails at `exercise`, before the band draw and + /// before the speech lowering, so a refused utterance mints no claim and + /// leaves the whole committed state byte-identical. Nothing here reaches + /// replay to be caught later. + #[test] + fn soul_a_refused_utterance_dies_at_the_gate_and_allocates_nothing() { + let (mut kernel, speech, active) = speech_kernel("GateNotReplay"); + let speak = affordance_named(&active, "speak"); + let before = kernel.state.clone(); + + let cases: Vec<(SubjectId, DecisionInvocation, Vec)> = vec![ + // Unplaced: no co-location audience at all. + ( + speech.stranger, + say(speak, Vec::new(), "Anyone?"), + vec![ActionMismatch::NoAudience { precondition: 0 }], + ), + // Addressed at a subject one containment level down. + ( + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Down there.", + ), + vec![ActionMismatch::CannotReach { precondition: 0 }], + ), + // `recant` requires `Knows { at_least: Certain }` of the bound fact. + // Its unproposed slot names itself beside the precondition; the + // point is that the complete set lands at the gate, in one pass. + ( + speech.speaker, + DecisionInvocation { + affordance: speech.recant, + bindings: vec![binding("fact", Target::Entity(speech.flood))], + proposed: Vec::new(), + speech: None, + display: None, + }, + vec![ + ActionMismatch::SlotNotProposed { slot: 0 }, + ActionMismatch::FactUnknown { precondition: 0 }, + ], + ), + ]; + + for (actor, invocation, expected) in cases { + let error = utter(&mut kernel, actor, invocation).unwrap_err(); + let KernelError::ActionRejected(mismatches) = error else { + panic!("expected an action rejection, got {error:?}"); + }; + assert_eq!(mismatches, expected); + // No claim, no entity row, no event, no revision: the gate ran + // before anything was drawn or lowered. + assert_eq!(kernel.state, before); + } + } + + /// Fan-out is the sole way knowledge enters another subject from speech, and + /// it is not carried by the effect. A forged `Acted` that widens + /// the audience, appends a second telling, or tells a foreign fact is refused + /// by `apply_effect` itself, so replay is never the first reader to notice. + #[test] + fn soul_a_forged_wider_audience_does_not_apply() { + let (kernel, speech, _) = speech_kernel("WiderAudience"); + let command_id = CommandId::issue(); + let caller = play_caller(); + let invocation = say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Only the hall.", + ); + let granted = require_granted(&kernel.state, speech.speaker, invocation.affordance).unwrap(); + let honest = action::exercise( + &kernel.state, + command_id, + speech.speaker, + &granted, + &invocation, + ) + .expect("the honest event derives"); + let fact = honest.speech.expect("the honest claim"); + assert_eq!( + honest.effects[1], + ResolvedOp::Communicate { + speaker: speech.speaker, + fact, + to: Audience::Colocated, + } + ); + + // Widened to the horn, which covers the yard through `covers_place`. + let mut widened = honest.clone(); + widened.effects[1] = ResolvedOp::Communicate { + speaker: speech.speaker, + fact, + to: Audience::Channel(speech.horn), + }; + // A second telling appended to the same event. + let mut doubled = honest.clone(); + doubled.effects.push(ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }); + // A telling of a fact this act did not mint. + let mut foreign = honest.clone(); + foreign.effects[1] = ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }; + + for forged in [widened, doubled, foreign] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + } + + /// The reducer re-derives the audience gate from committed state, so a forged + /// `Communicate` for a speaker with no standing in the room is refused even + /// when the fact is live and the event carries no mismatch. The same telling + /// by a speaker who is in the room applies. + #[test] + fn a_telling_by_a_speaker_outside_its_audience_does_not_apply() { + let (kernel, speech, _) = speech_kernel("OutsideAudience"); + let resolves_to = kernel.state.revision + 1; + + let mut candidate = kernel.state.clone(); + let error = apply_operation( + &mut candidate, + &ResolvedOp::Communicate { + speaker: speech.stranger, + fact: speech.flood, + to: Audience::Colocated, + }, + &[], + resolves_to, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + + let mut candidate = kernel.state.clone(); + apply_operation( + &mut candidate, + &ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }, + &[], + resolves_to, + ) + .expect("a speaker inside its audience tells"); + } + + /// A speech act that lands nothing moves no digest at all, the speaker's own + /// included. `AssertClaim` writes `entities` and `facts`, and neither is a + /// scope component, so an in-flight proposal held by anyone in the world + /// survives an utterance nobody heard. + #[test] + fn soul_speech_that_lands_nothing_moves_no_digest_including_the_speakers() { + let (mut kernel, speech, active) = speech_kernel("NoDigestMove"); + let speak = affordance_named(&active, "speak"); + let everyone = [ + speech.speaker, + speech.listener, + speech.bystander, + speech.stranger, + ]; + let before: Vec = everyone + .iter() + .map(|subject| digest_of(&kernel, *subject)) + .collect(); + let facts_before = kernel.state.facts.len(); + + // The bystander stands alone in the yard. + utter(&mut kernel, speech.bystander, + say(speak, Vec::new(), "Nobody is here."), + ) + .expect("speaking into an empty room commits"); + + assert_eq!(kernel.state.facts.len(), facts_before + 1); + assert_eq!(kernel.events().len(), 1); + assert!(kernel.state.knowledge.is_empty()); + for (subject, digest) in everyone.iter().zip(before) { + assert_eq!( + digest_of(&kernel, *subject), + digest, + "an utterance nobody heard moved a scope" + ); + } + } + + /// The resolver does not model a `Communicate`'s fan-out, so a same-patch + /// telling followed by a `Forget` of what that telling would have landed is + /// refused at resolve although apply would accept it. The asymmetry is + /// fail-closed, and it does not refuse the order that must work: forgetting + /// first and being told again in the same patch commits, and the telling is + /// what the subject ends up holding. + #[test] + fn soul_a_same_patch_telling_then_forget_fails_closed_only() { + let (mut kernel, speech, active) = speech_kernel("SamePatchOrder"); + let tell = ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }; + let forget = ComponentOp::Forget { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + }; + + let error = kernel + .submit( + command( + &active, + CallerId::Play, + operations(vec![tell.clone(), forget.clone()]), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + assert_eq!( + mismatches, + vec![Mismatch::NoOperationEffect { operation: 1 }] + ); + + // The legitimate order. The listener holds the fact first, forgets it, + // and the telling in the same patch lands it again as a telling, which + // is what the committed state carries. + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }]), + ); + let active = kernel.snapshot().unwrap(); + submit_play(&mut kernel, &active, operations(vec![forget, tell])); + assert_eq!( + knows(&kernel, speech.listener, speech.flood), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: None, + }, + acquired_at: active.revision + 1, + }) + ); + } + + /// `verify_state_shape` checks the forward speech direction only: an event's + /// claim is asserted by the acting subject and named by no other event. The + /// reverse, that every claim is named by some event, is deliberately absent, + /// because a world may declare a claim with no event behind it, in Draft + /// or, by the play table, in Active. Such a + /// claim is a valid shape and its store reopens. + #[test] + fn an_orphan_claim_is_a_valid_shape_and_reopens() { + let (mut kernel, speech, active) = speech_kernel("OrphanClaim"); + // The Draft-declared fact is an orphan by construction: no event names + // it. Reopening runs the shape verifier over the replayed state. + assert!(kernel.state.facts.contains_key(&speech.flood)); + assert!( + kernel + .events() + .iter() + .all(|event| event.speech.is_none()) + ); + + let before = kernel.state.clone(); + let receipt = kernel + .submit( + command( + &active, + CallerId::Play, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rumour"), + label: "a rumour".into(), + statement: Statement::new("The gate is unguarded.").unwrap(), + standing: FactStandingRef::Claimed { + by: Ref::Existing(speech.speaker), + }, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(CallerId::Play), + ) + .expect("the play table declares a claim in Active"); + assert!(receipt.resulting_revision > 0); + assert_eq!(kernel.state.facts.len(), before.facts.len() + 1); + let facts = kernel.state.facts.clone(); + let exported = kernel.export().unwrap(); + drop(kernel); + let replayed = WorldKernel::open(&exported).expect("the orphan store is healthy"); + assert_eq!(replayed.state.facts, facts); + } + + /// Replay equality across every new arm, twice, with no RNG and no clock in + /// any of them: a speech act, a telling, an authored acquisition, a forget, + /// a reach change, and a controller change all reproduce byte-identically + /// from the journal, and reopening again reproduces the same state. + #[test] + fn soul_replay_is_exact_across_every_new_arm() { + let (exported, expected, expected_events) = { + let (mut kernel, speech, _) = speech_kernel("ReplayArms"); + utter(&mut kernel, speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The hinge is flooding.", + ), + ) + .expect("the proclamation commits"); + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ + ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }, + ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }, + ComponentOp::SetController { + channel: Ref::Existing(speech.horn), + controller: Some(Ref::Existing(speech.listener)), + }, + ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Place(Ref::Existing(speech.yard)), + }, + ]), + ); + let active = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + }]), + ); + assert!(!kernel.state.knowledge.is_empty()); + assert!(!kernel.state.facts.is_empty()); + (kernel.export().unwrap(), kernel.state.clone(), kernel.events()) + }; + + for _ in 0..2 { + let replayed = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(replayed.state.facts, expected.facts); + assert_eq!(replayed.state.channels, expected.channels); + assert_eq!(replayed.state.knowledge, expected.knowledge); + assert_eq!(replayed.state.entities, expected.entities); + assert_eq!(replayed.events(), expected_events); + assert_eq!(replayed.state, expected); + } + } + + /// The statement's bytes are stored twice, and only one of the two copies + /// is a read surface. `facts[fact].statement` is the readable home: + /// `spoken()` and every projection consult it. The committed event's own + /// `AssertClaim` effect carries the same bytes as the replay witness — + /// required so `apply_effect` can re-derive the identical event on replay + /// without re-deriving the statement from elsewhere — but nothing reads + /// that copy back out. Those two are the whole of it, and neither reaches + /// a subject-facing surface. + #[test] + fn soul_the_utterance_is_stored_in_facts_and_in_the_committed_effect() { + let (mut kernel, speech, active) = speech_kernel("OneHome"); + let speak = affordance_named(&active, "speak"); + let text = "A statement that appears nowhere else."; + utter(&mut kernel, speech.speaker, + say(speak, Vec::new(), text), + ) + .expect("the kernel speak commits"); + let claim = minted_claim(&kernel); + + assert_eq!(kernel.state.facts[&claim].statement.as_str(), text); + assert_eq!( + kernel.state.entities[&claim].label, CLAIM_LABEL, + "the label is a name, not a transcript" + ); + // The event no longer embeds the invocation, and its `speech` field is + // the fact id. The bytes still appear in the event, inside the committed + // `AssertClaim` effect. + let events = kernel.events(); + let event = events.last().unwrap(); + assert_eq!(event.speech, Some(claim)); + assert_eq!( + event.effects[0], + ResolvedOp::AssertClaim { + fact: claim, + statement: Statement::new(text).unwrap(), + by: speech.speaker, + }, + "the event carries the statement as a replay witness, not a second read surface" + ); + // The facts are the whole of it: strip them and the + // rest of the state is silent. + let mut stripped = kernel.state.clone(); + let facts: Vec<_> = stripped.facts.keys().copied().collect(); + for fact in facts { + stripped.facts.remove(&fact); + } + let encoded = stripped.encoded_documents(); + assert!( + !encoded + .windows(text.len()) + .any(|window| window == text.as_bytes()) + ); + // The statement declared in Draft is untouched by any of it. + assert_eq!( + kernel.state.facts[&speech.flood].statement.as_str(), + FLOOD_STATEMENT + ); + } +} + +/// One witnessed event over a place subtree: who it reaches, who it leaves +/// alone, where it is refused, and what it costs an in-flight binding. +#[cfg(test)] +mod witness_tests { + use super::tests::{ + play_caller, auth_principal, command, creation, operations, owner, + reject_play, submit_play, + }; + use super::*; + + /// Nesting, because "under a place" is the whole question. A hemisphere + /// holds a region and a far coast; the region holds a village and one + /// unwalked hollow; subjects stand in the village, on the coast, and in the + /// hemisphere under neither. The hollow is empty so a witness has a place + /// that reaches nobody. + struct Nesting { + hemisphere: EntityId, + region: EntityId, + village: EntityId, + coast: EntityId, + hollow: EntityId, + villager: SubjectId, + neighbour: SubjectId, + coaster: SubjectId, + drifter: SubjectId, + asteroid: EntityId, + moon: EntityId, + ferry: EdgeId, + } + + fn place(handle: &str, label: &str, container: Option<&str>) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: container.map(|value| Ref::Draft(DraftHandle::new(value))), + }) + } + + fn stander(handle: &str, label: &str, place: &str, speak: &Ref) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak.clone(), Ref::Draft(DraftHandle::new("beacon"))]), + position: Some(Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + } + + fn sky_fact(handle: &str, label: &str, statement: &str, evidence: &str) -> Declaration { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + statement: Statement::new(statement).unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + } + + fn witness(fact: EntityId, place: EntityId, confidence: Confidence) -> ComponentOp { + ComponentOp::Witness { + fact: Ref::Existing(fact), + place: Ref::Existing(place), + confidence, + } + } + + fn nesting_kernel(title: &str) -> (WorldKernel, Nesting, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let before = kernel.snapshot().unwrap(); + let speak = super::tests::speak_entry(&kernel); + submit_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + place("hemisphere", "The Lit Hemisphere", None), + place("region", "The Rhythm Region", Some("hemisphere")), + place("village", "The Anchor Village", Some("region")), + place("hollow", "The Unwalked Hollow", Some("region")), + place("coast", "The Far Coast", Some("hemisphere")), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("ferry"), + label: "The Coast Ferry".into(), + from: Ref::Draft(DraftHandle::new("coast")), + to: Ref::Draft(DraftHandle::new("village")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("path"), + label: "The Hollow Path".into(), + from: Ref::Draft(DraftHandle::new("village")), + to: Ref::Draft(DraftHandle::new("hollow")), + access: AccessKind::Public, + cost: Cost(1), + }), + // A world-authored verb with no speaker in it: the + // proposer chooses which declared place the entry + // binds and nothing else. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("beacon"), + kind: AffordanceKindName("beacon".into()), + roles: vec![ + RoleSpec { + role: Role("fact".into()), + kind: RefKind::Entity(EntityKind::Fact), + }, + RoleSpec { + role: Role("place".into()), + kind: RefKind::Entity(EntityKind::Place), + }, + ], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Witness { + confidence: Confidence::Believed, + }, + roles: vec![Role("fact".into()), Role("place".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + stander("villager", "The Anchor Villager", "village", &speak), + stander("neighbour", "The Anchor Neighbour", "village", &speak), + stander("coaster", "The Coast Watcher", "coast", &speak), + stander("drifter", "The Open Drifter", "hemisphere", &speak), + sky_fact( + "asteroid", + "the asteroid over the region", + "An asteroid crossed the sky above the region.", + "vault:asteroid", + ), + sky_fact( + "moon", + "the second moon", + "A second moon rose over the hemisphere.", + "vault:moon", + ), + ], + operations: Vec::new(), + evidence: vec![ + EvidenceRef::new("vault:asteroid"), + EvidenceRef::new("vault:moon"), + ], + }, + }, + ); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared entity") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared subject") + .0 + }; + let nesting = Nesting { + hemisphere: entity("The Lit Hemisphere"), + region: entity("The Rhythm Region"), + village: entity("The Anchor Village"), + coast: entity("The Far Coast"), + hollow: entity("The Unwalked Hollow"), + villager: subject("The Anchor Villager"), + neighbour: subject("The Anchor Neighbour"), + coaster: subject("The Coast Watcher"), + drifter: subject("The Open Drifter"), + asteroid: entity("the asteroid over the region"), + moon: entity("the second moon"), + ferry: *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Coast Ferry") + .expect("a declared route") + .0, + }; + let active = kernel.snapshot().unwrap(); + (kernel, nesting, active) + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&(subject, fact)) + .copied() + } + + fn seen(confidence: Confidence, acquired_at: u64) -> Option { + Some(Knowledge { + confidence, + source: KnowledgeSource::Witnessed, + acquired_at, + }) + } + + /// The subtree is the whole reach: everyone under the named place, nobody + /// beside it, and a wider place reaches the wider set. + #[test] + fn a_witness_reaches_every_subject_under_the_place_and_no_other() { + let (mut kernel, world, active) = nesting_kernel("Reach"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Believed, + )]), + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!(knows(&kernel, world.coaster, world.asteroid), None); + assert_eq!(knows(&kernel, world.drifter, world.asteroid), None); + + let after = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &after, + operations(vec![witness( + world.moon, + world.hemisphere, + Confidence::Certain, + )]), + ); + for subject in [ + world.villager, + world.neighbour, + world.coaster, + world.drifter, + ] { + assert_eq!( + knows(&kernel, subject, world.moon), + seen(Confidence::Certain, after.revision + 1) + ); + } + + // No witness names a teller, so nothing in the world was told. + assert!( + kernel + .state + .knowledge + .values() + .all(|entry| !matches!(entry.source, KnowledgeSource::Told { .. })), + "a witness wrote a told row" + ); + } + + /// The knower owns its credence. A holder is dropped from the landing + /// whatever it holds and however it came by it, so a witness cannot reset a + /// mind by repeating itself. + #[test] + fn a_witness_never_overwrites_a_holder() { + let (kernel, world, _) = nesting_kernel("Holder"); + // `Told` has exactly one writer, so the holder's row is planted at the + // layer that can hold one and the witness is applied beside it. + let held = Knowledge { + confidence: Confidence::Doubted, + source: KnowledgeSource::Told { + by: world.coaster, + via: None, + }, + acquired_at: 0, + }; + let mut state = kernel.state.clone(); + let state_revision = state.revision; + state.knowledge.insert((world.villager, world.asteroid), held); + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place: world.region, + confidence: Confidence::Certain, + }, + &[], + state_revision + 1, + ) + .expect("the witness lands"); + assert_eq!(state.knowledge[&(world.villager, world.asteroid)], held); + assert_eq!( + state.knowledge[&(world.neighbour, world.asteroid)], + Knowledge { + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + acquired_at: state_revision + 1, + } + ); + } + + /// A witnessed event is only its reception, so a landing that reaches + /// nobody is not an event the world recorded. Both layers refuse it, and + /// they refuse the same two cases: an empty subtree, and a subtree whose + /// every stander already holds the fact. + #[test] + fn a_witness_over_nobody_is_refused_at_resolve_and_at_apply() { + let (mut kernel, world, active) = nesting_kernel("Nobody"); + let forged = |place: EntityId, state: &WorldState| { + let resolves_to = state.revision + 1; + let mut state = state.clone(); + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place, + confidence: Confidence::Certain, + }, + &[], + resolves_to, + ) + .unwrap_err() + }; + + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.hollow, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert!(matches!( + forged(world.hollow, &kernel.state), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + + // Every stander already holds it, which is the same refusal. + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain, + )]), + ); + let after = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &after, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert!(matches!( + forged(world.village, &kernel.state), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + + // A forged effect naming a place that is not one, or no live fact, is + // refused by the arm's own kind check before any of that. + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!(matches!( + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place: world.asteroid, + confidence: Confidence::Certain, + }, + &[], + resolves_to, + ) + .unwrap_err(), + KernelError::Invariant(message) if message == "a witness names no live fact or place" + )); + } + + /// The candidate map models the fan-out, so a subject this patch moved into + /// the subtree is a recipient and a subject it moved out is not. The resolve + /// layer and the apply layer agree on both. + #[test] + fn a_mid_patch_relocation_into_the_subtree_counts() { + let (mut kernel, world, active) = nesting_kernel("Relocation"); + // The village's own standers already hold it, so the relocated coaster + // is the only candidate recipient left. + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + let seeded = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &seeded, + operations(vec![ + ComponentOp::Relocate { + subject: Ref::Existing(world.coaster), + via: Ref::Existing(world.ferry), + }, + witness(world.asteroid, world.village, Confidence::Certain), + ]), + ); + assert_eq!( + kernel.state.positions[&world.coaster], + Position { + place: world.village + } + ); + assert_eq!( + knows(&kernel, world.coaster, world.asteroid), + seen(Confidence::Certain, seeded.revision + 1) + ); + + // The inverse: the coast's only stander leaves before the witness, so + // the coast reaches nobody. Both layers say so. + let moved = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &moved, + operations(vec![witness(world.moon, world.coast, Confidence::Certain)]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!(matches!( + apply_operations( + &mut state, + &[ResolvedOp::Witness { + fact: world.moon, + place: world.coast, + confidence: Confidence::Certain, + }], + &[], + resolves_to, + ) + .unwrap_err(), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + } + + /// The components carry the keys of a subject's own knowledge, so a witness + /// moves exactly the components of the subjects that learned something. + #[test] + fn a_witness_moves_every_recipients_scope_components_and_nobody_elses() { + let (mut kernel, world, active) = nesting_kernel("Digest"); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.neighbour), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Doubted, + }]), + ); + let digest = |kernel: &WorldKernel, subject_id: SubjectId| { + scope_components(&kernel.state, subject_id) + }; + let learner = digest(&kernel, world.villager); + let holder = digest(&kernel, world.neighbour); + let outsider = digest(&kernel, world.coaster); + + let seeded = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &seeded, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert_ne!(digest(&kernel, world.villager), learner); + assert_eq!(digest(&kernel, world.neighbour), holder); + assert_eq!(digest(&kernel, world.coaster), outsider); + } + + /// The slot names a fact and a place, never a subject, so an exercised + /// witness lands the subtree with no teller anywhere in it. A slot whose + /// place position binds a subject is refused before it is ever declared. + #[test] + fn a_witness_affordance_lowers_with_no_speaker() { + let (mut kernel, world, active) = nesting_kernel("Affordance"); + let beacon = *active + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .expect("the villager exists") + .affordances + .iter() + .find(|id| { + active + .affordances + .iter() + .any(|entry| entry.id == **id && entry.entry.kind.0 == "beacon") + }) + .expect("the villager holds the beacon entry"); + let caller = play_caller(); + kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::Act { + actor: world.villager, + invocation: DecisionInvocation { + affordance: beacon, + bindings: vec![ + RoleBinding { + role: Role("fact".into()), + target: Target::Entity(world.asteroid), + }, + RoleBinding { + role: Role("place".into()), + target: Target::Entity(world.region), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the beacon lands"); + assert_eq!( + kernel + .events() + .last() + .expect("a committed event") + .effects, + vec![ResolvedOp::Witness { + fact: world.asteroid, + place: world.region, + confidence: Confidence::Believed, + }] + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!(knows(&kernel, world.coaster, world.asteroid), None); + + // The second role is a place, and a subject cannot serve it, so a slot + // that named one is refused at affordance declaration. + let rules = ComponentOpKind::Witness { + confidence: Confidence::Believed, + } + .arity(); + assert_eq!(rules.len(), 2); + assert!(patch::role_kind_fits( + &rules[0], + RefKind::Entity(EntityKind::Fact) + )); + assert!(patch::role_kind_fits( + &rules[1], + RefKind::Entity(EntityKind::Place) + )); + assert!(!patch::role_kind_fits(&rules[1], RefKind::Subject(None))); + } + + /// A journal carrying a witness replays to digest equality, and the rows it + /// wrote pass the shape check with no clause of their own. + #[test] + fn a_world_with_a_witness_replays() { + let (mut kernel, world, active) = nesting_kernel("Replay"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + let committed = kernel.state.clone(); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = + WorldKernel::open(&exported).expect("it replays"); + assert_eq!(reopened.state, committed); + assert_eq!( + knows(&reopened, world.villager, world.asteroid), + seen(Confidence::Certain, active.revision + 1) + ); + } + + /// PA.f49: `acquired_at` stamps the revision the write's own commit + /// resolves to on every path, genesis included. Genesis resolves to + /// revision 0 itself — `state.revision` never advances past 0 for the + /// creating commit — so a fact a genesis patch both declares and grants + /// knowledge of lands at `acquired_at: 0`, not one revision ahead of the + /// state it was written into. + #[test] + fn a_genesis_seeded_knowledge_row_is_acquired_at_revision_zero() { + let mut creation = creation("PAf49Genesis"); + creation.patch.declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("founding"), + label: "The Founding Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Claimed { + by: Ref::Draft(DraftHandle::new("human")), + }, + })); + creation.patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Draft(DraftHandle::new("human")), + fact: Ref::Draft(DraftHandle::new("founding")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + let (kernel, _) = WorldKernel::create(creation, &auth_principal(owner())).unwrap(); + assert_eq!(kernel.state.revision, 0); + let human = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Human") + .expect("genesis admits the declared human") + .0; + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == "Stated by the table.") + .expect("genesis admits the declared fact") + .0; + assert_eq!( + kernel.state.knowledge[&(human, fact)].acquired_at, + 0, + "a genesis-seeded row landed one revision ahead of the state it was written into" + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + } + + /// PA.f49: every commit after genesis still stamps the revision it + /// resolves to, one past the state it was applied against. + #[test] + fn a_later_commits_knowledge_row_is_acquired_at_that_commits_revision() { + let (mut kernel, world, active) = nesting_kernel("PAf49Later"); + submit_play( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.villager), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }]), + ); + assert_eq!(kernel.state.revision, active.revision + 1); + assert_eq!( + kernel.state.knowledge[&(world.villager, world.asteroid)].acquired_at, + active.revision + 1 + ); + } + + /// PA.f49: the shape check refuses a knowledge row forged ahead of the + /// world's own revision — the check `verify_state_shape` gained alongside + /// the genesis fix, so a corrupt or forged `acquired_at` cannot pass + /// replay silently. + #[test] + fn a_shape_check_refuses_a_knowledge_row_forged_ahead_of_the_world_revision() { + let (mut kernel, world, active) = nesting_kernel("PAf49Shape"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + let mut forged = kernel.state.clone(); + let entry = forged + .knowledge + .get_mut(&(world.villager, world.asteroid)) + .expect("the witness landed on the villager"); + entry.acquired_at = forged.revision + 1; + assert!(journal::verify_state_shape(&forged).is_err()); + } + + /// The two callers of the shared owners answer the same question. A + /// `Reach::Place` channel's fan-out and a witness over the same place select + /// the same subjects over the same state, so "under a place" and "already a + /// knower" cannot drift between a declared broadcast area and a witnessed + /// event. A grep proves there is one body; this proves the two lanes reach + /// it. + #[test] + fn soul_a_place_reach_fan_out_and_a_witness_select_the_same_subjects() { + let (kernel, world, _) = nesting_kernel("One owner"); + let mut state = kernel.state.clone(); + // One holder, so the already-holds half of the selection is exercised + // and not merely the subtree half. + state.knowledge.insert( + (world.neighbour, world.asteroid), + Knowledge { + confidence: Confidence::Doubted, + source: KnowledgeSource::Witnessed, + acquired_at: 0, + }, + ); + for root in [world.hemisphere, world.region, world.village, world.coast] { + let horn = state + .entities + .keys() + .copied() + .find(|id| !state.channels.contains_key(id)) + .expect("an unused key for the horn"); + state.channels.insert( + horn, + patch::ChannelRecord { + reach: patch::Reach::Place(root), + controller: None, + }, + ); + for speaker in [world.coaster, world.drifter, world.villager] { + // `fan_out` is exactly the shared pair with the speaker taken + // out; the speaker clause is the only thing it owns itself. + let mut expected = under_place(&state, root); + expected.remove(&speaker); + assert_eq!( + fan_out( + &state, + speaker, + world.asteroid, + &patch::Audience::Channel(horn), + ), + unheld(&state, world.asteroid, expected), + "the two lanes disagreed about {root:?} for {speaker:?}" + ); + } + state.channels.remove(&horn); + } + } + + /// Presence in the subtree is read from `positions` alone. A place covers + /// itself, covers its children transitively, and covers nothing beside it; + /// a subject standing nowhere is under nothing, at every root including the + /// world's widest. + #[test] + fn soul_under_place_covers_itself_and_below_and_never_the_placeless() { + let (kernel, world, _) = nesting_kernel("Nesting"); + let under = |root: EntityId| under_place(&kernel.state, root); + // The village holds its two standers and nobody else. + assert_eq!( + under(world.village), + BTreeSet::from([world.villager, world.neighbour]) + ); + // The region covers the village transitively and the drifter standing + // one level above it is not swept in. + assert_eq!( + under(world.region), + BTreeSet::from([world.villager, world.neighbour]) + ); + // The hemisphere covers everything below it and the drifter standing + // exactly at it, not merely below. + assert_eq!( + under(world.hemisphere), + BTreeSet::from([ + world.villager, + world.neighbour, + world.coaster, + world.drifter, + ]) + ); + assert_eq!(under(world.coast), BTreeSet::from([world.coaster])); + assert!(under(world.hollow).is_empty()); + + // A subject with no position is under nothing, at every root including + // the world's widest, and the widest witness in the world does not + // reach it. Presence is read from `positions` alone: there is no second + // notion of being somewhere for a placeless subject to fall back on. + let mut adrift = kernel.state.clone(); + let adrift_revision = adrift.revision; + adrift.positions.remove(&world.drifter); + for root in [ + world.hemisphere, + world.region, + world.village, + world.coast, + world.hollow, + ] { + assert!( + !under_place(&adrift, root).contains(&world.drifter), + "a placeless subject was under {root:?}" + ); + } + apply_operation( + &mut adrift, + &ResolvedOp::Witness { + fact: world.moon, + place: world.hemisphere, + confidence: Confidence::Certain, + }, + &[], + adrift_revision + 1, + ) + .expect("the hemisphere still reaches the standers"); + assert!( + !adrift + .knowledge + .contains_key(&(world.drifter, world.moon)), + "a placeless subject witnessed the widest event in the world" + ); + for subject in [world.villager, world.neighbour, world.coaster] { + assert_eq!( + adrift.knowledge[&(subject, world.moon)], + Knowledge { + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + acquired_at: adrift_revision + 1, + } + ); + } + } + + /// The candidate model and the apply arm are handed a patch built so they + /// could disagree: the only subject the witness can reach is one this same + /// patch declares and places, and every subject already standing there + /// already holds the fact. If the resolver did not see the draft stander it + /// would refuse a landing the apply pass performs; if the apply pass did + /// not see it, it would refuse a landing the resolver admitted. Both see + /// it. The inverse — a draft subject declared with no position — is refused + /// by both. + #[test] + fn soul_a_subject_declared_and_placed_in_one_patch_is_a_recipient_at_both_layers() { + let (mut kernel, world, active) = nesting_kernel("Draft stander"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + let beacon = *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "beacon") + .expect("the beacon entry is declared") + .0; + let arrival = + |kernel: &mut WorldKernel, handle: &str, label: &str, position: Option| { + let snapshot = kernel.snapshot().unwrap(); + let caller = CallerId::Play; + kernel.submit( + command( + &snapshot, + caller.clone(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: format!("The Hollow Shed for {handle}"), + kind: EntityKind::Place, + container: Some(Ref::Existing(world.hollow)), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([Ref::Existing(beacon)]), + position: position.map(Ref::Existing), + import_key: None, + }), + ], + operations: vec![witness( + world.asteroid, + world.village, + Confidence::Certain, + )], + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + + // Declared with no position: under nothing, so the witness still + // reaches nobody and the resolver says so. + match arrival(&mut kernel, "ghost", "The Unplaced Arrival", None) { + Err(KernelError::PatchRejected(set)) => assert_eq!( + set, + vec![Mismatch::NoOperationEffect { operation: 0 }], + "a placeless draft subject was counted as a recipient" + ), + other => panic!("expected a refusal, got {other:?}"), + } + + // Declared and placed under the witnessed place: the resolver's + // candidate map carries the draft position, and the apply pass derives + // the same subject from live state. + let before_arrival = kernel.state.revision; + let receipt = arrival( + &mut kernel, + "arrival", + "The Village Arrival", + Some(world.village), + ); + assert!( + matches!(receipt, Ok(_)), + "{receipt:?}" + ); + let arrived = *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == "The Village Arrival") + .expect("the arrival is declared") + .0; + assert_eq!( + knows(&kernel, arrived, world.asteroid), + seen(Confidence::Certain, before_arrival + 1) + ); + // The standers who already held it kept their own rows, from the + // earlier witness, and this landing did not touch them. + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + } + + /// The other way the two layers could disagree about who already holds the + /// fact: an earlier operation in the same patch takes it away. The + /// resolver's candidate map drops the row and the apply pass drops the + /// stored one, so a forget-then-witness lands rather than being refused as + /// reaching nobody. + #[test] + fn soul_a_forget_before_a_witness_agrees_at_both_layers() { + let (mut kernel, world, active) = nesting_kernel("Forget first"); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + // Everyone under the village holds it, so the witness alone is refused. + let seeded = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &seeded, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + + let seeded = kernel.snapshot().unwrap(); + let receipt = submit_play( + &mut kernel, + &seeded, + operations(vec![ + ComponentOp::Forget { + subject: Ref::Existing(world.villager), + fact: Ref::Existing(world.asteroid), + }, + witness(world.asteroid, world.village, Confidence::Certain), + ]), + ); + assert!(receipt.resulting_revision > 0, "{receipt:?}"); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Certain, seeded.revision + 1), + "the forgotten subject was not re-reached" + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1), + "a holder the patch did not touch was overwritten" + ); + } + + /// What a witness hands the narrative lane's interruption renderer. The + /// renderer takes a subject's own `ScopeComponents` and its own knowledge + /// rows and nothing else, so both of its inputs are pinned here rather than + /// in the lane that owns the prose: exactly one component moved, `knows`, + /// which is the anonymous line and names no author; and the row the witness + /// wrote carries no `minted_at`, which is the sole gate on an `Overheard` + /// row, so no attributable line can be built from it. + #[test] + fn soul_a_witness_moves_only_knows_and_writes_no_spoken_row() { + let (mut kernel, world, active) = nesting_kernel("Anonymous"); + let before = scope_components(&kernel.state, world.villager); + submit_play( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + let after = scope_components(&kernel.state, world.villager); + assert_ne!(before.knows, after.knows); + assert_eq!( + after, + ScopeComponents { + knows: after.knows.clone(), + ..before + }, + "a witness moved a component other than what this person knows" + ); + + let snapshot = kernel.snapshot().unwrap(); + let held = snapshot + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .expect("the learner is snapshotted"); + assert!( + held.knowledge + .iter() + .filter(|row| row.fact == world.asteroid) + .all(|row| row.minted_at.is_none() && row.source == KnowledgeSource::Witnessed), + "a witnessed row carried a speech act" + ); + } +} + +/// The clock, commitments, pressure, boundaries, and scale. +#[cfg(test)] +mod clock_tests { + use super::patch::{PreconditionRef, PressureSourceRef}; + use super::tests::{ + act, affordance_named, auth_principal, authority_kind, command, creation, + human_principal, office, operations, owner, play_caller, reject_play, + speech_world, submit_play, + }; + use super::*; + + /// The canonical IDs of the clock fixture: a hall containing a yard, a + /// dead end reached by exactly one route, three subjects, a resource, and + /// one commitment of each kind. + pub(crate) struct Clockwork { + yard: EntityId, + dead_end: EntityId, + gate: EdgeId, + reeve: SubjectId, + farmer: SubjectId, + treasury: SubjectId, + routine: CommitmentKey, + obligation: CommitmentKey, + goal: CommitmentKey, + deliver: AffordanceId, + threaten: AffordanceId, + } + + const ROUTINE_DUE: u64 = 60; + const LATE_DUE: u64 = 100; + + fn minutes(value: u32) -> TickMinutes { + TickMinutes::new(value).expect("a valid span") + } + + pub(crate) fn clock_kernel(title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (clockwork, active) = clock_world(&mut kernel); + (kernel, clockwork, active) + } + + fn clock_world(kernel: &mut WorldKernel) -> (Clockwork, WorldSnapshot) { + let before = kernel.snapshot().unwrap(); + let speak = super::tests::speak_entry(kernel); + let person = |handle: &str, label: &str, kind: SubjectKind, place: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Draft(DraftHandle::new("deliver")), + Ref::Draft(DraftHandle::new("threaten")), + ]), + position: Some(Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + }; + let subject = |handle: &str| Ref::Draft(DraftHandle::new(handle)); + submit_play( + kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + evidence: vec![EvidenceRef::new("vault:harvest")], + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Long Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("yard"), + label: "The Cavity Yard".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + // Nothing inside it, nobody in it, and one route out: + // the world has not grown into it yet. + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("grain"), + label: "Winter Grain".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("stair"), + label: "The Yard Stair".into(), + from: Ref::Draft(DraftHandle::new("yard")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("back"), + label: "The Hall Steps".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Draft(DraftHandle::new("yard")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Draft(DraftHandle::new("dead-end")), + access: AccessKind::Public, + cost: Cost(1), + }), + // An affordance whose legitimacy is a promise rather + // than a jurisdiction, and one that presses directly. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("deliver"), + kind: AffordanceKindName("deliver".into()), + roles: vec![RoleSpec { + role: Role("creditor".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::Committed { + to: Role("creditor".into()), + kind: CommitmentKind::Obligation, + }], + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::CreateCommitment { + kind: CommitmentKind::Obligation, + horizon: minutes(1440), + period: None, + }, + roles: vec![Role("actor".into()), Role("creditor".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("threaten"), + kind: AffordanceKindName("threaten".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AdvancePressure { + by: PressureMagnitude(3), + }, + roles: vec![Role("target".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + person("reeve", "The Yard Reeve", SubjectKind::Person, "yard"), + person("farmer", "The Yard Farmer", SubjectKind::Person, "yard"), + person( + "treasury", + "The Hall Treasury", + SubjectKind::Institution, + "hall", + ), + ], + operations: vec![ + ComponentOp::Admit { + holder: subject("farmer"), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(4), + evidence: EvidenceRef::new("vault:harvest"), + }, + // 0: the routine, whose check is where its subject stands. + ComponentOp::CreateCommitment { + subject: subject("farmer"), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(ROUTINE_DUE), + period: Some(minutes(10)), + checks: vec![PreconditionRef::Present { + at: Ref::Draft(DraftHandle::new("yard")), + }], + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: subject("farmer"), + counterparty: Some(subject("treasury")), + kind: CommitmentKind::Obligation, + due: FictionalMinutes(LATE_DUE), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: subject("reeve"), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(LATE_DUE), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::Bind { + subject: subject("reeve"), + target: DependencyRef::Route(Ref::Draft(DraftHandle::new("gate"))), + }, + ], + }, + }, + ); + let active = kernel.snapshot().unwrap(); + let place = |label: &str| { + active + .places + .iter() + .find(|place| place.label == label) + .expect("the declared place") + .id + }; + let who = |label: &str| { + active + .subjects + .iter() + .find(|subject| subject.label == label) + .expect("the declared subject") + .id + }; + let reeve = who("The Yard Reeve"); + let farmer = who("The Yard Farmer"); + let key_of = |subject: SubjectId, kind: CommitmentKind| { + *kernel + .state + .commitments + .get(&subject) + .expect("the subject holds commitments") + .iter() + .find(|(_, commitment)| commitment.kind == kind) + .expect("the declared commitment") + .0 + }; + let gate = active + .routes + .iter() + .find(|route| route.label == "The Field Gate") + .expect("the declared route") + .id; + ( + Clockwork { + yard: place("The Cavity Yard"), + dead_end: place("The Unwalked Road"), + gate, + reeve, + farmer, + treasury: who("The Hall Treasury"), + routine: key_of(farmer, CommitmentKind::Routine), + obligation: key_of(farmer, CommitmentKind::Obligation), + goal: key_of(reeve, CommitmentKind::Goal), + deliver: affordance_named(&active, "deliver"), + threaten: affordance_named(&active, "threaten"), + }, + active, + ) + } + + fn tick(kernel: &mut WorldKernel, span: u32) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CallerId::Play, + CommandBody::AdvanceTime { + minutes: minutes(span), + }, + ), + &AuthenticatedCaller::fixture(CallerId::Play), + ) + } + + fn exercise( + kernel: &mut WorldKernel, + actor: SubjectId, + affordance: AffordanceId, + bindings: Vec, + ) -> Result { + act( + kernel, + actor, + DecisionInvocation { + affordance, + bindings, + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + ) + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn pressure(kernel: &WorldKernel, target: SubjectId, source: PressureSource) -> u32 { + kernel + .state + .pressures + .get(&target) + .and_then(|held| held.get(&source)) + .map_or(0, |magnitude| magnitude.0) + } + + fn due(kernel: &WorldKernel, subject: SubjectId, key: CommitmentKey) -> FictionalMinutes { + kernel + .state + .commitments + .get(&subject) + .and_then(|held| held.get(&key)) + .expect("the live commitment") + .due + } + + /// Verification 12: a defaulted commitment advances pressure on + /// its subject, and the pressure grows with the next tick. + #[test] + fn a_defaulted_commitment_advances_pressure_one_step_per_tick() { + let (mut kernel, clockwork, _) = clock_kernel("Default"); + let sourced = PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + }; + + tick(&mut kernel, 120).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 1); + assert_eq!( + kernel.state.pressures[&clockwork.farmer].len(), + 1, + "only the past-due obligation pressed the farmer" + ); + + tick(&mut kernel, 1).expect("the second tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 2); + } + + /// Verification 19: a due routine fulfils with no inference and no pressure, + /// and a blocked one neither rolls nor presses. + #[test] + fn a_due_routine_auto_fulfils_and_a_blocked_one_does_not() { + let (mut kernel, clockwork, active) = clock_kernel("Routine"); + let holdings = kernel.state.holdings.clone(); + let positions = kernel.state.positions.clone(); + let edges = kernel.state.edges.clone(); + + tick(&mut kernel, ROUTINE_DUE as u32).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 10) + ); + assert!( + kernel.state.pressures.is_empty(), + "a routine raises nothing" + ); + assert_eq!(kernel.state.holdings, holdings); + assert_eq!(kernel.state.positions, positions); + assert_eq!(kernel.state.edges, edges); + + // Out of the yard: the check fails, so the routine neither rolls nor + // presses, and it retries on the next tick. + let route = |label: &str| { + active + .routes + .iter() + .find(|route| route.label == label) + .expect("the declared route") + .id + }; + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(clockwork.farmer), + via: Ref::Existing(route("The Yard Stair")), + }]), + ); + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 10) + ); + assert!( + kernel.state.pressures.is_empty(), + "a blocked routine neither rolls nor presses" + ); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(clockwork.farmer), + via: Ref::Existing(route("The Hall Steps")), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 20) + ); + } + + /// A tick with nothing due is still a commit: the clock moved, which is a + /// canonical change. + #[test] + fn a_tick_with_nothing_due_moves_only_the_clock() { + let (mut kernel, _, _) = clock_kernel("Quiet"); + let before = kernel.state.clone(); + let before_events = kernel.events(); + + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(kernel.state.header.now, FictionalMinutes(1)); + assert_eq!(kernel.state.revision, before.revision + 1); + assert!(kernel.state.pressures.is_empty()); + assert_eq!(kernel.state.commitments, before.commitments); + assert_eq!(kernel.state.holdings, before.holdings); + assert_eq!(kernel.state.positions, before.positions); + assert_eq!(kernel.events(), before_events); + + tick(&mut kernel, 2).expect("the tick commits"); + assert_eq!(kernel.state.header.now, FictionalMinutes(3)); + } + + /// A closed route in one place becomes political pressure in another without + /// anyone deciding that it should. The tick never reduces; only an operation + /// does. + #[test] + fn an_unavailable_dependency_presses_its_depender() { + let (mut kernel, clockwork, _) = clock_kernel("Dependency"); + let sourced = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 0); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 1); + + // Repair stops the pressing but never unwrites what accrued. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::OpenRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 1); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ResolvePressure { + source: PressureSourceRef::Dependency(DependencyRef::Route(Ref::Existing( + clockwork.gate, + ))), + target: Ref::Existing(clockwork.reeve), + }]), + ); + assert!( + !kernel.state.pressures.contains_key(&clockwork.reeve), + "an emptied target removes its key rather than storing an empty map" + ); + } + + /// The clock moves through exactly one command body. + #[test] + fn time_advances_only_through_advance_time() { + let (mut kernel, clockwork, _) = clock_kernel("OnlyTick"); + tick(&mut kernel, 5).expect("the tick commits"); + let now = kernel.state.header.now; + + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + assert_eq!(kernel.state.header.now, now); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + assert_eq!(kernel.state.header.now, now); + } + + /// Who may tick, when, and how far. + #[test] + fn advance_time_negatives() { + let mut kernel = WorldKernel::create(creation("Negatives"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + + let active = kernel.snapshot().unwrap(); + // A span is constructor-checked, so a malformed one never reaches a + // command at all. + assert!(TickMinutes::new(0).is_none()); + assert!(TickMinutes::new(super::patch::MAX_ROUTE_COST + 1).is_none()); + + for caller in [ + CallerId::Principal(human_principal()), + CallerId::Principal(owner()), + ] { + let error = kernel + .submit( + command( + &active, + caller.clone(), + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + // Play ticks. + submit_play( + &mut kernel, + &active, + CommandBody::AdvanceTime { + minutes: minutes(7), + }, + ); + assert_eq!(kernel.state.header.now, FictionalMinutes(7)); + + // And a span that would overflow the clock is refused rather than + // wrapping. + kernel.state.header.get_mut().now = FictionalMinutes(u64::MAX); + let snapshot = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &snapshot, + CallerId::Play, + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(CallerId::Play), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Serialization(_)), "{error:?}"); + } + + /// The whole motion is re-derived at apply, so a forged fulfilment, target, + /// magnitude, or clock reading is one comparison. + #[test] + fn a_forged_motion_does_not_apply() { + let (kernel, clockwork, _) = clock_kernel("Forged"); + let to = FictionalMinutes(120); + let honest = clock::derive_motion(&kernel.state, to); + assert!(!honest.fulfilled.is_empty() || !honest.pressed.is_empty()); + + let forgeries = [ + // A forged clock reading. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to: FictionalMinutes(121), + motion: honest.clone(), + }, + // A fulfilment nothing derived. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: vec![clock::RoutineFulfilled { + subject: clockwork.farmer, + key: clockwork.routine, + next_due: FictionalMinutes(9_999), + }], + pressed: honest.pressed.clone(), + }, + }, + // A forged magnitude. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: honest.fulfilled.clone(), + pressed: honest + .pressed + .iter() + .map(|written| clock::PressureWritten { + magnitude: PressureMagnitude(written.magnitude.0 + 9), + ..written.clone() + }) + .collect(), + }, + }, + // A pressure row for an untouched subject. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: honest.fulfilled.clone(), + pressed: honest + .pressed + .iter() + .cloned() + .chain(std::iter::once(clock::PressureWritten { + target: clockwork.treasury, + source: PressureSource::Subject(clockwork.reeve), + magnitude: PressureMagnitude(5), + })) + .collect(), + }, + }, + ]; + for forged in forgeries { + let mut candidate = kernel.state.clone(); + let error = apply_effect(&mut candidate, CommandId::issue(), &CallerId::Play, &forged) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + } + + // The honest one applies. + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: honest, + }, + ) + .expect("the honest motion applies"); + assert_eq!(candidate.header.now, to); + } + + /// Replay across a tick is exact, and every envelope is idempotent. + #[test] + fn restart_replay_across_a_tick_is_exact() { + let (mut kernel, clockwork, _) = clock_kernel("Replay"); + + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + tick(&mut kernel, 60).expect("the routine tick commits"); + tick(&mut kernel, 60).expect("the obligation tick commits"); + let snapshot = kernel.snapshot().unwrap(); + let repeat = command( + &snapshot, + CallerId::Play, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + kernel + .submit(repeat.clone(), &AuthenticatedCaller::verified_play()) + .expect("the discharge commits"); + // Discharge removes every pressure row it sourced. + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 0 + ); + + let before = kernel.state.clone(); + let before_snapshot = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + let mut replayed = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(replayed.state, before); + assert_eq!(replayed.snapshot().unwrap(), before_snapshot); + assert!(matches!( + replayed.submit(repeat, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// Every commitment shape check, in one complete sorted set. + #[test] + fn commitment_declaration_negatives() { + let (mut kernel, clockwork, active) = clock_kernel("Shapes"); + let before = kernel.state.clone(); + let create = |kind: CommitmentKind, + counterparty: Option, + due: u64, + period: Option, + checks: Vec| { + ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.farmer), + counterparty: counterparty.map(Ref::Existing), + kind, + due: FictionalMinutes(due), + period, + checks, + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + } + }; + + assert_eq!( + reject_play( + &mut kernel, + &active, + operations(vec![ + // 0: a routine with no period. + create(CommitmentKind::Routine, None, 500, None, Vec::new()), + // 1: a goal with a period. + create( + CommitmentKind::Goal, + None, + 500, + Some(minutes(10)), + Vec::new() + ), + // 2: checks on a non-routine. + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 500, + None, + vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + ), + // 3: born past due. + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 0, + None, + Vec::new() + ), + // 4: a promise to oneself with a counterparty. + create( + CommitmentKind::Obligation, + Some(clockwork.farmer), + 500, + None, + Vec::new() + ), + // 5: a goal with a counterparty. + create( + CommitmentKind::Goal, + Some(clockwork.treasury), + 500, + None, + Vec::new() + ), + // 6: a discharge of a key nobody holds. + ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: CommitmentKey { + command: CommandId::issue(), + index: 0, + }, + }, + ]), + ), + { + let mut expected = vec![ + Mismatch::CommitmentPeriodMismatch { operation: 0 }, + Mismatch::CommitmentPeriodMismatch { operation: 1 }, + Mismatch::ChecksOnNonRoutine { operation: 2 }, + Mismatch::CommitmentDueInThePast { operation: 3 }, + Mismatch::SelfCommitment { operation: 4 }, + Mismatch::GoalWithCounterparty { operation: 5 }, + Mismatch::UnknownCommitment { operation: 6 }, + ]; + expected.sort(); + expected + } + ); + assert_eq!(kernel.state, before); + + // Repairing exactly those commits. + submit_play( + &mut kernel, + &active, + operations(vec![ + create( + CommitmentKind::Routine, + None, + 500, + Some(minutes(10)), + Vec::new(), + ), + create(CommitmentKind::Goal, None, 500, None, Vec::new()), + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 500, + None, + Vec::new(), + ), + ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.routine, + }, + ]), + ); + assert!( + !kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.routine), + "the discharge removed the routine" + ); + } + + /// `Committed` reads the actor's own commitments: the farmer promised the + /// treasury and the reeve did not. + #[test] + fn committed_reads_the_actors_own_commitments() { + let (mut kernel, clockwork, _) = clock_kernel("Committed"); + + // The reeve promised the treasury nothing. + let error = exercise( + &mut kernel, + clockwork.reeve, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + + // The farmer did, so the entry commits and mints a second obligation + // whose due date the kernel computed. + let before = kernel.state.commitments[&clockwork.farmer].len(); + exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .expect("the delivery commits"); + assert_eq!( + kernel.state.commitments[&clockwork.farmer].len(), + before + 1 + ); + } + + /// `Committed` reads the actor's commitments at Act time: once the + /// obligation to the treasury is discharged, the promisor's act that needs + /// it is refused and nothing commits. + #[test] + fn a_discharged_commitment_refuses_the_act_that_needs_it() { + let (mut kernel, clockwork, _) = clock_kernel("DischargeThenAct"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + let events = kernel.events().len(); + let error = exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!( + matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + ), + "{error:?}" + ); + assert_eq!(kernel.events().len(), events); + } + + /// `Committed` is a conjunction: the actor holds a commitment to this very + /// counterparty and of this very kind. The farmer owes the treasury an + /// obligation and nobody else, so naming the reeve fails the counterparty + /// half while the kind half holds. + #[test] + fn committed_requires_the_named_counterparty() { + let (mut kernel, clockwork, _) = clock_kernel("CommittedCounterparty"); + let error = exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.reeve))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + } + + /// The other half: the reeve holds a routine toward the treasury, a kind + /// `deliver` does not ask for, so the counterparty half holds and the kind + /// half fails. The farmer's own obligation to the same treasury still passes. + #[test] + fn committed_requires_the_named_kind() { + let (mut kernel, clockwork, _) = clock_kernel("CommittedKind"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: Some(Ref::Existing(clockwork.treasury)), + kind: CommitmentKind::Routine, + due: FictionalMinutes(ROUTINE_DUE), + period: Some(minutes(10)), + checks: vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + statement: Statement::new("A routine held toward the treasury.").unwrap(), + }]), + ); + assert!( + kernel.state.commitments[&clockwork.reeve] + .values() + .any(|held| held.kind == CommitmentKind::Routine + && held.counterparty == Some(clockwork.treasury)), + "the fixture reeve holds a routine to the treasury" + ); + let error = exercise( + &mut kernel, + clockwork.reeve, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .expect("an obligation to the same counterparty passes"); + } + + /// A tick that only advances pressure moves nobody's scope components; a tick + /// that fulfils a routine moves exactly that subject's. + #[test] + fn a_pressure_tick_moves_no_scope_components_and_a_routine_tick_moves_one() { + let (mut kernel, clockwork, _) = clock_kernel("Digests"); + let digests = |kernel: &WorldKernel| -> BTreeMap { + kernel + .state + .subjects + .keys() + .map(|subject_id| (*subject_id, scope_components(&kernel.state, *subject_id))) + .collect() + }; + + // Past the obligation and the goal, but the routine is blocked out of + // the yard first so only pressure moves. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.routine, + }]), + ); + let before = digests(&kernel); + tick(&mut kernel, 200).expect("the tick commits"); + assert!(!kernel.state.pressures.is_empty(), "the tick pressed"); + assert_eq!(digests(&kernel), before, "pressure binds no proposal"); + + // A routine fulfilment moves exactly its own subject's digest. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(500), + period: Some(minutes(60)), + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ); + let before = digests(&kernel); + tick(&mut kernel, 400).expect("the tick commits"); + let after = digests(&kernel); + for (subject, digest) in &before { + if *subject == clockwork.reeve { + assert_ne!(after[subject], *digest, "the fulfilling subject's scope moved"); + } else { + assert_eq!(after[subject], *digest, "everyone else's scope is untouched"); + } + } + } + + /// Soul falsification: pressure magnitude cannot overflow or go negative, + /// and zero is spelled by absence at both ends. + #[test] + fn soul_pressure_saturates_and_never_underflows() { + let (mut kernel, clockwork, _) = clock_kernel("Saturate"); + let sourced = PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + }; + + // A tick over a magnitude already at the ceiling saturates rather than + // wrapping. + let mut brimming = kernel.state.clone(); + brimming.pressures.insert( + clockwork.farmer, + BTreeMap::from([(sourced, PressureMagnitude(u32::MAX))]), + ); + let motion = clock::derive_motion(&brimming, FictionalMinutes(LATE_DUE)); + let written = motion + .pressed + .iter() + .find(|written| written.source == sourced) + .expect("the past-due obligation pressed"); + assert_eq!(written.magnitude, PressureMagnitude(u32::MAX)); + + // Reducing by more than the row holds removes it instead of wrapping. + tick(&mut kernel, u32::try_from(LATE_DUE).unwrap()).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 1); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ReducePressure { + source: PressureSourceRef::Commitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }, + target: Ref::Existing(clockwork.farmer), + by: PressureMagnitude(9), + }]), + ); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 0); + assert!( + !kernel.state.pressures.contains_key(&clockwork.farmer), + "an emptied target keeps no empty inner map" + ); + + // Resolving an absent row changes nothing and is refused. + let snapshot = kernel.snapshot().unwrap(); + let mismatches = reject_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ResolvePressure { + source: PressureSourceRef::Commitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }, + target: Ref::Existing(clockwork.farmer), + }]), + ); + assert_eq!( + mismatches, + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + + /// Soul falsification: `now` is in no scope. A tick with nothing due moves + /// the clock and not one subject's components. + #[test] + fn soul_a_clock_only_tick_moves_no_scope_components() { + let (mut kernel, _, _) = clock_kernel("ClockOnly"); + let digests = |kernel: &WorldKernel| -> BTreeMap { + kernel + .state + .subjects + .keys() + .map(|subject_id| (*subject_id, scope_components(&kernel.state, *subject_id))) + .collect() + }; + let before = digests(&kernel); + let before_now = kernel.state.header.now; + + // Short of every due date in the fixture. + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!(kernel.state.header.now, FictionalMinutes(before_now.0 + 10)); + assert!(kernel.state.pressures.is_empty()); + assert_eq!(digests(&kernel), before, "the clock entered a scope"); + } + + // ---- genesis may not rule or mint ---------------------------------- + + /// Only Play rules or mints, and Play writes only after genesis: the + /// check reports every offender, not the first, so a scan narrowed to one + /// fact or one operation fails here. + #[test] + fn genesis_may_not_rule_or_mint() { + let mut input = creation("RulesAndMints"); + for handle in ["first-rule", "second-rule"] { + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + } + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + for _ in 0..2 { + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + } + let Err(error) = WorldKernel::create(input, &auth_principal(owner())) else { + panic!("a genesis patch that rules and mints was admitted"); + }; + let KernelError::PatchRejected(set) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + let offender = |site| Mismatch::RuledWithoutAuthority { site }; + assert_eq!( + set, + vec![ + offender(patch::Site::Declaration(DraftHandle::new("first-rule"))), + offender(patch::Site::Declaration(DraftHandle::new("second-rule"))), + offender(patch::Site::Operation(0)), + offender(patch::Site::Operation(1)), + ] + ); + } + + /// `prepare_creation` and `WorldState::genesis` both forbid rulings at + /// genesis. A creation patch that carries a `Ruled` fact is refused before + /// a world is ever written. + #[test] + fn a_genesis_patch_carrying_a_ruled_fact_is_refused() { + let mut input = creation("RuledGenesis"); + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rule"), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let Err(error) = WorldKernel::create(input, &auth_principal(owner())) else { + panic!("a genesis patch carrying a Ruled fact was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Declaration(DraftHandle::new("rule")), + })), + "{error:?}" + ); + } + + /// The `Mint` half: a creation patch that carries a `Mint` is refused the + /// same way. + #[test] + fn a_genesis_patch_carrying_a_mint_is_refused() { + let mut input = creation("MintGenesis"); + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + let Err(error) = WorldKernel::create(input, &auth_principal(owner())) else { + panic!("a genesis patch carrying a Mint was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Operation(0), + })), + "{error:?}" + ); + } + + /// `WorldState::genesis` re-decides `forbid_rulings_at_genesis` on its own + /// terms, independent of `prepare_creation` — that is what protects + /// journal replay of a stored genesis commit, not only a freshly + /// admitted one. Called directly, bypassing `prepare_creation` entirely, + /// so this cannot be satisfied by `prepare_creation`'s own check. + #[test] + fn genesis_itself_refuses_a_ruled_fact_and_a_mint() { + let mut input = creation("GenesisRuleDirect"); + let world_id = WorldId::of(input.id()); + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rule"), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let title = normalize_title(&input.title).unwrap(); + let resolved = patch::resolve_patch( + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), + input.id(), + &input.patch, + ) + .expect("the resolver is actor-blind and accepts a Ruled fact"); + let effect = WorldEffect::WorldCreated { + owner: input.owner.clone(), + title, + resolved, + }; + let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + + let mut input = creation("GenesisMintDirect"); + let world_id = WorldId::of(input.id()); + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + let title = normalize_title(&input.title).unwrap(); + let resolved = patch::resolve_patch( + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), + input.id(), + &input.patch, + ) + .expect("the resolver is actor-blind and accepts a Mint"); + let effect = WorldEffect::WorldCreated { + owner: input.owner.clone(), + title, + resolved, + }; + let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + } + + /// Soul falsification: a discharge names one subject's own live key. + #[test] + fn soul_discharging_a_foreign_or_already_discharged_commitment_is_refused() { + let (mut kernel, clockwork, _) = clock_kernel("Discharge"); + + // The farmer's obligation, claimed by the reeve. + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.reeve), + key: clockwork.obligation, + }]), + ), + vec![Mismatch::UnknownCommitment { operation: 0 }] + ); + + // Discharged once, and then not again. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ), + vec![Mismatch::UnknownCommitment { operation: 0 }] + ); + } + + /// Soul falsification: a routine re-arms by exactly one period per command, + /// whatever the span, and a non-routine cannot carry checks. + #[test] + fn soul_a_routine_re_arms_exactly_one_period_per_command() { + let (mut kernel, clockwork, _) = clock_kernel("Rearm"); + let period = u64::from( + kernel.state.commitments[&clockwork.farmer][&clockwork.routine] + .period + .expect("a routine carries a period") + .minutes(), + ); + let start = due(&kernel, clockwork.farmer, clockwork.routine); + + // One roll per command, even for a span that clears many periods. + tick(&mut kernel, u32::try_from(period * 10).unwrap()).expect("the long tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(start.0 + period) + ); + tick(&mut kernel, 1).expect("the short tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(start.0 + 2 * period) + ); + + // Checks belong to routines alone. + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(100_000), + period: None, + checks: vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ), + vec![Mismatch::ChecksOnNonRoutine { operation: 0 }] + ); + } + + /// Soul falsification: `derive_motion` is a function of state and span + /// alone, and the committed effect is exactly what `reduce` re-derives for + /// a tick that fulfils a routine, presses past-due promises, and presses a + /// failing dependency at once. + #[test] + fn soul_derive_motion_is_pure_and_the_tick_replays_exactly() { + let (mut kernel, clockwork, _) = clock_kernel("Pure"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + + // The same state and the same span, twenty times: one answer. + let span = u32::try_from(LATE_DUE + 10).unwrap(); + let to = FictionalMinutes(LATE_DUE + 10); + let first = clock::derive_motion(&kernel.state, to); + assert!(!first.fulfilled.is_empty(), "the routine is due"); + assert!( + first.pressed.len() >= 2, + "past-due promises and the closed route all press" + ); + for _ in 0..20 { + assert_eq!(clock::derive_motion(&kernel.state, to), first); + } + + // And the commit carries exactly that motion. + let snapshot = kernel.snapshot().unwrap(); + let ticking = command( + &snapshot, + CallerId::Play, + CommandBody::AdvanceTime { + minutes: minutes(span), + }, + ); + let expected = reduce(&kernel.state, &ticking).expect("the tick reduces"); + assert_eq!( + expected, + WorldEffect::TimeAdvanced { + minutes: minutes(span), + to, + motion: first, + } + ); + // Applying the re-derived effect to a copy reproduces the committed + // state exactly, which is the replay identity the journal relies on. + let mut replayed = kernel.state.clone(); + apply_effect(&mut replayed, ticking.id(), &CallerId::Play, &expected) + .expect("the re-derived effect applies"); + kernel + .submit(ticking, &AuthenticatedCaller::fixture(CallerId::Play)) + .expect("the tick commits"); + assert_eq!(replayed.header.now, kernel.state.header.now); + assert_eq!(replayed.commitments, kernel.state.commitments); + assert_eq!(replayed.pressures, kernel.state.pressures); + } + + // ---- system capabilities ------------------------------------------ + + fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + body: CommandBody, + ) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command(&snapshot, caller.clone(), body), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn shed_under(container: EntityId, handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: EntityKind::Place, + container: Some(Ref::Existing(container)), + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + /// The mismatch vocabulary is kernel-internal plus controller telemetry. It + /// never enters a commit, and `verify_state_shape` never grows a clause for + /// it because no partition holds one. + #[test] + fn mismatch_never_appears_in_a_world_commit() { + let (mut kernel, clockwork, _) = clock_kernel("Separation"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the play table's patch commits"); + + let bytes = kernel.state.encoded_documents(); + let text = String::from_utf8_lossy(&bytes); + for tag in [ + "outside_jurisdiction", + "unresolved_draft", + "no_canonical_change", + "mismatch", + ] { + assert!(!text.contains(tag), "{tag} reached world state"); + } + } + + // ---- Soul: the confinement predicate past its declaration lane ------ + + // ---- Cut 3: the play authority, `Ruled` facts and `Mint` ----------- + + fn ruled_fact_patch(handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + fn resource_named(kernel: &WorldKernel, label: &str) -> EntityId { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .map(|(id, _)| id) + .expect("the declared resource") + } + + /// Invariant 5, first half, and P3.1: the play authority declares in + /// Active with no answer. + #[test] + fn the_play_authority_declares_in_active_without_an_answer() { + let (mut kernel, clockwork, _) = clock_kernel("PlayDeclares"); + let receipt = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: shed_under(clockwork.dead_end, "play-shed"), + }, + ) + .expect("the play authority declares unanswered in Active"); + assert!(receipt.resulting_revision > 0); + } + + /// Invariant 5: the play authority reaches the whole world, unconfined to + /// a ground. Writing under a place no jurisdiction covers is exactly what + /// a confined author cannot do. + #[test] + fn the_play_authority_is_unconfined() { + let (mut kernel, clockwork, _) = clock_kernel("PlayUnconfined"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: shed_under(clockwork.dead_end, "unconfined-shed"), + }, + ) + .expect("the play authority is confined to no ground"); + } + + /// Invariant 5: the play authority advances time, the clock's precedent. + #[test] + fn the_play_authority_advances_time() { + let (mut kernel, _clockwork, active) = clock_kernel("PlayClock"); + let receipt = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdvanceTime { + minutes: minutes(30), + }, + ) + .expect("the play authority advances time"); + assert!(receipt.resulting_revision > 0); + assert!(kernel.state.header.now > active.now); + } + + /// P3.4: a ruled fact is world truth to every subject that knows it. + #[test] + fn the_play_authority_rules_a_fact_and_a_witness_knows_it_as_canon() { + let (mut kernel, clockwork, _) = clock_kernel("PlayRules"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("verdict")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch, + }, + ) + .expect("the play authority rules a fact and grants it as knowledge"); + + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == "Stated by the table.") + .map(|(id, _)| id) + .expect("the ruled fact"); + assert_eq!(kernel.state.facts[&fact].standing, FactStanding::Ruled); + + let snapshot = kernel.snapshot().unwrap(); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .expect("the reeve's snapshot"); + let known = subject + .knowledge + .iter() + .find(|held| held.fact == fact) + .expect("the reeve knows the ruled fact"); + assert_eq!(known.standing, FactStandingView::Canonical); + } + + /// P3.5: minted quantity balances the ledger, and replay reproduces it. + #[test] + fn the_play_authority_mints_and_the_ledger_balances() { + let (exported, reeve, grain) = { + let (mut kernel, clockwork, _) = clock_kernel("PlayMints"); + let grain = resource_named(&kernel, "Winter Grain"); + let before = held(&kernel.state, clockwork.reeve, grain); + assert_eq!(before, 0); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Mint { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(7), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority mints"); + let after = held(&kernel.state, clockwork.reeve, grain); + assert_eq!(before + 7, after); + (kernel.export().unwrap(), clockwork.reeve, grain) + }; + let replayed = WorldKernel::open(&exported).expect("the minted export replays"); + assert_eq!(held(&replayed.state, reeve, grain), 7); + } + + /// The evidenced-knowledge clause is unchanged: a receipt cannot vouch for + /// an assertion the kernel never evaluated, and a `Ruled` fact is exactly + /// such an assertion. + #[test] + fn a_ruled_fact_cannot_be_known_evidenced() { + let (mut kernel, clockwork, _) = clock_kernel("PlayEvidenced"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("verdict")), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }); + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::EvidencedKnowledgeOfClaim { operation: 0 })), + "{error:?}" + ); + } + + /// The evidence gate on `Canonical` facts and `Admit` is one predicate at + /// the same sites for genesis and for Play (P3.3). `Play` carries no + /// receipts, so its `Admit` is refused without one. + #[test] + fn the_evidence_gate_holds_for_play() { + let (mut kernel, clockwork, _) = clock_kernel("PlayEvidenceGate"); + let grain = resource_named(&kernel, "Winter Grain"); + + // Without a receipt: `Play`'s `Admit` is refused exactly as anyone's. + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:uncited"), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::AdmitWithoutEvidence { operation: 0 })), + "{error:?}" + ); + + // With the receipt cited in the same patch, `Play`'s `Admit` is + // admitted like anyone unconfined's. + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:cited"), + }], + evidence: vec![EvidenceRef::new("vault:cited")], + }, + }, + ) + .expect("an evidenced admit is admitted for the play authority too"); + } + + /// P3.5, replay half, folded with a ruled fact: reopening the journal + /// reproduces both across the digest. + #[test] + fn a_journal_holding_a_ruled_fact_and_a_mint_replays() { + let (exported, expected) = { + let (mut kernel, clockwork, _) = clock_kernel("PlayReplay"); + let grain = resource_named(&kernel, "Winter Grain"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::Mint { + holder: Ref::Existing(clockwork.farmer), + resource: Ref::Existing(grain), + qty: Quantity(2), + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch, + }, + ) + .expect("the play authority rules and mints in one patch"); + (kernel.export().unwrap(), kernel.snapshot().unwrap()) + }; + let replayed = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(replayed.snapshot().unwrap(), expected); + let exported = replayed.export().unwrap(); + drop(replayed); + let replayed_again = + WorldKernel::open(&exported).expect("the export replays a second time"); + assert_eq!(replayed_again.snapshot().unwrap(), expected); + } + + // ---- Cut 4: retirement ------------------------------------------- + + fn retire_patch(subject: SubjectId) -> WorldPatch { + WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Retire { + subject: Ref::Existing(subject), + }], + evidence: Vec::new(), + } + } + + /// Play retires a subject. + fn play_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result { + submit_as( + kernel, + CallerId::Play, + CommandBody::AdmitPatch { + patch: retire_patch(subject), + }, + ) + } + + /// P4.1, replay half: reopening the journal reproduces a retirement — no + /// grants and `retired` both survive the round trip. + #[test] + fn a_retired_subject_holds_no_grants_across_a_replay() { + let (exported, reeve) = { + let (mut kernel, clockwork, active) = clock_kernel("RetireReplay"); + assert!( + !active + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap() + .affordances + .is_empty(), + "the reeve holds grants before retirement" + ); + play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); + (kernel.export().unwrap(), clockwork.reeve) + }; + let replayed = WorldKernel::open(&exported).expect("the export replays"); + let snapshot = replayed.snapshot().unwrap(); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == reeve) + .expect("the retired subject's own row"); + assert!(subject.retired); + assert!(subject.affordances.is_empty(), "a retired subject holds no grants"); + } + + /// P4.1: Play's `Act` for a retired subject is denied, because `Retire` + /// removed its grants. + #[test] + fn a_retired_subject_cannot_act() { + let (mut kernel, clockwork, _) = clock_kernel("RetireCannotAct"); + play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); + let error = exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); + } + + /// P4.1: no position, so a witness at the retired subject's former place + /// never reaches it, while a still-present subject at the same place + /// does. + #[test] + fn a_retired_subject_hears_nothing() { + let (mut kernel, clockwork, _) = clock_kernel("RetireHearsNothing"); + play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::Witness { + fact: Ref::Draft(DraftHandle::new("news")), + place: Ref::Existing(clockwork.yard), + confidence: Confidence::Certain, + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch, + }, + ) + .expect("the play authority witnesses at the yard"); + let snapshot = kernel.snapshot().unwrap(); + let reeve = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .expect("the retired reeve's own row"); + assert!(reeve.knowledge.is_empty(), "{:?}", reeve.knowledge); + let farmer = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.farmer) + .expect("the farmer's own row"); + assert!(!farmer.knowledge.is_empty(), "the farmer still hears it"); + } + + /// P4.2: events, knowledge, holdings, and commitments all survive + /// retirement untouched. + #[test] + fn a_retired_subject_keeps_its_history() { + let (mut kernel, clockwork, _) = clock_kernel("RetireKeepsHistory"); + let before_holdings = kernel.state.holdings.get(&clockwork.farmer).cloned(); + let before_commitments = kernel.state.commitments.get(&clockwork.farmer).cloned(); + assert!(before_holdings.is_some()); + assert!(before_commitments.is_some()); + play_retires(&mut kernel, clockwork.farmer).expect("play retires the farmer"); + assert_eq!( + kernel.state.holdings.get(&clockwork.farmer).cloned(), + before_holdings + ); + assert_eq!( + kernel.state.commitments.get(&clockwork.farmer).cloned(), + before_commitments + ); + assert!(kernel.state.subjects.contains_key(&clockwork.farmer)); + } + + /// P4.1: retiring twice is `NoOperationEffect`, not a second retirement. + #[test] + fn retiring_twice_is_no_effect() { + let (mut kernel, clockwork, _) = clock_kernel("RetireTwice"); + play_retires(&mut kernel, clockwork.reeve).expect("the first retirement commits"); + let error = play_retires(&mut kernel, clockwork.reeve).unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::NoOperationEffect { operation: 0 })), + "{error:?}" + ); + } + + // ---- Cut 5: granting and revoking affordances --------------------- + + fn wave_affordance() -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("wave"), + kind: AffordanceKindName("wave".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AdvancePressure { + by: PressureMagnitude(1), + }, + roles: vec![Role("target".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }) + } + + /// P5.1: the seed lane is the owner in Draft, and it grants the player a + /// verb the same way any owner-authored `GrantAffordance` does. + #[test] + fn the_seed_grants_the_player_a_verb_in_draft() { + let mut kernel = WorldKernel::create(creation("SeedGrantsDraft"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let before = kernel.snapshot().unwrap(); + let commons = before.places[0].id; + let speak = super::tests::speak_entry(&kernel); + submit_play( + &mut kernel, + &before, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + wave_affordance(), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("player"), + label: "The Player".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(commons)), + import_key: None, + }), + ], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Draft(DraftHandle::new("player")), + affordance: Ref::Draft(DraftHandle::new("wave")), + }], + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + let player = snapshot + .subjects + .iter() + .find(|subject| subject.label == "The Player") + .expect("the declared player"); + assert_eq!(player.affordances.len(), 2); + } + + /// P5.1: Play grants and revokes a verb in Active. + #[test] + fn the_play_authority_grants_and_revokes_in_active() { + let (mut kernel, clockwork, _) = clock_kernel("PlayGrantRevoke"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![wave_affordance()], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Draft(DraftHandle::new("wave")), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority grants a new verb"); + let after_grant = kernel.snapshot().unwrap(); + assert_eq!( + after_grant + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap() + .affordances + .len(), + 4 + ); + + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority revokes a held verb"); + let after_revoke = kernel.snapshot().unwrap(); + let reeve = after_revoke + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap(); + assert_eq!(reeve.affordances.len(), 3); + assert!(!reeve.affordances.contains(&clockwork.threaten)); + } + + // ---- Retirement fix batch (PA.f31-PA.f35) ------------------------------ + + fn human_subject(snapshot: &WorldSnapshot) -> SubjectId { + snapshot + .subjects + .iter() + .find(|subject| subject.label == "The Human") + .expect("the genesis human") + .id + } + + /// PA.f31: `verify_state_shape` no longer judges a `DecisionEvent` against + /// the subject's *present* controller identity. Retiring a subject that + /// has acted commits, and the history survives a full reopen-and-replay + /// (`open` -> `verify_history` -> `verify_state_shape` for every + /// commit, per the caller census in the report). + #[test] + fn retiring_a_subject_that_acted_survives_reopen_and_replay() { + let exported = { + let (mut kernel, clockwork, _) = clock_kernel("PAf31RetireActed"); + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + play_retires(&mut kernel, clockwork.reeve) + .expect("a subject with history can be retired"); + kernel.export().unwrap() + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + let retired = reopened + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.label == "The Yard Reeve") + .expect("the reeve survives replay") + .retired; + assert!(retired); + } + + /// PA.f31: revoking a verb a subject has already used commits, and the + /// event that used it survives reopen-and-replay for the same reason: the + /// grant a `DecisionEvent` rode is judged once, at commit, not re-judged + /// against the present-day grant set. + #[test] + fn revoking_a_used_verb_survives_reopen_and_replay() { + let exported = { + let (mut kernel, clockwork, _) = clock_kernel("PAf31RevokeUsed"); + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + let before = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &before, + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }]), + ); + kernel.export().unwrap() + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!(reopened.events().len(), 1); + } + + /// PA.f32(b, c): once the world is Active, the human's Draft approval is + /// frozen history, so the owner may retire the human — the player's + /// subject may die — and the retire survives reopen-and-replay because + /// the journal's approval-shape check no longer re-reads the present-day + /// controller roster in Active. + #[test] + fn retiring_the_human_in_active_survives_reopen_and_replay() { + let (exported, human) = { + let (mut kernel, clockwork, active) = clock_kernel("PAf32ActiveRetire"); + let _ = &clockwork; + let human = human_subject(&active); + play_retires(&mut kernel, human).expect("play retires the human subject"); + (kernel.export().unwrap(), human) + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + let retired = reopened + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.id == human) + .expect("the human survives replay") + .retired; + assert!(retired); + } + + /// PA.f33: audience derivation (`audience()`) is the one owner of who a + /// channel reaches, so a channel may still *declare* a retired member, + /// but that member is filtered out at the one read site — it gains no + /// knowledge from a telling into that channel. + #[test] + fn channel_audience_excludes_a_retired_member() { + let (mut kernel, clockwork, _) = clock_kernel("PAf33Audience"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); + let mut patch = ruled_fact_patch("news"); + patch.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(clockwork.reeve), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Draft(DraftHandle::new("wire"))), + }); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) + .expect("admitted"); + let reeve_knows = kernel.state.knowledge_of(clockwork.reeve).count(); + assert_eq!(reeve_knows, 0, "a retired subject was an audience"); + } + + /// PA.f33: `Communicate` resolves and refuses a retired speaker with + /// `RetiredSubjectActed`, whether or not it is also that channel's + /// controller. + #[test] + fn a_retired_subject_cannot_speak_through_a_channel() { + let (mut kernel, clockwork, _) = clock_kernel("PAf33RetiredSpeaks"); + let mut declare = ruled_fact_patch("wire-decl"); + declare.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(clockwork.reeve), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch: declare }) + .expect("declare"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); + let wire = *kernel.state.channels.keys().next().unwrap(); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Existing(wire)), + }); + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f33: `CanReach` is `audience().contains(target)`, so a retired + /// target fails the same precondition every other reach check now + /// respects — one statement of reach, one fix. + #[test] + fn a_retired_subject_is_unreachable_through_can_reach() { + let mut kernel = WorldKernel::create(creation("PAf33CanReach"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, _) = speech_world(&mut kernel); + play_retires(&mut kernel, speech.listener).expect("play retires the listener"); + let invocation = DecisionInvocation { + affordance: speech.whisper, + bindings: vec![binding("target", Target::Subject(speech.listener))], + proposed: Vec::new(), + speech: Some(Statement::new("Are you still there?").unwrap()), + display: None, + }; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::Act { + actor: speech.speaker, + invocation, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::ActionRejected(set) + if set.contains(&ActionMismatch::CannotReach { precondition: 0 })), + "{error:?}" + ); + } + + /// PA.f34: `AcquireKnowledge` refuses a retired subject. + #[test] + fn a_retired_subject_cannot_acquire_knowledge() { + let (mut kernel, clockwork, _) = clock_kernel("PAf34Acquire"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f34: `Forget` refuses a retired subject. + #[test] + fn a_retired_subject_cannot_forget() { + let (mut kernel, clockwork, _) = clock_kernel("PAf34Forget"); + let mut declare = ruled_fact_patch("news"); + declare.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch: declare }) + .expect("the reeve learns the fact"); + let fact = *kernel.state.knowledge_of(clockwork.reeve).next().unwrap().0; + play_retires(&mut kernel, clockwork.reeve).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Existing(fact), + }]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 0 }]); + } + + /// PA.f34: `InstallIncumbent` refuses a retired subject as incumbent. + #[test] + fn a_retired_subject_cannot_take_office() { + let (mut kernel, clockwork, _) = clock_kernel("PAf34Office"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(clockwork.treasury), + office: office("warden"), + delegated: BTreeSet::from([authority_kind("levy")]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(clockwork.treasury), + office: office("warden"), + incumbent: Ref::Existing(clockwork.farmer), + }, + ]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 1 }]); + } + + /// PA.f34: a retired subject's holdings remain transferable — a body may + /// still be looted after it stops acting. + #[test] + fn holdings_are_still_transferable_from_a_retired_holder() { + let (mut kernel, clockwork, _) = clock_kernel("PAf34Loot"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let grain = *kernel + .state + .holdings + .get(&clockwork.farmer) + .expect("the retired farmer still holds grain") + .keys() + .next() + .expect("at least one resource"); + submit_play( + &mut kernel, + &before, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(clockwork.farmer), + to: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(2), + }]), + ); + assert_eq!( + kernel.state.holdings[&clockwork.reeve][&grain], + Quantity(2) + ); + } + + /// PA.f35, MuA: the resolver's `Retire` arm removes the subject's + /// Position (`positions.remove`) in the same candidate pass a later + /// `Relocate` in the same patch reads, so retire-then-relocate in one + /// patch is rejected as `UnplacedSubject` rather than silently placing a + /// retired subject. + #[test] + fn retiring_then_relocating_in_one_patch_is_rejected() { + let (mut kernel, clockwork, _) = clock_kernel("PAf35RetireRelocate"); + let stair = *kernel + .state + .edges + .iter() + .find(|(_, edge)| edge.endpoints().0 == clockwork.yard) + .unwrap() + .0; + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ComponentOp::Relocate { + subject: Ref::Existing(clockwork.reeve), + via: Ref::Existing(stair), + }, + ]), + ); + assert_eq!(error, vec![Mismatch::UnplacedSubject { operation: 1 }]); + } + + /// PA.f35, MuE: the resolver's `Retire` arm inserts the subject into its + /// own-patch `retired` candidate set, so a second `Retire` of the same + /// subject in one patch is caught as a no-op rather than silently + /// re-resolving. + #[test] + fn retiring_the_same_subject_twice_in_one_patch_is_a_noop_the_second_time() { + let (mut kernel, clockwork, _) = clock_kernel("PAf35DoubleRetire"); + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ]), + ); + assert_eq!(error, vec![Mismatch::NoOperationEffect { operation: 1 }]); + } + + // ---- Retirement fix batch (PA.f36-PA.f38) ------------------------------ + + /// PA.f37: a retired subject cannot become a promisor. `CreateCommitment` + /// refuses it with `RetiredSubjectActed`, the same mismatch a retired + /// office incumbent draws. + #[test] + fn a_retired_subject_cannot_be_a_promisor() { + let (mut kernel, clockwork, _) = clock_kernel("PAf37Promisor"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_play( + &mut kernel, + &before, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.farmer), + counterparty: None, + kind: CommitmentKind::Obligation, + due: FictionalMinutes(LATE_DUE + 1), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.") + .unwrap(), + }]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 0 }]); + } + + /// PA.f37: once a subject is retired, the clock stops moving what it + /// holds — its routine no longer rolls and its obligation no longer + /// presses — while a live subject's goal and dependency still move on the + /// same tick. Nothing is discharged or deleted; the retired subject's + /// commitments stay on record, un-fulfilled and un-pressed, exactly as + /// they were the moment it retired. + #[test] + fn after_retirement_a_tick_moves_none_of_the_retired_subjects_commitments() { + let (mut kernel, clockwork, _) = clock_kernel("PAf37Frozen"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + play_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); + let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + routine_before, + "a retired subject's routine still rolled" + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 0, + "a retired subject's obligation still pressed" + ); + assert_eq!( + pressure( + &kernel, + clockwork.reeve, + PressureSource::Commitment { + subject: clockwork.reeve, + key: clockwork.goal, + } + ), + 1, + "the live subject's goal did not press" + ); + assert_eq!( + pressure(&kernel, clockwork.reeve, dependency_source), + 1, + "the live subject's dependency did not press" + ); + + assert!( + kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.routine), + "the frozen routine was discharged or deleted rather than left as history" + ); + assert!( + kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.obligation), + "the frozen obligation was discharged or deleted rather than left as history" + ); + } + + /// PA.f37, the other half: retiring the subject that holds the goal and + /// the dependency freezes those instead, while the still-live farmer's + /// routine and obligation keep moving. Soul's probe retired a subject + /// whose routine rolled and whose goal and dependency kept pressing; this + /// pins the dependency loop in `derive_motion` the first test above never + /// exercises, since the farmer it retires holds no dependency. + #[test] + fn after_retirement_a_tick_moves_none_of_the_retired_subjects_goal_or_dependency() { + let (mut kernel, clockwork, _) = clock_kernel("PAf37FrozenDep"); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + play_retires(&mut kernel, clockwork.reeve).expect("retire the reeve"); + let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); + let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + + assert_eq!( + pressure( + &kernel, + clockwork.reeve, + PressureSource::Commitment { + subject: clockwork.reeve, + key: clockwork.goal, + } + ), + 0, + "a retired subject's goal still pressed" + ); + assert_eq!( + pressure(&kernel, clockwork.reeve, dependency_source), + 0, + "a retired subject's dependency still pressed" + ); + assert_ne!( + due(&kernel, clockwork.farmer, clockwork.routine), + routine_before, + "the live subject's routine did not roll" + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 1, + "the live subject's obligation did not press" + ); + } + + /// PA.f37: the freeze survives a full reopen-and-replay, the same way + /// every other retirement effect in this batch does. + #[test] + fn a_retired_subjects_frozen_commitments_survive_reopen_and_replay() { + let (exported, farmer, routine, obligation) = { + let (mut kernel, clockwork, _) = clock_kernel("PAf37Replay"); + play_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + ( + kernel.export().unwrap(), + clockwork.farmer, + clockwork.routine, + clockwork.obligation, + ) + }; + let reopened = WorldKernel::open(&exported).expect("the export replays"); + assert_eq!( + due(&reopened, farmer, routine), + FictionalMinutes(ROUTINE_DUE), + "the routine rolled somewhere along the replayed path" + ); + assert_eq!( + pressure( + &reopened, + farmer, + PressureSource::Commitment { + subject: farmer, + key: obligation, + } + ), + 0, + "the obligation pressed somewhere along the replayed path" + ); + } + + // ---- Retirement fix batch, test gaps (PA.f39) -------------------------- + + /// PA.f39, M2: `AcquireKnowledge` refuses a retired subject regardless of + /// source. `Evidenced` already carries its own provenance guard + /// (`EvidencedKnowledgeOfClaim`), which makes it plausible for a future + /// edit to narrow the retirement check to `source != Evidenced`; this + /// proves the retirement check still fires for an `Evidenced` acquire + /// too. + #[test] + fn a_retired_subject_cannot_acquire_evidenced_knowledge() { + let (mut kernel, clockwork, _) = clock_kernel("PAf39Evidenced"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); + let patch = WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("news"), + label: "The Harvest Report".into(), + statement: Statement::new("The winter grain is counted.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:count"), + }, + })], + operations: vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }], + evidence: vec![EvidenceRef::new("vault:count")], + }; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { patch }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f39, Soul's probe S2: `CanReach` to a placeless target reachable + /// only through a `Reach::Subjects` channel — no co-location is possible + /// — is refused once the target retires. This exercises `audience()`'s + /// channel side, which PA.f33's Colocated-only `CanReach` test + /// (`a_retired_subject_is_unreachable_through_can_reach`) never reaches, + /// and kills a mutation that removes `audience()`'s retired filter. + #[test] + fn a_retired_placeless_subject_is_unreachable_through_a_subjects_channel() { + let (mut kernel, clockwork, _) = clock_kernel("PAf39S2"); + let speak = super::tests::speak_entry(&kernel); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![ + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("outcast"), + label: "The Placeless Outcast".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak.clone()]), + position: None, + import_key: None, + }), + Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Outcast Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Draft(DraftHandle::new("outcast")), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("hail"), + kind: AffordanceKindName("hail".into()), + roles: vec![ + RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("channel".into()), + kind: RefKind::Entity(EntityKind::Channel), + }, + ], + preconditions: vec![Precondition::CanReach { + subject: Role("target".into()), + via: AudienceSpec::Channel(Role("channel".into())), + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + ], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(clockwork.farmer), + affordance: Ref::Draft(DraftHandle::new("hail")), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority declares the placeless outcast and its channel"); + + let positions = kernel.state.positions.clone(); + let outcast = *kernel + .state + .subjects + .keys() + .find(|id| !positions.contains_key(id)) + .expect("the declared placeless outcast"); + let wire = *kernel.state.channels.keys().next().expect("the declared channel"); + let snapshot = kernel.snapshot().unwrap(); + let hail = affordance_named(&snapshot, "hail"); + let invocation = DecisionInvocation { + affordance: hail, + bindings: vec![ + binding("target", Target::Subject(outcast)), + binding("channel", Target::Entity(wire)), + ], + proposed: Vec::new(), + speech: Some(Statement::new("Hail!").unwrap()), + display: None, + }; + submit_as( + &mut kernel, + play_caller(), + CommandBody::Act { + actor: clockwork.farmer, + invocation: invocation.clone(), + }, + ) + .expect("the live outcast is reachable through the channel"); + + play_retires(&mut kernel, outcast).expect("retire the outcast"); + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::Act { + actor: clockwork.farmer, + invocation, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::ActionRejected(set) + if set.contains(&ActionMismatch::CannotReach { precondition: 0 })), + "{error:?}" + ); + } +} + +/// After genesis only Play writes, and a world is born Active. Each rule here +/// is the one the reducer's single admission gate decides, on commit and at +/// the commit-time re-decision. +#[cfg(test)] +mod agency_tests { + use super::tests::{ + act, affordance_named, auth_principal, command, creation, first_grant, human_principal, + operations, owner, play_command, reject_play, speak, subject_by_label, submit_play, + tick_body, + }; + use super::*; + + fn world(title: &str) -> WorldKernel { + let (kernel, _) = WorldKernel::create(creation(title), + &auth_principal(owner()), + ) + .unwrap(); + kernel + } + + fn declare_place_patch(handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + #[test] + fn after_genesis_only_play_writes() { + let mut kernel = world("PlayOnly"); + let snapshot = kernel.snapshot().unwrap(); + let human = subject_by_label(&kernel.state, "The Human"); + let persona = subject_by_label(&kernel.state, "The Witness"); + let operator = subject_by_label(&kernel.state, "The Council"); + let convene = affordance_named(&snapshot, "convene"); + let bodies = vec![ + ( + "declare", + CommandBody::AdmitPatch { + patch: declare_place_patch("annex"), + }, + ), + ( + "retire", + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(persona), + }]), + ), + ( + "grant", + operations(vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(human), + affordance: Ref::Existing(convene), + }]), + ), + ( + "revoke", + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(operator), + affordance: Ref::Existing(convene), + }]), + ), + ("advance", tick_body(5)), + ( + "act", + CommandBody::Act { + actor: human, + invocation: speak(first_grant(&snapshot, human), "Hello."), + }, + ), + ]; + + for (name, body) in &bodies { + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + ] { + let commits = kernel.journal.commit_count(); + let error = kernel + .submit( + command(&snapshot, caller.clone(), body.clone()), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::Unauthorized), + "{name} as {caller:?}: {error:?}" + ); + assert_eq!(kernel.journal.commit_count(), commits, "{name} committed"); + assert_eq!(kernel.snapshot().unwrap(), snapshot, "{name} moved the world"); + } + } + for (name, body) in bodies { + let before = kernel.snapshot().unwrap(); + let receipt = kernel + .submit( + play_command(&before, body), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_or_else(|error| panic!("Play {name}: {error:?}")); + assert!(receipt.resulting_revision > 0, "Play {name}"); + } + } + + #[test] + fn apply_effect_re_decides_play() { + let kernel = world("ReDecide"); + let state = &kernel.state; + let command_id = CommandId::issue(); + let human = subject_by_label(state, "The Human"); + let affordance = first_grant(&kernel.snapshot().unwrap(), human); + let invocation = speak(affordance, "Spoken."); + let granted = require_granted(state, human, affordance).unwrap(); + let event = action::exercise(state, command_id, human, &granted, &invocation).unwrap(); + let minutes = TickMinutes::new(9).unwrap(); + let to = state.header.now.checked_add(minutes).unwrap(); + let effects = [ + ( + "patch", + WorldEffect::PatchAdmitted { + resolved: patch::resolve_patch( + state, + command_id, + &declare_place_patch("annex"), + ) + .unwrap(), + }, + ), + ("act", WorldEffect::Acted { invocation, event }), + ( + "tick", + WorldEffect::TimeAdvanced { + minutes, + to, + motion: clock::derive_motion(state, to), + }, + ), + ]; + for (name, effect) in &effects { + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + ] { + let mut candidate = state.clone(); + let error = apply_effect(&mut candidate, command_id, &caller, effect).unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{name}: {error:?}"); + assert_eq!(&candidate, state, "{name} mutated before refusing"); + } + let mut candidate = state.clone(); + apply_effect(&mut candidate, command_id, &CallerId::Play, effect) + .unwrap_or_else(|error| panic!("Play {name}: {error:?}")); + assert_ne!(&candidate, state, "Play {name} changed nothing"); + } + } + + /// The gate sits at the top of `reduce`, so a non-Play caller learns + /// nothing about the world through a refusal: a patch that would be + /// rejected for naming an unknown subject, and an act the actor has no + /// grant for, both come back Unauthorized. + #[test] + fn a_non_play_caller_is_refused_before_the_world_is_read() { + let mut kernel = world("Blind"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + let ungranted = affordance_named(&snapshot, "convene"); + let broken = operations(vec![ComponentOp::Retire { + subject: Ref::Existing(SubjectId::issue()), + }]); + let denied = CommandBody::Act { + actor: persona, + invocation: speak(ungranted, "Not mine."), + }; + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + ] { + for body in [broken.clone(), denied.clone()] { + let error = kernel + .submit( + command(&snapshot, caller.clone(), body), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + } + // The same commands from Play are refused for what they are. + let error = reject_play(&mut kernel, &snapshot, broken); + assert!(!error.is_empty()); + let error = act(&mut kernel, persona, speak(ungranted, "Not mine.")).unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); + } + + #[test] + fn a_world_is_born_active() { + let mut kernel = world("BornActive"); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot.revision, 0); + let human = subject_by_label(&kernel.state, "The Human"); + act(&mut kernel, human, speak(first_grant(&snapshot, human), "At once.")).unwrap(); + let accepted = kernel.snapshot().unwrap(); + assert_eq!(accepted.revision, 1); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + + let mut kernel = world("BornActiveClock"); + let genesis = kernel.snapshot().unwrap(); + submit_play(&mut kernel, &genesis, tick_body(1)); + assert_eq!(kernel.snapshot().unwrap().revision, 1); + } + + /// Retirement is stored once, on the subject, and a live subject's row is + /// the shape it had before the flag existed. + #[test] + fn a_live_subjects_row_is_unchanged_by_the_flag() { + let live = SubjectState { + label: "Walker".into(), + kind: SubjectKind::Person, + import_key: None, + retired: false, + }; + let live_json = serde_json::to_value(&live).unwrap(); + assert!(live_json.get("retired").is_none()); + let retired = SubjectState { retired: true, ..live.clone() }; + let retired_json = serde_json::to_value(&retired).unwrap(); + assert_eq!(retired_json["retired"], true); + assert_eq!(serde_json::from_value::(live_json).unwrap(), live); + assert_eq!(serde_json::from_value::(retired_json).unwrap(), retired); + } + + #[test] + fn a_patch_carrying_a_controller_does_not_decode() { + let Declaration::Subject(declared) = crate::tests::subject("walker", "Walker", SubjectKind::Person) + else { + unreachable!() + }; + let mut json = serde_json::to_value(&declared).unwrap(); + serde_json::from_value::(json.clone()) + .expect("the declaration decodes as built"); + json["controller"] = serde_json::json!({"type": "operational_agent"}); + assert!(serde_json::from_value::(json).is_err()); + } + + /// Retire sets the flag `is_retired` reads, and nothing else retires. + #[test] + fn retirement_lives_on_the_subject() { + let mut kernel = world("RetireFlag"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + assert!(!is_retired(&kernel.state, persona)); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(persona), + }]), + ); + assert!(kernel.state.subjects[&persona].retired); + assert!(is_retired(&kernel.state, persona)); + assert!(!kernel.state.positions.contains_key(&persona)); + assert!(!kernel.state.affordance_grants.contains_key(&persona)); + let after = kernel.snapshot().unwrap(); + assert!(after.subjects.iter().find(|s| s.id == persona).unwrap().retired); + let exported = kernel.export().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&exported).unwrap(); + assert!(is_retired(&reopened.state, persona)); + assert_eq!(reopened.snapshot().unwrap(), after); + } + + #[test] + fn retired_tags_do_not_decode() { + fn refused(json: &str) { + assert!(serde_json::from_str::(json).is_err(), "{json} decoded"); + } + let id = "\"00000000-0000-4000-8000-000000000000\""; + refused::(r#"{"type":"approve_draft"}"#); + refused::(r#"{"type":"activate_world"}"#); + refused::(&format!(r#"{{"type":"controller","id":{id}}}"#)); + refused::(r#"{"type":"system","id":{"capability":"clock"}}"#); + refused::(r#"{"type":"system","id":{"capability":"play"}}"#); + refused::(&format!( + r#"{{"type":"system","id":{{"capability":"consumer","consumer":{id}}}}}"# + )); + refused::(r#"{"type":"draft_approved","principal":"p"}"#); + refused::(r#"{"type":"world_activated"}"#); + assert_eq!( + serde_json::from_str::(r#"{"type":"play"}"#).unwrap(), + CallerId::Play + ); + } + + #[test] + fn a_revoke_may_leave_a_subject_with_no_verbs() { + let mut kernel = world("Mute"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + let only = first_grant(&snapshot, persona); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(persona), + affordance: Ref::Existing(only), + }]), + ); + assert!( + !kernel + .state + .affordance_grants + .contains_key(&persona), + "the emptied row was kept" + ); + let error = act(&mut kernel, persona, speak(only, "Silent.")).unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); + journal::verify_state_shape(&kernel.state).expect("a mute subject is a legal shape"); + let accepted = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + assert_eq!( + WorldKernel::open(&exported) + .unwrap() + .snapshot() + .unwrap(), + accepted + ); + } + + #[test] + fn a_subject_may_be_declared_with_no_verbs() { + let mute = |handle: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: SubjectKind::Person, + affordances: BTreeSet::new(), + position: Some(Ref::Draft(DraftHandle::new(super::tests::COMMONS))), + import_key: None, + }) + }; + let mut input = creation("Mutes"); + input.patch.declarations.push(mute("born-mute")); + let (mut kernel, _) = WorldKernel::create(input, + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let speaking = first_grant(&snapshot, subject_by_label(&kernel.state, "The Human")); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + position: None, + ..match mute("declared-mute") { + Declaration::Subject(subject) => subject, + _ => unreachable!(), + } + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + for label in ["The born-mute", "The declared-mute"] { + let found = snapshot + .subjects + .iter() + .find(|subject| subject.label == label) + .unwrap(); + assert!(found.affordances.is_empty(), "{label}"); + assert!( + !kernel + .state + .affordance_grants + .contains_key(&found.id), + "{label} holds a grant row" + ); + let error = act(&mut kernel, found.id, speak(speaking, "Mute.")).unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{label}: {error:?}"); + } + } + + #[test] + fn a_retired_subject_takes_no_grant() { + let mut kernel = world("RetiredGrants"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + let convene = affordance_named(&snapshot, "convene"); + let grant = ComponentOp::GrantAffordance { + subject: Ref::Existing(persona), + affordance: Ref::Existing(convene), + }; + let revoke = ComponentOp::RevokeAffordance { + subject: Ref::Existing(persona), + affordance: Ref::Existing(first_grant(&snapshot, persona)), + }; + let retire = ComponentOp::Retire { + subject: Ref::Existing(persona), + }; + for op in [grant.clone(), revoke.clone()] { + let mismatches = reject_play( + &mut kernel, + &snapshot, + operations(vec![retire.clone(), op]), + ); + assert_eq!( + mismatches, + vec![Mismatch::GrantsToRetired { operation: 1 }], + "same patch" + ); + } + submit_play(&mut kernel, &snapshot, operations(vec![retire])); + let snapshot = kernel.snapshot().unwrap(); + for op in [grant, revoke] { + let mismatches = reject_play(&mut kernel, &snapshot, operations(vec![op])); + assert_eq!(mismatches, vec![Mismatch::GrantsToRetired { operation: 0 }]); + } + } + + #[test] + fn retire_applies_to_every_subject() { + let mut kernel = world("RetireAll"); + let snapshot = kernel.snapshot().unwrap(); + let everyone = ["The Human", "The Witness", "The Council"] + .map(|label| subject_by_label(&kernel.state, label)); + submit_play( + &mut kernel, + &snapshot, + operations( + everyone + .iter() + .map(|subject| ComponentOp::Retire { + subject: Ref::Existing(*subject), + }) + .collect(), + ), + ); + let after = kernel.snapshot().unwrap(); + assert_eq!(after.subjects.len(), everyone.len()); + for subject in &after.subjects { + assert!(subject.retired, "{} was not retired", subject.label); + assert!(subject.affordances.is_empty()); + assert!(subject.position.is_none()); + } + assert!(kernel.state.affordance_grants.is_empty()); + let exported = kernel.export().unwrap(); + drop(kernel); + assert_eq!( + WorldKernel::open(&exported) + .unwrap() + .snapshot() + .unwrap(), + after + ); + } + + /// `apply_operation` re-decides the retired guard the resolver also holds: + /// a forged `PatchAdmitted` that grants a retired subject a verb is refused + /// at apply rather than leaving a grant row the shape check calls corrupt. + #[test] + fn apply_refuses_a_grant_to_a_retired_subject() { + let mut kernel = world("ForgedGrant"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + let convene = affordance_named(&snapshot, "convene"); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(persona), + }]), + ); + let forged = WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::GrantAffordance { + subject: persona, + affordance: convene, + }], + evidence: Vec::new(), + }, + }; + let mut candidate = kernel.state.clone(); + let error = + apply_effect(&mut candidate, CommandId::issue(), &CallerId::Play, &forged).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert!( + !candidate + .affordance_grants + .contains_key(&persona), + "a retired subject was granted a verb" + ); + } +} diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs new file mode 100644 index 000000000..b01de3373 --- /dev/null +++ b/native/aetherlight/src/patch.rs @@ -0,0 +1,6699 @@ +//! Closed-patch resolution: the one owner of draft handles, reference kinds, and +//! declaration-lane ID allocation. +//! +//! Only [`derive_id`] allocates a canonical ID, and it is called from exactly +//! two sites: [`resolve_patch`] here, and `action::exercise`, which mints one +//! referent per speech-carrying invocation — always a `Claimed` fact asserted by +//! the acting subject. +//! +//! A patch names structure two ways and no other way: an exact canonical ID that +//! already keys a partition, or a draft handle declared in the same patch. +//! Resolution accumulates the complete mismatch set first and allocates only +//! after that set is empty, so a rejected patch never mints an ID. + +use super::clock::{FictionalMinutes, TickMinutes}; +use super::docs::Docs; +use super::grammar::GrammarRefusal; +use super::{ + AffordanceId, ByEndpoint, ChildOf, CommandId, EdgeId, EntityId, SubjectId, SubjectKind, + SubjectState, WorldId, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet, btree_map::Entry}; +use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; +use uuid::Uuid; + +mod candidate; +use candidate::{Candidate, Overlay}; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EntityKind { + Place, + Resource, + Fact, + Channel, +} + +/// Exactly the edge kinds that have a record shape. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EdgeKind { + Route, +} + +/// Traversal rule. A `Restricted` route names the authority kind that opens it: +/// the door names its own key, and the kernel reads neither the door nor the key +/// beyond comparing the name. [`route_admits`] is the sole statement of who gets +/// through, reached identically by `resolve_patch`'s `Relocate` arm and by +/// `Precondition::Reachable`'s edge admission. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "access", rename_all = "snake_case")] +pub(crate) enum AccessKind { + Public, + Restricted { requires: AuthorityKindName }, +} + +/// A world-declared authority name: canonical text, `[a-z][a-z0-9_]{0,47}`. The +/// kernel carries it, compares it for equality, and reads it no other way. A +/// closed enum here would make "conscript" or "audit" a kernel change and put a +/// world's political vocabulary in the reducer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct AuthorityKindName(pub(crate) String); + +/// What an authority covers. Distinct from a subject, which says *whose* +/// authority it is and stays one field. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "over", content = "id", rename_all = "snake_case")] +pub(crate) enum AuthorityTarget { + Subject(SubjectId), + /// That place and everything contained in it, by `EntityRecord.container`. + PlaceSubtree(EntityId), +} + +impl AuthorityTarget { + /// The referent this target names, so "does grant A cover grant B's ground" + /// is the one covering predicate rather than a second one. + pub(super) fn as_referent(self) -> super::Target { + match self { + Self::Subject(subject_id) => super::Target::Subject(subject_id), + Self::PlaceSubtree(entity_id) => super::Target::Entity(entity_id), + } + } +} + +/// The proposal-time twin of [`AuthorityTarget`], carrying references. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "over", content = "ref", rename_all = "snake_case")] +pub(crate) enum AuthorityTargetRef { + Subject(Ref), + PlaceSubtree(Ref), +} + +/// One jurisdiction: a kind and the ground it runs over. Ordered `(kind, over)` +/// so a subject's grant set has one canonical order. A jurisdiction is a set of +/// these, so revoking one place is not a restatement of the whole scope. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct AuthorityGrant { + pub(crate) kind: AuthorityKindName, + pub(crate) over: AuthorityTarget, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct AuthorityGrantRef { + pub(crate) kind: AuthorityKindName, + pub(crate) over: AuthorityTargetRef, +} + +/// Canonical text, scoped to its institution: the pair (institution, name) is +/// the identity, the same discipline a `Role` gets inside one affordance. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct OfficeName(pub(crate) String); + +/// A seat inside one institution. It carries no term and no selection method: +/// there is no clock, so nothing can expire, and a field nothing reads is a +/// decoration the next pass has to delete. `delegated` is the field that earns +/// its keep — `scope_components` reads it and `Authorized` resolves through it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Office { + /// A person subject, or vacant. A vacancy is an ordinary state. + pub(crate) incumbent: Option, + /// Which of the institution's authority kinds this office lends its + /// incumbent. Non-empty: an office lending nothing is inert. + pub(crate) delegated: BTreeSet, +} + +/// World-declared canonical text, kernel-opaque, `[a-z][a-z0-9_]{0,47}`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct GrievanceKindName(pub(crate) String); + + +impl crate::docs::DocKey for GrievanceKindName { + fn key_text(&self) -> String { + self.0.clone() + } +} + +/// Where one kind of grievance goes, and who may bring it. One forum per +/// grievance kind, world-wide; per-jurisdiction forums would key this on +/// `(GrievanceKindName, AuthorityTarget)`, and that key has no consumer yet. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Forum { + /// Any subject. A one-person magistrate is a legitimate forum, so the + /// kernel branches on `SubjectKind` here as it does everywhere else: not at + /// all. + pub(crate) forum: SubjectId, + /// Who may bring this grievance. It reuses `AuthorityTarget`'s type and its + /// covering predicate and is emphatically not stored in the `authority` + /// partition, so `RevokeAuthority` cannot strip standing. + pub(crate) standing: AuthorityTarget, +} + +/// Whole minutes: the kernel's only time unit, so route cost adds and compares +/// with no converter. The valid range is checked, not typed, so a bad cost joins +/// the complete mismatch set instead of failing deserialization. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Cost(pub(crate) u32); + +/// One year of minutes; bounds path sums. +pub(super) const MAX_ROUTE_COST: u32 = 525_600; + +/// A conserved count. Unsigned because a holding can never be negative: a signed +/// type would make "owes 3 iron" representable and push the real check to runtime +/// anyway. Subtraction is `checked_sub` and its failure is `InsufficientCustody`; +/// addition is `checked_add` and its failure is `QuantityOverflow`. No saturating +/// arithmetic anywhere, because a silent clamp is a silent conservation break. +/// There is no maximum: nothing sums quantities across resources, so the honest +/// bound is the type's. There is no unit, because a unit is where prices enter. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Quantity(pub(crate) u64); + +/// What a subject depends on. A dependency is a bare relation: no magnitude, no +/// kind beyond its target namespace, no clock, no cost. The variant selects the +/// resolver, so the target kind is carried by the type rather than checked after +/// the fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum DependencyTarget { + Resource(EntityId), + Route(EdgeId), + Subject(SubjectId), +} + +/// The proposal-time twin of [`DependencyTarget`], carrying references rather +/// than canonical IDs. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "ref", rename_all = "snake_case")] +pub(crate) enum DependencyRef { + Resource(Ref), + Route(Ref), + Subject(Ref), +} + +/// Where a subject stands. One place, derived from nothing else. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct Position { + pub(crate) place: EntityId, +} + +/// Namespace plus declared kind of a draft handle. A reference states the kind it +/// expects; resolution refuses a handle that answers with another one. A subject +/// expectation carries `None` where the referring position constrains the +/// namespace but not the kind. +/// +/// It is one predicate serving three readers: the resolution index, `Mismatch`, +/// and an affordance's `RoleSpec`, which persists inside the catalog and so +/// requires the serde derives. `Affordance` names the catalog namespace, which +/// carries no components and can never be a role's target. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "kind", rename_all = "snake_case")] +pub enum RefKind { + Subject(Option), + Entity(EntityKind), + Edge(EdgeKind), + Affordance, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct DraftHandle(String); + +impl DraftHandle { + pub(super) fn new(value: impl Into) -> Self { + Self(value.into()) + } +} + +/// A reference is an exact canonical ID or a handle resolved in the same patch. +/// There is no third form and no `From`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "ref", content = "value", rename_all = "snake_case")] +pub enum Ref { + Existing(Id), + Draft(DraftHandle), +} + +/// A referent in any of the three referent namespaces, or in the catalog. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "ref", rename_all = "snake_case")] +pub enum RefName { + Subject(Ref), + Entity(Ref), + Edge(Ref), + Affordance(Ref), +} + +/// A world-declared affordance name. Canonical text, `[a-z][a-z0-9_]{0,47}`, +/// because it becomes a generated tool name and a tool name must be stable, +/// unique, and safe. The kernel carries it and branches on it nowhere; that is +/// what keeps genre out of the reducer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct AffordanceKindName(pub String); + +/// A named slot in one affordance, bound to a referent at invocation time. +/// Canonical text, `[a-z][a-z0-9_]{0,31}` — it becomes a tool parameter name. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct Role(pub(crate) String); + +/// What a role must be bound to. `RefKind` is reused rather than restated: it +/// already spells subject, entity kind, and edge kind, so the binding kind-check +/// and the declaration kind-check are one predicate. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoleSpec { + pub(crate) role: Role, + pub(crate) kind: RefKind, +} + +/// Committed world text: canonical, non-empty. The kernel stores it, hands it to +/// a projection, and reads it no other way. Nothing compares two `Statement`s: +/// no dedup, no interning, no contradiction check, no similarity. Two facts with +/// byte-identical statements are two facts. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct Statement(String); + +impl Statement { + pub fn new(value: impl Into) -> Option { + let value = value.into(); + is_canonical_text(&value).then_some(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// How a fact stands. Immutable after admission: there is no `SetStanding`. A +/// claim never becomes canon and canon never degrades to a claim, so nothing +/// ever has to decide which of two facts wins. A world in which a court rules on +/// a rumour declares a *new* `Canonical` fact; the rumour survives beside it, +/// which is what makes a later `Redress` reading possible at all. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStanding { + /// Admitted with a receipt, through the same evidence gate `Admit` uses. + Canonical { evidence: EvidenceRef }, + /// Asserted by a subject. The kernel does not evaluate the assertion. + Claimed { by: SubjectId }, + /// Stated by the play table. The kernel does not evaluate it; only `Play` + /// may write it. + Ruled, +} + +/// The proposal-time twin of [`FactStanding`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStandingRef { + Canonical { evidence: EvidenceRef }, + Claimed { by: Ref }, + Ruled, +} + +/// One `EntityKind::Fact` row's payload. Write-once: only declaration and +/// `AssertClaim` ever write `facts`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactRecord { + pub(crate) statement: Statement, + pub(crate) standing: FactStanding, +} + +/// Where a channel carries. A place reach is the subtree, through the same +/// [`covers_place`] walk a `PlaceSubtree` jurisdiction uses. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum Reach { + /// Exactly these subjects. May be empty: an empty reach is the named + /// silenced state, which is the outcome this component exists to hold. + Subjects(BTreeSet), + /// Everyone positioned at that place or anywhere inside it. + Place(EntityId), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum ReachRef { + Subjects(BTreeSet>), + Place(Ref), +} + +/// One `EntityKind::Channel` row's payload. It carries no latency: there is no +/// clock, so a latency field would be read by nothing and bound by nothing. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelRecord { + pub(crate) reach: Reach, + /// Who may speak on it besides those inside its reach, and whose scope + /// components carry it. The horn belongs to the temple, not to whoever happens + /// to be within earshot of it. + pub(crate) controller: Option, +} + +/// A small closed ordinal. Ordered ascending by declaration order, so derived +/// `Ord` *is* the semantics and `Knows { at_least }` is one `>=`. Three levels: +/// two cannot express "I heard it but I doubt it", which is the state deception +/// produces; four or more is a scale nothing in the vocabulary distinguishes. +/// There is no zero — forgetting is a removed key, exactly as `Quantity(0)` is +/// unstorable. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Confidence { + Doubted, + Believed, + Certain, +} + +/// Three sources with named writers: `Witnessed` is written by +/// `AcquireKnowledge` and by `Witness`, `Evidenced` by `AcquireKnowledge`, and +/// `Told` only by `Communicate`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum KnowledgeSource { + Witnessed, + /// `via: None` is co-location. + Told { + by: SubjectId, + via: Option, + }, + /// A visible act of `by`, perceived in the same place. Written only by + /// `ResolvedOp::Display`, which the kernel alone lowers. + Seen { + by: SubjectId, + }, + Evidenced, +} + +/// What one subject holds of one fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Knowledge { + pub(crate) confidence: Confidence, + pub(crate) source: KnowledgeSource, + /// The revision at which this subject acquired this row: witnessed, + /// told, shown, or seeded by an author. Written by every writer of this + /// map (PA.f44), so the Projector's recency marker can tell a row minted + /// with no `minted_at` — a patch, a seed, a ruled fact — from one the + /// subject already held before its last act. + pub(crate) acquired_at: u64, +} + +/// The source an author may write. `Told` is unrepresentable here: only +/// `Communicate` writes it, so no author can forge a teller. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum AuthoredSource { + Witnessed, + Evidenced, +} + +/// Where a telling lands. `Colocated` is derived from `positions` at check and +/// at apply; it is never a stored channel, so no entity is minted per place and +/// no world must enumerate a village to let people talk in a room. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Audience { + Colocated, + Channel(EntityId), +} + +impl Audience { + pub(super) fn channel(self) -> Option { + match self { + Self::Colocated => None, + Self::Channel(entity_id) => Some(entity_id), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceRef { + Colocated, + Channel(Ref), +} + +/// The catalog form: a declared affordance names a role, the invoker binds a +/// channel to it, and `exercise` lowers this plus the bindings into the +/// canonical [`Audience`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceSpec { + Colocated, + Channel(Role), +} + +/// What a subject has promised. The kernel branches on this twice — the tick +/// behaves differently per kind and the scale count reads `Goal` — so it is a +/// closed enum rather than a world-declared name. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum CommitmentKind { + Routine, + Obligation, + Goal, +} + +/// Deterministic from the creating command and the operation's index within +/// that command's lowered operations. No `EdgeId`: nothing references a +/// commitment by identity, so a structural key is the whole answer. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct CommitmentKey { + pub(crate) command: CommandId, + pub(crate) index: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Commitment { + pub(crate) kind: CommitmentKind, + /// `None` is a promise to oneself: a personal `Goal`. A counterparty equal + /// to the subject is refused. + pub(crate) counterparty: Option, + /// Absolute. "Past due" is `due <= now`: one comparison, no countdown + /// fanned across the partition. + pub(crate) due: FictionalMinutes, + /// Required for `Routine` — that is what makes it recur — and forbidden + /// otherwise. On auto-fulfilment `due` rolls forward by this. + pub(crate) period: Option, + /// What must hold for a `Routine` to auto-fulfil. Role-free canonical + /// checks. Empty for `Obligation` and `Goal`. + pub(crate) checks: Vec, + /// What is promised, as the promisor would state it. Without it a promise + /// is a clock and a name, and on the road both parties invented the rest. + pub(crate) statement: Statement, +} + +/// Nonzero by construction; saturating in both directions. A separate newtype +/// from [`super::Magnitude`], which is an effect ceiling and shares nothing with +/// this but a word. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct PressureMagnitude(pub(crate) u32); + +/// Target-major, because every reader is: the typed view shows pressure on +/// self. Source-major has no reader. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", content = "of", rename_all = "snake_case")] +pub(crate) enum PressureSource { + /// A past-due commitment. Carries the promisor and the structural key. + Commitment { + subject: SubjectId, + key: CommitmentKey, + }, + /// An unavailable dependency of the pressed subject. This is how a closed + /// route in one realm becomes a political problem in another without anyone + /// deciding that it should be. + Dependency(DependencyTarget), + /// Another subject, pressing directly through an affordance effect. + Subject(SubjectId), +} + +/// The proposal-time twin of [`PressureSource`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", content = "of", rename_all = "snake_case")] +pub(crate) enum PressureSourceRef { + Commitment { + subject: Ref, + key: CommitmentKey, + }, + Dependency(DependencyRef), + Subject(Ref), +} + +/// The role-free canonical twin of [`Precondition`]. A `Precondition` names +/// roles; a `BoundPrecondition` names referents, so a commitment's checks are +/// storable with no second binding path and one evaluator serves both the +/// invocation pipeline and the tick. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum BoundPrecondition { + Present { + at: EntityId, + }, + Reachable { + to: EntityId, + within: Cost, + }, + Holds { + resource: EntityId, + at_least: Quantity, + }, + Authorized { + over: super::Target, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: EntityId, + at_least: Confidence, + }, + CanBroadcast { + via: Audience, + }, + CanReach { + subject: SubjectId, + via: Audience, + }, + Committed { + to: SubjectId, + kind: CommitmentKind, + }, +} + +/// The proposal-time twin of [`BoundPrecondition`], carried by +/// `CreateCommitment` so a patch may name a check over structure it declares. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum PreconditionRef { + Present { + at: Ref, + }, + Reachable { + to: Ref, + within: Cost, + }, + Holds { + resource: Ref, + at_least: Quantity, + }, + Authorized { + over: AuthorityTargetRef, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: Ref, + at_least: Confidence, + }, + CanBroadcast { + via: AudienceRef, + }, + CanReach { + subject: Ref, + via: AudienceRef, + }, + Committed { + to: Ref, + kind: CommitmentKind, + }, +} + +/// What must already be true of committed state before an invocation is +/// admitted. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum Precondition { + /// The acting subject's Position names the place bound to `at`. + Present { at: Role }, + /// A path exists from the actor's place to the place bound to `to`, over + /// open routes this subject may traverse, with summed cost at most `within`. + Reachable { to: Role, within: Cost }, + /// The acting subject's own holding of the resource bound to `resource` is + /// at least `at_least`. + Holds { resource: Role, at_least: Quantity }, + /// The acting subject's effective authority — its own grants plus what + /// every office it occupies lends — holds a grant of `kind` whose target + /// covers the referent bound to `over`. + Authorized { over: Role, kind: AuthorityKindName }, + /// A forum takes `grievance` and the acting subject is inside its standing. + HasStanding { grievance: GrievanceKindName }, + /// The acting subject holds the fact bound to `fact` at `at_least` or + /// better. + Knows { fact: Role, at_least: Confidence }, + /// The acting subject has an audience at all: it is positioned, for + /// co-location, or it is inside the bound channel's reach or is its + /// controller. + CanBroadcast { via: AudienceSpec }, + /// The referent bound to `subject` is inside that audience. Addressing does + /// not narrow the audience: a telling still lands on everyone in it. + CanReach { subject: Role, via: AudienceSpec }, + /// The acting subject holds a commitment of `kind` to the referent bound to + /// `to`. This is what lets a world author an affordance whose legitimacy is + /// a promise rather than a jurisdiction. + Committed { to: Role, kind: CommitmentKind }, +} + +/// Exactly the operations an affordance may propose. `Admit` is absent because +/// minting quantity requires an `EvidenceRef` and an invocation carries no +/// evidence list, so admitting it here would be a second creation path beside +/// the single evidenced one. `OpenOffice`, `CloseOffice`, `OpenForum`, and +/// `CloseForum` are absent because constituting an office or a forum has no +/// live in-play reader an affordance would serve; they stay patch-lane only. +/// +/// `Witness` is a slot and `Communicate` is not, because a witnessed event is +/// world-caused and names no speaker, while speech is the actor's own act and +/// reaches an invocation only through the kernel-owned `carries_speech` +/// lowering: a proposer that could `Communicate` would choose a speaker, and a +/// proposer that `Witness`es chooses only where. +/// +/// The four civic variants carry their payload on the variant rather than on +/// the slot or the invocation: an authority kind and an office name are not +/// referents, so they cannot be roles, and a proposer's only degree of freedom +/// stays magnitude. The world fixes the kind when it authors the entry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ComponentOpKind { + Relocate, + OpenRoute, + CloseRoute, + AlterCost, + Transfer, + Transform, + Consume, + Bind, + Release, + GrantAuthority { + kind: AuthorityKindName, + }, + RevokeAuthority { + kind: AuthorityKindName, + }, + InstallIncumbent { + office: OfficeName, + }, + VacateOffice { + office: OfficeName, + }, + /// Source is fixed to `Witnessed`: only `Communicate` writes a teller, and + /// `Evidenced` needs a patch's evidence list, which an invocation has not. + AcquireKnowledge { + confidence: Confidence, + }, + /// A world-authored event with no speaker: a beacon, a bell, a blast. The + /// slot names a fact and a place, never a subject, so a proposer's only + /// degree of freedom is which declared place the entry binds. The source is + /// `Witnessed` by construction — `ComponentOp::Witness` has no field a + /// teller could enter — so this lowering cannot forge one however it is + /// bound. + Witness { + confidence: Confidence, + }, + Forget, + /// The kind, the horizon, and the period are fixed on the variant, so a + /// proposer's only degree of freedom stays magnitude. `due` is + /// `now + horizon`, computed by the kernel at lowering: an absolute due on + /// a catalog entry would be a fixed date the world outgrows. + CreateCommitment { + kind: CommitmentKind, + horizon: TickMinutes, + period: Option, + }, + /// The source is fixed to the acting subject, so it cannot be forged. A + /// world authoring `threaten`, `reassure`, or `forgive` needs these three. + AdvancePressure { + by: PressureMagnitude, + }, + ReducePressure { + by: PressureMagnitude, + }, + ResolvePressure, +} + +/// The referent shape of one operation: the single source of both the +/// declaration check and the lowering. +pub(super) enum RoleKindRule { + Exact(RefKind), + AnyDependencyTarget, + AnyAuthorityTarget, +} + +/// Which magnitude, if any, an operation carries. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BoundsDimension { + None, + Quantity, + Cost, +} + +impl ComponentOpKind { + pub(super) fn arity(&self) -> Vec { + let subject = || RoleKindRule::Exact(ANY_SUBJECT); + let route = || RoleKindRule::Exact(ROUTE); + let resource = || RoleKindRule::Exact(RefKind::Entity(EntityKind::Resource)); + match self { + Self::Relocate => vec![subject(), route()], + Self::OpenRoute | Self::CloseRoute | Self::AlterCost => vec![route()], + Self::Transfer => vec![subject(), subject(), resource()], + Self::Transform => vec![subject(), resource(), resource()], + Self::Consume => vec![subject(), resource()], + Self::Bind | Self::Release => vec![subject(), RoleKindRule::AnyDependencyTarget], + Self::GrantAuthority { .. } | Self::RevokeAuthority { .. } => { + vec![subject(), RoleKindRule::AnyAuthorityTarget] + } + Self::InstallIncumbent { .. } => vec![subject(), subject()], + Self::VacateOffice { .. } => vec![subject()], + Self::AcquireKnowledge { .. } | Self::Forget => { + vec![subject(), RoleKindRule::Exact(FACT)] + } + Self::Witness { .. } => vec![RoleKindRule::Exact(FACT), RoleKindRule::Exact(PLACE)], + // Promisor and counterparty. A `Goal` slot is refused at admission + // with `GoalWithCounterparty`: a promise to oneself has no second + // referent to bind, so the action lane authors `Routine` and + // `Obligation` and the patch lane authors goals. + Self::CreateCommitment { .. } => vec![subject(), subject()], + Self::AdvancePressure { .. } | Self::ReducePressure { .. } | Self::ResolvePressure => { + vec![subject()] + } + } + } + + pub(super) fn dimension(&self) -> BoundsDimension { + match self { + Self::Transfer | Self::Transform | Self::Consume => BoundsDimension::Quantity, + Self::AlterCost => BoundsDimension::Cost, + _ => BoundsDimension::None, + } + } + + /// The civic names this variant carries, so one validator checks them all. + fn payload_names(&self) -> Vec<&str> { + match self { + Self::GrantAuthority { kind } | Self::RevokeAuthority { kind } => vec![&kind.0], + Self::InstallIncumbent { office } | Self::VacateOffice { office } => vec![&office.0], + _ => Vec::new(), + } + } +} + +/// Whether a declared role kind can serve a position governed by this rule. +pub(super) fn role_kind_fits(rule: &RoleKindRule, declared: RefKind) -> bool { + match rule { + RoleKindRule::Exact(RefKind::Subject(_)) => matches!(declared, RefKind::Subject(_)), + RoleKindRule::Exact(expected) => *expected == declared, + RoleKindRule::AnyDependencyTarget => matches!( + declared, + RefKind::Subject(_) | RefKind::Entity(EntityKind::Resource) | RefKind::Edge(_) + ), + RoleKindRule::AnyAuthorityTarget => { + matches!(declared, RefKind::Subject(_) | PLACE) + } + } +} + +/// The magnitude ceiling for one slot. A closed enum matched to the operation's +/// dimension rather than a struct of optional ceilings: an `Option` ceiling that +/// is `None` is not a ceiling, and a struct admits the nonsense of a cost +/// ceiling on a `Transfer`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "bound", content = "max", rename_all = "snake_case")] +pub(crate) enum Bounds { + None, + Quantity(Quantity), + Cost(Cost), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct EffectSlot { + pub(crate) op_kind: ComponentOpKind, + /// Positional: exactly the referents `op_kind` takes, in `arity()` order. + pub(crate) roles: Vec, + pub(crate) bounds: Bounds, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct OutcomeBand { + /// At least 1. A zero-weight band is a branch that can never be selected. + pub(crate) weight: u32, + /// Indices into `effect_slots`, strictly increasing. Empty is legal and is + /// how a world expresses "the attempt does nothing". + pub(crate) effects: Vec, +} + +/// One catalog entry: what an affordance *is*. Who may use it is +/// `affordance_grants` and nothing else, so an entry carries no audience. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Affordance { + pub kind: AffordanceKindName, + /// Ordered, so the generated tool's parameters are stable across builds. + pub(crate) roles: Vec, + pub(crate) preconditions: Vec, + pub(crate) effect_slots: Vec, + pub(crate) outcome_bands: Vec, + /// Every invocation of this entry carries exactly one utterance. The + /// kernel's only behaviour is to record it in the event; any world may + /// declare a speaking affordance, so this is not a Speak special case. + pub(crate) carries_speech: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct AffordanceDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) kind: AffordanceKindName, + pub(crate) roles: Vec, + pub(crate) preconditions: Vec, + pub(crate) effect_slots: Vec, + pub(crate) outcome_bands: Vec, + pub(crate) carries_speech: bool, +} + +/// Where a failed check appeared. One way to say it, for declarations and +/// operations alike. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "site", content = "at", rename_all = "snake_case")] +pub enum Site { + Declaration(DraftHandle), + Operation(usize), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct EvidenceRef(String); + +impl EvidenceRef { + /// An author's evidence receipts are built here, and `Deserialize` + /// already mints one from any string, so this constructor gates nothing. + /// Canonical text is checked by the resolver, in the complete mismatch set. + pub(super) fn new(value: impl Into) -> Self { + Self(value.into()) + } + + pub(super) fn text(&self) -> &str { + &self.0 + } +} + +/// The Aetheria record a subject was imported from: the CultCache schema id and +/// the record key, compared exactly as two separate texts so no pair of +/// distinct records can spell one key. Admission keeps the mapping injective; +/// a key is never matched by prefix, case or normalisation. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct ImportKey { + schema: String, + record: String, +} + +/// The longest either part of an import key may be, in bytes. +const MAX_IMPORT_KEY_PART_BYTES: usize = 200; + +impl ImportKey { + pub fn new(schema: impl Into, record: impl Into) -> Self { + Self { + schema: schema.into(), + record: record.into(), + } + } + + pub fn schema(&self) -> &str { + &self.schema + } + + pub fn record(&self) -> &str { + &self.record + } + + /// The one predicate for an import key, called by the resolver and by the + /// load-time state gate alike. The record part is canonical free text: not + /// empty, at most 200 bytes, no leading, trailing or doubled space, already NFC + /// (refused, never normalised, so the kernel derives no second spelling), + /// no control or format character, and no whitespace but U+0020. The schema + /// part is a schema id: the same text with no space at all. + pub(super) fn is_canonical(&self) -> bool { + is_canonical_key_text(&self.record) + && is_canonical_key_text(&self.schema) + && !self.schema.contains(' ') + } +} + +fn is_canonical_key_text(part: &str) -> bool { + !part.is_empty() + && part.len() <= MAX_IMPORT_KEY_PART_BYTES + && !part.starts_with(' ') + && !part.ends_with(' ') + && !part.contains(" ") + && unicode_normalization::is_nfc(part) + && part.chars().all(|c| { + !c.is_control() + && c.general_category() != GeneralCategory::Format + && (c == ' ' || !c.is_whitespace()) + }) +} + +/// Why an import key cannot join a world: the resolver names these by draft +/// handle, the state gates by invariant text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ImportKeyFault { + Malformed, + Held, + Duplicate, +} + +/// The one decision on a key: malformed, held by a subject already in the +/// world (`held` asks the subjects' `ByImportKey` index, retired ones +/// included, so a key is never reissued), or already claimed in `declared` +/// (which it joins). Every door that admits or loads subjects calls this, so +/// none can decide otherwise. +pub(super) fn import_key_fault<'a>( + key: &'a ImportKey, + held: impl Fn(&ImportKey) -> bool, + declared: &mut BTreeSet<&'a ImportKey>, +) -> Option { + if !key.is_canonical() { + Some(ImportKeyFault::Malformed) + } else if held(key) { + Some(ImportKeyFault::Held) + } else if !declared.insert(key) { + Some(ImportKeyFault::Duplicate) + } else { + None + } +} + +/// `position` is the subject's presence: one place it stands in. A subject +/// declared without one is unplaced until a later pass gives placement an owner. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct SubjectDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) kind: SubjectKind, + /// The catalog entries this subject may exercise. Every entry is a + /// reference, so a genesis patch declares a catalog and grants from it + /// atomically. + pub(crate) affordances: BTreeSet>, + pub(crate) position: Option>, + /// The record this subject was imported from, if any. Absent from a + /// subject nobody imported, so such a world's state and digests are what + /// they were before import keys existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) import_key: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct EntityDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) kind: EntityKind, + /// Legal only for `EntityKind::Place`, and only ever names a place. + pub(crate) container: Option>, +} + +/// A declared route is open. A route that should start closed is `declare` plus +/// `CloseRoute` in the same patch, so `open` has one writer family. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct RouteDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) from: Ref, + pub(crate) to: Ref, + pub(crate) access: AccessKind, + pub(crate) cost: Cost, +} + +/// A fact's label is a short authored name ("the flooding of the lower hinge"), +/// never a transcript: the statement is never copied into the label and the +/// label is never derived from the statement, so the utterance has exactly one +/// home in state. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingRef, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) reach: ReachRef, + pub(crate) controller: Option>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum Declaration { + Subject(SubjectDeclaration), + /// Places and resources only. `Fact` and `Channel` carry a payload and have + /// their own declarations, so a referenceable empty one is unrepresentable. + Entity(EntityDeclaration), + Route(RouteDeclaration), + Affordance(AffordanceDeclaration), + Fact(FactDeclaration), + Channel(ChannelDeclaration), +} + +/// The operations that change a component of an already canonical structure. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ComponentOp { + Relocate { + subject: Ref, + via: Ref, + }, + OpenRoute { + route: Ref, + }, + CloseRoute { + route: Ref, + }, + AlterCost { + route: Ref, + cost: Cost, + }, + Transfer { + from: Ref, + to: Ref, + resource: Ref, + qty: Quantity, + }, + /// One-for-one relabel: the same `qty` leaves `from_resource` and arrives in + /// `into_resource`, held by the same subject. A ratio would be a recipe, and + /// recipes belong to the consumer that owns production; the op shape makes a + /// non-conserving transform unrepresentable rather than merely checkable. A + /// world that needs lossy conversion writes `Transform` plus `Consume`, and + /// both terms then appear in the ledger. + Transform { + holder: Ref, + from_resource: Ref, + into_resource: Ref, + qty: Quantity, + }, + Consume { + holder: Ref, + resource: Ref, + qty: Quantity, + }, + /// The only creation path for quantity, in every lane including genesis. Its + /// `evidence` must appear in the same patch's `evidence` list, which makes + /// creation attributable; the commit chain then makes it tamper-evident. + Admit { + holder: Ref, + resource: Ref, + qty: Quantity, + evidence: EvidenceRef, + }, + /// Creates quantity with no receipt. Only `Play` may write it; every other + /// author creates quantity through `Admit` and its evidence. + Mint { + holder: Ref, + resource: Ref, + qty: Quantity, + }, + Bind { + subject: Ref, + target: DependencyRef, + }, + Release { + subject: Ref, + target: DependencyRef, + }, + /// Adds one grant. An identical grant is `NoOperationEffect`; one that + /// overlaps another the holder already has is `OverlappingJurisdiction`. + GrantAuthority { + holder: Ref, + grant: AuthorityGrantRef, + }, + RevokeAuthority { + holder: Ref, + grant: AuthorityGrantRef, + }, + /// Creates or reconstitutes an office, preserving any sitting incumbent. + /// Clipping an office's powers under a sitting incumbent is a political + /// act, and this is how it is written. + OpenOffice { + institution: Ref, + office: OfficeName, + delegated: BTreeSet, + }, + CloseOffice { + institution: Ref, + office: OfficeName, + }, + InstallIncumbent { + institution: Ref, + office: OfficeName, + incumbent: Ref, + }, + VacateOffice { + institution: Ref, + office: OfficeName, + }, + OpenForum { + grievance: GrievanceKindName, + forum: Ref, + standing: AuthorityTargetRef, + }, + CloseForum { + grievance: GrievanceKindName, + }, + /// Source is authored: `Witnessed` by an author or an affordance, + /// `Evidenced` only over a `Canonical` fact. + AcquireKnowledge { + subject: Ref, + fact: Ref, + source: AuthoredSource, + confidence: Confidence, + }, + /// One telling. It stores the audience, never the recipients: the fan-out is + /// re-derived at apply from live `positions` and `channels`. + Communicate { + speaker: Ref, + fact: Ref, + to: AudienceRef, + }, + /// One witnessed event over a place subtree: a beacon, a bell, a blast, an + /// asteroid. It names no speaker, because the row it lands is + /// `KnowledgeSource::Witnessed` — there is no teller to forge and none is + /// implied. It stores the place, never the recipients: the subtree is + /// re-derived at apply from live `positions`. Everyone already holding the + /// fact is untouched, and a witness that reaches nobody is refused. + Witness { + fact: Ref, + place: Ref, + confidence: Confidence, + }, + Forget { + subject: Ref, + fact: Ref, + }, + SetReach { + channel: Ref, + reach: ReachRef, + }, + SetController { + channel: Ref, + controller: Option>, + }, + /// Two identical creations are two commitments, not `NoOperationEffect`: + /// the key is command-derived so they cannot collide, and two promises of + /// the same thing to the same counterparty are two promises. This is where + /// a commitment differs from a grant, a holding, and a dependency, all of + /// which are set-shaped. + CreateCommitment { + subject: Ref, + counterparty: Option>, + kind: CommitmentKind, + due: FictionalMinutes, + period: Option, + checks: Vec, + statement: Statement, + }, + /// Removes the commitment and every pressure row sourced by it. Fulfilment, + /// default, and release are one write: the kernel never learns who invoked + /// an operation, so three names would be three spellings of one removal + /// with a distinction only a consumer can read. + DischargeCommitment { + subject: Ref, + key: CommitmentKey, + }, + /// Insert-or-add, saturating. With absence meaning zero, creation and + /// advance are the same write. + AdvancePressure { + source: PressureSourceRef, + target: Ref, + by: PressureMagnitude, + }, + /// Saturating subtract; removal at zero. + ReducePressure { + source: PressureSourceRef, + target: Ref, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSourceRef, + target: Ref, + }, + /// Ends a subject for good: no grants, no position, no audience, its + /// history kept. Play's alone, like every post-genesis patch. + Retire { + subject: Ref, + }, + /// Grants one more standing catalog entry to an existing subject. Play's + /// alone. + GrantAffordance { + subject: Ref, + affordance: Ref, + }, + /// Revokes a grant. A subject left with no verb holds no grant row and + /// simply cannot act. + RevokeAffordance { + subject: Ref, + affordance: Ref, + }, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct WorldPatch { + pub(crate) declarations: Vec, + pub(crate) operations: Vec, + pub(crate) evidence: Vec, +} + +/// The one byte bound on a `WorldPatch` frame from any external source, and +/// the three item bounds on a `WorldPatch` as a value. One owner, two +/// consumers: the consumer ingress decodes against them through +/// `decode_patch`, and `check_patch_caps` applies the same three item caps to +/// an assembled value before submission. +pub(crate) const MAX_PATCH_BYTES: usize = 256 * 1024; +pub(crate) const MAX_PATCH_DECLARATIONS: usize = 64; +pub(crate) const MAX_PATCH_OPERATIONS: usize = 128; +pub(crate) const MAX_PATCH_EVIDENCE: usize = 64; + +/// Why a patch was refused before the resolver ever saw it. Not a second +/// structural vocabulary: nothing here reads world state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PatchDecodeError { + TooLarge { bytes: usize }, + NotCanonical, + Malformed, + TooManyDeclarations { count: usize }, + TooManyOperations { count: usize }, + TooManyEvidence { count: usize }, +} + +/// The one decode owner for a `WorldPatch` from a byte source. The byte cap is +/// applied to the frame before `rmp_serde` sees it, so no item is deserialized +/// out of a frame the world would not accept; the item caps are checked on the +/// decoded value before `resolve_patch`, which is the first thing that costs +/// `state ∪ patch`. +pub(crate) fn decode_patch(bytes: &[u8]) -> Result { + if bytes.len() > MAX_PATCH_BYTES { + return Err(PatchDecodeError::TooLarge { bytes: bytes.len() }); + } + let patch: WorldPatch = + rmp_serde::from_slice(bytes).map_err(|_| PatchDecodeError::Malformed)?; + // The canonical round-trip the journal and the presence route already + // require, so one frame has one encoding. + if rmp_serde::to_vec_named(&patch).map_err(|_| PatchDecodeError::Malformed)? != bytes { + return Err(PatchDecodeError::NotCanonical); + } + check_patch_caps(&patch)?; + Ok(patch) +} + +/// The same three item caps against an in-memory draft, for the lane that +/// builds rather than decodes. +pub(crate) fn check_patch_caps(patch: &WorldPatch) -> Result<(), PatchDecodeError> { + if patch.declarations.len() > MAX_PATCH_DECLARATIONS { + return Err(PatchDecodeError::TooManyDeclarations { + count: patch.declarations.len(), + }); + } + if patch.operations.len() > MAX_PATCH_OPERATIONS { + return Err(PatchDecodeError::TooManyOperations { + count: patch.operations.len(), + }); + } + if patch.evidence.len() > MAX_PATCH_EVIDENCE { + return Err(PatchDecodeError::TooManyEvidence { + count: patch.evidence.len(), + }); + } + Ok(()) +} + +/// One named structural check that a patch failed. A rejection carries the +/// complete set, never the first failure. It never enters `WorldState`, +/// `WorldEffect`, `CommandEnvelope`, or `WorldCommit`; the serde derives exist +/// for telemetry readers outside the kernel, under their own row type and +/// schema. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "mismatch", rename_all = "snake_case")] +pub enum Mismatch { + EmptyHandle { + position: usize, + }, + DuplicateHandle { + handle: DraftHandle, + }, + EmptyLabel { + handle: DraftHandle, + }, + /// The world is bound to a grammar and this affordance's kind is not one of + /// its verbs. + AffordanceKindNotInGrammar { + handle: DraftHandle, + }, + /// The kind is a verb of the bound grammar, but the declared roles are not + /// its signature (name, referent kind or order). + AffordanceRolesDisagreeWithGrammar { + handle: DraftHandle, + }, + /// The grammar binds the kernel's speak verb as anything but a Conversation. + SpeakRenderPathDisagreesWithGrammar { + handle: DraftHandle, + }, + /// An import key is empty, has whitespace, or is longer than 200 bytes in + /// either part. + MalformedImportKey { + handle: DraftHandle, + }, + /// Two subjects in one patch declare the same import key. + DuplicateImportKey { + handle: DraftHandle, + }, + /// A subject already in the world, retired or not, holds this import key. + ImportKeyHeld { + handle: DraftHandle, + }, + UnresolvedDraft { + site: Site, + referent: DraftHandle, + expected: RefKind, + }, + WrongKind { + site: Site, + referent: RefName, + expected: RefKind, + actual: RefKind, + }, + UnknownCanonical { + site: Site, + expected: RefKind, + }, + EmptyEvidence { + position: usize, + }, + CanonicalCollision { + handle: DraftHandle, + }, + NoCanonicalChange, + /// A genesis-lane resolution (the same empty-state case `is_genesis` + /// tests) declared no subject, so the world would have nobody to act. This + /// is a rejected patch, not a corrupt journal: the kernel must survive it. + NoDecisionSubject, + /// A declared place contains itself through its container chain. + ContainmentCycle { + referent: DraftHandle, + }, + RouteSelfLoop { + referent: DraftHandle, + }, + InvalidCost { + site: Site, + }, + SubjectNotAtOrigin { + operation: usize, + }, + RouteClosed { + operation: usize, + }, + RouteAccessRestricted { + operation: usize, + }, + UnplacedSubject { + operation: usize, + }, + /// An operation that changes nothing is not a canonical change. + NoOperationEffect { + operation: usize, + }, + /// The holder does not hold enough. Absence is zero, so "holds none at all" + /// is this variant at the boundary rather than a second name. + InsufficientCustody { + operation: usize, + }, + /// A custody operation naming `Quantity(0)`: it moves nothing. + ZeroQuantity { + operation: usize, + }, + /// A credit that would leave a holding above `u64::MAX`. + QuantityOverflow { + operation: usize, + }, + /// An `Admit` whose `EvidenceRef` is not listed in this patch's `evidence`. + AdmitWithoutEvidence { + operation: usize, + }, + /// A `Bind` or `Release` naming the acting subject as its own target. + SelfDependency { + operation: usize, + }, + /// The candidate ledger does not balance for this resource: the total after + /// the patch is not the total before plus what was admitted and gained, less + /// what was consumed and spent. + CustodyNotConserved { + resource: RefName, + }, + /// `kind` is not `[a-z][a-z0-9_]{0,47}`, or a `Role` is not + /// `[a-z][a-z0-9_]{0,31}`. Tool and parameter names must be safe. + InvalidAffordanceName { + handle: DraftHandle, + }, + /// Two entries in the candidate graph share one kind name; the generated + /// tool catalog would have two tools with one name. + DuplicateAffordanceKind { + handle: DraftHandle, + }, + DuplicateRole { + handle: DraftHandle, + role: Role, + }, + /// A precondition or a slot names a role the entry does not declare. + UnknownRole { + handle: DraftHandle, + role: Role, + }, + /// A declared role's `RefKind` cannot serve the position that reads it, or + /// names a namespace no invocation target can bind. + RoleKindUnfit { + handle: DraftHandle, + role: Role, + }, + SlotRoleArity { + handle: DraftHandle, + slot: usize, + }, + /// The slot's `Bounds` variant does not match its `op_kind`'s dimension, or + /// the ceiling is zero, or a cost ceiling is outside `1..=MAX_ROUTE_COST`. + SlotBoundMismatch { + handle: DraftHandle, + slot: usize, + }, + NoOutcomeBand { + handle: DraftHandle, + }, + ZeroBandWeight { + handle: DraftHandle, + band: usize, + }, + /// A band names a slot index the entry does not have. + DanglingBandEffect { + handle: DraftHandle, + band: usize, + }, + /// A band's `effects` are not strictly increasing. + BandEffectsNotCanonical { + handle: DraftHandle, + band: usize, + }, + /// No effect slots and no speech: the entry can never change anything. + InertAffordance { + handle: DraftHandle, + }, + /// An `OfficeName`, `AuthorityKindName`, or `GrievanceKindName` that is not + /// `[a-z][a-z0-9_]{0,47}`. + InvalidCivicName { + site: Site, + }, + /// `OpenOffice` lending no authority kind. + EmptyDelegation { + operation: usize, + }, + /// The institution named by an office operation is not + /// `SubjectKind::Institution`. + OfficeOnNonInstitution { + operation: usize, + }, + /// An incumbent that is not `SubjectKind::Person`. This is the check that + /// keeps an institution's operational organ and its person-shaped voice two + /// subjects joined by an office. + OfficeHolderNotPerson { + operation: usize, + }, + /// This person already occupies another office of this institution. + DuplicateIncumbency { + operation: usize, + }, + /// `InstallIncumbent`, `VacateOffice`, or `CloseOffice` naming an office the + /// institution does not have. + UnknownOffice { + operation: usize, + }, + /// `CloseForum` naming a grievance no forum takes. + UnknownForum { + operation: usize, + }, + /// One subject would hold two grants of the same kind over overlapping + /// targets, from any combination of direct grant and office delegation. + /// Overlap between *different* subjects is layered government and legal: + /// `Authorized` is a permission predicate, not an exclusivity claim, and + /// this rule exists so nothing ever has to arbitrate between two sources. + OverlappingJurisdiction { + operation: usize, + }, + /// A catalog entry declares a role named `actor`, which the kernel binds. + ReservedRole { + handle: DraftHandle, + }, + /// An `EntityDeclaration` naming `Fact` or `Channel`. Those kinds carry a + /// payload and have their own declaration; a payload-less one would make a + /// referenceable, empty fact a legal state. + PayloadEntityKind { + handle: DraftHandle, + }, + /// A `Canonical` fact declaration whose `EvidenceRef` is not listed in this + /// patch's `evidence`. + FactWithoutEvidence { + handle: DraftHandle, + }, + EmptyStatement { + handle: DraftHandle, + }, + /// A commitment statement that is empty, padded, or spans lines. + NoncanonicalText { + operation: usize, + }, + /// `AcquireKnowledge { source: Evidenced }` over a `Claimed` fact. + EvidencedKnowledgeOfClaim { + operation: usize, + }, + /// A `Communicate` whose speaker is neither inside the audience nor the + /// channel's controller. + SpeakerOutsideAudience { + operation: usize, + }, + /// A catalog entry with `carries_speech` and no `CanBroadcast` or + /// `CanReach`: its speech would have no audience to lower. + SpeechWithoutAudience { + handle: DraftHandle, + }, + /// More than one, so the lowering could not choose. + AmbiguousSpeechAudience { + handle: DraftHandle, + }, + /// A `Routine` with no period, or a non-`Routine` with one. + CommitmentPeriodMismatch { + operation: usize, + }, + /// A non-`Routine` carrying checks. Nothing would ever evaluate them. + ChecksOnNonRoutine { + operation: usize, + }, + /// `due <= now` at creation. A promise cannot be born past due; it would + /// press on its subject on the very next tick with no chance to act. + CommitmentDueInThePast { + operation: usize, + }, + /// `counterparty == subject`. + SelfCommitment { + operation: usize, + }, + /// A goal is a promise to oneself, and a promise to another is an + /// obligation. This keeps the scale count's `Goal` clause meaning one thing. + GoalWithCounterparty { + operation: usize, + }, + /// `DischargeCommitment` naming a key the subject does not hold. + UnknownCommitment { + operation: usize, + }, + /// A `Ruled` fact or a `Mint` was written by a caller other than the play + /// authority. + RuledWithoutAuthority { + site: Site, + }, + /// `Communicate`, `AcquireKnowledge`, `Forget`, or `InstallIncumbent` + /// named a retired subject as the one acting, learning, forgetting, or + /// taking office. A retired subject is a body, not an actor: it may still + /// be a holdings source (looted), a channel member, or a route endpoint, + /// but it cannot be the one who speaks, knows, or holds office. + RetiredSubjectActed { + operation: usize, + }, + /// `GrantAffordance` or `RevokeAffordance` named a retired subject: it + /// holds no grant this patch may touch. + GrantsToRetired { + operation: usize, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct EntityRecord { + pub(super) label: String, + pub(super) kind: EntityKind, + /// `Some` only for `EntityKind::Place`, and only ever a place. + pub(super) container: Option, +} + +/// One variant per edge kind that has a shape, so no record carries fields that +/// are meaningless for its discriminator. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(super) enum EdgeRecord { + Route { + label: String, + from: EntityId, + to: EntityId, + access: AccessKind, + cost: Cost, + open: bool, + }, +} + +impl EdgeRecord { + pub(super) fn endpoints(&self) -> (EntityId, EntityId) { + match self { + Self::Route { from, to, .. } => (*from, *to), + } + } + + pub(super) fn label(&self) -> &str { + match self { + Self::Route { label, .. } => label, + } + } + + pub(super) fn cost(&self) -> Cost { + match self { + Self::Route { cost, .. } => *cost, + } + } + + pub(super) fn access(&self) -> &AccessKind { + match self { + Self::Route { access, .. } => access, + } + } + + pub(super) fn is_open(&self) -> bool { + match self { + Self::Route { open, .. } => *open, + } + } + + pub(super) fn set_open(&mut self, value: bool) { + match self { + Self::Route { open, .. } => *open = value, + } + } + + pub(super) fn set_cost(&mut self, value: Cost) { + match self { + Self::Route { cost, .. } => *cost = value, + } + } +} + +/// The handle-to-ID binding table for one subject. The handle is commit-scoped +/// provenance; it never enters `WorldState`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedSubject { + pub(super) handle: DraftHandle, + pub(super) subject_id: SubjectId, + pub(super) subject: SubjectState, + pub(super) affordances: BTreeSet, + pub(super) position: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedEntity { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, +} + +/// The handle-to-ID binding for one catalog entry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedAffordance { + pub(super) handle: DraftHandle, + pub(super) affordance_id: AffordanceId, + pub(super) affordance: Affordance, +} + +/// A declared fact: one `entities` row and one `facts` row, allocated together +/// so the bijection has one writer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedFact { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) fact: FactRecord, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedChannel { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) channel: ChannelRecord, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedRoute { + pub(super) handle: DraftHandle, + pub(super) edge_id: EdgeId, + pub(super) edge: EdgeRecord, +} + +/// A lowered operation. `Relocate` carries no endpoints: they are read from the +/// route at apply time, so a forged effect cannot assert a destination the route +/// does not have. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ResolvedOp { + Relocate { + subject_id: SubjectId, + edge_id: EdgeId, + }, + OpenRoute { + edge_id: EdgeId, + }, + CloseRoute { + edge_id: EdgeId, + }, + AlterCost { + edge_id: EdgeId, + cost: Cost, + }, + Transfer { + from: SubjectId, + to: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Transform { + holder: SubjectId, + from_resource: EntityId, + into_resource: EntityId, + qty: Quantity, + }, + Consume { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Admit { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + evidence: EvidenceRef, + }, + Mint { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Bind { + subject: SubjectId, + target: DependencyTarget, + }, + Release { + subject: SubjectId, + target: DependencyTarget, + }, + GrantAuthority { + holder: SubjectId, + grant: AuthorityGrant, + }, + RevokeAuthority { + holder: SubjectId, + grant: AuthorityGrant, + }, + OpenOffice { + institution: SubjectId, + office: OfficeName, + delegated: BTreeSet, + }, + CloseOffice { + institution: SubjectId, + office: OfficeName, + }, + InstallIncumbent { + institution: SubjectId, + office: OfficeName, + incumbent: SubjectId, + }, + VacateOffice { + institution: SubjectId, + office: OfficeName, + }, + OpenForum { + grievance: GrievanceKindName, + forum: SubjectId, + standing: AuthorityTarget, + }, + CloseForum { + grievance: GrievanceKindName, + }, + AcquireKnowledge { + subject: SubjectId, + fact: EntityId, + source: AuthoredSource, + confidence: Confidence, + }, + /// Stores the audience, never the recipients. `apply_operation` re-derives + /// the fan-out from live `positions`/`channels`, exactly as `Relocate` + /// stores `edge_id` and re-derives the destination, so a forged effect + /// cannot assert a landing the world does not have. + Communicate { + speaker: SubjectId, + fact: EntityId, + to: Audience, + }, + /// A visible act: the actor's own sentence, seen by everyone standing in + /// the actor's place. Lowered only by the kernel's speech path beside + /// `AssertClaim`, never by a patch, so no author can move a + /// person's body from outside the person. There is no audience field: a + /// display cannot go down a channel, and the room is re-derived from live + /// `positions` at apply, so a forged effect cannot assert a landing the + /// world does not have. + Display { + actor: SubjectId, + fact: EntityId, + }, + /// Stores the place, never the recipients. `apply_operation` re-derives the + /// subtree from live `positions`, so a forged effect cannot assert a + /// landing the world does not have. There is no speaker field, so this + /// operation cannot write `KnowledgeSource::Told` however it is forged. + Witness { + fact: EntityId, + place: EntityId, + confidence: Confidence, + }, + Forget { + subject: SubjectId, + fact: EntityId, + }, + SetReach { + channel: EntityId, + reach: Reach, + }, + SetController { + channel: EntityId, + controller: Option, + }, + /// Kernel-only: no [`ComponentOp`] twin, because no proposer may author one. + /// Synthesized by `action::exercise` for a speech-carrying invocation and by + /// nothing else. Inserts the entity row and the `facts` row; it writes no + /// knowledge, because a speaker's own knowledge of its claim is not implied. + AssertClaim { + fact: EntityId, + statement: Statement, + by: SubjectId, + }, + CreateCommitment { + subject: SubjectId, + key: CommitmentKey, + commitment: Commitment, + }, + DischargeCommitment { + subject: SubjectId, + key: CommitmentKey, + }, + AdvancePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ReducePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSource, + target: SubjectId, + }, + Retire { + subject: SubjectId, + }, + GrantAffordance { + subject: SubjectId, + affordance: AffordanceId, + }, + RevokeAffordance { + subject: SubjectId, + affordance: AffordanceId, + }, +} + +/// One resource's movement across a whole patch. Accumulators are `u128` so an +/// intermediate total cannot overflow while a stored per-holder `Quantity` stays +/// `u64`. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub(super) struct LedgerDelta { + pub(super) before: u128, + pub(super) after: u128, + pub(super) admitted: u128, + pub(super) consumed: u128, + pub(super) gained: u128, + pub(super) spent: u128, +} + +/// The only statement of custody conservation, called by the resolver over the +/// candidate map and again by `admit_resolved` over the committed partitions. +/// Returns the first resource whose ledger does not balance, in key order, so +/// the verdict is deterministic. +/// +/// `Transfer` contributes to no term: its correctness is *proven by* this +/// equation, because a transfer that moved a different amount out than in breaks +/// the total for that resource. `Transform` contributes the same `qty` to one +/// `spent` and one `gained`, so the one-for-one rule is this equation restricted +/// to a single operation. Nothing else states conservation anywhere. +pub(super) fn check_ledger(deltas: &BTreeMap) -> Option { + deltas + .iter() + .find(|(_, delta)| { + let credited = delta + .before + .checked_add(delta.admitted) + .and_then(|total| total.checked_add(delta.gained)); + let expected = credited + .and_then(|total| total.checked_sub(delta.consumed)) + .and_then(|total| total.checked_sub(delta.spent)); + expected != Some(delta.after) + }) + .map(|(resource, _)| resource.clone()) +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedPatch { + pub(super) subjects: Vec, + pub(super) entities: Vec, + pub(super) routes: Vec, + pub(super) affordances: Vec, + pub(super) facts: Vec, + pub(super) channels: Vec, + pub(super) operations: Vec, + pub(super) evidence: Vec, +} + +impl ResolvedPatch { + pub(super) fn declares_nothing(&self) -> bool { + self.subjects.is_empty() + && self.entities.is_empty() + && self.routes.is_empty() + && self.affordances.is_empty() + && self.facts.is_empty() + && self.channels.is_empty() + && self.evidence.is_empty() + } +} + +const SUBJECT_NAMESPACE: &str = "ghostlight.id.subject.v1"; +pub(super) const ENTITY_NAMESPACE: &str = "ghostlight.id.entity.v1"; +const EDGE_NAMESPACE: &str = "ghostlight.id.edge.v1"; +const AFFORDANCE_NAMESPACE: &str = "ghostlight.id.affordance.v1"; + +const PLACE: RefKind = RefKind::Entity(EntityKind::Place); +const FACT: RefKind = RefKind::Entity(EntityKind::Fact); +const CHANNEL: RefKind = RefKind::Entity(EntityKind::Channel); +const ROUTE: RefKind = RefKind::Edge(EdgeKind::Route); +const ANY_SUBJECT: RefKind = RefKind::Subject(None); + +/// A candidate-graph key: a structure this patch declares, or one the world +/// already holds. Candidate topology is checked before any ID is minted, so it +/// is keyed by reference rather than by canonical ID. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Key { + Existing(Id), + Draft(DraftHandle), +} + +fn key_of(reference: &Ref) -> Key { + match reference { + Ref::Existing(id) => Key::Existing(*id), + Ref::Draft(handle) => Key::Draft(handle.clone()), + } +} + +/// [`DependencyTarget`] over candidate keys, so a dependency on a structure this +/// patch declares is checked before any ID is minted. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum TargetKey { + Resource(Key), + Route(Key), + Subject(Key), +} + +/// [`PressureSource`] over candidate keys. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum PressureSourceKey { + Commitment { + subject: Key, + key: CommitmentKey, + }, + Dependency(TargetKey), + Subject(Key), +} + +/// [`AuthorityTarget`] over candidate keys, so a grant over a place this patch +/// declares is checked before any ID is minted. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum AuthorityTargetKey { + Subject(Key), + PlaceSubtree(Key), +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct GrantKey { + kind: AuthorityKindName, + over: AuthorityTargetKey, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct OfficeCandidate { + incumbent: Option>, + delegated: BTreeSet, +} + +/// Whether a candidate `Subject` grant target and a candidate `PlaceSubtree` +/// grant target of one kind name overlapping ground: a `PlaceSubtree` grant +/// covers a `Subject` grant's target when the subject's committed position +/// sits under that subtree. Checked live against `state` rather than the +/// candidate graph, because `covers` reads committed position and +/// containment, not anything a patch declares; a target still in this +/// patch's drafts has no committed position and so cannot overlap here. This +/// is the one cross-shape case `Candidate::targets_overlap` leaves alone by +/// construction — same-shape overlap is its job, not this one's. +fn grant_targets_nest( + state: &super::WorldState, + left: &AuthorityTargetKey, + right: &AuthorityTargetKey, +) -> bool { + let place_and_subject = |a: &AuthorityTargetKey, b: &AuthorityTargetKey| match (a, b) { + ( + AuthorityTargetKey::PlaceSubtree(Key::Existing(place)), + AuthorityTargetKey::Subject(Key::Existing(subject_id)), + ) => Some((*place, *subject_id)), + _ => None, + }; + place_and_subject(left, right) + .or_else(|| place_and_subject(right, left)) + .is_some_and(|(place, subject_id)| { + super::covers( + state, + AuthorityTarget::PlaceSubtree(place), + super::Target::Subject(subject_id), + ) + }) +} + +fn target_key_of(target: AuthorityTarget) -> AuthorityTargetKey { + match target { + AuthorityTarget::Subject(subject_id) => { + AuthorityTargetKey::Subject(Key::Existing(subject_id)) + } + AuthorityTarget::PlaceSubtree(entity_id) => { + AuthorityTargetKey::PlaceSubtree(Key::Existing(entity_id)) + } + } +} + +fn grant_key_of(grant: &AuthorityGrant) -> GrantKey { + GrantKey { + kind: grant.kind.clone(), + over: target_key_of(grant.over), + } +} + +/// The candidate authority of one subject, projected to the canonical referents +/// [`covers`](super::covers) reads. A grant naming structure this patch declares +/// cannot cover a place an already-canonical route reaches, so the projection +/// loses nothing the `Restricted` rule asks about. +fn canonical_grants(grants: &BTreeSet) -> BTreeSet { + grants + .iter() + .filter_map(|grant| { + let over = match &grant.over { + AuthorityTargetKey::Subject(Key::Existing(subject_id)) => { + AuthorityTarget::Subject(*subject_id) + } + AuthorityTargetKey::PlaceSubtree(Key::Existing(entity_id)) => { + AuthorityTarget::PlaceSubtree(*entity_id) + } + _ => return None, + }; + Some(AuthorityGrant { + kind: grant.kind.clone(), + over, + }) + }) + .collect() +} + +/// A fact in the candidate graph. Only its standing matters to resolution: the +/// statement is never read and never compared. +#[derive(Clone, Debug, PartialEq, Eq)] +enum FactCandidate { + Canonical, + Claimed(Key), + Ruled, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum ReachKey { + Subjects(BTreeSet>), + Place(Key), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ChannelCandidate { + reach: ReachKey, + controller: Option>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum KnowledgeSourceKey { + Witnessed, + Told { + by: Key, + via: Option>, + }, + Seen { + by: Key, + }, + Evidenced, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct KnowledgeCandidate { + confidence: Confidence, + source: KnowledgeSourceKey, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum AudienceKey { + Colocated, + Channel(Key), +} + +#[derive(Clone, Debug)] +struct RouteCandidate { + from: Key, + to: Key, + access: AccessKind, + cost: Cost, + open: bool, +} + +/// The only canonical ID allocator, called from exactly two sites: +/// [`resolve_patch`] and `action::exercise`. Deterministic on purpose: journal +/// replay recomputes `reduce` and requires effect equality, so a reduce arm can +/// never draw a `Uuid::new_v4`. Preimage fields are length-prefixed where they +/// are variable-width, so the concatenation is unambiguous — `discriminator` +/// included: a bare presence byte followed by a length prefix means +/// `Some("")` and `None` write different bytes, where an unprefixed +/// `Some("")` would have written nothing, same as `None`. +pub(super) fn derive_id( + namespace: &str, + world_id: WorldId, + command_id: CommandId, + handle: &DraftHandle, + discriminator: Option<&str>, +) -> Uuid { + let mut hasher = Sha256::new(); + hasher.update(namespace.as_bytes()); + hasher.update(world_id.0.as_bytes()); + hasher.update(command_id.0.as_bytes()); + hasher.update((handle.0.len() as u64).to_be_bytes()); + hasher.update(handle.0.as_bytes()); + match discriminator { + Some(discriminator) => { + hasher.update([1u8]); + hasher.update((discriminator.len() as u64).to_be_bytes()); + hasher.update(discriminator.as_bytes()); + } + None => hasher.update([0u8]), + } + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&hasher.finalize()[..16]); + Uuid::from_bytes(bytes) +} + +pub(super) fn is_canonical_text(value: &str) -> bool { + !value.trim().is_empty() && value.trim() == value +} + +pub(super) fn is_valid_cost(cost: Cost) -> bool { + (1..=MAX_ROUTE_COST).contains(&cost.0) +} + +/// The one role name the kernel owns. A catalog entry may not declare it and an +/// invocation may not bind it: stage 2 binds it to the acting subject, so a slot +/// that must land on the actor — the payee of a levy, say — says so instead of +/// letting the proposer point it at a friend. +pub(super) const ACTOR_ROLE: &str = "actor"; + +/// Authority kinds, office names, and grievance kinds share the affordance +/// alphabet: world-declared, kernel-opaque, and safe to surface in a generated +/// tool description. +pub(super) fn is_civic_name(value: &str) -> bool { + is_tool_name(value, 48) +} + +/// `[a-z][a-z0-9_]{0,max-1}`. Affordance kinds and roles become generated tool +/// and parameter names, so the alphabet is the safe one and the bound is stated +/// rather than assumed. +fn is_tool_name(value: &str, max: usize) -> bool { + let mut characters = value.chars(); + characters + .next() + .is_some_and(|first| first.is_ascii_lowercase()) + && value.len() <= max + && value.chars().all(|character| { + character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_' + }) +} + +/// The handle of the kernel-built Speak entry. It is indexed in the same draft +/// index as world-declared entries, so a genesis subject grants it with an +/// ordinary `Ref::Draft` and there is no second grant path. +pub(super) const KERNEL_SPEAK_HANDLE: &str = "ghostlight.affordance.speak"; + +/// The grant every genesis subject carries: a draft reference to the +/// kernel-built entry, resolved by the ordinary handle index. World ingress and +/// every fixture name this rather than repeating the handle literal. +pub(super) fn kernel_speak_grant() -> BTreeSet> { + BTreeSet::from([Ref::Draft(DraftHandle::new(KERNEL_SPEAK_HANDLE))]) +} + +/// Zero roles, zero slots, one empty band, one utterance, and one audience: a +/// voice fills the room it is standing in. Zero roles is load-bearing — the +/// Interpreter lane submits no bindings and a consumer's speak payload carries +/// only +/// text. The precondition is not vacuous: an unplaced subject has no +/// co-location audience and fails with `NoAudience`. +pub(super) fn kernel_speak_entry() -> Affordance { + Affordance { + kind: AffordanceKindName("speak".into()), + roles: Vec::new(), + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + } +} + +/// Whether a stored catalog entry would still be admitted by the declaration +/// validator. One validator, two readers: the resolver rejects a bad entry, and +/// opening an export refuses a chain that already holds one. +pub(super) fn entry_is_admissible(entry: &Affordance) -> bool { + let mut mismatches = Vec::new(); + validate_affordance( + &DraftHandle::new(""), + &entry.kind, + &entry.roles, + &entry.preconditions, + &entry.effect_slots, + &entry.outcome_bands, + entry.carries_speech, + &mut mismatches, + ); + mismatches.is_empty() +} + +/// The catalog-entry resolver, beside `resolve_entity`/`_subject`/`_route`. An +/// entry carries no components, so there is nothing to check past namespace +/// agreement. +fn resolve_affordance( + site: Site, + reference: &Ref, + index: &BTreeMap, + catalog: &Docs, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: RefKind::Affordance, + }); + None + } + Some(kind) if *kind != RefKind::Affordance => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Affordance(reference.clone()), + expected: RefKind::Affordance, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(affordance_id) => { + if catalog.contains_key(affordance_id) { + Some(Key::Existing(*affordance_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: RefKind::Affordance, + }); + None + } + } + } +} + +/// The one validator of a catalog entry, run per declared entry in declaration +/// order inside the resolver's accumulate-then-gate loop. +fn validate_affordance( + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + preconditions: &[Precondition], + effect_slots: &[EffectSlot], + outcome_bands: &[OutcomeBand], + carries_speech: bool, + mismatches: &mut Vec, +) { + let site = || Site::Declaration(handle.clone()); + if !is_tool_name(&kind.0, 48) || roles.iter().any(|spec| !is_tool_name(&spec.role.0, 32)) { + mismatches.push(Mismatch::InvalidAffordanceName { + handle: handle.clone(), + }); + } + let mut declared: BTreeMap = BTreeMap::new(); + for spec in roles { + if spec.role.0 == ACTOR_ROLE { + mismatches.push(Mismatch::ReservedRole { + handle: handle.clone(), + }); + } + match declared.entry(spec.role.clone()) { + Entry::Vacant(slot) => { + slot.insert(spec.kind); + } + Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateRole { + handle: handle.clone(), + role: spec.role.clone(), + }), + } + // No `Target` names the catalog namespace, so a role of that kind could + // never be bound. + if spec.kind == RefKind::Affordance { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: spec.role.clone(), + }); + } + } + // The kernel binds `actor` to the acting subject, so preconditions and + // slots may name it like any role. + declared.insert(Role(ACTOR_ROLE.into()), ANY_SUBJECT); + let require = + |role: &Role, expected: RefKind, mismatches: &mut Vec| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(actual) if *actual != expected => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + Some(_) => {} + }; + let require_subject = |role: &Role, mismatches: &mut Vec| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(RefKind::Subject(_)) => {} + Some(_) => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + }; + let require_audience = |via: &AudienceSpec, mismatches: &mut Vec| match via { + AudienceSpec::Colocated => {} + AudienceSpec::Channel(role) => require(role, CHANNEL, mismatches), + }; + for precondition in preconditions { + match precondition { + Precondition::Present { at } => { + require(at, RefKind::Entity(EntityKind::Place), mismatches); + } + Precondition::Reachable { to, within } => { + require(to, RefKind::Entity(EntityKind::Place), mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site() }); + } + } + Precondition::Holds { resource, .. } => { + require(resource, RefKind::Entity(EntityKind::Resource), mismatches); + } + Precondition::Authorized { over, kind } => { + // Jurisdiction runs over subjects, places, and routes. A + // resource, fact, or channel is covered by nothing, so a role + // of that kind is refused at declaration rather than always + // failing at invocation. + match declared.get(over) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: over.clone(), + }), + Some(RefKind::Subject(_)) | Some(&PLACE) | Some(&ROUTE) => {} + Some(_) => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: over.clone(), + }), + } + if !is_civic_name(&kind.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + } + Precondition::HasStanding { grievance } => { + if !is_civic_name(&grievance.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + } + Precondition::Knows { fact, .. } => require(fact, FACT, mismatches), + Precondition::CanBroadcast { via } => require_audience(via, mismatches), + Precondition::CanReach { subject, via } => { + require_subject(subject, mismatches); + require_audience(via, mismatches); + } + Precondition::Committed { to, .. } => require_subject(to, mismatches), + } + } + // A speech-carrying entry must name exactly one audience: the lowering reads + // it, so none is unlowerable and two is unchoosable. + if carries_speech { + let audiences = preconditions + .iter() + .filter(|precondition| { + matches!( + precondition, + Precondition::CanBroadcast { .. } | Precondition::CanReach { .. } + ) + }) + .count(); + if audiences == 0 { + mismatches.push(Mismatch::SpeechWithoutAudience { + handle: handle.clone(), + }); + } else if audiences > 1 { + mismatches.push(Mismatch::AmbiguousSpeechAudience { + handle: handle.clone(), + }); + } + } + for (index, slot) in effect_slots.iter().enumerate() { + let arity = slot.op_kind.arity(); + if slot + .op_kind + .payload_names() + .iter() + .any(|name| !is_civic_name(name)) + { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + if slot.roles.len() != arity.len() { + mismatches.push(Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: index, + }); + } + for (role, rule) in slot.roles.iter().zip(arity.iter()) { + match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(declared_kind) if !role_kind_fits(rule, *declared_kind) => { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }); + } + Some(_) => {} + } + } + let fits = match (slot.op_kind.dimension(), slot.bounds) { + (BoundsDimension::None, Bounds::None) => true, + (BoundsDimension::Quantity, Bounds::Quantity(ceiling)) => ceiling.0 >= 1, + (BoundsDimension::Cost, Bounds::Cost(ceiling)) => is_valid_cost(ceiling), + _ => false, + }; + if !fits { + mismatches.push(Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: index, + }); + } + } + if outcome_bands.is_empty() { + mismatches.push(Mismatch::NoOutcomeBand { + handle: handle.clone(), + }); + } + for (index, band) in outcome_bands.iter().enumerate() { + if band.weight == 0 { + mismatches.push(Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: index, + }); + } + if band.effects.iter().any(|slot| *slot >= effect_slots.len()) { + mismatches.push(Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: index, + }); + } + if band.effects.windows(2).any(|pair| pair[0] >= pair[1]) { + mismatches.push(Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: index, + }); + } + } + if effect_slots.is_empty() && !carries_speech { + mismatches.push(Mismatch::InertAffordance { + handle: handle.clone(), + }); + } +} + +/// The one entity resolver. `expected` names the kind the referring site +/// requires; a handle or ID that answers with another kind is `WrongKind`. +fn resolve_entity( + site: Site, + expected_kind: EntityKind, + reference: &Ref, + index: &BTreeMap, + entities: &Docs, + mismatches: &mut Vec, +) -> Option> { + let expected = RefKind::Entity(expected_kind); + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected, + }); + None + } + Some(kind) if *kind != expected => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Entity(reference.clone()), + expected, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(entity_id) => match entities.get(entity_id) { + None => { + mismatches.push(Mismatch::UnknownCanonical { site, expected }); + None + } + Some(record) if record.kind != expected_kind => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Entity(reference.clone()), + expected, + actual: RefKind::Entity(record.kind), + }); + None + } + Some(_) => Some(Key::Existing(*entity_id)), + }, + } +} + +fn resolve_subject( + site: Site, + reference: &Ref, + index: &BTreeMap, + subjects: &Docs, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: ANY_SUBJECT, + }); + None + } + Some(RefKind::Subject(_)) => Some(Key::Draft(named.clone())), + Some(kind) => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Subject(reference.clone()), + expected: ANY_SUBJECT, + actual: *kind, + }); + None + } + }, + Ref::Existing(subject_id) => { + if subjects.contains_key(subject_id) { + Some(Key::Existing(*subject_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: ANY_SUBJECT, + }); + None + } + } + } +} + +fn resolve_route( + site: Site, + reference: &Ref, + index: &BTreeMap, + edges: &Docs, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: ROUTE, + }); + None + } + Some(kind) if *kind != ROUTE => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Edge(reference.clone()), + expected: ROUTE, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(edge_id) => { + if edges.contains_key(edge_id) { + Some(Key::Existing(*edge_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: ROUTE, + }); + None + } + } + } +} + +fn resolve_dependency_target( + site: Site, + target: &DependencyRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match target { + DependencyRef::Resource(reference) => resolve_entity( + site, + EntityKind::Resource, + reference, + index, + &state.entities, + mismatches, + ) + .map(TargetKey::Resource), + DependencyRef::Route(reference) => { + resolve_route(site, reference, index, &state.edges, mismatches).map(TargetKey::Route) + } + DependencyRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(TargetKey::Subject) + } + } +} + +/// The candidate kind of a subject reference: the declared kind for a handle +/// this patch introduces, the committed kind otherwise. +fn subject_kind_of( + key: &Key, + index: &BTreeMap, + state: &super::WorldState, +) -> Option { + match key { + Key::Existing(subject_id) => state.subjects.get(subject_id).map(|subject| subject.kind), + Key::Draft(handle) => match index.get(handle) { + Some(RefKind::Subject(kind)) => *kind, + _ => None, + }, + } +} + +/// The institution half of every office operation: one subject reference, one +/// canonical office name, and the kind check that keeps an institution's +/// operational organ and its person-shaped voice two subjects. +fn resolve_office_institution( + position: usize, + institution: &Ref, + office: &OfficeName, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option> { + let named = is_civic_name(&office.0); + if !named { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let key = resolve_subject( + Site::Operation(position), + institution, + index, + &state.subjects, + mismatches, + )?; + if subject_kind_of(&key, index, state) != Some(SubjectKind::Institution) { + mismatches.push(Mismatch::OfficeOnNonInstitution { + operation: position, + }); + return None; + } + named.then_some(key) +} + +/// The one reach resolver: every member of a subject set, or one place. +fn resolve_reach( + site: Site, + reach: &ReachRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match reach { + ReachRef::Subjects(members) => { + let mut resolved = BTreeSet::new(); + let mut complete = true; + for reference in members { + match resolve_subject(site.clone(), reference, index, &state.subjects, mismatches) { + Some(key) => { + resolved.insert(key); + } + None => complete = false, + } + } + complete.then_some(ReachKey::Subjects(resolved)) + } + ReachRef::Place(reference) => resolve_entity( + site, + EntityKind::Place, + reference, + index, + &state.entities, + mismatches, + ) + .map(ReachKey::Place), + } +} + +/// A channel controller is optional, so "declared none" and "named one that did +/// not resolve" are two answers, not one. +fn resolve_controller( + site: Site, + controller: &Option>, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option>> { + match controller { + None => Some(None), + Some(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches).map(Some) + } + } +} + +fn resolve_audience( + site: Site, + audience: &AudienceRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match audience { + AudienceRef::Colocated => Some(AudienceKey::Colocated), + AudienceRef::Channel(reference) => resolve_entity( + site, + EntityKind::Channel, + reference, + index, + &state.entities, + mismatches, + ) + .map(AudienceKey::Channel), + } +} + +fn resolve_authority_target( + site: Site, + target: &AuthorityTargetRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match target { + AuthorityTargetRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(AuthorityTargetKey::Subject) + } + AuthorityTargetRef::PlaceSubtree(reference) => resolve_entity( + site, + EntityKind::Place, + reference, + index, + &state.entities, + mismatches, + ) + .map(AuthorityTargetKey::PlaceSubtree), + } +} + +/// What a holder holds in the candidate map. Absence is zero, at both levels. +fn candidate_held( + holdings: &Overlay<'_, (Key, Key), Quantity>, + holder: &Key, + resource: &Key, +) -> u64 { + holdings + .get(&(holder.clone(), resource.clone())) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the slot, so one representation of nothing survives the patch. +fn candidate_set( + holdings: &mut Overlay<'_, (Key, Key), Quantity>, + holder: &Key, + resource: &Key, + value: u64, +) { + let slot = (holder.clone(), resource.clone()); + if value == 0 { + holdings.remove(&slot); + } else { + holdings.insert(slot, Quantity(value)); + } +} + +/// A bound grammar is the whole catalog: a kind it lacks, or a role signature +/// it does not carry, is refused. A world with no grammar is not checked. +fn check_against_grammar( + state: &super::WorldState, + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + mismatches: &mut Vec, +) { + let Some(grammar) = &state.header.grammar else { + return; + }; + let handle = handle.clone(); + mismatches.extend(grammar.refusal(kind, roles).map(|refusal| match refusal { + GrammarRefusal::KindNotInGrammar => Mismatch::AffordanceKindNotInGrammar { handle }, + GrammarRefusal::RolesDisagree => Mismatch::AffordanceRolesDisagreeWithGrammar { handle }, + GrammarRefusal::SpeakNotConversation => { + Mismatch::SpeakRenderPathDisagreesWithGrammar { handle } + } + })); +} + +/// The one resolution owner for every admission lane: declarations, references, +/// topology admission, and operation preconditions. Every check runs against the +/// complete candidate graph — what the world already holds plus what this patch +/// declares — and the whole mismatch set closes before the first ID is minted. +pub(super) fn resolve_patch( + state: &super::WorldState, + command_id: CommandId, + patch: &WorldPatch, +) -> Result> { + let world_id = state.header.world_id; + let genesis = super::is_genesis(state.revision, &state.subjects); + let mut mismatches = Vec::new(); + let mut index: BTreeMap = BTreeMap::new(); + + // The kernel-built Speak entry enters the same index as a world-declared + // one, before the declaration loop, so a world reusing its handle collides + // as a duplicate handle rather than through a reserved-name check. + let speak_handle = DraftHandle::new(KERNEL_SPEAK_HANDLE); + if genesis { + index.insert(speak_handle.clone(), RefKind::Affordance); + } + if genesis { + // The kernel-built entry is held to the grammar like any declaration. + let speak = kernel_speak_entry(); + check_against_grammar(state, &speak_handle, &speak.kind, &speak.roles, &mut mismatches); + } + let mut graph = Candidate::new(state); + if genesis { + graph.declare_kind(kernel_speak_entry().kind); + } + + let mut declared_keys: BTreeSet<&ImportKey> = BTreeSet::new(); + for (position, declaration) in patch.declarations.iter().enumerate() { + let (handle, label, kind) = match declaration { + Declaration::Subject(subject) => ( + &subject.handle, + Some(&subject.label), + RefKind::Subject(Some(subject.kind)), + ), + Declaration::Entity(entity) => ( + &entity.handle, + Some(&entity.label), + RefKind::Entity(entity.kind), + ), + Declaration::Route(route) => (&route.handle, Some(&route.label), ROUTE), + // A catalog entry's name is its `kind`, checked by the entry + // validator against the tool-name alphabet rather than against the + // label rule. + Declaration::Affordance(affordance) => (&affordance.handle, None, RefKind::Affordance), + Declaration::Fact(fact) => (&fact.handle, Some(&fact.label), FACT), + Declaration::Channel(channel) => (&channel.handle, Some(&channel.label), CHANNEL), + }; + let named = is_canonical_text(&handle.0); + if !named { + mismatches.push(Mismatch::EmptyHandle { position }); + } + if label.is_some_and(|label| !is_canonical_text(label)) { + mismatches.push(Mismatch::EmptyLabel { + handle: handle.clone(), + }); + } + if named { + match index.entry(handle.clone()) { + Entry::Vacant(slot) => { + slot.insert(kind); + } + Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateHandle { + handle: handle.clone(), + }), + } + } + if let Declaration::Subject(subject) = declaration + && let Some(key) = &subject.import_key + { + let handle = subject.handle.clone(); + match import_key_fault(key, |key| graph.import_key_held(key), &mut declared_keys) { + Some(ImportKeyFault::Malformed) => { + mismatches.push(Mismatch::MalformedImportKey { handle }); + } + Some(ImportKeyFault::Held) => mismatches.push(Mismatch::ImportKeyHeld { handle }), + Some(ImportKeyFault::Duplicate) => { + mismatches.push(Mismatch::DuplicateImportKey { handle }); + } + None => {} + } + } + if let Declaration::Affordance(affordance) = declaration { + validate_affordance( + &affordance.handle, + &affordance.kind, + &affordance.roles, + &affordance.preconditions, + &affordance.effect_slots, + &affordance.outcome_bands, + affordance.carries_speech, + &mut mismatches, + ); + check_against_grammar( + state, + &affordance.handle, + &affordance.kind, + &affordance.roles, + &mut mismatches, + ); + if graph.declare_kind(affordance.kind.clone()) { + mismatches.push(Mismatch::DuplicateAffordanceKind { + handle: affordance.handle.clone(), + }); + } + } + if let Declaration::Entity(entity) = declaration + && matches!(entity.kind, EntityKind::Fact | EntityKind::Channel) + { + mismatches.push(Mismatch::PayloadEntityKind { + handle: handle.clone(), + }); + } + if let Declaration::Fact(fact) = declaration { + if !is_canonical_text(fact.statement.as_str()) { + mismatches.push(Mismatch::EmptyStatement { + handle: handle.clone(), + }); + } + // The same predicate `Admit` uses, moved into the declaration loop so + // one rule serves evidenced quantity and evidenced canon alike. + if let FactStandingRef::Canonical { evidence } = &fact.standing + && !(is_canonical_text(&evidence.0) && patch.evidence.contains(evidence)) + { + mismatches.push(Mismatch::FactWithoutEvidence { + handle: handle.clone(), + }); + } + } + } + + for (position, evidence) in patch.evidence.iter().enumerate() { + if !is_canonical_text(&evidence.0) { + mismatches.push(Mismatch::EmptyEvidence { position }); + } + } + + let mut deltas: BTreeMap, LedgerDelta> = BTreeMap::new(); + let mut declared_places: Vec<(DraftHandle, Key)> = Vec::new(); + + for declaration in &patch.declarations { + match declaration { + Declaration::Entity(entity) => { + if entity.kind == EntityKind::Place { + declared_places + .push((entity.handle.clone(), Key::Draft(entity.handle.clone()))); + } + if let Some(reference) = &entity.container { + if entity.kind != EntityKind::Place { + mismatches.push(Mismatch::WrongKind { + site: Site::Declaration(entity.handle.clone()), + referent: RefName::Entity(reference.clone()), + expected: PLACE, + actual: RefKind::Entity(entity.kind), + }); + } else if let Some(parent) = resolve_entity( + Site::Declaration(entity.handle.clone()), + EntityKind::Place, + reference, + &index, + &state.entities, + &mut mismatches, + ) { + graph.containers.insert(Key::Draft(entity.handle.clone()), parent); + } + } + } + Declaration::Affordance(_) => {} + Declaration::Fact(fact) => { + let standing = match &fact.standing { + FactStandingRef::Canonical { .. } => Some(FactCandidate::Canonical), + FactStandingRef::Claimed { by } => resolve_subject( + Site::Declaration(fact.handle.clone()), + by, + &index, + &state.subjects, + &mut mismatches, + ) + .map(FactCandidate::Claimed), + FactStandingRef::Ruled => Some(FactCandidate::Ruled), + }; + if let Some(standing) = standing { + graph.facts.insert(Key::Draft(fact.handle.clone()), standing); + } + } + Declaration::Channel(channel) => { + let reach = resolve_reach( + Site::Declaration(channel.handle.clone()), + &channel.reach, + &index, + state, + &mut mismatches, + ); + let controller = resolve_controller( + Site::Declaration(channel.handle.clone()), + &channel.controller, + &index, + state, + &mut mismatches, + ); + if let (Some(reach), Some(controller)) = (reach, controller) { + graph.channels.insert( + Key::Draft(channel.handle.clone()), + ChannelCandidate { reach, controller }, + ); + } + } + Declaration::Subject(subject) => { + let mut granted = BTreeSet::new(); + for reference in &subject.affordances { + if let Some(affordance_key) = resolve_affordance( + Site::Declaration(subject.handle.clone()), + reference, + &index, + &state.affordance_catalog, + &mut mismatches, + ) { + granted.insert(affordance_key); + } + } + if !granted.is_empty() { + graph.affordance_holdings.insert(Key::Draft(subject.handle.clone()), granted); + } + if let Some(reference) = &subject.position + && let Some(place) = resolve_entity( + Site::Declaration(subject.handle.clone()), + EntityKind::Place, + reference, + &index, + &state.entities, + &mut mismatches, + ) + { + graph.positions.insert(Key::Draft(subject.handle.clone()), place); + } + } + Declaration::Route(route) => { + let from = resolve_entity( + Site::Declaration(route.handle.clone()), + EntityKind::Place, + &route.from, + &index, + &state.entities, + &mut mismatches, + ); + let to = resolve_entity( + Site::Declaration(route.handle.clone()), + EntityKind::Place, + &route.to, + &index, + &state.entities, + &mut mismatches, + ); + if !is_valid_cost(route.cost) { + mismatches.push(Mismatch::InvalidCost { + site: Site::Declaration(route.handle.clone()), + }); + } + if let (Some(from), Some(to)) = (from, to) { + if from == to { + mismatches.push(Mismatch::RouteSelfLoop { + referent: route.handle.clone(), + }); + } + graph.routes.insert( + Key::Draft(route.handle.clone()), + RouteCandidate { + from, + to, + access: route.access.clone(), + cost: route.cost, + open: true, + }, + ); + } + } + } + } + + // Containment acyclicity. Containment is immutable after admission and + // admission already refused cycles, so every cycle contains a declared + // place; walking from each declared place names them all. + for (handle, start) in &declared_places { + if graph.contains_itself(start) { + mismatches.push(Mismatch::ContainmentCycle { + referent: handle.clone(), + }); + } + } + + for (position, operation) in patch.operations.iter().enumerate() { + let site = Site::Operation(position); + match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + statement, + } => { + if !is_canonical_text(statement.as_str()) { + mismatches.push(Mismatch::NoncanonicalText { + operation: position, + }); + } + let subject_key = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let counterparty_key = counterparty.as_ref().map(|reference| { + resolve_subject( + site.clone(), + reference, + &index, + &state.subjects, + &mut mismatches, + ) + }); + let mut checks_resolve = true; + for check in checks { + checks_resolve &= + resolve_check(site.clone(), check, &index, state, &mut mismatches); + } + if (*kind == CommitmentKind::Routine) != period.is_some() { + mismatches.push(Mismatch::CommitmentPeriodMismatch { + operation: position, + }); + } + if let Some(period) = period + && !is_valid_cost(Cost(period.minutes())) + { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + } + if *kind != CommitmentKind::Routine && !checks.is_empty() { + mismatches.push(Mismatch::ChecksOnNonRoutine { + operation: position, + }); + } + // A promise cannot be born past due: it would press on its + // subject on the very next tick with no chance to act. + if *due <= state.header.now { + mismatches.push(Mismatch::CommitmentDueInThePast { + operation: position, + }); + } + if counterparty.is_some() && *kind == CommitmentKind::Goal { + mismatches.push(Mismatch::GoalWithCounterparty { + operation: position, + }); + } + let Some(subject_key) = subject_key else { + continue; + }; + // A retired subject cannot act, and making a promise is + // acting: refused here the same way `RetiredSubjectActed` + // refuses a retired office incumbent below. + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + if let Some(counterparty_key) = &counterparty_key { + match counterparty_key { + None => continue, + Some(counterparty_key) if *counterparty_key == subject_key => { + mismatches.push(Mismatch::SelfCommitment { + operation: position, + }); + continue; + } + Some(_) => {} + } + } + if !checks_resolve { + continue; + } + graph.commitments.insert( + ( + subject_key, + CommitmentKey { + command: command_id, + index: position as u32, + }, + ), + (), + ); + } + ComponentOp::DischargeCommitment { subject, key } => { + let Some(subject_key) = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ) else { + continue; + }; + if graph.commitments.remove(&(subject_key, *key)).is_none() { + mismatches.push(Mismatch::UnknownCommitment { + operation: position, + }); + } + } + ComponentOp::AdvancePressure { source, target, by } + | ComponentOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ComponentOp::AdvancePressure { .. }); + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + let slot = (target_key, source_key); + let current = graph.pressures.get(&slot).unwrap_or_default(); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + // A zero step and a subtraction that hits a floor both change + // nothing, which is one name and not three. + if next == current { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if next == 0 { + graph.pressures.remove(&slot); + } else { + graph.pressures.insert(slot, next); + } + } + ComponentOp::ResolvePressure { source, target } => { + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + if graph.pressures.remove(&(target_key, source_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::Relocate { subject, via } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let route_key = resolve_route( + Site::Operation(position), + via, + &index, + &state.edges, + &mut mismatches, + ); + let (Some(subject_key), Some(route_key)) = (subject_key, route_key) else { + continue; + }; + let Some(route) = graph.routes.get(&route_key) else { + continue; + }; + let mut admitted = true; + match graph.positions.get(&subject_key) { + None => { + mismatches.push(Mismatch::UnplacedSubject { + operation: position, + }); + admitted = false; + } + Some(place) if place != route.from => { + mismatches.push(Mismatch::SubjectNotAtOrigin { + operation: position, + }); + admitted = false; + } + Some(_) => {} + } + if !route.open { + mismatches.push(Mismatch::RouteClosed { + operation: position, + }); + admitted = false; + } + // The resolver reads authority for the subject being moved, not + // for whoever proposed the patch, which is what keeps it + // actor-blind: the patch lane and the action lane get + // the same answer for the same move. A destination this patch + // declares is canonically unknown, so only a `Public` route + // reaches it. + let opened = match &route.to { + Key::Existing(destination) => route_admits( + state, + &canonical_grants(&graph.effective_authority(&subject_key)), + &route.access, + *destination, + ), + Key::Draft(_) => route.access == AccessKind::Public, + }; + if !opened { + mismatches.push(Mismatch::RouteAccessRestricted { + operation: position, + }); + admitted = false; + } + if admitted { + graph.positions.insert(subject_key, route.to); + } + } + ComponentOp::Retire { subject } => { + let Some(subject_key) = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ) else { + continue; + }; + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + graph.retire(subject_key.clone()); + graph.positions.remove(&subject_key); + graph.affordance_holdings.remove(&subject_key); + } + ComponentOp::OpenRoute { route } | ComponentOp::CloseRoute { route } => { + let open = matches!(operation, ComponentOp::OpenRoute { .. }); + let Some(route_key) = resolve_route( + Site::Operation(position), + route, + &index, + &state.edges, + &mut mismatches, + ) else { + continue; + }; + let Some(candidate) = graph.routes.get_mut(&route_key) else { + continue; + }; + if candidate.open == open { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.open = open; + } + } + ComponentOp::AlterCost { route, cost } => { + let route_key = resolve_route( + Site::Operation(position), + route, + &index, + &state.edges, + &mut mismatches, + ); + if !is_valid_cost(*cost) { + mismatches.push(Mismatch::InvalidCost { + site: Site::Operation(position), + }); + continue; + } + let Some(route_key) = route_key else { continue }; + let Some(candidate) = graph.routes.get_mut(&route_key) else { + continue; + }; + if candidate.cost == *cost { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.cost = *cost; + } + } + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => { + let from_key = resolve_subject( + Site::Operation(position), + from, + &index, + &state.subjects, + &mut mismatches, + ); + let to_key = resolve_subject( + Site::Operation(position), + to, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(from_key), Some(to_key), Some(resource_key)) = + (from_key, to_key, resource_key) + else { + continue; + }; + if from_key == to_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let held = candidate_held(&graph.holdings, &from_key, &resource_key); + let Some(remaining) = held.checked_sub(qty.0) else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(credited) = + candidate_held(&graph.holdings, &to_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &from_key, &resource_key, remaining); + candidate_set(&mut graph.holdings, &to_key, &resource_key, credited); + // A transfer contributes to no ledger term: the equation proves + // it, because moving a different amount out than in breaks the + // resource's total. + deltas.entry(resource_key).or_default(); + } + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let from_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + from_resource, + &index, + &state.entities, + &mut mismatches, + ); + let into_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + into_resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(from_key), Some(into_key)) = + (holder_key, from_key, into_key) + else { + continue; + }; + if from_key == into_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&graph.holdings, &holder_key, &from_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(gained) = + candidate_held(&graph.holdings, &holder_key, &into_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &holder_key, &from_key, remaining); + candidate_set(&mut graph.holdings, &holder_key, &into_key, gained); + deltas.entry(from_key).or_default().spent += u128::from(qty.0); + deltas.entry(into_key).or_default().gained += u128::from(qty.0); + } + ComponentOp::Consume { + holder, + resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&graph.holdings, &holder_key, &resource_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &holder_key, &resource_key, remaining); + deltas.entry(resource_key).or_default().consumed += u128::from(qty.0); + } + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let evidenced = is_canonical_text(&evidence.0) && patch.evidence.contains(evidence); + if !evidenced { + mismatches.push(Mismatch::AdmitWithoutEvidence { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 || !evidenced { + continue; + } + let Some(admitted) = + candidate_held(&graph.holdings, &holder_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &holder_key, &resource_key, admitted); + deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); + } + ComponentOp::Mint { + holder, + resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 { + continue; + } + let Some(minted) = + candidate_held(&graph.holdings, &holder_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut graph.holdings, &holder_key, &resource_key, minted); + deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); + } + ComponentOp::Bind { subject, target } | ComponentOp::Release { subject, target } => { + let bind = matches!(operation, ComponentOp::Bind { .. }); + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let target_key = resolve_dependency_target( + Site::Operation(position), + target, + &index, + state, + &mut mismatches, + ); + let (Some(subject_key), Some(target_key)) = (subject_key, target_key) else { + continue; + }; + if target_key == TargetKey::Subject(subject_key.clone()) { + mismatches.push(Mismatch::SelfDependency { + operation: position, + }); + continue; + } + let slot = (subject_key, target_key); + if graph.dependencies.contains_key(&slot) == bind { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if bind { + graph.dependencies.insert(slot, ()); + } else { + graph.dependencies.remove(&slot); + } + } + ComponentOp::GrantAuthority { holder, grant } + | ComponentOp::RevokeAuthority { holder, grant } => { + let granting = matches!(operation, ComponentOp::GrantAuthority { .. }); + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + if !is_civic_name(&grant.kind.0) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let over = resolve_authority_target( + Site::Operation(position), + &grant.over, + &index, + state, + &mut mismatches, + ); + let (Some(holder_key), Some(over)) = (holder_key, over) else { + continue; + }; + let entry = GrantKey { + kind: grant.kind.clone(), + over, + }; + // Admission-time only: a `Subject` grant landing inside a + // `PlaceSubtree` grant the holder already has, or the reverse, + // is a second source for the same kind of act. This does not + // reach `targets_overlap`/`verify_state_shape`, which stay + // structural and position-independent; a later `Relocate` + // that creates this shape is not re-derived as a violation. + let mut grants = graph.grants_of(&holder_key); + if granting + && grants.iter().any(|other| { + other.kind == entry.kind + && grant_targets_nest(state, &entry.over, &other.over) + }) + { + mismatches.push(Mismatch::OverlappingJurisdiction { + operation: position, + }); + continue; + } + if grants.contains(&entry) == granting { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + if granting { + grants.insert(entry); + } else { + grants.remove(&entry); + } + graph.set_grants(holder_key, grants); + } + } + ComponentOp::GrantAffordance { subject, affordance } + | ComponentOp::RevokeAffordance { subject, affordance } => { + let granting = matches!(operation, ComponentOp::GrantAffordance { .. }); + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let affordance_key = resolve_affordance( + Site::Operation(position), + affordance, + &index, + &state.affordance_catalog, + &mut mismatches, + ); + let (Some(subject_key), Some(affordance_key)) = (subject_key, affordance_key) + else { + continue; + }; + // A retired subject holds no grant a patch may touch. + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::GrantsToRetired { + operation: position, + }); + continue; + } + let mut granted = graph.affordance_holdings.get(&subject_key).unwrap_or_default(); + if granted.contains(&affordance_key) == granting { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if granting { + granted.insert(affordance_key); + } else { + granted.remove(&affordance_key); + } + if granted.is_empty() { + graph.affordance_holdings.remove(&subject_key); + } else { + graph.affordance_holdings.insert(subject_key, granted); + } + } + ComponentOp::OpenOffice { + institution, + office, + delegated, + } => { + let institution_key = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ); + if delegated.is_empty() { + mismatches.push(Mismatch::EmptyDelegation { + operation: position, + }); + } + if delegated.iter().any(|kind| !is_civic_name(&kind.0)) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let Some(institution_key) = institution_key else { + continue; + }; + if delegated.is_empty() { + continue; + } + let slot = (institution_key, office.clone()); + let current = graph.office(&slot); + if current + .as_ref() + .is_some_and(|current| ¤t.delegated == delegated) + { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.set_office( + slot, + Some(OfficeCandidate { + incumbent: current.and_then(|current| current.incumbent), + delegated: delegated.clone(), + }), + ); + } + } + ComponentOp::CloseOffice { + institution, + office, + } + | ComponentOp::VacateOffice { + institution, + office, + } => { + let closing = matches!(operation, ComponentOp::CloseOffice { .. }); + let Some(institution_key) = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ) else { + continue; + }; + let slot = (institution_key, office.clone()); + let Some(current) = graph.office(&slot) else { + mismatches.push(Mismatch::UnknownOffice { + operation: position, + }); + continue; + }; + if closing { + graph.set_office(slot, None); + } else if current.incumbent.is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.set_office( + slot, + Some(OfficeCandidate { + incumbent: None, + ..current + }), + ); + } + } + ComponentOp::InstallIncumbent { + institution, + office, + incumbent, + } => { + let institution_key = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ); + let incumbent_key = resolve_subject( + Site::Operation(position), + incumbent, + &index, + &state.subjects, + &mut mismatches, + ); + if let Some(incumbent_key) = &incumbent_key + && subject_kind_of(incumbent_key, &index, state) != Some(SubjectKind::Person) + { + mismatches.push(Mismatch::OfficeHolderNotPerson { + operation: position, + }); + continue; + } + let (Some(institution_key), Some(incumbent_key)) = (institution_key, incumbent_key) + else { + continue; + }; + if graph.is_retired(&incumbent_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + let slot = (institution_key.clone(), office.clone()); + let Some(current) = graph.office(&slot) else { + mismatches.push(Mismatch::UnknownOffice { + operation: position, + }); + continue; + }; + if graph.offices_of(&institution_key).iter().any(|(name, other)| { + name != office && other.incumbent.as_ref() == Some(&incumbent_key) + }) { + mismatches.push(Mismatch::DuplicateIncumbency { + operation: position, + }); + continue; + } + if current.incumbent.as_ref() == Some(&incumbent_key) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.set_office( + slot, + Some(OfficeCandidate { + incumbent: Some(incumbent_key), + ..current + }), + ); + } + } + ComponentOp::OpenForum { + grievance, + forum, + standing, + } => { + if !is_civic_name(&grievance.0) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let forum_key = resolve_subject( + Site::Operation(position), + forum, + &index, + &state.subjects, + &mut mismatches, + ); + let standing_key = resolve_authority_target( + Site::Operation(position), + standing, + &index, + state, + &mut mismatches, + ); + let (Some(forum_key), Some(standing_key)) = (forum_key, standing_key) else { + continue; + }; + if graph.redress.get(grievance) == Some((forum_key.clone(), standing_key.clone())) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.redress.insert(grievance.clone(), (forum_key, standing_key)); + } + } + ComponentOp::CloseForum { grievance } => { + if graph.redress.remove(grievance).is_none() { + mismatches.push(Mismatch::UnknownForum { + operation: position, + }); + } + } + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + // Evidenced knowledge is knowledge of canon. A receipt cannot + // vouch for an assertion the kernel never evaluated. + if *source == AuthoredSource::Evidenced + && graph.facts.get(&fact_key) != Some(FactCandidate::Canonical) + { + mismatches.push(Mismatch::EvidencedKnowledgeOfClaim { + operation: position, + }); + continue; + } + let entry = KnowledgeCandidate { + confidence: *confidence, + source: match source { + AuthoredSource::Witnessed => KnowledgeSourceKey::Witnessed, + AuthoredSource::Evidenced => KnowledgeSourceKey::Evidenced, + }, + }; + let slot = (subject_key, fact_key); + if graph.knowledge.get(&slot) == Some(entry.clone()) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + graph.knowledge.insert(slot, entry); + } + } + ComponentOp::Forget { subject, fact } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + if graph.is_retired(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + if graph.knowledge.remove(&(subject_key, fact_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::Communicate { speaker, fact, to } => { + let speaker_key = resolve_subject( + Site::Operation(position), + speaker, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let audience = resolve_audience( + Site::Operation(position), + to, + &index, + state, + &mut mismatches, + ); + let (Some(speaker_key), Some(_), Some(audience)) = + (speaker_key, fact_key, audience) + else { + continue; + }; + if graph.is_retired(&speaker_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + // Ontology admission: communication reaches only subjects inside + // the channel's reach, and a speaker outside it is not speaking. + if !graph.in_audience(&speaker_key, &audience, &speaker_key) { + mismatches.push(Mismatch::SpeakerOutsideAudience { + operation: position, + }); + } + } + ComponentOp::Witness { + fact, + place, + confidence, + } => { + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let place_key = resolve_entity( + Site::Operation(position), + EntityKind::Place, + place, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(fact_key), Some(place_key)) = (fact_key, place_key) else { + continue; + }; + // The apply-time fan-out, modelled: every candidate subject + // standing under the place — canonical positions plus this + // patch's own declarations and its own relocations, which + // earlier arms have already written into `positions` — less + // everyone this map already has holding the fact, which is the + // same "already a knower" test `unheld` applies over committed + // state. + let entry = KnowledgeCandidate { + confidence: *confidence, + source: KnowledgeSourceKey::Witnessed, + }; + let recipients: Vec> = graph + .occupants_under(&place_key) + .into_iter() + .filter(|subject_key| { + !graph.knowledge.contains_key(&(subject_key.clone(), fact_key.clone())) + }) + .collect(); + if recipients.is_empty() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + for subject_key in recipients { + graph.knowledge.insert((subject_key, fact_key.clone()), entry.clone()); + } + } + } + ComponentOp::SetReach { channel, reach } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let reach_key = resolve_reach( + Site::Operation(position), + reach, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(reach_key)) = (channel_key, reach_key) else { + continue; + }; + let Some(candidate) = graph.channels.get_mut(&channel_key) else { + continue; + }; + if candidate.reach == reach_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.reach = reach_key; + } + } + ComponentOp::SetController { + channel, + controller, + } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let controller_key = resolve_controller( + Site::Operation(position), + controller, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(controller_key)) = (channel_key, controller_key) + else { + continue; + }; + let Some(candidate) = graph.channels.get_mut(&channel_key) else { + continue; + }; + if candidate.controller == controller_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.controller = controller_key; + } + } + } + // Disjointness, checked against the complete candidate graph after each + // operation that could widen someone's jurisdiction, so two operations + // in one patch collide with each other and the failure names the one + // that created the collision. Only three operations can: a new grant, a + // widened office, and a new incumbency. + if matches!( + operation, + ComponentOp::GrantAuthority { .. } + | ComponentOp::OpenOffice { .. } + | ComponentOp::InstallIncumbent { .. } + ) && graph.overlapping() + { + mismatches.push(Mismatch::OverlappingJurisdiction { + operation: position, + }); + } + } + + // Conservation, over the complete candidate after every operation has been + // applied in order. Never per operation: a patch whose operations + // individually balance but whose net does not is impossible, and an + // intermediate negative was already caught above as `InsufficientCustody`. + for (resource_key, delta) in &mut deltas { + (delta.before, delta.after) = graph.custody(resource_key); + } + if let Some(resource) = check_ledger(&deltas) { + mismatches.push(Mismatch::CustodyNotConserved { + resource: RefName::Entity(match resource { + Key::Existing(entity_id) => Ref::Existing(entity_id), + Key::Draft(handle) => Ref::Draft(handle), + }), + }); + } + + if patch.declarations.is_empty() && patch.operations.is_empty() { + mismatches.push(Mismatch::NoCanonicalChange); + } + + if genesis + && !patch + .declarations + .iter() + .any(|declaration| matches!(declaration, Declaration::Subject(_))) + { + mismatches.push(Mismatch::NoDecisionSubject); + } + + if !mismatches.is_empty() { + mismatches.sort(); + return Err(mismatches); + } + + // No canonical ID exists above this line. Allocation starts only now. + let mut collisions = Vec::new(); + let mut entities = Vec::new(); + let mut allocated_entities: BTreeMap = BTreeMap::new(); + for declaration in &patch.declarations { + let Declaration::Entity(entity) = declaration else { + continue; + }; + let entity_id = EntityId(derive_id( + ENTITY_NAMESPACE, + world_id, + command_id, + &entity.handle, + None, + )); + if state.entities.contains_key(&entity_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: entity.handle.clone(), + }); + } + allocated_entities.insert(entity.handle.clone(), entity_id); + entities.push(ResolvedEntity { + handle: entity.handle.clone(), + entity_id, + entity: EntityRecord { + label: entity.label.clone(), + kind: entity.kind, + container: None, + }, + }); + } + // Facts and channels allocate through the same entity namespace and the same + // `derive_id`, so no namespace is added and `RefKind::Entity` types every + // reference to one. They stay out of `entities` above so that vector remains + // a zip over the place and resource declarations. + for declaration in &patch.declarations { + let handle = match declaration { + Declaration::Fact(fact) => &fact.handle, + Declaration::Channel(channel) => &channel.handle, + _ => continue, + }; + let entity_id = EntityId(derive_id( + ENTITY_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.entities.contains_key(&entity_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated_entities.insert(handle.clone(), entity_id); + } + let entity_id_of = |key: &Key| -> EntityId { + match key { + Key::Existing(entity_id) => *entity_id, + Key::Draft(handle) => *allocated_entities + .get(handle) + .expect("a draft entity reference resolved above"), + } + }; + for (resolved, declaration) in entities + .iter_mut() + .zip( + patch + .declarations + .iter() + .filter_map(|declaration| match declaration { + Declaration::Entity(entity) => Some(entity), + _ => None, + }), + ) + { + resolved.entity.container = declaration + .container + .as_ref() + .map(|reference| entity_id_of(&key_of(reference))); + } + + let mut allocated_routes: BTreeMap = BTreeMap::new(); + let mut routes = Vec::new(); + for declaration in &patch.declarations { + let Declaration::Route(route) = declaration else { + continue; + }; + let edge_id = EdgeId(derive_id( + EDGE_NAMESPACE, + world_id, + command_id, + &route.handle, + None, + )); + if state.edges.contains_key(&edge_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: route.handle.clone(), + }); + } + allocated_routes.insert(route.handle.clone(), edge_id); + routes.push(ResolvedRoute { + handle: route.handle.clone(), + edge_id, + edge: EdgeRecord::Route { + label: route.label.clone(), + from: entity_id_of(&key_of(&route.from)), + to: entity_id_of(&key_of(&route.to)), + access: route.access.clone(), + cost: route.cost, + open: true, + }, + }); + } + + let mut allocated_affordances: BTreeMap = BTreeMap::new(); + let mut affordances = Vec::new(); + let allocate_affordance = |handle: &DraftHandle, + entry: Affordance, + affordances: &mut Vec, + allocated: &mut BTreeMap, + collisions: &mut Vec| { + let affordance_id = AffordanceId(derive_id( + AFFORDANCE_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.affordance_catalog.contains_key(&affordance_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated.insert(handle.clone(), affordance_id); + affordances.push(ResolvedAffordance { + handle: handle.clone(), + affordance_id, + affordance: entry, + }); + }; + if genesis { + allocate_affordance( + &speak_handle, + kernel_speak_entry(), + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + for declaration in &patch.declarations { + let Declaration::Affordance(input) = declaration else { + continue; + }; + allocate_affordance( + &input.handle, + Affordance { + kind: input.kind.clone(), + roles: input.roles.clone(), + preconditions: input.preconditions.clone(), + effect_slots: input.effect_slots.clone(), + outcome_bands: input.outcome_bands.clone(), + carries_speech: input.carries_speech, + }, + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + let affordance_id_of = |key: &Key| -> AffordanceId { + match key { + Key::Existing(affordance_id) => *affordance_id, + Key::Draft(handle) => *allocated_affordances + .get(handle) + .expect("a draft affordance reference resolved above"), + } + }; + + let mut allocated_subjects: BTreeMap = BTreeMap::new(); + let mut subjects = Vec::new(); + for declaration in &patch.declarations { + let Declaration::Subject(input) = declaration else { + continue; + }; + let subject_id = SubjectId(derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &input.handle, + None, + )); + if state.subjects.contains_key(&subject_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: input.handle.clone(), + }); + } + allocated_subjects.insert(input.handle.clone(), subject_id); + let granted = input + .affordances + .iter() + .map(|reference| affordance_id_of(&key_of(reference))) + .collect(); + subjects.push(ResolvedSubject { + handle: input.handle.clone(), + subject_id, + subject: SubjectState { + label: input.label.clone(), + kind: input.kind, + import_key: input.import_key.clone(), + retired: false, + }, + affordances: granted, + position: input.position.as_ref().map(|reference| Position { + place: entity_id_of(&key_of(reference)), + }), + }); + } + + let subject_id_of = |key: &Key| -> SubjectId { + match key { + Key::Existing(subject_id) => *subject_id, + Key::Draft(handle) => *allocated_subjects + .get(handle) + .expect("a draft subject reference resolved above"), + } + }; + let edge_id_of = |key: &Key| -> EdgeId { + match key { + Key::Existing(edge_id) => *edge_id, + Key::Draft(handle) => *allocated_routes + .get(handle) + .expect("a draft route reference resolved above"), + } + }; + let target_of = |target: &DependencyRef| -> DependencyTarget { + match target { + DependencyRef::Resource(reference) => { + DependencyTarget::Resource(entity_id_of(&key_of(reference))) + } + DependencyRef::Route(reference) => { + DependencyTarget::Route(edge_id_of(&key_of(reference))) + } + DependencyRef::Subject(reference) => { + DependencyTarget::Subject(subject_id_of(&key_of(reference))) + } + } + }; + let authority_target_of = |target: &AuthorityTargetRef| -> AuthorityTarget { + match target { + AuthorityTargetRef::Subject(reference) => { + AuthorityTarget::Subject(subject_id_of(&key_of(reference))) + } + AuthorityTargetRef::PlaceSubtree(reference) => { + AuthorityTarget::PlaceSubtree(entity_id_of(&key_of(reference))) + } + } + }; + let reach_of = |reach: &ReachRef| -> Reach { + match reach { + ReachRef::Subjects(members) => Reach::Subjects( + members + .iter() + .map(|reference| subject_id_of(&key_of(reference))) + .collect(), + ), + ReachRef::Place(reference) => Reach::Place(entity_id_of(&key_of(reference))), + } + }; + let controller_of = |controller: &Option>| -> Option { + controller + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))) + }; + let audience_of = |audience: &AudienceRef| -> Audience { + match audience { + AudienceRef::Colocated => Audience::Colocated, + AudienceRef::Channel(reference) => Audience::Channel(entity_id_of(&key_of(reference))), + } + }; + let mut declared_facts = Vec::new(); + let mut declared_channels = Vec::new(); + for declaration in &patch.declarations { + match declaration { + Declaration::Fact(fact) => declared_facts.push(ResolvedFact { + handle: fact.handle.clone(), + entity_id: entity_id_of(&Key::Draft(fact.handle.clone())), + entity: EntityRecord { + label: fact.label.clone(), + kind: EntityKind::Fact, + container: None, + }, + fact: FactRecord { + statement: fact.statement.clone(), + standing: match &fact.standing { + FactStandingRef::Canonical { evidence } => FactStanding::Canonical { + evidence: evidence.clone(), + }, + FactStandingRef::Claimed { by } => FactStanding::Claimed { + by: subject_id_of(&key_of(by)), + }, + FactStandingRef::Ruled => FactStanding::Ruled, + }, + }, + }), + Declaration::Channel(channel) => declared_channels.push(ResolvedChannel { + handle: channel.handle.clone(), + entity_id: entity_id_of(&Key::Draft(channel.handle.clone())), + entity: EntityRecord { + label: channel.label.clone(), + kind: EntityKind::Channel, + container: None, + }, + channel: ChannelRecord { + reach: reach_of(&channel.reach), + controller: controller_of(&channel.controller), + }, + }), + _ => {} + } + } + let grant_of = |grant: &AuthorityGrantRef| -> AuthorityGrant { + AuthorityGrant { + kind: grant.kind.clone(), + over: authority_target_of(&grant.over), + } + }; + let precondition_of = |check: &PreconditionRef| -> BoundPrecondition { + match check { + PreconditionRef::Present { at } => BoundPrecondition::Present { + at: entity_id_of(&key_of(at)), + }, + PreconditionRef::Reachable { to, within } => BoundPrecondition::Reachable { + to: entity_id_of(&key_of(to)), + within: *within, + }, + PreconditionRef::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: entity_id_of(&key_of(resource)), + at_least: *at_least, + }, + PreconditionRef::Authorized { over, kind } => BoundPrecondition::Authorized { + over: authority_target_of(over).as_referent(), + kind: kind.clone(), + }, + PreconditionRef::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + PreconditionRef::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: entity_id_of(&key_of(fact)), + at_least: *at_least, + }, + PreconditionRef::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: audience_of(via), + }, + PreconditionRef::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: subject_id_of(&key_of(subject)), + via: audience_of(via), + }, + PreconditionRef::Committed { to, kind } => BoundPrecondition::Committed { + to: subject_id_of(&key_of(to)), + kind: *kind, + }, + } + }; + let pressure_source_of = |source: &PressureSourceRef| -> PressureSource { + match source { + PressureSourceRef::Commitment { subject, key } => PressureSource::Commitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + PressureSourceRef::Dependency(target) => PressureSource::Dependency(target_of(target)), + PressureSourceRef::Subject(reference) => { + PressureSource::Subject(subject_id_of(&key_of(reference))) + } + } + }; + let operations = patch + .operations + .iter() + .enumerate() + .map(|(position, operation)| match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + statement, + } => ResolvedOp::CreateCommitment { + subject: subject_id_of(&key_of(subject)), + key: CommitmentKey { + command: command_id, + index: position as u32, + }, + commitment: Commitment { + kind: *kind, + counterparty: counterparty + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))), + due: *due, + period: *period, + checks: checks.iter().map(precondition_of).collect(), + statement: statement.clone(), + }, + }, + ComponentOp::DischargeCommitment { subject, key } => ResolvedOp::DischargeCommitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + ComponentOp::AdvancePressure { source, target, by } => ResolvedOp::AdvancePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ReducePressure { source, target, by } => ResolvedOp::ReducePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ResolvePressure { source, target } => ResolvedOp::ResolvePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + }, + ComponentOp::Retire { subject } => ResolvedOp::Retire { + subject: subject_id_of(&key_of(subject)), + }, + ComponentOp::GrantAffordance { + subject, + affordance, + } => ResolvedOp::GrantAffordance { + subject: subject_id_of(&key_of(subject)), + affordance: affordance_id_of(&key_of(affordance)), + }, + ComponentOp::RevokeAffordance { + subject, + affordance, + } => ResolvedOp::RevokeAffordance { + subject: subject_id_of(&key_of(subject)), + affordance: affordance_id_of(&key_of(affordance)), + }, + ComponentOp::Relocate { subject, via } => ResolvedOp::Relocate { + subject_id: subject_id_of(&key_of(subject)), + edge_id: edge_id_of(&key_of(via)), + }, + ComponentOp::OpenRoute { route } => ResolvedOp::OpenRoute { + edge_id: edge_id_of(&key_of(route)), + }, + ComponentOp::CloseRoute { route } => ResolvedOp::CloseRoute { + edge_id: edge_id_of(&key_of(route)), + }, + ComponentOp::AlterCost { route, cost } => ResolvedOp::AlterCost { + edge_id: edge_id_of(&key_of(route)), + cost: *cost, + }, + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => ResolvedOp::Transfer { + from: subject_id_of(&key_of(from)), + to: subject_id_of(&key_of(to)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => ResolvedOp::Transform { + holder: subject_id_of(&key_of(holder)), + from_resource: entity_id_of(&key_of(from_resource)), + into_resource: entity_id_of(&key_of(into_resource)), + qty: *qty, + }, + ComponentOp::Consume { + holder, + resource, + qty, + } => ResolvedOp::Consume { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => ResolvedOp::Admit { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + evidence: evidence.clone(), + }, + ComponentOp::Mint { + holder, + resource, + qty, + } => ResolvedOp::Mint { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Bind { subject, target } => ResolvedOp::Bind { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, + ComponentOp::Release { subject, target } => ResolvedOp::Release { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, + ComponentOp::GrantAuthority { holder, grant } => ResolvedOp::GrantAuthority { + holder: subject_id_of(&key_of(holder)), + grant: grant_of(grant), + }, + ComponentOp::RevokeAuthority { holder, grant } => ResolvedOp::RevokeAuthority { + holder: subject_id_of(&key_of(holder)), + grant: grant_of(grant), + }, + ComponentOp::OpenOffice { + institution, + office, + delegated, + } => ResolvedOp::OpenOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + delegated: delegated.clone(), + }, + ComponentOp::CloseOffice { + institution, + office, + } => ResolvedOp::CloseOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + }, + ComponentOp::InstallIncumbent { + institution, + office, + incumbent, + } => ResolvedOp::InstallIncumbent { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + incumbent: subject_id_of(&key_of(incumbent)), + }, + ComponentOp::VacateOffice { + institution, + office, + } => ResolvedOp::VacateOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + }, + ComponentOp::OpenForum { + grievance, + forum, + standing, + } => ResolvedOp::OpenForum { + grievance: grievance.clone(), + forum: subject_id_of(&key_of(forum)), + standing: authority_target_of(standing), + }, + ComponentOp::CloseForum { grievance } => ResolvedOp::CloseForum { + grievance: grievance.clone(), + }, + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => ResolvedOp::AcquireKnowledge { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + source: *source, + confidence: *confidence, + }, + ComponentOp::Communicate { speaker, fact, to } => ResolvedOp::Communicate { + speaker: subject_id_of(&key_of(speaker)), + fact: entity_id_of(&key_of(fact)), + to: audience_of(to), + }, + ComponentOp::Witness { + fact, + place, + confidence, + } => ResolvedOp::Witness { + fact: entity_id_of(&key_of(fact)), + place: entity_id_of(&key_of(place)), + confidence: *confidence, + }, + ComponentOp::Forget { subject, fact } => ResolvedOp::Forget { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + }, + ComponentOp::SetReach { channel, reach } => ResolvedOp::SetReach { + channel: entity_id_of(&key_of(channel)), + reach: reach_of(reach), + }, + ComponentOp::SetController { + channel, + controller, + } => ResolvedOp::SetController { + channel: entity_id_of(&key_of(channel)), + controller: controller_of(controller), + }, + }) + .collect(); + + if !collisions.is_empty() { + collisions.sort(); + return Err(collisions); + } + + Ok(ResolvedPatch { + subjects, + entities, + routes, + affordances, + facts: declared_facts, + channels: declared_channels, + operations, + evidence: patch.evidence.clone(), + }) +} + +/// Whether every referent one stored check names resolves. The canonical +/// lowering runs after allocation, so a check that does not resolve here would +/// have nothing to lower to. +fn resolve_check( + site: Site, + check: &PreconditionRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> bool { + let entity = |kind: EntityKind, reference: &Ref, mismatches: &mut Vec| { + resolve_entity( + site.clone(), + kind, + reference, + index, + &state.entities, + mismatches, + ) + .is_some() + }; + let audience = |via: &AudienceRef, mismatches: &mut Vec| { + resolve_audience(site.clone(), via, index, state, mismatches).is_some() + }; + let subject = |reference: &Ref, mismatches: &mut Vec| { + resolve_subject(site.clone(), reference, index, &state.subjects, mismatches).is_some() + }; + match check { + PreconditionRef::Present { at } => entity(EntityKind::Place, at, mismatches), + PreconditionRef::Reachable { to, within } => { + let resolved = entity(EntityKind::Place, to, mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::Holds { resource, .. } => { + entity(EntityKind::Resource, resource, mismatches) + } + PreconditionRef::Authorized { over, kind } => { + let resolved = + resolve_authority_target(site.clone(), over, index, state, mismatches).is_some(); + if !is_civic_name(&kind.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::HasStanding { grievance } => { + if is_civic_name(&grievance.0) { + true + } else { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + false + } + } + PreconditionRef::Knows { fact, .. } => entity(EntityKind::Fact, fact, mismatches), + PreconditionRef::CanBroadcast { via } => audience(via, mismatches), + PreconditionRef::CanReach { + subject: named, + via, + } => subject(named, mismatches) & audience(via, mismatches), + PreconditionRef::Committed { to, .. } => subject(to, mismatches), + } +} + +fn resolve_pressure_source( + site: Site, + source: &PressureSourceRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match source { + PressureSourceRef::Commitment { subject, key } => { + resolve_subject(site, subject, index, &state.subjects, mismatches) + .map(|subject| PressureSourceKey::Commitment { subject, key: *key }) + } + PressureSourceRef::Dependency(target) => { + resolve_dependency_target(site, target, index, state, mismatches) + .map(PressureSourceKey::Dependency) + } + PressureSourceRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(PressureSourceKey::Subject) + } + } +} + +/// Whether `place` is `root` or is contained in it, over canonical state: one +/// upward walk in the shape of [`containment_terminates`], bounded by the graph +/// size. It is total because `admit_resolved` refuses a non-terminating chain, +/// so the bound is belt-and-braces rather than a repair loop. The question it +/// answers is "is this target inside my ground". Enumerating who stands under a +/// place is the other direction and has its own owner: `under_place` walks the +/// subtree by the entities partition's `ChildOf` index. +pub(super) fn covers_place( + entities: &Docs, + root: EntityId, + place: EntityId, +) -> bool { + let mut current = Some(place); + for _ in 0..=entities.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = entities.get(&node).and_then(|record| record.container), + } + } + false +} + +/// The canonical twin of the candidate graph's `Candidate::targets_overlap`: whether two +/// jurisdictions of one kind cover common ground. +pub(super) fn targets_overlap( + entities: &Docs, + left: AuthorityTarget, + right: AuthorityTarget, +) -> bool { + match (left, right) { + (AuthorityTarget::Subject(one), AuthorityTarget::Subject(other)) => one == other, + (AuthorityTarget::PlaceSubtree(one), AuthorityTarget::PlaceSubtree(other)) => { + covers_place(entities, one, other) || covers_place(entities, other, one) + } + _ => false, + } +} + +/// Whether a subject holding `grants` may traverse a route with this access +/// rule toward `destination`. The sole statement of the `Restricted` rule, +/// called by `resolve_patch`'s `Relocate` arm, by `apply_operation`'s, and by +/// `Precondition::Reachable`'s edge admission — one rule, three callers, no +/// drift. Openness is a separate claim with its own name, so it is not folded +/// in here. +pub(super) fn route_admits( + state: &super::WorldState, + grants: &BTreeSet, + access: &AccessKind, + destination: EntityId, +) -> bool { + match access { + AccessKind::Public => true, + AccessKind::Restricted { requires } => grants.iter().any(|grant| { + &grant.kind == requires + && super::covers(state, grant.over, super::Target::Entity(destination)) + }), + } +} + +/// The same containment walk over canonical state, for the admission and replay +/// invariants. `admit_resolved` runs it after inserting a place, so a container +/// chain that never terminates dies before the partition keeps it. +pub(super) fn containment_terminates( + start: EntityId, + entities: &Docs, +) -> bool { + let mut current = entities.get(&start).and_then(|record| record.container); + for _ in 0..=entities.len() { + match current { + None => return true, + Some(node) if node == start => return false, + Some(node) => current = entities.get(&node).and_then(|record| record.container), + } + } + false +} +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{ + ADMIT_KIND, FIXTURE_ENTITIES, LEVY_KIND, admit_topology, authority_kind, + auth_principal, civic_world, command, creation, grant_to, human_principal, office, + over_place, owner, reject_play, speak_entry, submit_play, + }; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommandId, KernelError, WorldKernel, + }; + + fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + container: None, + }) + } + + fn contained(handle: &str, label: &str, container: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new(container))), + }) + } + + fn route(handle: &str, label: &str, from: &str, to: &str, cost: u32) -> Declaration { + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + from: Ref::Draft(DraftHandle::new(from)), + to: Ref::Draft(DraftHandle::new(to)), + access: AccessKind::Public, + cost: Cost(cost), + }) + } + + /// Every fixture institution is declared by a post-genesis `AdmitPatch`, so + /// it grants the committed Speak entry by canonical reference: the kernel + /// synthesizes that entry once, at genesis, and a later patch names it like + /// any other structure a previous commit allocated. + fn institution( + kernel: &WorldKernel, + handle: &str, + label: &str, + position: Option>, + ) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Institution, + affordances: BTreeSet::from([speak_entry(kernel)]), + position, + import_key: None, + }) + } + + fn patch_of(declarations: Vec) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } + } + + fn operations_of(operations: Vec) -> WorldPatch { + WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + } + } + + fn draft(handle: &str) -> DraftHandle { + DraftHandle::new(handle) + } + + fn at(handle: &str) -> Site { + Site::Declaration(DraftHandle::new(handle)) + } + + fn admit(patch: WorldPatch) -> CommandBody { + CommandBody::AdmitPatch { + patch, + } + } + + /// A minimal admissible entry, so a validation test changes exactly one + /// thing and names exactly one rejection. + fn catalog_entry( + handle: &str, + kind: &str, + roles: Vec, + effect_slots: Vec, + outcome_bands: Vec, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles, + preconditions: Vec::new(), + effect_slots, + outcome_bands, + carries_speech: false, + }) + } + + fn role_spec(role: &str, kind: RefKind) -> RoleSpec { + RoleSpec { + role: Role(role.into()), + kind, + } + } + + fn transfer_slot(roles: Vec<&str>, bounds: Bounds) -> EffectSlot { + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: roles.into_iter().map(|role| Role(role.into())).collect(), + bounds, + } + } + + fn transfer_roles() -> Vec { + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Resource)), + ] + } + + fn band(effects: Vec) -> OutcomeBand { + OutcomeBand { weight: 1, effects } + } + + #[test] + fn a_catalog_entry_with_a_dangling_or_noncanonical_band_is_rejected() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let slots = vec![ + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + ]; + let handle = DraftHandle::new("verb"); + + for (bands, expected) in [ + ( + vec![band(vec![2])], + Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![band(vec![1, 0])], + Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![OutcomeBand { + weight: 0, + effects: vec![0], + }], + Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: 0, + }, + ), + ( + Vec::new(), + Mismatch::NoOutcomeBand { + handle: handle.clone(), + }, + ), + ] { + let rejected = reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + slots.clone(), + bands, + )])), + ); + assert_eq!(rejected, vec![expected]); + assert!(kernel.state.affordance_catalog.len() == before.affordances.len()); + } + + // No effect slots and no speech: the entry could never change anything. + let rejected = reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + Vec::new(), + Vec::new(), + vec![band(Vec::new())], + )])), + ); + assert_eq!(rejected, vec![Mismatch::InertAffordance { handle }]); + } + + #[test] + fn a_slot_whose_roles_do_not_match_its_operation_is_rejected() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let handle = DraftHandle::new("verb"); + + // A `Transfer` takes three referents, not two. + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: 0 + }] + ); + + // Its third referent is a resource, not a place. + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Place)), + ], + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: Role("goods".into()) + }] + ); + + // A `Transfer` carries a quantity, so an unbounded slot has no ceiling. + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot(vec!["from", "to", "goods"], Bounds::None)], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: 0 + }] + ); + + // A slot naming a role the entry does not declare. + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "cargo"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::UnknownRole { + handle, + role: Role("cargo".into()) + }] + ); + } + + #[test] + fn a_grant_naming_an_undeclared_affordance_is_rejected_and_the_same_patch_commits() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let entries_before = kernel.state.affordance_catalog.len(); + let subjects_before = kernel.state.subjects.len(); + + let granting = |handle: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([Ref::Draft(DraftHandle::new(handle))]), + position: None, + import_key: None, + }) + }; + + assert_eq!( + reject_play( + &mut kernel, + &before, + admit(patch_of(vec![granting("verb")])) + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("late-arrival")), + referent: DraftHandle::new("verb"), + expected: RefKind::Affordance, + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before); + assert_eq!(kernel.state.subjects.len(), subjects_before); + + // Declaring the entry in the same patch commits both atomically. + let receipt = submit_play( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + ), + granting("verb"), + ])), + ); + assert!(receipt.resulting_revision > 0); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before + 1); + assert_eq!(kernel.state.subjects.len(), subjects_before + 1); + let granted = kernel + .state + .affordance_grants + .values() + .find(|entries| entries.len() == 1) + .expect("the new subject's grant set"); + assert!( + granted + .iter() + .all(|id| kernel.state.affordance_catalog.contains_key(id)) + ); + } + + #[test] + fn two_entries_cannot_share_one_kind_name() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let slot = transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))); + let rejected = reject_play( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "first", + "haul", + transfer_roles(), + vec![slot.clone()], + vec![band(vec![0])], + ), + catalog_entry( + "second", + "haul", + transfer_roles(), + vec![slot], + vec![band(vec![0])], + ), + ])), + ); + assert_eq!( + rejected, + vec![Mismatch::DuplicateAffordanceKind { + handle: DraftHandle::new("second") + }] + ); + + // A kind name outside the tool-name alphabet is refused for the same + // reason: it becomes a generated tool name. + let rejected = reject_play( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "loud", + "Haul It", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + )])), + ); + assert_eq!( + rejected, + vec![Mismatch::InvalidAffordanceName { + handle: DraftHandle::new("loud") + }] + ); + } + + fn draft_world() -> WorldKernel { + WorldKernel::create(creation("Kharad"), + &auth_principal(owner()), + ) + .expect("draft world") + .0 + } + + /// The position reference names a place that no declaration and no partition + /// provides. Nothing commits and nothing is allocated. + #[test] + fn a_subject_declared_at_an_undeclared_place_is_rejected_and_allocates_nothing() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::UnresolvedDraft { + site: at("rhythm-authority"), + referent: draft("kharad-rhythm-road"), + expected: PLACE, + }] + ); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + assert_eq!(kernel.state.subjects.len(), before.subjects.len()); + } + + /// A place, a route into it, and a subject standing there are one atomic + /// commit: every reference resolves to an ID the same patch allocated. + #[test] + fn a_declared_place_and_its_dependents_commit_atomically() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let patch = patch_of(vec![ + entity("cavity-yard", "The Cavity Yard", EntityKind::Place), + entity("kharad-rhythm-road", "The Rhythm Road", EntityKind::Place), + route( + "yard-road", + "The Yard Ramp", + "cavity-yard", + "kharad-rhythm-road", + 12, + ), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(draft("kharad-rhythm-road"))), + ), + ]); + let receipt = submit_play(&mut kernel, &before, admit(patch)); + assert!(receipt.resulting_revision > 0); + + let after = kernel.snapshot().unwrap(); + assert_eq!(after.revision, before.revision + 1); + assert_eq!(kernel.journal.commit_count(), commits_before + 1); + assert_eq!(kernel.state.entities.len(), 3); + let road = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Rhythm Road") + .expect("the road is admitted") + .0; + let yard = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Cavity Yard") + .expect("the yard is admitted") + .0; + let (_, edge) = kernel.state.edges.iter().next().expect("the route lands"); + assert_eq!(edge.endpoints(), (yard, road)); + assert_eq!(edge.cost(), Cost(12)); + assert!(edge.is_open()); + let admitted = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Rhythm Authority") + .expect("the institution is admitted") + .0; + assert_eq!( + kernel.state.positions.get(&admitted), + Some(&Position { place: road }) + ); + } + + /// A handle of the wrong namespace kind is a runtime mismatch. The + /// cross-namespace canonical case is a compile error instead: + /// `Ref::::Existing(subject_id)` does not compile, because + /// `SubjectId`, `EntityId`, and `EdgeId` are distinct newtypes with no + /// conversion between them and no public `Uuid` constructor. + #[test] + fn a_draft_handle_of_the_wrong_kind_is_rejected() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![ + entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-tithe"))), + ), + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::WrongKind { + site: at("rhythm-authority"), + referent: RefName::Entity(Ref::Draft(draft("rhythm-tithe"))), + expected: PLACE, + actual: RefKind::Entity(EntityKind::Resource), + }] + ); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Rejection carries the complete failed-check set, not the first failure, + /// and repairing exactly that set is enough to commit. + #[test] + fn rejection_returns_every_failed_check_and_repairing_exactly_those_commits() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + let broken = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + entity("rhythm-road", " ", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("cavity-yard"))), + ), + ]); + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(broken), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::DuplicateHandle { + handle: DraftHandle::new("rhythm-road"), + }, + Mismatch::EmptyLabel { + handle: DraftHandle::new("rhythm-road"), + }, + Mismatch::UnresolvedDraft { + site: at("rhythm-authority"), + referent: draft("cavity-yard"), + expected: PLACE, + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.journal.commit_count(), 1); + + let repaired = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + entity("cavity-yard", "The Cavity Yard", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("cavity-yard"))), + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + }), + ]); + let receipt = submit_play(&mut kernel, &before, admit(repaired)); + assert!(receipt.resulting_revision > 0); + assert_eq!(kernel.state.entities.len(), 3); + } + + #[test] + fn an_empty_patch_is_no_canonical_change() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(Vec::new())), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![Mismatch::NoCanonicalChange]); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), 1); + } + + /// Three places whose containers form a cycle name themselves, and the + /// unrelated empty label joins the same complete set. + #[test] + fn a_containment_cycle_is_rejected_with_the_complete_set() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![ + contained("yard", "The Cavity Yard", "road"), + contained("road", "The Rhythm Road", "gate"), + contained("gate", "The Rain Gate", "yard"), + entity("orphan", " ", EntityKind::Place), + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::ContainmentCycle { + referent: draft("yard"), + }, + Mismatch::ContainmentCycle { + referent: draft("road"), + }, + Mismatch::ContainmentCycle { + referent: draft("gate"), + }, + Mismatch::EmptyLabel { + handle: draft("orphan"), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + } + + #[test] + fn a_route_endpoint_that_is_not_a_place_is_rejected() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![ + entity("yard", "The Cavity Yard", EntityKind::Place), + entity("tithe", "The Rhythm Tithe", EntityKind::Resource), + route("ramp", "The Yard Ramp", "yard", "tithe", 12), + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::WrongKind { + site: at("ramp"), + referent: RefName::Entity(Ref::Draft(draft("tithe"))), + expected: PLACE, + actual: RefKind::Entity(EntityKind::Resource), + }] + ); + assert!(kernel.state.edges.is_empty()); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// One name for one failed check, whether the cost arrives in a declaration + /// or in an operation. + #[test] + fn an_invalid_route_cost_is_rejected_from_declaration_and_from_alter_cost() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(WorldPatch { + declarations: vec![Declaration::Route(RouteDeclaration { + handle: draft("free-ride"), + label: "The Free Ride".into(), + from: Ref::Existing(topology.yard), + to: Ref::Existing(topology.road), + access: AccessKind::Public, + cost: Cost(0), + })], + operations: vec![ComponentOp::AlterCost { + route: Ref::Existing(topology.ramp), + cost: Cost(MAX_ROUTE_COST + 1), + }], + evidence: Vec::new(), + }), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::InvalidCost { + site: at("free-ride"), + }, + Mismatch::InvalidCost { + site: Site::Operation(0), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Each refusal has exactly one name: a closed route, a restricted one, and + /// a route that does not start where the subject stands. + #[test] + fn relocate_without_an_open_public_route_is_rejected() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + for (edge_id, expected) in [ + (topology.shutter, Mismatch::RouteClosed { operation: 0 }), + ( + topology.toll, + Mismatch::RouteAccessRestricted { operation: 0 }, + ), + (topology.span, Mismatch::SubjectNotAtOrigin { operation: 0 }), + ] { + let error = kernel + .submit( + command( + &active, + CallerId::Play, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(edge_id), + }])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![expected]); + } + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!( + kernel.state.positions.get(&topology.walker), + Some(&Position { + place: topology.yard + }) + ); + } + + /// PA.f48: `Candidate::effective_authority` is the resolver's twin of + /// `delegated_authority`, and must share its predicate for "is this + /// institution live". Retiring the lending institution and granting the + /// same ground directly to its former office-holder, in one patch, must + /// not be read as an overlap with a lend the retirement already killed. + #[test] + fn a_grant_after_retiring_the_lending_institution_is_admitted() { + let mut kernel = draft_world(); + let (_, civic, before) = civic_world(&mut kernel); + + // The office lends levy over the whole hall; grant the reeve levy + // directly over the chamber the hall contains, so a resolver that + // still counted the dead lend would see two distinct, overlapping + // `GrantKey`s (not one collapsed duplicate) and refuse. + let receipt = submit_play( + &mut kernel, + &before, + admit(operations_of(vec![ + ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }, + grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber)), + ])), + ); + assert!( + receipt.resulting_revision > 0, + "a dead institution's lend must not collide with a fresh direct grant over the same ground" + ); + } + + /// PA.f48: a `Relocate` through a restricted route open only through a + /// dead institution's delegated authority is refused by the resolver + /// itself, as an ordinary `RouteAccessRestricted` mismatch — not + /// admitted by the resolver and then blown up as a `KernelError::Invariant` + /// when canonical apply recomputes the same authority, correctly finds it + /// gone, and refuses the already-applied `Retire`'s sibling operation. + #[test] + fn a_relocate_relying_only_on_a_retiring_institutions_authority_is_refused_by_the_resolver() { + let mut kernel = draft_world(); + let (topology, civic, before) = civic_world(&mut kernel); + + // `topology.walker` already exists and already stands at `yard`, so + // this delegation patch is operations-only: no declaration. + let delegated = submit_play( + &mut kernel, + &before, + admit(operations_of(vec![ + grant_to(civic.treasury, ADMIT_KIND, over_place(civic.chamber)), + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("portal"), + delegated: BTreeSet::from([authority_kind(ADMIT_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("portal"), + incumbent: Ref::Existing(topology.walker), + }, + ])), + ); + assert!( + delegated.resulting_revision > 0, + "expected the delegation patch to apply, got {delegated:?}" + ); + let after_delegation = kernel.snapshot().unwrap(); + + let commits_before = kernel.journal.commit_count(); + let mismatches = reject_play( + &mut kernel, + &after_delegation, + admit(operations_of(vec![ + ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }, + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(civic.postern), + }, + ])), + ); + assert_eq!( + mismatches, + vec![Mismatch::RouteAccessRestricted { operation: 1 }], + "the resolver must refuse the dead institution's lend itself, not let apply blow up" + ); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), after_delegation); + } + + #[test] + fn relocate_moves_the_subject_and_nothing_else() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + let entities_before = kernel.state.entities.clone(); + let edges_before = kernel.state.edges.clone(); + + let receipt = submit_play( + &mut kernel, + &active, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }])), + ); + assert!(receipt.resulting_revision > 0); + assert_eq!( + kernel.state.positions.get(&topology.walker), + Some(&Position { + place: topology.road + }) + ); + assert_eq!(kernel.state.entities, entities_before); + assert_eq!(kernel.state.edges, edges_before); + let after = kernel.snapshot().unwrap(); + assert_eq!( + after + .subjects + .iter() + .find(|subject| subject.id == topology.walker) + .expect("the walker is in the snapshot") + .position, + Some(topology.road) + ); + } + + #[test] + fn restart_replay_after_a_relocate_is_exact() { + let (mut kernel, _) = WorldKernel::create(creation("Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = kernel.snapshot().unwrap(); + let envelope = command( + &active, + CallerId::Play, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }])), + ); + kernel + .submit(envelope.clone(), &AuthenticatedCaller::verified_play()) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + assert_eq!( + reopened.state.positions.get(&topology.walker), + Some(&Position { + place: topology.road + }) + ); + assert!(matches!( + reopened.submit(envelope, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + #[test] + fn the_snapshot_exposes_places_routes_and_positions_deterministically() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot, kernel.snapshot().unwrap()); + + assert_eq!(snapshot.places.len(), 4); + let place_ids: Vec<_> = snapshot.places.iter().map(|place| place.id).collect(); + let mut sorted_places = place_ids.clone(); + sorted_places.sort(); + assert_eq!(place_ids, sorted_places); + assert!(place_ids.contains(&topology.gate)); + + assert_eq!(snapshot.routes.len(), 4); + let route_ids: Vec<_> = snapshot.routes.iter().map(|route| route.id).collect(); + let mut sorted_routes = route_ids.clone(); + sorted_routes.sort(); + assert_eq!(route_ids, sorted_routes); + let shutter = snapshot + .routes + .iter() + .find(|route| route.id == topology.shutter) + .expect("the shutter is in the snapshot"); + assert!(!shutter.open); + assert_eq!(shutter.cost, Cost(5)); + assert_eq!(shutter.from, topology.yard); + + for subject in &snapshot.subjects { + assert_eq!( + subject.position, + kernel + .state + .positions + .get(&subject.id) + .map(|position| position.place) + ); + } + } + + #[test] + fn restart_replay_after_a_committed_patch_is_exact() { + let (mut kernel, _) = WorldKernel::create(creation("Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let before = kernel.snapshot().unwrap(); + let envelope = command( + &before, + CallerId::Play, + admit(patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + ), + ])), + ); + kernel + .submit(envelope.clone(), &AuthenticatedCaller::verified_play()) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); + drop(kernel); + + let mut reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + assert!(matches!( + reopened.submit(envelope, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); + } + + /// One allocator, a pure function of `(world_id, command_id, handle)`: the + /// same handle text under two commands gets two IDs, and the same command + /// re-resolved gets the same ones. + #[test] + fn genesis_and_admit_patch_share_one_allocator() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + let genesis_human = before + .subjects + .iter() + .find(|subject| subject.label == "The Human") + .expect("the genesis human subject") + .id; + + let patch = patch_of(vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("human"), + label: "Another Human".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + })]); + submit_play(&mut kernel, &before, admit(patch.clone())); + let admitted = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "Another Human") + .expect("the admitted subject") + .0; + assert_ne!(admitted, genesis_human); + + let command_id = CommandId::issue(); + let first = resolve_patch(&kernel.state, command_id, &patch).unwrap(); + let second = resolve_patch(&kernel.state, command_id, &patch).unwrap(); + assert_eq!(first, second); + } + + /// The durable half of "a rejected patch mints nothing": the export, not + /// just the in-memory head, carries no commit and no byte of any ID the + /// rejected patch would have allocated. + #[test] + fn a_rejected_patch_leaves_no_commit_and_no_id_in_the_export() { + let (mut kernel, _) = WorldKernel::create(creation("Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let before = kernel.snapshot().unwrap(); + let handle = DraftHandle::new("rhythm-authority"); + let envelope = command( + &before, + CallerId::Play, + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ); + let command_id = envelope.id(); + + let error = kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_err(); + assert!(matches!(error, KernelError::PatchRejected(_))); + + // Every ID the patch would have allocated, had resolution closed. + let would_be = [ + derive_id( + SUBJECT_NAMESPACE, + before.world_id, + command_id, + &handle, + None, + ), + derive_id( + AFFORDANCE_NAMESPACE, + before.world_id, + command_id, + &handle, + Some("speak"), + ), + ]; + + let exported = kernel.export().unwrap(); + drop(kernel); + let raw = &exported; + for id in would_be { + assert!( + !raw.windows(16).any(|window| window == id.as_bytes()), + "a rejected patch left {id} in the export" + ); + } + + let reopened = WorldKernel::open(&exported).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), before); + assert_eq!(reopened.journal.commit_count(), 1); + assert_eq!(reopened.state.entities.len(), FIXTURE_ENTITIES); + assert!( + !reopened + .state + .subjects + .contains_key(&SubjectId(would_be[0])) + ); + } + + /// `discriminator` is length-prefixed like `handle`, so `Some("")` and + /// `None` write different bytes into the preimage and cannot collide — + /// and neither can any other pair of discriminators whose bytes would + /// otherwise concatenate to the same string. + #[test] + fn derive_id_does_not_collide_some_empty_discriminator_with_none() { + let (kernel, _) = WorldKernel::create( + creation("DeriveId"), + &auth_principal(owner()), + ) + .unwrap(); + let world_id = kernel.state.header.world_id; + let command_id = CommandId::issue(); + let handle = DraftHandle::new("a-handle"); + assert_ne!( + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, None), + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, Some("")), + ); + // A concatenation-style collision across the handle/discriminator + // boundary: without a length prefix on the discriminator, "ab" + "" + // and "a" + "b" would hash identically. + assert_ne!( + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ab"), + Some(""), + ), + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("a"), + Some("b"), + ), + ); + } + + /// The `PatchAdmitted` arm is not a trusting applier. A forged effect, a + /// replayed one and a non-owner caller each die inside `apply_effect`, + /// without the journal's reduce-equality check running. + #[test] + fn apply_effect_rejects_a_forged_stale_or_unauthorized_patch_effect() { + let kernel = draft_world(); + let patch = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + ), + ]); + let resolved = resolve_patch(&kernel.state, CommandId::issue(), &patch).unwrap(); + let honest = super::super::WorldEffect::PatchAdmitted { + resolved: resolved.clone(), + }; + + // Forged: the position names a place no partition holds, and the effect + // no longer carries the entity that would have created it. + let mut forged = resolved.clone(); + forged.entities.clear(); + forged.subjects[0].position = Some(Position { + place: super::super::EntityId::issue(), + }); + let mut candidate = kernel.state.clone(); + let forged_error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &super::super::WorldEffect::PatchAdmitted { + resolved: forged, + }, + ) + .unwrap_err(); + assert!(matches!(forged_error, KernelError::Invariant(_))); + + // Stale: the honest effect applied twice collides on its own IDs. + let mut candidate = kernel.state.clone(); + super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &honest, + ) + .unwrap(); + let stale_error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &honest, + ) + .unwrap_err(); + assert!(matches!(stale_error, KernelError::Invariant(_))); + + // A non-Play caller never reaches admission. + let mut candidate = kernel.state.clone(); + let unauthorized = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(human_principal()), + &honest, + ) + .unwrap_err(); + assert!(matches!(unauthorized, KernelError::Unauthorized)); + assert_eq!(candidate, kernel.state); + } + + /// Soul falsification: the three pass-2 `Mismatch` variants that no landed + /// test names are each reachable from a real patch. + #[test] + fn soul_self_loop_unplaced_subject_and_no_effect_are_each_reachable() { + let mut kernel = draft_world(); + let before = kernel.snapshot().unwrap(); + + // A route whose two endpoints resolve to one place. + let error = kernel + .submit( + command( + &before, + CallerId::Play, + admit(patch_of(vec![ + entity("hollow", "The Hollow", EntityKind::Place), + route("noose", "The Noose", "hollow", "hollow", 4), + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::RouteSelfLoop { + referent: draft("noose") + }] + ); + + let topology = admit_topology(&mut kernel); + // Every fixture subject stands somewhere now, so the unplaced case is + // declared here rather than borrowed from a genesis accident. + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(&kernel); + submit_play( + &mut kernel, + &before, + admit(patch_of(vec![Declaration::Subject(SubjectDeclaration { + handle: draft("nowhere"), + label: "The Unplaced".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([speak]), + position: None, + import_key: None, + })])), + ); + let active = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + let unplaced = *kernel + .state + .subjects + .iter() + .find(|(subject_id, _)| !kernel.state.positions.contains_key(*subject_id)) + .expect("the unplaced subject this test declared") + .0; + + // Relocating a subject that stands nowhere. + let error = kernel + .submit( + command( + &active, + CallerId::Play, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(unplaced), + via: Ref::Existing(topology.ramp), + }])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![Mismatch::UnplacedSubject { operation: 0 }]); + + // Three operations that each change nothing: the ramp is already open, + // the shutter already closed, and the ramp already costs twelve. + let error = kernel + .submit( + command( + &active, + CallerId::Play, + admit(operations_of(vec![ + ComponentOp::OpenRoute { + route: Ref::Existing(topology.ramp), + }, + ComponentOp::CloseRoute { + route: Ref::Existing(topology.shutter), + }, + ComponentOp::AlterCost { + route: Ref::Existing(topology.ramp), + cost: Cost(12), + }, + ])), + ), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![ + Mismatch::NoOperationEffect { operation: 0 }, + Mismatch::NoOperationEffect { operation: 1 }, + Mismatch::NoOperationEffect { operation: 2 }, + ] + ); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!(kernel.journal.commit_count(), commits_before); + } + + /// Soul falsification: `admit_resolved` re-derives every relocate + /// precondition, so a forged effect naming a route the subject does not + /// stand on, a closed route, or a restricted one dies at apply time. + #[test] + fn soul_a_forged_relocate_effect_is_refused_at_apply_time() { + let mut kernel = draft_world(); + let topology = admit_topology(&mut kernel); + for edge_id in [topology.span, topology.shutter, topology.toll] { + let forged = super::super::WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::Relocate { + subject_id: topology.walker, + edge_id, + }], + evidence: Vec::new(), + }, + }; + let mut candidate = kernel.state.clone(); + let error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Play, + &forged, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + } +} diff --git a/native/aetherlight/src/patch/candidate.rs b/native/aetherlight/src/patch/candidate.rs new file mode 100644 index 000000000..1934f0048 --- /dev/null +++ b/native/aetherlight/src/patch/candidate.rs @@ -0,0 +1,1294 @@ +//! The candidate graph of one resolution: what the world holds plus what the +//! patch writes, without copying the world. +//! +//! Every candidate map is an [`Overlay`]: the committed partition read through a +//! base function, and the patch's own writes in a local map. Nothing here +//! iterates a committed partition; each scale-sensitive read is a named method +//! of [`Candidate`] whose cost is bounded by what the patch wrote plus what the +//! read returns, through the partitions' point reads and `indexed`. A +//! `Candidate` lives for one `resolve_patch` call and is never written back: +//! `admit_resolved` stays the only writer of the ontology partitions. + +use super::{ + AffordanceKindName, AudienceKey, AuthorityTargetKey, ChannelCandidate, CommitmentKey, + DependencyTarget, FactCandidate, GrantKey, GrievanceKindName, ImportKey, Key, + KnowledgeCandidate, KnowledgeSource, KnowledgeSourceKey, OfficeCandidate, OfficeName, + PressureSource, PressureSourceKey, Quantity, Reach, ReachKey, RouteCandidate, TargetKey, + grant_key_of, target_key_of, +}; +use crate::{AffordanceId, EdgeId, EntityId, SubjectId, WorldState}; +use std::collections::{BTreeMap, BTreeSet}; + +/// One committed partition seen through a patch: reads fall through to the +/// partition by point get, writes land in `local`, and a removal is a `None` +/// there. A `Key::Draft` key has no committed value, so its base is `None`. +pub(super) struct Overlay<'s, K: Ord + Clone, V: Clone> { + state: &'s WorldState, + base: fn(&WorldState, &K) -> Option, + local: BTreeMap>, +} + +impl<'s, K: Ord + Clone, V: Clone> Overlay<'s, K, V> { + fn new(state: &'s WorldState, base: fn(&WorldState, &K) -> Option) -> Self { + Self { state, base, local: BTreeMap::new() } + } + + pub(super) fn get(&self, key: &K) -> Option { + match self.local.get(key) { + Some(written) => written.clone(), + None => (self.base)(self.state, key), + } + } + + pub(super) fn contains_key(&self, key: &K) -> bool { + match self.local.get(key) { + Some(written) => written.is_some(), + None => (self.base)(self.state, key).is_some(), + } + } + + pub(super) fn insert(&mut self, key: K, value: V) { + self.local.insert(key, Some(value)); + } + + /// The value the key held, if any. + pub(super) fn remove(&mut self, key: &K) -> Option { + let held = self.get(key); + if held.is_some() { + self.local.insert(key.clone(), None); + } + held + } + + /// Copies the committed value into `local` on first mutable touch; a miss + /// writes nothing. + pub(super) fn get_mut(&mut self, key: &K) -> Option<&mut V> { + if !self.local.contains_key(key) { + let committed = (self.base)(self.state, key)?; + self.local.insert(key.clone(), Some(committed)); + } + self.local.get_mut(key)?.as_mut() + } + + /// The entries the patch has touched, removals as `None`. + pub(super) fn local(&self) -> &BTreeMap> { + &self.local + } +} + +fn existing(key: &Key) -> Option { + match key { + Key::Existing(id) => Some(*id), + Key::Draft(_) => None, + } +} + +fn target_of(key: &TargetKey) -> Option { + Some(match key { + TargetKey::Resource(id) => DependencyTarget::Resource(existing(id)?), + TargetKey::Route(id) => DependencyTarget::Route(existing(id)?), + TargetKey::Subject(id) => DependencyTarget::Subject(existing(id)?), + }) +} + +fn source_of(key: &PressureSourceKey) -> Option { + Some(match key { + PressureSourceKey::Commitment { subject, key } => { + PressureSource::Commitment { subject: existing(subject)?, key: *key } + } + PressureSourceKey::Dependency(target) => PressureSource::Dependency(target_of(target)?), + PressureSourceKey::Subject(subject) => PressureSource::Subject(existing(subject)?), + }) +} + +fn office_candidate(office: &crate::Office) -> OfficeCandidate { + OfficeCandidate { + incumbent: office.incumbent.map(Key::Existing), + delegated: office.delegated.clone(), + } +} + +fn base_container(state: &WorldState, key: &Key) -> Option> { + state.entities.get(&existing(key)?)?.container.map(Key::Existing) +} + +fn base_route(state: &WorldState, key: &Key) -> Option { + let record = state.edges.get(&existing(key)?)?; + let (from, to) = record.endpoints(); + Some(RouteCandidate { + from: Key::Existing(from), + to: Key::Existing(to), + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + }) +} + +fn base_position(state: &WorldState, key: &Key) -> Option> { + state.positions.get(&existing(key)?).map(|position| Key::Existing(position.place)) +} + +fn base_holding(state: &WorldState, key: &(Key, Key)) -> Option { + let (holder, resource) = (existing(&key.0)?, existing(&key.1)?); + state.holdings.get(&holder)?.get(&resource).copied() +} + +fn base_dependency(state: &WorldState, key: &(Key, TargetKey)) -> Option<()> { + let (subject, target) = (existing(&key.0)?, target_of(&key.1)?); + state.dependencies.get(&subject)?.contains(&target).then_some(()) +} + +fn base_grants(state: &WorldState, key: &Key) -> Option> { + state.authority.get(&existing(key)?).map(|grants| grants.iter().map(grant_key_of).collect()) +} + +fn base_office(state: &WorldState, key: &(Key, OfficeName)) -> Option { + state.selection.get(&existing(&key.0)?)?.get(&key.1).map(office_candidate) +} + +fn base_forum( + state: &WorldState, + key: &GrievanceKindName, +) -> Option<(Key, AuthorityTargetKey)> { + state + .redress + .get(key) + .map(|forum| (Key::Existing(forum.forum), target_key_of(forum.standing))) +} + +fn base_fact(state: &WorldState, key: &Key) -> Option { + state.facts.get(&existing(key)?).map(|record| match &record.standing { + crate::FactStanding::Canonical { .. } => FactCandidate::Canonical, + crate::FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), + crate::FactStanding::Ruled => FactCandidate::Ruled, + }) +} + +fn base_retired(state: &WorldState, key: &Key) -> Option<()> { + crate::is_retired(state, existing(key)?).then_some(()) +} + +fn base_affordances( + state: &WorldState, + key: &Key, +) -> Option>> { + state + .affordance_grants + .get(&existing(key)?) + .map(|granted| granted.iter().map(|id| Key::Existing(*id)).collect()) +} + +fn base_channel(state: &WorldState, key: &Key) -> Option { + state.channels.get(&existing(key)?).map(|record| ChannelCandidate { + reach: match &record.reach { + Reach::Subjects(members) => { + ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) + } + Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), + }, + controller: record.controller.map(Key::Existing), + }) +} + +fn base_knowledge( + state: &WorldState, + key: &(Key, Key), +) -> Option { + let (subject, fact) = (existing(&key.0)?, existing(&key.1)?); + state.knowledge.get(&(subject, fact)).map(|entry| KnowledgeCandidate { + confidence: entry.confidence, + source: match entry.source { + KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, + KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, + KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { + by: Key::Existing(by), + via: via.map(Key::Existing), + }, + KnowledgeSource::Seen { by } => KnowledgeSourceKey::Seen { by: Key::Existing(by) }, + }, + }) +} + +fn base_commitment(state: &WorldState, key: &(Key, CommitmentKey)) -> Option<()> { + state.commitments.get(&existing(&key.0)?)?.contains_key(&key.1).then_some(()) +} + +fn base_pressure(state: &WorldState, key: &(Key, PressureSourceKey)) -> Option { + let (target, source) = (existing(&key.0)?, source_of(&key.1)?); + state.pressures.get(&target)?.get(&source).map(|magnitude| magnitude.0) +} + +/// The candidate graph: canonical topology plus everything this patch declares +/// and operates. Containment, endpoints, and preconditions all read it. +/// +/// `authority`, `selection` and `retired` are private: a write to any of them +/// goes through a method that re-judges the holders whose candidate effective +/// authority it can change, so `overlapping` is always the set of holders that +/// hold two grants of one kind over overlapping ground, exactly what a scan of +/// every holder would answer. That equality holds because the committed world is +/// disjoint (every commit checks it, and opening a world verifies it), so only +/// a holder the patch touched can enter the set. +pub(super) struct Candidate<'s> { + state: &'s WorldState, + pub(super) containers: Overlay<'s, Key, Key>, + pub(super) routes: Overlay<'s, Key, RouteCandidate>, + pub(super) positions: Overlay<'s, Key, Key>, + pub(super) holdings: Overlay<'s, (Key, Key), Quantity>, + pub(super) dependencies: Overlay<'s, (Key, TargetKey), ()>, + authority: Overlay<'s, Key, BTreeSet>, + selection: Overlay<'s, (Key, OfficeName), OfficeCandidate>, + pub(super) redress: Overlay<'s, GrievanceKindName, (Key, AuthorityTargetKey)>, + pub(super) facts: Overlay<'s, Key, FactCandidate>, + retired: Overlay<'s, Key, ()>, + pub(super) affordance_holdings: Overlay<'s, Key, BTreeSet>>, + pub(super) channels: Overlay<'s, Key, ChannelCandidate>, + pub(super) knowledge: Overlay<'s, (Key, Key), KnowledgeCandidate>, + pub(super) commitments: Overlay<'s, (Key, CommitmentKey), ()>, + pub(super) pressures: Overlay<'s, (Key, PressureSourceKey), u32>, + /// The affordance kinds this patch declares. + kinds: BTreeSet, + overlapping: BTreeSet>, +} + +impl<'s> Candidate<'s> { + pub(super) fn new(state: &'s WorldState) -> Self { + Self { + state, + containers: Overlay::new(state, base_container), + routes: Overlay::new(state, base_route), + positions: Overlay::new(state, base_position), + holdings: Overlay::new(state, base_holding), + dependencies: Overlay::new(state, base_dependency), + authority: Overlay::new(state, base_grants), + selection: Overlay::new(state, base_office), + redress: Overlay::new(state, base_forum), + facts: Overlay::new(state, base_fact), + retired: Overlay::new(state, base_retired), + affordance_holdings: Overlay::new(state, base_affordances), + channels: Overlay::new(state, base_channel), + knowledge: Overlay::new(state, base_knowledge), + commitments: Overlay::new(state, base_commitment), + pressures: Overlay::new(state, base_pressure), + kinds: BTreeSet::new(), + overlapping: BTreeSet::new(), + } + } + + // ---- Named reads ------------------------------------------------------- + + /// Whether the affordance kind is already named: by the catalog (its + /// `ByKind` index) or by this patch. + pub(super) fn kind_taken(&self, kind: &AffordanceKindName) -> bool { + self.kinds.contains(kind) || self.state.kind_taken(kind) + } + + /// Names a kind for this patch, reporting whether it was already taken. + pub(super) fn declare_kind(&mut self, kind: AffordanceKindName) -> bool { + let taken = self.kind_taken(&kind); + self.kinds.insert(kind); + taken + } + + /// Whether a subject in the world, retired or not, holds this import key + /// (the subjects' `ByImportKey` index). + pub(super) fn import_key_held(&self, key: &ImportKey) -> bool { + self.state.import_key_held(key) + } + + /// Every subject standing at or under a place: the committed subtree's + /// occupants (`under_place`) less every subject this patch gave a position + /// or took one from, plus the subjects whose written position the candidate + /// containment places under it. A written position can only be a draft + /// place's or a relocation's, so the committed subtree cannot hold it. + pub(super) fn occupants_under(&self, place: &Key) -> BTreeSet> { + let mut occupants: BTreeSet> = match place { + Key::Existing(root) => { + crate::under_place(self.state, *root).into_iter().map(Key::Existing).collect() + } + Key::Draft(_) => BTreeSet::new(), + }; + let written = self.positions.local(); + occupants.retain(|subject| !written.contains_key(subject)); + for (subject, standing) in written { + if let Some(standing) = standing + && self.covers(place, standing) + { + occupants.insert(subject.clone()); + } + } + occupants + } + + /// The offices of one institution: the committed row merged with the + /// patch's writes to its offices. + pub(super) fn offices_of( + &self, + institution: &Key, + ) -> BTreeMap { + let mut offices = BTreeMap::new(); + if let Some(id) = existing(institution) + && let Some(committed) = self.state.selection.get(&id) + { + offices.extend( + committed.iter().map(|(name, office)| (name.clone(), office_candidate(office))), + ); + } + let from = (institution.clone(), OfficeName(String::new())); + for ((held_by, name), written) in self.selection.local().range(from..) { + if held_by != institution { + break; + } + match written { + Some(office) => { + offices.insert(name.clone(), office.clone()); + } + None => { + offices.remove(name); + } + } + } + offices + } + + /// Every office a subject holds, by (institution, name): the committed + /// offices it holds (`ByIncumbent`) unless the patch rewrote them, plus the + /// written offices that name it. + pub(super) fn offices_held_by( + &self, + holder: &Key, + ) -> BTreeMap<(Key, OfficeName), OfficeCandidate> { + let mut held = BTreeMap::new(); + let written = self.selection.local(); + if let Some(id) = existing(holder) { + for (_, institution) in self.state.selection.indexed(id..=id) { + for (name, office) in &self.state.selection[&institution] { + let slot = (Key::Existing(institution), name.clone()); + if office.incumbent == Some(id) && !written.contains_key(&slot) { + held.insert(slot, office_candidate(office)); + } + } + } + } + for (slot, office) in written { + if let Some(office) = office + && office.incumbent.as_ref() == Some(holder) + { + held.insert(slot.clone(), office.clone()); + } + } + held + } + + /// What a resource's total was and is: the sum over the holders the patch + /// wrote, before and after. Every other holder is on both sides of the + /// equation and cancels. + pub(super) fn custody(&self, resource: &Key) -> (u128, u128) { + let (mut before, mut after) = (0u128, 0u128); + for ((holder, held), written) in self.holdings.local() { + if held != resource { + continue; + } + let committed = base_holding(self.state, &(holder.clone(), held.clone())); + before += committed.map_or(0, |quantity| u128::from(quantity.0)); + after += written.map_or(0, |quantity| u128::from(quantity.0)); + } + (before, after) + } + + /// Whether `place` is `root`, or reaches it through the candidate container + /// chain. The walk is bounded by the graph size, so a cycle that does not + /// include either end still terminates. + pub(super) fn covers(&self, root: &Key, place: &Key) -> bool { + let bound = self.state.entities.len() + self.containers.local().len(); + let mut current = Some(place.clone()); + for _ in 0..=bound { + match current { + None => return false, + Some(node) if node == *root => return true, + Some(node) => current = self.containers.get(&node), + } + } + false + } + + /// Whether a place reaches itself through its container chain: the same + /// walk, started one link up so a place is not its own ancestor by + /// definition. + pub(super) fn contains_itself(&self, start: &Key) -> bool { + self.containers.get(start).is_some_and(|parent| self.covers(start, &parent)) + } + + /// Whether two jurisdictions of one kind cover common ground. Structural on + /// purpose: identity for named subordinates, containment for territory, and + /// never across the two, so the answer cannot decay when a subject walks + /// somewhere. Containment is fixed at declaration, so every way of creating + /// an overlap is a checked operation. + fn targets_overlap(&self, left: &AuthorityTargetKey, right: &AuthorityTargetKey) -> bool { + match (left, right) { + (AuthorityTargetKey::Subject(one), AuthorityTargetKey::Subject(other)) => one == other, + (AuthorityTargetKey::PlaceSubtree(one), AuthorityTargetKey::PlaceSubtree(other)) => { + self.covers(one, other) || self.covers(other, one) + } + _ => false, + } + } + + // ---- Authority, offices and retirement ---------------------------------- + + pub(super) fn grants_of(&self, holder: &Key) -> BTreeSet { + self.authority.get(holder).unwrap_or_default() + } + + pub(super) fn office(&self, slot: &(Key, OfficeName)) -> Option { + self.selection.get(slot) + } + + pub(super) fn is_retired(&self, subject: &Key) -> bool { + self.retired.contains_key(subject) + } + + /// Own grants plus what every held office lends, over the candidate graph. + /// A retired institution lends nothing, the same predicate + /// `delegated_authority` reads canonically: `Retire` does not vacate + /// offices, so the resolver and the kernel must not disagree about whether + /// a dead institution's grants still reach its office-holders. + pub(super) fn effective_authority(&self, holder: &Key) -> BTreeSet { + let mut effective = self.grants_of(holder); + for ((institution, _), office) in self.offices_held_by(holder) { + if self.is_retired(&institution) { + continue; + } + for grant in self.grants_of(&institution) { + if office.delegated.contains(&grant.kind) { + effective.insert(grant); + } + } + } + effective + } + + /// Whether any holder in the candidate graph holds two grants of one kind + /// over overlapping ground, from any combination of direct grant and office + /// delegation. + pub(super) fn overlapping(&self) -> bool { + !self.overlapping.is_empty() + } + + /// Replaces a subject's own grants; an empty set removes the row. + pub(super) fn set_grants(&mut self, holder: Key, grants: BTreeSet) { + if grants.is_empty() { + self.authority.remove(&holder); + } else { + self.authority.insert(holder.clone(), grants); + } + // An institution's grants reach its office-holders. + let mut affected = self.incumbents_of(&holder); + affected.insert(holder); + self.rejudge(affected); + } + + /// Writes one office, or closes it (`None`). + pub(super) fn set_office( + &mut self, + slot: (Key, OfficeName), + office: Option, + ) { + let mut affected = BTreeSet::new(); + affected.extend(self.selection.get(&slot).and_then(|old| old.incumbent)); + affected.extend(office.iter().filter_map(|new| new.incumbent.clone())); + match office { + Some(office) => self.selection.insert(slot, office), + None => { + self.selection.remove(&slot); + } + } + self.rejudge(affected); + } + + /// Marks a subject retired. A retired institution lends nothing, so its + /// office-holders are judged again. + pub(super) fn retire(&mut self, subject: Key) { + self.retired.insert(subject.clone(), ()); + let affected = self.incumbents_of(&subject); + self.rejudge(affected); + } + + fn incumbents_of(&self, institution: &Key) -> BTreeSet> { + self.offices_of(institution).into_values().filter_map(|office| office.incumbent).collect() + } + + fn rejudge(&mut self, holders: BTreeSet>) { + for holder in holders { + let effective: Vec = self.effective_authority(&holder).into_iter().collect(); + let overlaps = effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind && self.targets_overlap(&one.over, &other.over) + }) + }); + if overlaps { + self.overlapping.insert(holder); + } else { + self.overlapping.remove(&holder); + } + } + } + + /// Whether `subject` stands in the audience, over the candidate graph: the + /// same question `audience()` answers over committed state, asked before + /// any ID is minted. A controller is inside its own channel's audience for + /// the purpose of speaking on it: the horn belongs to the temple. + pub(super) fn in_audience( + &self, + subject: &Key, + audience: &AudienceKey, + speaker: &Key, + ) -> bool { + match audience { + AudienceKey::Colocated => { + match (self.positions.get(speaker), self.positions.get(subject)) { + (Some(here), Some(there)) => here == there, + _ => false, + } + } + AudienceKey::Channel(channel) => { + let Some(record) = self.channels.get(channel) else { + return false; + }; + if record.controller.as_ref() == Some(subject) { + return true; + } + match &record.reach { + ReachKey::Subjects(members) => members.contains(subject), + ReachKey::Place(root) => self + .positions + .get(subject) + .is_some_and(|place| self.covers(root, &place)), + } + } + } + } +} + +/// The reference the overlays are measured against, in test builds only: the +/// candidate graph as it was before overlays, every partition copied into a map +/// and every read a scan of those maps. +#[cfg(test)] +pub(super) struct Materialized { + pub(super) containers: BTreeMap, Key>, + pub(super) routes: BTreeMap, RouteCandidate>, + pub(super) positions: BTreeMap, Key>, + pub(super) holdings: BTreeMap<(Key, Key), Quantity>, + pub(super) dependencies: BTreeSet<(Key, TargetKey)>, + pub(super) authority: BTreeMap, BTreeSet>, + pub(super) selection: BTreeMap<(Key, OfficeName), OfficeCandidate>, + pub(super) redress: BTreeMap, AuthorityTargetKey)>, + pub(super) facts: BTreeMap, FactCandidate>, + pub(super) retired: BTreeSet>, + pub(super) affordance_holdings: BTreeMap, BTreeSet>>, + pub(super) channels: BTreeMap, ChannelCandidate>, + pub(super) knowledge: BTreeMap<(Key, Key), KnowledgeCandidate>, + pub(super) commitments: BTreeSet<(Key, CommitmentKey)>, + pub(super) pressures: BTreeMap<(Key, PressureSourceKey), u32>, +} + +#[cfg(test)] +fn apply_written(map: &mut BTreeMap, local: &BTreeMap>) { + for (key, written) in local { + match written { + Some(value) => { + map.insert(key.clone(), value.clone()); + } + None => { + map.remove(key); + } + } + } +} + +#[cfg(test)] +fn apply_written_set(set: &mut BTreeSet, local: &BTreeMap>) { + for (key, written) in local { + if written.is_some() { + set.insert(key.clone()); + } else { + set.remove(key); + } + } +} + +#[cfg(test)] +impl Materialized { + /// The committed world copied whole: what the resolver seeded its candidate + /// maps with, moved here as the reference. + pub(super) fn seeded(state: &WorldState) -> Self { + let containers: BTreeMap, Key> = state + .entities + .iter() + .filter_map(|(entity_id, record)| { + record + .container + .map(|container| (Key::Existing(*entity_id), Key::Existing(container))) + }) + .collect(); + let routes: BTreeMap, RouteCandidate> = state + .edges + .iter() + .map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + ( + Key::Existing(*edge_id), + RouteCandidate { + from: Key::Existing(from), + to: Key::Existing(to), + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + }, + ) + }) + .collect(); + let positions: BTreeMap, Key> = state + .positions + .iter() + .map(|(subject_id, position)| (Key::Existing(*subject_id), Key::Existing(position.place))) + .collect(); + let holdings: BTreeMap<(Key, Key), Quantity> = state + .holdings + .iter() + .flat_map(|(subject_id, held)| { + held.iter().map(move |(entity_id, quantity)| { + ( + (Key::Existing(*subject_id), Key::Existing(*entity_id)), + *quantity, + ) + }) + }) + .collect(); + let dependencies: BTreeSet<(Key, TargetKey)> = state + .dependencies + .iter() + .flat_map(|(subject_id, bound)| { + bound.iter().map(move |target| { + ( + Key::Existing(*subject_id), + match target { + DependencyTarget::Resource(id) => TargetKey::Resource(Key::Existing(*id)), + DependencyTarget::Route(id) => TargetKey::Route(Key::Existing(*id)), + DependencyTarget::Subject(id) => TargetKey::Subject(Key::Existing(*id)), + }, + ) + }) + }) + .collect(); + let authority: BTreeMap, BTreeSet> = state + .authority + .iter() + .map(|(subject_id, grants)| { + ( + Key::Existing(*subject_id), + grants.iter().map(grant_key_of).collect(), + ) + }) + .collect(); + let selection: BTreeMap<(Key, OfficeName), OfficeCandidate> = state + .selection + .iter() + .flat_map(|(institution, offices)| { + offices.iter().map(move |(name, office)| { + ( + (Key::Existing(*institution), name.clone()), + OfficeCandidate { + incumbent: office.incumbent.map(Key::Existing), + delegated: office.delegated.clone(), + }, + ) + }) + }) + .collect(); + let redress: BTreeMap, AuthorityTargetKey)> = state + .redress + .iter() + .map(|(grievance, forum)| { + ( + grievance.clone(), + (Key::Existing(forum.forum), target_key_of(forum.standing)), + ) + }) + .collect(); + let facts: BTreeMap, FactCandidate> = state + .facts + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + match &record.standing { + crate::FactStanding::Canonical { .. } => FactCandidate::Canonical, + crate::FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), + crate::FactStanding::Ruled => FactCandidate::Ruled, + }, + ) + }) + .collect(); + // `Retire` and the affordance grant operations read and write these + // candidates. `retired` seeds from the committed subject rows: a declared subject is always + // fresh and unretired, so drafts start out of the set. `affordance_holdings` + // seeds from committed `affordance_grants` and is extended below for a + // subject this same patch declares. + let retired: BTreeSet> = state + .subjects + .keys() + .filter(|subject_id| crate::is_retired(state, **subject_id)) + .map(|subject_id| Key::Existing(*subject_id)) + .collect(); + let affordance_holdings: BTreeMap, BTreeSet>> = state + .affordance_grants + .iter() + .map(|(subject_id, granted)| { + ( + Key::Existing(*subject_id), + granted.iter().map(|id| Key::Existing(*id)).collect(), + ) + }) + .collect(); + let channels: BTreeMap, ChannelCandidate> = state + .channels + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + ChannelCandidate { + reach: match &record.reach { + Reach::Subjects(members) => { + ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) + } + Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), + }, + controller: record.controller.map(Key::Existing), + }, + ) + }) + .collect(); + // Keys and payload, so an `AcquireKnowledge` that changes nothing is + // `NoOperationEffect` before any ID is minted. `Witness` is modelled here + // too: its landing is a subtree of `positions`, both maps are candidate + // maps, and so the fan-out it will perform at apply is derivable now — a + // subject this patch relocated into the subtree counts, and a witness that + // reaches nobody is refused at resolve exactly as `apply_operation` + // refuses it. + // + // `Communicate` never enters, and the difference is not scale. A telling is + // an act whose occurrence does not depend on its reception: its empty + // fan-out is legal, so there is nothing for this map to refuse and no + // refusal for it to predict. A witnessed event is only its reception, so + // its landing is its legality. + // + // Neither operation can write `Told`. This map can represent a `Told` + // entry, but no `ComponentOp` can construct one: `AcquireKnowledge` takes + // an `AuthoredSource`, `Witness` takes no source at all, and neither type + // has a `Told` variant — + // `action::no_component_op_kind_lowers_to_a_told_knowledge_write` pins both + // lowering sites that could otherwise drift. If a future operation is ever + // given the power to write `Told` directly — bypassing `Communicate`'s own + // apply-time fan-out — it must model that fan-out into this candidate graph + // first, or `resolve_patch` will silently reason about a knowledge state + // the apply pass will not produce. + let knowledge: BTreeMap<(Key, Key), KnowledgeCandidate> = state + .knowledge + .iter() + .map(|((subject_id, fact), entry)| { + ( + (Key::Existing(*subject_id), Key::Existing(*fact)), + KnowledgeCandidate { + confidence: entry.confidence, + source: match entry.source { + KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, + KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, + KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { + by: Key::Existing(by), + via: via.map(Key::Existing), + }, + KnowledgeSource::Seen { by } => KnowledgeSourceKey::Seen { + by: Key::Existing(by), + }, + }, + }, + ) + }) + .collect(); + // Presence is all a discharge asks, and a create cannot collide: the key is + // command-derived and the index is unique within one patch. + let commitments: BTreeSet<(Key, CommitmentKey)> = state + .commitments + .iter() + .flat_map(|(subject_id, held)| { + held.keys() + .map(move |key| (Key::Existing(*subject_id), *key)) + }) + .collect(); + let pressures: BTreeMap<(Key, PressureSourceKey), u32> = state + .pressures + .iter() + .flat_map(|(target, held)| { + held.iter().map(move |(source, magnitude)| { + ( + ( + Key::Existing(*target), + match source { + PressureSource::Commitment { subject, key } => { + PressureSourceKey::Commitment { + subject: Key::Existing(*subject), + key: *key, + } + } + PressureSource::Dependency(DependencyTarget::Resource(entity_id)) => { + PressureSourceKey::Dependency(TargetKey::Resource(Key::Existing( + *entity_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { + PressureSourceKey::Dependency(TargetKey::Route(Key::Existing( + *edge_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Subject(subject_id)) => { + PressureSourceKey::Dependency(TargetKey::Subject(Key::Existing( + *subject_id, + ))) + } + PressureSource::Subject(subject_id) => { + PressureSourceKey::Subject(Key::Existing(*subject_id)) + } + }, + ), + magnitude.0, + ) + }) + }) + .collect(); + Self { + containers, + routes, + positions, + holdings, + dependencies, + authority, + selection, + redress, + facts, + retired, + affordance_holdings, + channels, + knowledge, + commitments, + pressures, + } + } + + /// Whether `place` is `root`, or reaches it through the container chain. + pub(super) fn covers(&self, root: &Key, place: &Key) -> bool { + let mut current = Some(place); + for _ in 0..=self.containers.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = self.containers.get(node), + } + } + false + } + + fn targets_overlap(&self, left: &AuthorityTargetKey, right: &AuthorityTargetKey) -> bool { + match (left, right) { + (AuthorityTargetKey::Subject(one), AuthorityTargetKey::Subject(other)) => one == other, + (AuthorityTargetKey::PlaceSubtree(one), AuthorityTargetKey::PlaceSubtree(other)) => { + self.covers(one, other) || self.covers(other, one) + } + _ => false, + } + } + + /// Every subject whose position the container chain puts under `place`. + pub(super) fn occupants_under(&self, place: &Key) -> BTreeSet> { + self.positions + .iter() + .filter(|(_, standing)| self.covers(place, standing)) + .map(|(subject, _)| subject.clone()) + .collect() + } + + pub(super) fn offices_of( + &self, + institution: &Key, + ) -> BTreeMap { + self.selection + .iter() + .filter(|((held_by, _), _)| held_by == institution) + .map(|((_, name), office)| (name.clone(), office.clone())) + .collect() + } + + pub(super) fn offices_held_by( + &self, + holder: &Key, + ) -> BTreeMap<(Key, OfficeName), OfficeCandidate> { + self.selection + .iter() + .filter(|(_, office)| office.incumbent.as_ref() == Some(holder)) + .map(|(slot, office)| (slot.clone(), office.clone())) + .collect() + } + + /// Own grants plus what every held office lends, walking every office. + pub(super) fn effective_authority(&self, holder: &Key) -> BTreeSet { + let mut effective = self.authority.get(holder).cloned().unwrap_or_default(); + for ((institution, _), office) in &self.selection { + if office.incumbent.as_ref() != Some(holder) || self.retired.contains(institution) { + continue; + } + for grant in self.authority.get(institution).into_iter().flatten() { + if office.delegated.contains(&grant.kind) { + effective.insert(grant.clone()); + } + } + } + effective + } + + /// Every holder in the graph with two grants of one kind over overlapping + /// ground, from any combination of direct grant and office delegation. + pub(super) fn overlapping_holders(&self) -> BTreeSet> { + let holders: BTreeSet<&Key> = self + .authority + .keys() + .chain(self.selection.values().filter_map(|office| office.incumbent.as_ref())) + .collect(); + holders + .into_iter() + .filter(|holder| { + let effective: Vec = + self.effective_authority(holder).into_iter().collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind && self.targets_overlap(&one.over, &other.over) + }) + }) + }) + .cloned() + .collect() + } + + /// What a resource's holders hold in all. + pub(super) fn total(&self, resource: &Key) -> u128 { + self.holdings + .iter() + .filter(|((_, held), _)| held == resource) + .map(|(_, quantity)| u128::from(quantity.0)) + .sum() + } +} + +#[cfg(test)] +impl Candidate<'_> { + /// Every candidate map, in full: the committed world with the patch's writes + /// applied. The named reads must equal scans of it. + pub(super) fn materialized(&self) -> Materialized { + let mut all = Materialized::seeded(self.state); + apply_written(&mut all.containers, self.containers.local()); + apply_written(&mut all.routes, self.routes.local()); + apply_written(&mut all.positions, self.positions.local()); + apply_written(&mut all.holdings, self.holdings.local()); + apply_written_set(&mut all.dependencies, self.dependencies.local()); + apply_written(&mut all.authority, self.authority.local()); + apply_written(&mut all.selection, self.selection.local()); + apply_written(&mut all.redress, self.redress.local()); + apply_written(&mut all.facts, self.facts.local()); + apply_written_set(&mut all.retired, self.retired.local()); + apply_written(&mut all.affordance_holdings, self.affordance_holdings.local()); + apply_written(&mut all.channels, self.channels.local()); + apply_written(&mut all.knowledge, self.knowledge.local()); + apply_written_set(&mut all.commitments, self.commitments.local()); + apply_written(&mut all.pressures, self.pressures.local()); + all + } + + /// The holders the running judgement holds as overlapping. + pub(super) fn overlapping_holders(&self) -> &BTreeSet> { + &self.overlapping + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::patch::DraftHandle; + use crate::tests::{ + BAILIFF_OFFICE, LEVY_KIND, WARDEN_OFFICE, auth_principal, authority_kind, civic_world, + creation, office, operations, owner, reject_play, + }; + use crate::{Mismatch, WorldKernel}; + + fn civic_kernel(title: &str) -> (WorldKernel, crate::tests::Topology, crate::tests::Civic) { + let (mut kernel, _) = WorldKernel::create(creation(title), &auth_principal(owner())).unwrap(); + let (topology, civic, _) = civic_world(&mut kernel); + (kernel, topology, civic) + } + + fn levy_over(place: Key) -> GrantKey { + GrantKey { kind: authority_kind(LEVY_KIND), over: AuthorityTargetKey::PlaceSubtree(place) } + } + + /// Every named read, asked of the overlay and of a scan of the materialized + /// maps, must agree. + fn agrees( + graph: &Candidate<'_>, + label: &str, + places: &[Key], + holders: &[Key], + resource: &Key, + ) { + let all = graph.materialized(); + for place in places { + assert_eq!(graph.occupants_under(place), all.occupants_under(place), "{label}: under {place:?}"); + } + for holder in holders { + assert_eq!(graph.offices_of(holder), all.offices_of(holder), "{label}: offices of {holder:?}"); + assert_eq!( + graph.offices_held_by(holder), + all.offices_held_by(holder), + "{label}: offices held by {holder:?}" + ); + assert_eq!( + graph.effective_authority(holder), + all.effective_authority(holder), + "{label}: authority of {holder:?}" + ); + } + let overlapping = all.overlapping_holders(); + assert_eq!(graph.overlapping_holders(), &overlapping, "{label}: who overlaps"); + assert_eq!(graph.overlapping(), !overlapping.is_empty(), "{label}: whether anyone overlaps"); + // The written holders' sums stand in for the totals: every other holder + // is on both sides, so the two differ by the same amount. + let (before, after) = graph.custody(resource); + let seeded = Materialized::seeded(graph.state).total(resource); + assert_eq!( + after as i128 - before as i128, + all.total(resource) as i128 - seeded as i128, + "{label}: custody" + ); + for kind in ["speak", "levy", "novel"] { + let kind = AffordanceKindName(kind.into()); + assert_eq!( + graph.kind_taken(&kind), + crate::kind_taken_by_scan(graph.state, &kind) || graph.kinds.contains(&kind), + "{label}: kind {kind:?}" + ); + } + } + + /// The patch walks the places the clockwork rules care about: a subject + /// leaving and entering a subtree, a declared place and a declared subject + /// in it, a retirement, a vacated and refilled office, a grant that + /// overlaps what an office lends and its revocation, the retirement of the + /// lending institution, a declared institution, and custody written both + /// ways. After every step each named read equals a scan of the maps the + /// patch would have copied. + #[test] + fn candidate_reads_equal_materialized_scans() { + let (kernel, topology, civic) = civic_kernel("Candidate"); + let state = &kernel.state; + let (hall, chamber, road) = + (Key::Existing(civic.hall), Key::Existing(civic.chamber), Key::Existing(topology.road)); + let (treasury, reeve, farmer, outsider) = ( + Key::Existing(civic.treasury), + Key::Existing(civic.reeve), + Key::Existing(civic.farmer), + Key::Existing(civic.outsider), + ); + let grain = Key::Existing(civic.grain); + let annex: Key = Key::Draft(DraftHandle::new("annex")); + let scribe: Key = Key::Draft(DraftHandle::new("scribe")); + let ministry: Key = Key::Draft(DraftHandle::new("ministry")); + let places = [hall.clone(), chamber.clone(), road.clone(), annex.clone()]; + let holders = + [treasury.clone(), reeve.clone(), farmer.clone(), outsider.clone(), scribe.clone(), ministry.clone()]; + let check = |graph: &Candidate<'_>, label: &str| agrees(graph, label, &places, &holders, &grain); + + let mut graph = Candidate::new(state); + check(&graph, "untouched"); + assert!(!graph.overlapping() && graph.offices_held_by(&reeve).len() == 1); + assert_eq!( + graph.occupants_under(&hall).len(), + 3, + "the treasury, the reeve and the farmer stand under the hall" + ); + + graph.positions.insert(farmer.clone(), road.clone()); + check(&graph, "a subject leaves the subtree"); + assert!(!graph.occupants_under(&hall).contains(&farmer)); + + graph.positions.insert(outsider.clone(), chamber.clone()); + check(&graph, "a subject enters the subtree"); + assert!(graph.occupants_under(&hall).contains(&outsider)); + + graph.containers.insert(annex.clone(), chamber.clone()); + graph.positions.insert(scribe.clone(), annex.clone()); + check(&graph, "a declared place holds a declared subject"); + assert!(graph.occupants_under(&hall).contains(&scribe)); + assert_eq!(graph.occupants_under(&annex), BTreeSet::from([scribe.clone()])); + + graph.retire(farmer.clone()); + graph.positions.remove(&farmer); + check(&graph, "a subject is retired"); + assert!(!graph.occupants_under(&road).contains(&farmer)); + + let warden = (treasury.clone(), office(WARDEN_OFFICE)); + let seat = graph.office(&warden).expect("the treasury opens a warden office"); + graph.set_office(warden.clone(), Some(OfficeCandidate { incumbent: None, ..seat.clone() })); + check(&graph, "the warden office is vacated"); + assert!(graph.offices_held_by(&reeve).is_empty()); + graph.set_office(warden.clone(), Some(OfficeCandidate { incumbent: Some(outsider.clone()), ..seat })); + check(&graph, "the warden office is refilled"); + assert_eq!(graph.offices_held_by(&outsider).len(), 1); + assert_eq!(graph.offices_of(&treasury).len(), 2); + + // The outsider now holds levy over the hall through the office; a levy + // over the chamber of their own overlaps it. + graph.set_grants(outsider.clone(), BTreeSet::from([levy_over(chamber.clone())])); + check(&graph, "an overlapping grant"); + assert_eq!(graph.overlapping_holders(), &BTreeSet::from([outsider.clone()])); + graph.set_grants(outsider.clone(), BTreeSet::new()); + check(&graph, "the grant is revoked"); + assert!(!graph.overlapping()); + graph.set_grants(outsider.clone(), BTreeSet::from([levy_over(chamber.clone())])); + assert!(graph.overlapping()); + graph.retire(treasury.clone()); + check(&graph, "the lending institution is retired"); + assert!(!graph.overlapping(), "a retired institution lends nothing"); + + // A declared institution lends a declared place to a declared subject. + graph.set_grants(ministry.clone(), BTreeSet::from([levy_over(annex.clone())])); + let seat = (ministry.clone(), office("reeve")); + graph.set_office( + seat.clone(), + Some(OfficeCandidate { + incumbent: Some(scribe.clone()), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }), + ); + check(&graph, "a declared institution seats a declared subject"); + assert_eq!(graph.effective_authority(&scribe), BTreeSet::from([levy_over(annex.clone())])); + graph.set_grants(scribe.clone(), BTreeSet::from([levy_over(chamber.clone())])); + check(&graph, "the declared subject's own grant covers the lent place"); + assert_eq!(graph.overlapping_holders(), &BTreeSet::from([scribe.clone()])); + graph.set_office(seat, None); + check(&graph, "the office is closed"); + assert!(!graph.overlapping()); + + // Custody, written both ways: the farmer's grain goes, the scribe's comes. + graph.holdings.insert((farmer.clone(), grain.clone()), Quantity(2)); + graph.holdings.insert((scribe.clone(), grain.clone()), Quantity(5)); + graph.holdings.remove(&(outsider.clone(), grain.clone())); + check(&graph, "custody is rewritten"); + assert_eq!(graph.custody(&grain), (14, 7), "two of seven, five of none, and none of seven"); + + assert!(!graph.declare_kind(AffordanceKindName("novel".into()))); + assert!(graph.declare_kind(AffordanceKindName("novel".into())), "a kind is named once"); + assert!(graph.declare_kind(AffordanceKindName("speak".into())), "the catalog names speak"); + check(&graph, "kinds"); + } + + /// An overlay nobody has written reads exactly the partition the old seeding + /// copied, key for key, in every world that holds a document in some + /// partition; and a draft key, or an id nothing holds, reads as absent. + #[test] + fn an_untouched_overlay_reads_what_the_seeding_copied() { + let worlds = crate::golden_tests::populated_worlds(); + for state in &worlds { + let graph = Candidate::new(state); + let all = Materialized::seeded(state); + macro_rules! same { + ($($map:ident),*) => {$( + for (key, value) in &all.$map { + assert_eq!( + format!("{:?}", graph.$map.get(key)), + format!("{:?}", Some(value)), + stringify!($map) + ); + } + )*}; + } + macro_rules! same_set { + ($($map:ident),*) => {$( + for key in &all.$map { + assert!(graph.$map.contains_key(key), stringify!($map)); + } + )*}; + } + same!(containers, routes, positions, holdings, redress, facts, affordance_holdings, channels, knowledge, pressures); + same_set!(dependencies, commitments); + for (key, value) in &all.authority { + assert_eq!(&graph.grants_of(key), value); + } + for (slot, value) in &all.selection { + assert_eq!(graph.office(slot).as_ref(), Some(value)); + } + for key in &all.retired { + assert!(graph.is_retired(key)); + } + let nobody: Key = Key::Existing(SubjectId::issue()); + let nowhere: Key = Key::Existing(EntityId::issue()); + let drafted: Key = Key::Draft(DraftHandle::new("drafted")); + assert!(graph.positions.get(&nobody).is_none() && graph.positions.get(&drafted).is_none()); + assert!(graph.containers.get(&nowhere).is_none()); + assert!(graph.grants_of(&nobody).is_empty() && !graph.is_retired(&drafted)); + assert!(graph.office(&(nobody, office(WARDEN_OFFICE))).is_none()); + assert!(graph.occupants_under(&nowhere).is_empty()); + assert_eq!(graph.effective_authority(&drafted), BTreeSet::new()); + } + } + + /// The first overlap of a patch is named at the operation that made it, and + /// every later widening operation is named too while it stands; a revoke + /// that clears it makes the later widening operation clean. + #[test] + fn overlap_mismatches_are_unchanged() { + let (mut kernel, _, civic) = civic_kernel("Overlaps"); + let snapshot = kernel.snapshot().unwrap(); + let grant = |holder: SubjectId| crate::ComponentOp::GrantAuthority { + holder: crate::Ref::Existing(holder), + grant: crate::AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: crate::AuthorityTargetRef::PlaceSubtree(crate::Ref::Existing(civic.chamber)), + }, + }; + let revoke = |holder: SubjectId| match grant(holder) { + crate::ComponentOp::GrantAuthority { holder, grant } => { + crate::ComponentOp::RevokeAuthority { holder, grant } + } + other => other, + }; + let seat = crate::ComponentOp::InstallIncumbent { + institution: crate::Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: crate::Ref::Existing(civic.farmer), + }; + let at = |operation: usize| Mismatch::OverlappingJurisdiction { operation }; + + // The reeve holds the warden's levy over the hall, so a levy over the + // chamber of the reeve's own overlaps it, and the seating that follows + // still sees an overlap standing. + let both = reject_play( + &mut kernel, + &snapshot, + operations(vec![grant(civic.reeve), seat.clone()]), + ); + assert_eq!(both, vec![at(0), at(1)]); + + let cleared = reject_play( + &mut kernel, + &snapshot, + operations(vec![grant(civic.reeve), revoke(civic.reeve), seat]), + ); + assert_eq!(cleared, vec![at(0)]); + } +} diff --git a/native/aetherlight/src/views.rs b/native/aetherlight/src/views.rs new file mode 100644 index 000000000..ac3de4a3d --- /dev/null +++ b/native/aetherlight/src/views.rs @@ -0,0 +1,230 @@ +//! Cross-partition views: what a read needs that no one partition's index can +//! answer. +//! +//! A `Docs` projection is a pure function of one document. Two questions the +//! clock asks are joins: "is this dependency failing" reads dependencies with +//! edges, holdings and positions (two of its arms are anti-joins: a resource +//! not held, a subject not placed), and "is this due commitment live" reads +//! commitments with `subjects.retired`. [`Views`] answers them as state derived +//! from those partitions' change lists, so a tick reads the work due and the +//! rows failing instead of every dependency or every dead pledge in the world. +//! +//! `Views` is derived, never state: not digested, not encoded, never exported, +//! and ignored by `WorldState`'s equality (its `PartialEq` is always true, as a +//! `Docs` index is ignored). The one writer is [`Views::fold`], called by +//! `WorldState::finish` from the open logs before they close, so replay (genesis +//! and every replayed commit close through `finish`) rebuilds it on open and a +//! rollback has nothing to undo: the view never saw the transaction. It is read +//! only with clean logs, which `derive_motion` asserts. + +use super::clock::dependency_unavailable; +#[cfg(test)] +use super::docs; +use super::patch::DependencyTarget; +use super::{EntityId, FictionalMinutes, SubjectId, WorldState, is_retired}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +#[derive(Clone, Debug, Default)] +pub(crate) struct Views { + /// When live subjects' commitments fall due: a point for each distinct + /// due, holding the subjects that have a commitment due then. A retired + /// subject has no point. + live_due: BTreeMap>, + /// The (dependent, target) pairs failing a live dependent: a closed route, + /// a resource the dependent does not hold, a subject nobody places. + failing: BTreeSet<(SubjectId, DependencyTarget)>, +} + +/// A view is derived and carries no content of its own, so two worlds with the +/// same documents are equal whatever their views hold. +impl PartialEq for Views { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl Eq for Views {} + +/// Whether the six partitions the views read have no open log: the only time a +/// view is true. +pub(crate) fn readable(state: &WorldState) -> bool { + state.commitments.is_clean() + && state.subjects.is_clean() + && state.dependencies.is_clean() + && state.edges.is_clean() + && state.holdings.is_clean() + && state.positions.is_clean() +} + +impl Views { + /// Subjects with a live commitment due at or before `to`. + pub(crate) fn due_by(&self, to: FictionalMinutes) -> BTreeSet { + #[cfg(test)] + docs::count_rows(self.live_due.range(..=to).map(|(_, held)| held.len() as u64).sum()); + self.live_due + .range(..=to) + .flat_map(|(_, held)| held.iter().copied()) + .collect() + } + + /// Every failing (dependent, target), in order. + pub(crate) fn failing(&self) -> impl Iterator { + #[cfg(test)] + docs::count_rows(self.failing.len() as u64); + self.failing.iter() + } + + /// Brings the views up to the open logs of the six partitions. Called by + /// `WorldState::finish` before the logs close; nothing else writes a view. + pub(crate) fn fold(&mut self, state: &WorldState) { + // Dues. A subject whose commitments or retirement changed loses the + // points its commitments held before and regains them if it is live. + let mut before: BTreeMap> = BTreeMap::new(); + for (subject, old, _) in state.commitments.changes() { + before.insert(*subject, old); + } + for (subject, _, _) in state.subjects.changes() { + before.entry(*subject).or_insert_with(|| state.commitments.get(subject)); + } + for (subject, old) in &before { + for commitment in old.into_iter().flat_map(|held| held.values()) { + if let Some(due) = self.live_due.get_mut(&commitment.due) { + due.remove(subject); + if due.is_empty() { + self.live_due.remove(&commitment.due); + } + } + } + if is_retired(state, *subject) { + continue; + } + for commitment in state.commitments.get(subject).into_iter().flat_map(|held| held.values()) { + self.live_due.entry(commitment.due).or_default().insert(*subject); + } + } + + // Failing dependencies. A subject whose dependencies, holdings or + // retirement changed has every row re-judged; a route or a placement + // that changed re-judges its dependents. + let rejudged: BTreeSet = state + .dependencies + .changes() + .map(|(subject, _, _)| *subject) + .chain(state.holdings.changes().map(|(subject, _, _)| *subject)) + .chain(state.subjects.changes().map(|(subject, _, _)| *subject)) + .collect(); + for subject in &rejudged { + let rows: Vec<_> = self + .failing + .range( + (*subject, DependencyTarget::Resource(EntityId(Uuid::nil()))) + ..=(*subject, DependencyTarget::Subject(SubjectId(Uuid::max()))), + ) + .copied() + .collect(); + for row in rows { + self.failing.remove(&row); + } + if is_retired(state, *subject) { + continue; + } + for target in state.dependencies.get(subject).into_iter().flatten() { + if dependency_unavailable(state, *subject, *target) { + self.failing.insert((*subject, *target)); + } + } + } + let moved: BTreeSet = state + .edges + .changes() + .map(|(edge, _, _)| DependencyTarget::Route(*edge)) + .chain(state.positions.changes().map(|(subject, _, _)| DependencyTarget::Subject(*subject))) + .collect(); + // A changed dependencies key is already in `rejudged`, so the dependents + // left to judge are the unchanged ones, which the committed index names + // without walking the log once per target. + for target in moved { + for (_, dependent) in state.dependencies.indexed_unchanged(target..=target) { + if rejudged.contains(&dependent) { + continue; + } + let row = (dependent, target); + if !is_retired(state, dependent) && dependency_unavailable(state, dependent, target) { + self.failing.insert(row); + } else { + self.failing.remove(&row); + } + } + } + } +} + +/// The views as a scan of the committed documents derives them, and the +/// oracle's other tools (test builds). +#[cfg(test)] +impl Views { + pub(crate) fn rebuild(state: &WorldState) -> Self { + let mut views = Self::default(); + for (subject, held) in state.commitments.iter() { + if is_retired(state, *subject) { + continue; + } + for commitment in held.values() { + views.live_due.entry(commitment.due).or_default().insert(*subject); + } + } + for (subject, targets) in state.dependencies.iter() { + if is_retired(state, *subject) { + continue; + } + for target in targets { + if dependency_unavailable(state, *subject, *target) { + views.failing.insert((*subject, *target)); + } + } + } + views + } + + /// Content equality, which `PartialEq` deliberately is not. + pub(crate) fn same_as(&self, other: &Self) -> bool { + self.live_due == other.live_due && self.failing == other.failing + } + + /// Damages the view in one place: a stray failing row, else a missing + /// due point (the latest, which only its own subjects sit at). False when there + /// is nothing to damage that way. + pub(crate) fn corrupt_for_test(&mut self, stray: bool) -> bool { + if stray { + let row = (SubjectId(Uuid::from_u128(1)), DependencyTarget::Subject(SubjectId(Uuid::from_u128(2)))); + return self.failing.insert(row); + } + let Some(due) = self.live_due.keys().next_back().copied() else { + return false; + }; + self.live_due.remove(&due); + true + } + + /// The subjects with a dependency on `target`, by a scan of every row. + pub(crate) fn dependents_by_scan(state: &WorldState, target: DependencyTarget) -> Vec { + state + .dependencies + .iter() + .filter(|(_, held)| held.contains(&target)) + .map(|(subject, _)| *subject) + .collect() + } + + /// The subjects with a dependency on `target`, from the dependencies + /// partition's `DependsOn` index (true mid-transaction). + pub(crate) fn dependents_of(state: &WorldState, target: DependencyTarget) -> Vec { + state + .dependencies + .indexed(target..=target) + .into_iter() + .map(|(_, subject)| subject) + .collect() + } +} diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index a5e7e53c9..8381d325d 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -104,6 +104,27 @@ public sealed partial class RunStartTests Assert.Equal(LoadoutGenerator.AmmunitionCrates, weapon.Reserve); } + // A ship summoned into a running zone is stocked like one a run start stages: a fed fit carries the crates its weapon draws, + // and one whose scenario authored its cargo keeps exactly that. Kills: Summon skipping StockUnauthoredAmmunition. + [Fact] + public void ASummonedFedShipCarriesItsCrates() + { + var (hull, slots) = FedFit(bay: true); + var (_, arena, staged, failures) = Launch(new Scripted(false, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0))), Inputs(() => GalaxySeed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + + var summoned = ZoneStage.Summon(_items, arena, stage => + { + stage.Place(stage.Fit(hull, slots), float2(300, 0)); + var authored = stage.Place(stage.Fit(hull, slots), float2(-300, 0)); + stage.Cargo(authored); + }, failures); + + Assert.True(failures.Count == 0, string.Join("; ", failures)); + Assert.Equal(LoadoutGenerator.AmmunitionCrates, Assert.Single(summoned[0].Weapons).Reserve); + Assert.Equal(0, Assert.Single(summoned[1].Weapons).Reserve); + } + // The Loadout path with the DEFAULT stocking argument (what the boss in ZoneGenerator and the console `fly` call): a ship built from a // Loadout holds the crates its fed weapon draws, and one whose only weapon draws nothing holds none. Kills: Materialize // dropping its default StockAmmunition (every Loadout-built armed ship fires one magazine). @@ -166,4 +187,37 @@ public sealed partial class RunStartTests } Assert.True(fed > 0, "fixture: some new-run player ship carries an ammunition-fed weapon"); } + + // The HUD's ammunition label (Weapon.AmmoReadout): a magazine gun reads "magazine/reserve", a beam that names an AmmoType has no magazine (it + // draws a crate per interval) and reads its reserve alone, a weapon that draws nothing reads empty. Kills: a label that prints the beam's + // never-filled magazine as "0/N", or one that drops the magazine from a gun's. + [Fact] + public void TheAmmoLabelShowsAMagazineOnlyForAWeaponThatHasOne() + { + var (hull, _) = FedFit(bay: true); + var rounds = _cache.GetAll().Single(item => item.Name == "Fed Gun").Behaviors.OfType().Single().AmmoType; + _cache.Upsert(new WeaponItemData + { + Name = "Fed Beam", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, + Behaviors = { new ConstantWeaponData { AmmoType = rounds } } + }); + EquippableItemData Design(string name) => _cache.GetAll().Single(item => item.Name == name); + var loadout = new Loadout { Name = "label", Hull = _cache.RefOf(_cache.GetAll().Single(h => h.Name == hull)), WeaponGroups = new int[0][] }; + foreach (var (name, x) in new[] { ("Fed Gun", 3), ("Fed Beam", 2), ("Plain Gun", 1), ("Fed Bay", 4) }) + loadout.Slots.Add(new LoadoutSlot { Position = int2(x, 3), Rotation = ItemRotation.None, Design = _cache.RefOf(Design(name)) }); + var failures = new List(); + var ship = Loadouts.Materialize(_items, null, loadout, _ => null, failures); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + + string Label(string name) => ship.Weapons.Single(weapon => _items.GetData(weapon.Item.EquippableItem).Name == name).AmmoReadout; + var reserve = LoadoutGenerator.AmmunitionCrates; + Assert.Equal(reserve.ToString(), Label("Fed Beam")); + Assert.Equal($"{ship.Weapons.Single(w => _items.GetData(w.Item.EquippableItem).Name == "Fed Gun").Ammo}/{reserve}", Label("Fed Gun")); + Assert.Equal("", Label("Plain Gun")); + // The HUD shows the label (not the infinite-ammunition icon) exactly for the weapons that read something. + bool Shown(string name) => ship.Weapons.Single(weapon => _items.GetData(weapon.Item.EquippableItem).Name == name).ShowsAmmoReadout; + Assert.True(Shown("Fed Gun")); + Assert.True(Shown("Fed Beam")); + Assert.False(Shown("Plain Gun")); + } } diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs index ccf3fae29..0d5c39c21 100644 --- a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -40,10 +40,9 @@ public sealed class ChildrenWithinReachTests : IClassFixture("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); var planetSettings = authored.Read("PlanetSettings"); foreach (var galaxyZone in galaxy.Zones) @@ -51,7 +50,7 @@ public sealed class ChildrenWithinReachTests : IClassFixture("ZoneSettings"); tune?.Invoke(Settings); var pack = ZoneGenerator.GenerateZone(items, Settings, planetSettings, galaxy, galaxyZone, - galaxyZone == galaxy.Entrance && galaxy.IsPrelude, false); + true, false); foreach (var belt in pack.Planets.Select(cache.Get).OfType()) { Belts++; diff --git a/tests/Aetheria.Shared.Tests/CoastingTests.cs b/tests/Aetheria.Shared.Tests/CoastingTests.cs new file mode 100644 index 000000000..56b33151e --- /dev/null +++ b/tests/Aetheria.Shared.Tests/CoastingTests.cs @@ -0,0 +1,48 @@ +using System; +using CultMath; +using Xunit; +using static CultMath.math; +using float3 = CultMath.float3; +using Random = CultMath.Random; + +// The consumer's side of aetheria-gravity:ruling:no-drag-below-top-speed: a ship launched below its hull's top speed and +// left alone keeps that speed, at the global thrust tuning the game ships with (GameplaySettings.ThrustScale 0.1) as well as +// at the fixtures' 1. Reads only the ship's velocity after the zone steps: not Drag, DragScale or any field of the fix. +// Kills: drag reintroduced below top speed, or any deceleration whose size depends on ThrustScale. +public sealed class CoastingTests +{ + private const float PlayThrustScale = .1f; // GameplaySettings.ThrustScale's default, the value play runs at + + private static float CoastedSpeed(float thrustScale, float launchSpeed, float seconds) + { + using var cache = RestoredHullsTests.OpenCatalog(); + var hull = cache.GetByName("Longinus"); + var settings = RestoredHullsTests.Settings(); + settings.ThrustScale = thrustScale; + var items = new ItemManager(1u, cache, new ProvenanceLedger(), settings, _ => { }); + items.Random = new Random(1u); + var random = new Random(1); + var pack = new LoadoutGenerator(ref random, items, null, null, null, .5f).GenerateShipLoadout(candidate => candidate == hull); + Assert.NotNull(pack); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test", Owner = null }, null); + var ship = (Ship) EntitySerializer.Unpack(items, zone, pack); + zone.Admit(ship, piloted: false); + ship.Position = float3.zero; + zone.Update(0f); + + ship.MovementDirection = float2(0, 0); + ship.Velocity = float2(0, launchSpeed); + for (var i = 0; i < (int) (seconds * 60); i++) zone.Update(1f / 60f); + return length(ship.Velocity); + } + + [Theory] + [InlineData(PlayThrustScale)] + [InlineData(1f)] + public void AShipLaunchedBelowTopSpeedKeepsItsSpeed(float thrustScale) + { + const float launch = 50f; // Longinus's top speed is 100 + var speed = CoastedSpeed(thrustScale, launch, 10f); + Assert.True(speed >= launch - .01f, $"ThrustScale {thrustScale}: launched at {launch}, coasting 10 s left it at {speed}"); + } +} diff --git a/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs b/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs index 9878d95c6..083f7ac0f 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs @@ -139,6 +139,7 @@ public sealed class ConsumableSupplyTests : IDisposable _caches.Add(cache); var game = new SavedGame { + InfluenceScale = 1, Factions = new[] { maker }, Relationships = new[] { FactionRelationship.Neutral }, HomeZones = new Dictionary { { 0, 0 } }, @@ -282,8 +283,8 @@ public sealed class ConsumableSupplyTests : IDisposable cache.Upsert(new FactionProductData { Name = "Overdrive by Maker", Design = new CultRecordRef(overdrive.Key), Manufacturer = maker }); var authored = AuthoredSettings.Load(repo); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), cache, new PlayerSettings(), Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, 1); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), cache, _ => { }, null, 1); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); int stations = 0, ships = 0; diff --git a/tests/Aetheria.Shared.Tests/ContactRevealTests.cs b/tests/Aetheria.Shared.Tests/ContactRevealTests.cs index b7d1b88ab..65c69d21b 100644 --- a/tests/Aetheria.Shared.Tests/ContactRevealTests.cs +++ b/tests/Aetheria.Shared.Tests/ContactRevealTests.cs @@ -1991,4 +1991,33 @@ public sealed partial class ContactRevealTests : IDisposable Assert.False(bystander.IsHostileTo(intruder)); Assert.DoesNotContain(intruder, bystander.VisibleEnemies); } + + // The owner's own map decides whom it permits in its Critical area: with a Friendly entry for the visitor's faction she is + // permitted and the patrol holds her no enemy once tracked; with no entry she trespasses and the patrol does (base behaviour). + // Kills: the NPC arm of GetFactionRelationship left constant. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void RelationsDecidePresenceInOwnedSpace(bool friendly) + { + var patrol = Add(float3(0, 0, 0), new[] { "Eye", "Gun" }); + var visitor = Visitor(float3(0, 0, 60), player: false); + var owner = patrol.Faction; + _openCache.Upsert(owner); + var visitorRef = _openCache.Upsert(visitor.Faction); + if (friendly) + { + owner.Relations[visitorRef] = FactionRelationship.Friendly; + _openCache.Upsert(owner); + } + OwnedGalaxy(owner); + Tick(.05f); + Assert.Equal(friendly, visitor.PresencePermitted.Value); + + patrol.EntityInfoGathered[visitor] = 1f; + Tick(.05f); + + Assert.True(patrol.VisibleEntities.Contains(visitor)); + Assert.Equal(!friendly, patrol.IsHostileTo(visitor)); + } } diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs new file mode 100644 index 000000000..9479e31e3 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -0,0 +1,410 @@ +using System; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using Xunit; + +namespace Aetheria.Shared.Tests +{ + // The credits list against the repo's own licence files and the main menu that must reach it. + public class CreditsTests + { + private static string Root() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir != null && !File.Exists(Path.Combine(dir.FullName, "Assets", "Scripts", "UI", "MainMenu.cs"))) dir = dir.Parent; + return dir?.FullName ?? throw new InvalidOperationException("repo root not found"); + } + + private static string Read(string relative) => File.ReadAllText(Path.Combine(Root(), relative)); + + private static System.Collections.Generic.IReadOnlyList Load() => Credits.All(Read(Credits.NounProjectFile)); + + // A file under Assets that looks like a licence, attribution, notice, readme or sources list. Each one is either + // credited (the credit names it as its LicenceFile) or reviewed below with the reason it is not. + private static readonly Regex LicenceLike = new Regex( + @"^(LICEN[CS]E|COPYING|NOTICE|README|SOURCES|_SOURCES|Attribution|UFL)|OFL", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + // Discovered files whose own text names no holder and no licence, so there is nothing true to credit. A new + // licence-like file is not here until someone has read it and written the reason. + private static readonly System.Collections.Generic.Dictionary ReviewedNotCredited = new System.Collections.Generic.Dictionary + { + ["Assets/Scripts/ServerShared/NIH/LinqFaster/readme.txt"] = "usage guide for LinqFaster; names no holder and no licence", + ["Assets/Plugins/LowPoly_AsteroidsPack/README.pdf"] = "how to customise the asteroid pack; names no holder and no licence", + ["Assets/Plugins/Celestial Body/Textures/_Sources.txt"] = "URLs of the source textures only; states no licence", + }; + + // Copyright lines found in source headers whose holder no credit shows, each with the reason; keyed like HeaderKeys. + private static readonly System.Collections.Generic.Dictionary ReviewedHeaders = new System.Collections.Generic.Dictionary + { + ["microsoftopentechnologiesinc"] = "UniRx files derived from Rx.NET: the header names Microsoft Open Technologies and points at a License.txt that is not in the repo, so no licence is stated; decision owed", + }; + + // Source headers that credit someone ("Credit X", "Based on ...", a source URL) without stating a copyright holder or + // a licence, so there is no true notice to show. Each is the exact line the file carries and the reason it is not a + // credit; the test reads the file, so a line that moves or goes cannot leave a stale entry. + private static readonly (string file, string line, string reason)[] ReviewedAttributionLines = + { + ("Assets/Shaders/StableFluids/Fluid.cs", "// https://github.com/keijiro/StableFluids", "names Keijiro's StableFluids as the source; states no holder and no licence"), + ("Assets/Shaders/StableFluids/Fluid.shader", "// https://github.com/keijiro/StableFluids", "names Keijiro's StableFluids as the source; states no holder and no licence"), + ("Assets/Shaders/StableFluids/Fluid.compute", "// Based on https://github.com/keijiro/StableFluids", "names Keijiro's StableFluids as the source; states no holder and no licence"), + ("Assets/Plugins/Celestial Body/Scripts/Shaders/Includes/Triplanar.cginc", "// Based on: medium.com/@bgolus/normal-mapping-for-a-triplanar-shader-10bf39dca05a", "cites bgolus's article for the technique; states no holder and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Primitives/UILineTextureRenderer.cs", "/// Credit jonbro5556", "names a contributor; states no copyright and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Primitives/UILineRenderer.cs", "/// Credit jack.sydorenko, firagon", "names contributors; states no copyright and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Primitives/UILineRendererList.cs", "/// Credit jack.sydorenko, firagon", "names contributors; states no copyright and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Utilities/CableCurve.cs", "/// Credit Farfarer", "names a contributor; states no copyright and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Editor/BezierLineRendererEditor.cs", "///Credit Jason Horsburgh", "names a contributor; states no copyright and no licence"), + }; + + [Fact] + public void ReviewedAttributionLinesAreStillInTheirFiles() + { + Assert.Equal(Array.Empty(), ReviewedAttributionLines + .Where(entry => !File.Exists(Path.Combine(Root(), entry.file)) || !Read(entry.file).Replace("\r", "").Split('\n').Any(line => line.Trim('\uFEFF', ' ', '\t') == entry.line)) + .Select(entry => $"{entry.line} in {entry.file}").ToArray()); + Assert.All(ReviewedAttributionLines, entry => Assert.False(string.IsNullOrWhiteSpace(entry.reason))); + } + + // Bundled works with no licence-like file at all, found by reading Assets. Their licences are not stated in the + // repo, so they are not credited; each path must still exist, so this list cannot go stale unnoticed. + private static readonly string[] UnlicensedWorks = + { + "Assets/Plugins/Ink", + "Assets/Plugins/GPUTrail", + "Assets/Plugins/com.unity.uiextensions", + "Assets/Shaders/StableFluids", + }; + + // What each credited file itself states, written here independently of the credit text: these strings must + // appear in the file and in the credit's notice. + private static readonly (string file, string[] stated)[] Holders = + { + (Credits.TwemojiFile, new[] { "Jason Sofonia & Justine De Caires", "Twitter", "CC BY 4.0" }), + (Credits.PlaydeadFile, new[] { "Playdead" }), + (Credits.LiberationFile, new[] { "Google Corporation", "Red Hat, Inc." }), + (Credits.UniRxFile, new[] { "Yoshifumi Kawai" }), + (Credits.KdTreeFile, new[] { "Vili Vol\u010dini / viliwonka" }), + (Credits.SimplexNoiseFile, new[] { "Ashima Arts", "Ian McEwan", "Keijiro Takahashi" }), + (Credits.AmbientCgFile, new[] { "ambientCG" }), + (Credits.UnityShaderFile, new[] { "Unity Technologies" }), + (Credits.AdditiveUiFile, new[] { "Unity Technologies", "Supyrb", "Johannes Deml" }), + (Credits.AcesFile, new[] { "Academy of Motion Picture Arts and Sciences", "A.M.P.A.S." }), + (Credits.ClassicNoiseFile, new[] { "Ashima Arts", "Stefan Gustavson" }), + (Credits.BezierPathFile, new[] { "Herman Tulleken", "Use this code as you wish" }), + }; + + // Fonts that state holder and licence in their own name tables: the credit's LicenceFile is the licence text shipped + // beside them (which must carry the licence and the stated holder), and every font listed must embed the stated string (read from the file, not from the credit) and be shown by the + // credit. The ids are TrueType name ids: 0 is the copyright notice. + private static readonly (string credit, string[] fonts, string embedded)[] FontCredits = + { + (Credits.UbuntuLicenceFile, new[] { "Assets/Fonts/Ubuntu/Ubuntu-R.ttf", "Assets/Fonts/Ubuntu/Ubuntu-L.ttf", "Assets/Fonts/Ubuntu/Ubuntu-B.ttf", "Assets/Fonts/Ubuntu/UbuntuMono-R.ttf" }, + "Copyright 2011 Canonical Ltd."), + (Credits.MontserratLicenceFile, new[] { "Assets/Fonts/Ubuntu/Montserrat-Thin.ttf" }, "Copyright(c) 2014 by Julieta Ulanovsky"), + }; + + // Fonts credited through a licence file in the repo (see Holders), not through their own text. + private static readonly string[] FontsCreditedByLicenceFile = { "Assets/Fonts/Emoji/Twemoji.ttf", "Assets/TextMesh Pro/Fonts/LiberationSans.ttf" }; + + // Fonts under Assets that are not credited, each with the reason; every one must be unreferenced by any prefab, + // scene, material or asset outside Assets/Fonts (checked), so shipping it is not a decision made by accident. + private static readonly System.Collections.Generic.Dictionary ReviewedFonts = new System.Collections.Generic.Dictionary + { + ["Assets/Fonts/Retro/LRT Oksana.ttf"] = "EULA forbids more than personal use; unreferenced; decision owed", + ["Assets/Fonts/Retro/LRT Oksana Bold.ttf"] = "EULA forbids more than personal use; unreferenced; decision owed", + ["Assets/Fonts/Ubuntu/UbuntuMono-B.ttf"] = "unreferenced; same holder and licence as UbuntuMono-R, which the Ubuntu credit covers", + ["Assets/Fonts/ftn_SourceSansPro-Regular.otf"] = "unreferenced; embeds Adobe copyright under the SIL OFL 1.1; credit it if it is ever used", + }; + + private static string[] FontFiles() + { + var root = Root(); + return Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Where(path => path.EndsWith(".ttf", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".otf", StringComparison.OrdinalIgnoreCase)) + .OrderBy(path => path, StringComparer.Ordinal) + .ToArray(); + } + + // Every name-table record of a TrueType/OpenType file with the given name id, decoded (platform 3 as UTF-16BE, + // platform 1 as Latin-1). + private static System.Collections.Generic.List NameRecords(string relative, int nameId) + { + var d = File.ReadAllBytes(Path.Combine(Root(), relative)); + int U16(int at) => (d[at] << 8) | d[at + 1]; + long U32(int at) => ((long)d[at] << 24) | ((long)d[at + 1] << 16) | ((long)d[at + 2] << 8) | d[at + 3]; + var found = new System.Collections.Generic.List(); + for (int i = 0, n = U16(4); i < n; i++) + { + var rec = 12 + 16 * i; + if (System.Text.Encoding.ASCII.GetString(d, rec, 4) != "name") continue; + var table = (int)U32(rec + 8); + int count = U16(table + 2), strings = table + U16(table + 4); + for (var j = 0; j < count; j++) + { + var r = table + 6 + 12 * j; + if (U16(r + 6) != nameId) continue; + var text = System.Text.Encoding.GetEncoding(U16(r) == 3 ? "utf-16BE" : "latin1").GetString(d, strings + U16(r + 10), U16(r + 8)); + found.Add(text.Replace("\r", "").Trim()); + } + } + return found; + } + + private static string[] LicenceLikeFiles() + { + var root = Root(); + return Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + .Where(path => !path.EndsWith(".meta")) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Where(path => LicenceLike.IsMatch(Path.GetFileName(path))) + .OrderBy(path => path, StringComparer.Ordinal) + .ToArray(); + } + + // The ways a licence-like file can be accounted for; shared so the mutations in the report hit the same rule. + private static string[] Unaccounted(string[] found, System.Collections.Generic.IEnumerable credited) => + found.Where(path => !credited.Contains(path) && !ReviewedNotCredited.ContainsKey(path)).ToArray(); + + // Every copyright marker in a source header: "Copyright", "copyright", "(c)" (not the tail of an identifier), the copyright sign, "Copyright (c)", with an optional + // colon and "by". A line is scanned marker by marker: a holder runs to the next marker or the end of the line, so a + // second holder on the same line is a holder of its own. Credits.cs is the credit text itself, so it is not scanned. + private const string Marker = @"(?:copyright(?:\s*(?:\(c\)|\u00a9))?|(?\s*:)?\s*(?:by\s+)?[<\[]?(?.+?)(?=" + Marker + @"|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + private static string Key(string text) => new string(text.Where(char.IsLetterOrDigit).ToArray()).ToLowerInvariant(); + + // Words that follow "copyright" in licence and header prose and name no holder ("copyright notice", "COPYRIGHT HOLDERS BE + // LIABLE", "copyright laws"); a capitalised word after a bare "Copyright" is a holder unless it is one of these. + private static readonly string[] ProseAfterCopyright = + { "Notice", "Notices", "Holder", "Holders", "Owner", "Owners", "Law", "Laws", "Act", "Protection", "Statement", "Header", "Information", "Status", "Line", "Lines", "Text", "Licence", "License", "Material", "Works", "Work", "File", "Files" }; + + // The holders a line of source states: the text after each marker, cut at the end of its sentence, as keys. A holder + // is a year or a capitalised name; "copyright notice" in licence prose names nobody. Without a year the marker must + // be "(c)", the copyright sign or a colon, so "Copyright Notice" prose is not a holder either. + private static System.Collections.Generic.IEnumerable LineHolders(string line) + { + foreach (Match match in HeaderCopyright.Matches(line)) + { + var holder = Regex.Replace(match.Groups["holder"].Value.Trim(), @"(\.(\s.*)?|\s*All rights reserved.*)$", "", RegexOptions.IgnoreCase).Trim(' ', '\t', ',', ';', '>', ']'); + var marked = Regex.IsMatch(match.Value.Substring(0, match.Groups["holder"].Index - match.Index), @"\(c\)|\u00a9|:", RegexOptions.IgnoreCase); + var year = Regex.IsMatch(holder, @"^\d{4}"); + // "Copyright Epic Games, Inc." names a holder with no year or sign; licence prose after the word does not. + var named = holder.Length > 0 && char.IsUpper(holder[0]) && !ProseAfterCopyright.Contains(Regex.Match(holder, @"^\w+").Value, StringComparer.OrdinalIgnoreCase); + if (holder.Length == 0 || !(year || (named && (marked || Regex.IsMatch(match.Value, "^copyright", RegexOptions.IgnoreCase))))) continue; + yield return Key(Normal(holder)); + } + } + + private static System.Collections.Generic.Dictionary HeaderKeys() + { + var root = Root(); + var keys = new System.Collections.Generic.Dictionary(); + foreach (var path in Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Where(path => new[] { ".shader", ".hlsl", ".cginc", ".cs", ".compute" }.Any(ext => path.EndsWith(ext)) && path != "Assets/Scripts/ServerShared/Credits.cs")) + foreach (var line in Read(path).Split('\n')) + foreach (var key in LineHolders(line)) + keys.TryAdd(key, path); + return keys; + } + + // A copyright line in a source header is a notice the licence requires shown, so its holder is in a credit or in + // ReviewedHeaders with the reason; a removed credit, or a newly pasted header, fails here. + [Fact] + public void EveryCopyrightHolderInASourceHeaderIsCreditedOrReviewed() + { + var keys = HeaderKeys(); + Assert.Contains(Key("2015 Academy of Motion Picture Arts and Sciences (A.M.P.A.S"), keys.Keys); + Assert.Contains("2016unitytechnologies", keys.Keys); + Assert.Contains("2017supyrb", keys.Keys); + // The whole holder must equal a holder some credit's notice states, read by the same extractor: a bare year, a short + // name, or a prefix of a credited name is a different key and fails. + var shown = Load().SelectMany(credit => credit.Notice.Split('\n')).SelectMany(LineHolders).ToHashSet(); + Assert.Equal(Array.Empty(), keys.Where(k => !shown.Contains(k.Key) && !ReviewedHeaders.ContainsKey(k.Key)).Select(k => $"{k.Key} in {k.Value}").ToArray()); + Assert.Equal(Array.Empty(), ReviewedHeaders.Keys.Where(k => !keys.ContainsKey(k)).ToArray()); + } + + [Fact] + public void EveryLicenceLikeFileUnderAssetsIsCreditedOrReviewed() + { + var root = Root(); + var found = LicenceLikeFiles(); + Assert.Contains(Credits.TwemojiFile, found); + Assert.Contains(Credits.LiberationFile, found); + var credited = Load().Select(credit => credit.LicenceFile).ToArray(); + Assert.Equal(Array.Empty(), Unaccounted(found, credited)); + Assert.Equal(Array.Empty(), credited.Where(path => !File.Exists(Path.Combine(root, path))).ToArray()); + Assert.Equal(Array.Empty(), ReviewedNotCredited.Keys.Where(path => !found.Contains(path)).ToArray()); + Assert.Equal(Array.Empty(), ReviewedNotCredited.Keys.Where(path => credited.Contains(path)).ToArray()); + Assert.Equal(Array.Empty(), UnlicensedWorks.Where(path => !Directory.Exists(Path.Combine(root, path))).ToArray()); + } + + // Every holder the licence file states is in the credit that answers for it; the notices are typed into + // Credits.cs, so this is what keeps them true to the files. + [Fact] + public void EveryCreditShowsTheHoldersItsOwnFileStates() + { + var credits = Load(); + Assert.Equal(Holders.Select(h => h.file).Append(Credits.NounProjectFile).Concat(FontCredits.Select(f => f.credit)).OrderBy(f => f, StringComparer.Ordinal), + credits.Select(credit => credit.LicenceFile).OrderBy(f => f, StringComparer.Ordinal)); + foreach (var (file, stated) in Holders) + { + var text = Normal(Read(file)); + var notice = Normal(credits.Single(credit => credit.LicenceFile == file).Notice); + foreach (var holder in stated) + { + Assert.True(text.Contains(Normal(holder)), $"{file} does not state '{holder}'"); + Assert.True(notice.Contains(Normal(holder)), $"the credit for {file} omits '{holder}'"); + } + // And every copyright line the file carries, whatever the table above says. + foreach (var line in Read(file).Split('\n')) + { + var match = CopyrightLine.Match(line); + if (!match.Success) continue; + var body = Regex.Replace(match.Groups[1].Value.Replace("[", "").Replace("]", "").Trim(), @"(\.\s.*|\s*All rights reserved)?\.?$", "", RegexOptions.IgnoreCase); + Assert.True(notice.Contains(Normal(body)), $"the credit for {file} omits its copyright line '{body}'"); + } + } + } + + private static readonly Regex CopyrightLine = new Regex(@"copyright\s*(?:\(c\)|\u00a9)?\s*(\[?\d.*)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + // Dash variants and case folded, so the file's en dash and the screen's hyphen compare equal. + private static string Normal(string text) => text.Replace('\u2013', '-').Replace('\u2014', '-').Replace("\r", "").Replace(" by ", " ").ToLowerInvariant(); + + // The credit text is typed; the font files are the authority on who holds them. A wrong holder, or a font in the + // family that does not carry it, fails here. + [Fact] + public void FontCreditsShowWhatTheFontsThemselvesEmbed() + { + var credits = Load(); + foreach (var (creditFile, fonts, embedded) in FontCredits) + { + var notice = credits.Single(credit => credit.LicenceFile == creditFile).Notice; + var licenceText = Read(creditFile); + Assert.Contains(creditFile.Contains("UFL") ? "UBUNTU FONT LICENCE Version 1.0" : "SIL OPEN FONT LICENSE Version 1.1", licenceText); + Assert.True(Path.GetDirectoryName(creditFile) == Path.GetDirectoryName(fonts[0]).Replace('\\', '/'), "licence text sits beside its fonts"); + if (creditFile.Contains("OFL")) Assert.Contains(embedded, licenceText); + Assert.Contains(embedded, notice); + foreach (var font in fonts) + Assert.True(NameRecords(font, 0).Count > 0 && NameRecords(font, 0).All(record => record.StartsWith(embedded)), + $"{font} does not embed '{embedded}' as its copyright"); + } + Assert.Contains("Ubuntu Font Licence 1.0", NameRecords(FontCredits[0].fonts[0], 0)[0]); + Assert.Contains("Ubuntu Font Licence 1.0", credits.Single(credit => credit.LicenceFile == Credits.UbuntuLicenceFile).Licence); + Assert.Contains("SIL Open Font License, Version 1.1", NameRecords(FontCredits[1].fonts[0], 13)[0]); + Assert.Contains("SIL Open Font License 1.1", credits.Single(credit => credit.LicenceFile == Credits.MontserratLicenceFile).Licence); + } + + [Fact] + public void EveryFontUnderAssetsIsCreditedOrReviewedAsUnreferenced() + { + var root = Root(); + var accounted = FontCredits.SelectMany(f => f.fonts).Concat(FontsCreditedByLicenceFile).Concat(ReviewedFonts.Keys).ToArray(); + var fonts = FontFiles(); + Assert.Equal(Array.Empty(), fonts.Where(font => !accounted.Contains(font)).ToArray()); + Assert.Equal(Array.Empty(), accounted.Where(font => !fonts.Contains(font)).ToArray()); + // A reviewed font stays out of the credits only while nothing outside Assets/Fonts uses it. Prefabs and scenes + // reference the TMP SDF asset made from the font, not the .ttf, so the search follows the font guid, then the + // guid of every file under Assets/Fonts that references a guid already followed: the font's own SDF asset, and + // any other SDF asset carrying it in a fallback table. A use is a file outside Assets/Fonts naming any of them. + var files = Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Where(path => new[] { ".prefab", ".unity", ".mat", ".asset", ".controller" }.Any(ext => path.EndsWith(ext))) + .Select(path => (path, text: Read(path))) + .ToArray(); + var inFonts = files.Where(file => file.path.StartsWith("Assets/Fonts/")).ToArray(); + var outside = files.Where(file => !file.path.StartsWith("Assets/Fonts/")).ToArray(); + foreach (var font in ReviewedFonts.Keys) + { + var followed = new System.Collections.Generic.HashSet { Regex.Match(Read(font + ".meta"), @"guid: (\w+)").Groups[1].Value }; + Assert.All(followed, guid => Assert.Equal(32, guid.Length)); + for (var grew = true; grew;) + { + grew = false; + foreach (var file in inFonts.Where(file => followed.Any(guid => file.text.Contains(guid))).ToArray()) + grew |= followed.Add(Regex.Match(Read(file.path + ".meta"), @"guid: (\w+)").Groups[1].Value); + } + Assert.Equal(Array.Empty(), outside.Where(user => followed.Any(guid => user.text.Contains(guid))).Select(user => user.path).ToArray()); + } + } + + [Fact] + public void TwemojiComesFirst() + { + var twemoji = Load()[0]; + Assert.Equal("Twemoji", twemoji.Name); + Assert.Contains("CC BY 4.0", twemoji.Licence); + } + + // The expectations are stated here, not derived from the parser: 81 icon credits between the heading and the + // "Other" sub-heading's two artists, named at the ends and at the line that was once split across two. + [Fact] + public void EveryIconCreditInTheAttributionFileIsShown() + { + var text = Read(Credits.NounProjectFile); + Assert.StartsWith(Credits.NounProjectHeading, text.TrimStart('\uFEFF')); + var lines = Credits.NounProjectLines(text).ToArray(); + Assert.Equal(82, lines.Length); + Assert.Equal("Tornado by Bart Laubsch", lines[0]); + Assert.Equal("Alien Abduction by Bart Laubsch", lines[1]); + Assert.Equal("Hurricane by icon 54 from Smashicons Space by Ben Davis", lines[2]); + Assert.Equal("Space 2 - Solid by Ben Davis", lines[3]); + Assert.Contains("Other", lines); + Assert.Equal("Missile War Weapon by Freepik", lines[^1]); + // One credit per line: every line but the sub-heading names an artist and does not stop mid-sentence. + foreach (var line in lines.Where(line => line != "Other")) + { + Assert.Contains(" by ", line, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotMatch(@"\s(from|by)$", line); + } + var notice = Load().Single(credit => credit.LicenceFile == Credits.NounProjectFile).Notice.Split('\n'); + Assert.Equal(lines, notice); + } + + [Fact] + public void AnAttributionFileWithoutItsHeadingIsRefused() + { + Assert.Throws(() => Credits.NounProjectLines("Tornado by Bart Laubsch\nAlien Abduction by Bart Laubsch").ToArray()); + Assert.Throws(() => Credits.NounProjectLines("Noun Project\n\n").ToArray()); + } + + [Fact] + public void EntriesNameTheirLicenceAndHolder() + { + foreach (var credit in Load()) + { + Assert.False(string.IsNullOrWhiteSpace(credit.Name)); + Assert.False(string.IsNullOrWhiteSpace(credit.Licence)); + Assert.False(string.IsNullOrWhiteSpace(credit.Notice)); + } + } + + [Fact] + public void AnEmptyEntryIsRefused() + { + Assert.Throws(() => Credits.Validate(new[] { new Credit { Name = "x", Licence = "", Notice = "n", LicenceFile = "f" } })); + } + + // The Unity menu is not compilable headlessly, so this reads its source with comments removed (a commented-out + // button or call must not satisfy it): the main menu must offer Credits, and ShowCredits must build the Shared + // list. It proves the wiring exists, not that the screen draws. + [Fact] + public void MainMenuOffersACreditsPathThatRendersTheList() + { + var menu = Regex.Replace(Read("Assets/Scripts/UI/MainMenu.cs"), @"/\*.*?\*/|//[^\n]*", "", RegexOptions.Singleline); + var main = menu.Substring(menu.IndexOf("private void ShowMain()", StringComparison.Ordinal)); + main = main.Substring(0, main.IndexOf("private bool ShowCredits()", StringComparison.Ordinal)); + Assert.Contains("AddButton(\"Credits\"", main); + Assert.Contains("ShowCredits()", main); + var credits = menu.Substring(menu.IndexOf("private bool ShowCredits()", StringComparison.Ordinal)); + credits = credits.Substring(0, credits.IndexOf("private void ShowScenarios()", StringComparison.Ordinal)); + Assert.Contains("Credits.All(", credits); + // A build missing the attribution file refuses with a dialog instead of throwing in the click handler. + Assert.Contains("attribution == null", credits); + Assert.Contains("Refuse(", credits); + } + } +} diff --git a/tests/Aetheria.Shared.Tests/CrossingScenarioTests.cs b/tests/Aetheria.Shared.Tests/CrossingScenarioTests.cs index 9c827b968..efaa4998d 100644 --- a/tests/Aetheria.Shared.Tests/CrossingScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/CrossingScenarioTests.cs @@ -10,7 +10,7 @@ using float3 = CultMath.float3; public sealed partial class RunStartTests { // Crossing: the demo's cast; projector and Cell Blaster fitted in separate weapon groups with the Fire Control Array - // aboard; an unpiloted hostile Djinni, coasting at the Djinni's speed cap, that crosses the bow inside 400 m; and an unpiloted neutral one inside the Lightning Projector's + // aboard; an unpiloted hostile Djinni, coasting at 25 m/s, that crosses the bow inside 400 m; and an unpiloted neutral one inside the Lightning Projector's // arc, short of its Range and beyond three quarters of it. [Fact] public void CrossingConditions() @@ -43,12 +43,12 @@ public sealed partial class RunStartTests Assert.True(toCrosser.z > 0, "the crosser starts ahead"); Assert.True(abs(dot(crosser.Direction, player.Direction)) <= sin(radians(30f)) + 1e-4f, "the crosser faces within 30 degrees of perpendicular to the player's bow"); - // It is placed moving: toward the bow line at most of the Djinni's 50 m/s cap, so its run is its own and not only the + // It is placed moving: toward the bow line at the scenario's 25 m/s, so its run is its own and not only the // arena's pull on the player. var crosserVelocity = ((Ship) crosser).Velocity; Assert.True(crosserVelocity.x * toCrosser.x < 0, "the crosser starts moving toward the bow line"); - Assert.True(abs(crosserVelocity.x) >= 40f, "the crosser's speed toward the bow line is most of the Djinni's speed cap"); - Assert.True(length(crosserVelocity) >= 40f, "the crosser starts at most of the Djinni's speed cap"); + Assert.Equal(25f, abs(crosserVelocity.x), 3); + Assert.Equal(25f, length(crosserVelocity), 3); Assert.False(player.IsHostileTo(waiting) || waiting.IsHostileTo(player), "the waiting Djinni is neutral"); Assert.Equal(0, AgentsOf(arena, waiting)); @@ -71,7 +71,7 @@ public sealed partial class RunStartTests Assert.True(length(pass.Ahead) < CrossingMetres, "the crosser passes inside the stated distance"); Assert.True(FireControl.InArc(small, float3(pass.Ahead.x, 0, pass.Ahead.y)), "Cell Blaster bears on the crosser as it crosses"); Assert.True(dot(FireControl.MountDirection(small), float3(player.Direction.x, 0, player.Direction.y)) > 0, "Cell Blaster mounts forward"); - // At seed 112 with no input the pass is at about 3.6 s and 45 m; a seed, field or staging change that loses it moves these. + // At seed 112 with no input the pass is at about 3.6 s and 45 m, at 25 m/s relative (a hull under its top speed coasts, so the launch speed holds); a seed, field or staging change that loses it moves these. Assert.InRange(pass.Seconds, CrossingEarliest, CrossingLatest); Assert.InRange(length(pass.Ahead), 30f, 60f); } diff --git a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs new file mode 100644 index 000000000..a2daf444a --- /dev/null +++ b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs @@ -0,0 +1,89 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System.Linq; +using System.Collections.Generic; +using CultMath; +using UniRx; +using Xunit; + +// The demo loop on the shipped catalog (aetheria-release, mining 5a and the ore sheet): the player's own gun breaks a rock +// through the trigger, the ore lands in the hold, the Pirates station Zenith buys it, repairs the hull and sells a unit back. +public sealed partial class RunStartTests +{ + [Fact] + public void DemoLoop_mine_sell_repair_buy() + { + var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var player = staged.Player; + var belt = arena.Planets.Single(body => body.Value is AsteroidBeltData); + var rock = new ChunkId(belt.Key, 0); + var laser = player.Equipment.Select(equipped => equipped.Behaviors.OfType().FirstOrDefault()) + .First(weapon => weapon != null && weapon.Item.EquippableItem != null && _items.GetData(weapon.Item.EquippableItem).Name == "Light Laser"); + + // Once the ship's stats have settled. + for (var tick = 0; tick < 50; tick++) arena.Update(.02f); + // The belt drifts and the sun's well pulls, so the ship is held where it was put: forty units off the rock. + void Hold() + { + var at = arena.ChunkPose(rock.Field, rock.Index).xy; + player.Position = new float3(at.x, player.Position.y, at.y - 40f); + player.Velocity = float2.zero; + player.Direction = new float2(0, 1); + player.Aim = new float3(0, 0, 1); + } + Hold(); + arena.Update(.02f); + Hold(); + Assert.True(player.SetTarget(rock), "the rock is a target"); + var gains = new List(); + arena.CargoGained.Subscribe(gains.Add); + laser.Activate(); + for (var elapsed = 0f; elapsed < 20f && arena.ChunkExists(rock); elapsed += .02f) { Hold(); arena.Update(.02f); } + var info = player.ChunkInfo(rock); + Assert.False(arena.ChunkExists(rock), $"the laser broke the rock: designated {FireControl.Designated(laser, player, rock, out var range)} range {range} info {info} target {player.Target} pos {player.Position} rockpos {arena.ChunkPose(rock.Field, rock.Index)} hp {arena.Settings.AsteroidHitpoints.Evaluate(arena.AsteroidBelts[rock.Field].Data.Asteroids[0].Size)}"); + + var ores = new[] { "Rock", "New Metals", "Gold" }; + var held = player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType().Select(stack => (bay, stack))) + .Where(h => ores.Contains(_items.GetData(h.stack).Name)).ToArray(); + Assert.NotEmpty(held); + Assert.Empty(arena.FloatingItems); + // The feed saw every unit that went into the hold and none float. + Assert.NotEmpty(gains); + Assert.All(gains, gain => Assert.Equal((GainKind.Mined, 0), (gain.Kind, gain.Adrift))); + Assert.Equal(held.Sum(h => h.stack.Quantity), gains.Sum(gain => gain.Stored)); + + var zenith = arena.Entities.Single(entity => entity.HullData.Name == "Zenith"); + var credits = 0; + // Every mined stack goes in one sale: the market takes it all, whatever the full hold of Zenith has room for. + var value = StationServices.OreValue(_items, player.CargoBays); + Assert.True(value > 0); + Assert.Equal(gains.Sum(gain => gain.Stored), StationServices.TrySellOre(player.CargoBays, zenith, ref credits)); + Assert.Equal(value, credits); + Assert.DoesNotContain(player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()), c => ores.Contains(_items.GetData(c).Name)); + + var cell = Enumerable.Range(0, player.MaxArmor.GetLength(0)).SelectMany(x => Enumerable.Range(0, player.MaxArmor.GetLength(1)).Select(y => (x, y))) + .First(c => player.MaxArmor[c.x, c.y] > 0); + player.Armor[cell.x, cell.y] = 0; + var cost = StationServices.RepairCost(_items, player); + Assert.True(cost > 0); + var paid = credits; + credits += cost; + Assert.True(StationServices.TryRepair(player, ref credits)); + Assert.Equal(paid, credits); + Assert.Equal(player.MaxArmor[cell.x, cell.y], player.Armor[cell.x, cell.y]); + + // Zenith's whole stock is one 16-cell reactor, which fits only an empty 4x4: the player jettisons what the hold + // still carries, then buys it. + var hold = player.CargoBays[0]; + foreach (var leftover in hold.Cargo.Keys.ToArray()) hold.Remove(leftover); + var stock = zenith.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType().Select(piece => (bay, piece))).Single(); + credits = StationServices.BuyPrice(_items, stock.piece); + Assert.Equal(BuyResult.Bought, StationServices.TryBuy(_items, stock.piece, 1, ref credits, + () => stock.bay.TryTransferItem(hold, stock.piece))); + Assert.Equal(0, credits); + Assert.Contains(stock.piece, hold.Cargo.Keys); + } +} diff --git a/tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs b/tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs new file mode 100644 index 000000000..24ef521eb --- /dev/null +++ b/tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; + +// The interim ore sheet (rulings mining-demo-ore-minimal-yields-now, mining-demo-ore-prices-gear-scale): what the shipped catalog's +// Asteroid belt holds can be carried and sold, so mine, sell, repair closes on the existing stations. +public sealed class DemoOreSheetTests : IDisposable +{ + private static readonly string[] Ores = { "Rock", "New Metals", "Gold" }; + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-demoore-" + Guid.NewGuid().ToString("N")); + + public DemoOreSheetTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + private CultCache Shipped() + { + var path = Path.Combine(_root, "Aetheria.cc"); + File.Copy(TestCatalog.Repo, path, true); + return AetheriaStores.Open(path, catalogWritable: true, registry: TestCatalog.Registry()); + } + + private static CultRecordRef Asteroid(CultCache cache) => + cache.RefOf(cache.GetAll().Single(k => k.Name == "Asteroid")); + + [Fact] + public void AsteroidYieldsThreeOresInKeyOrder() + { + using var cache = Shipped(); + var yield = FieldKinds.Yield(Asteroid(cache), default, cache); + var amounts = yield.ToDictionary(y => cache.Get(y.Commodity).Name, y => y.Amount); + Assert.Equal(Ores.OrderBy(n => n).ToArray(), amounts.Keys.OrderBy(n => n).ToArray()); + Assert.Equal(6f, amounts["Rock"]); + Assert.Equal(3f, amounts["New Metals"]); + Assert.Equal(1f, amounts["Gold"]); + Assert.Equal(yield.Select(y => y.Commodity.Key.Value).OrderBy(k => k, StringComparer.Ordinal), yield.Select(y => y.Commodity.Key.Value)); + } + + [Fact] + public void EveryYieldedOreCanBeHeldAndSold() + { + using var cache = Shipped(); + var shape = new Shape(5, 5); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var bay = new Shape(4, 4); + foreach (var cell in bay.AllCoordinates) bay[cell] = true; + cache.Upsert(new VerseGrammar { Revision = 1 }); + cache.Upsert(new HullData { Name = "OreSkiff", HullType = HullType.Ship, Shape = shape, Price = 1000, Durability = 10, Armor = 10 }); + cache.Upsert(new CargoBayData { Name = "OreBay", Shape = new Shape(), InteriorShape = bay, Price = 20, Durability = 4 }); + cache.FlushAsync().GetAwaiter().GetResult(); + var items = new ItemManager(1u, cache, new ProvenanceLedger(), AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read("GameplaySettings"), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + EquippableItem Mint(string design) + { + var data = cache.GetByName(design); + return new EquippableItem + { + Data = cache.RefOf(data), Durability = data.Durability, + Lot = items.Lots.Add(new Lot { Design = cache.RefOf(data), Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + } + var ship = new Ship(items, zone, Mint("OreSkiff"), new EntitySettings()); + Assert.True(ship.TryEquip(Mint("OreBay"), new int2(1, 1))); + + foreach (var (commodity, _) in FieldKinds.Yield(Asteroid(cache), default, cache)) + { + var data = cache.Get(commodity); + Assert.NotNull(data.Shape); + Assert.True(data.Price > 0, data.Name); + Assert.True(data.Mass > 0, data.Name); + Assert.True(ship.CargoBays.Single().TryStore(new SimpleCommodity { Data = cache.RefOf(data), Quantity = 1 }), data.Name); + } + } + + [Fact] + public void TheSheetConverges() + { + var path = Path.Combine(_root, "Converge.cc"); + File.Copy(Path.Combine(RestoredHullsTests.FindRepoRoot(), "GameData", "Aetheria.cc"), path); + var before = File.ReadAllBytes(path); + var output = new StringWriter(); + Assert.Equal(0, EconomyCommand.Author(path, new List { new DemoOre() }, true, output, TestCatalog.Registry(), _root)); + Assert.Equal(before, File.ReadAllBytes(path)); + + using var cache = AetheriaStores.Open(path, registry: TestCatalog.Registry()); + var ids = cache.GetAll().Single(k => k.Name == "Asteroid").Yields.Select(y => y.Id).ToArray(); + Assert.Equal(new[] { "a57e0c000001", "a57e0c000002", "a57e0c000003" }, ids); + } +} diff --git a/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs b/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs index 54f46a57c..6298d30e8 100644 --- a/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs +++ b/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs @@ -8,7 +8,7 @@ using System.Linq; using CultMath; using Xunit; -// The demo scenario (aetheria-release, cut demo-galaxy): a prelude galaxy of a fixed cast whose antagonist's home is the +// The demo scenario (aetheria-release, cut demo-galaxy): a galaxy of a fixed cast whose antagonist's home is the // boss zone and the exit. The cast, the Pirates included, is in the shipped catalog. public sealed partial class RunStartTests { @@ -82,7 +82,7 @@ public sealed partial class RunStartTests Assert.DoesNotContain(_cache.GetAll(), faction => faction.Name.StartsWith("Pirates", StringComparison.Ordinal)); var refusal = Assert.Throws(() => DemoGalaxy(1)); Assert.Contains("Pirates", refusal.Message); - Assert.Contains(nameof(TutorialGenerationSettings.ProtagonistFaction), refusal.Message); + Assert.Contains(nameof(GalaxyCast.ProtagonistFaction), refusal.Message); } // The operator's ruling is that the first release is a demo: the one scenario a release build lists says so by name. @@ -144,12 +144,12 @@ public sealed partial class RunStartTests string.Join(",", zone.AdjacentZones.Select(adjacent => Array.IndexOf(g.Zones, adjacent)).OrderBy(index => index)))); Galaxy Reference(uint seed, float density) { - var cast = new TutorialGenerationSettings + var cast = new GalaxyCast { ProtagonistFaction = "Pirates", AntagonistFaction = "Zhe", BufferFaction = "Luc", - NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, LinkDensity = density + NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, LinkDensity = density, InfluenceScale = .5f }; - return RunStart.Generate(new Scripted(false, _ => { }, seed, galaxy => galaxy.Prelude(cast)), Inputs()); + return RunStart.Generate(new Scripted(false, _ => { }, seed, stage => stage.Cast(cast)), Inputs()); } foreach (var seed in DemoSeeds) @@ -172,50 +172,42 @@ public sealed partial class RunStartTests // A name that resolves to nothing refuses the galaxy whichever cast field names it, and the refusal names the field. [Theory] - [InlineData(nameof(TutorialGenerationSettings.ProtagonistFaction))] - [InlineData(nameof(TutorialGenerationSettings.AntagonistFaction))] - [InlineData(nameof(TutorialGenerationSettings.BufferFaction))] - [InlineData(nameof(TutorialGenerationSettings.QuestFaction))] - [InlineData(nameof(TutorialGenerationSettings.NeutralFactions))] + [InlineData(nameof(GalaxyCast.ProtagonistFaction))] + [InlineData(nameof(GalaxyCast.AntagonistFaction))] + [InlineData(nameof(GalaxyCast.BufferFaction))] + [InlineData(nameof(GalaxyCast.QuestFaction))] + [InlineData(nameof(GalaxyCast.NeutralFactions))] public void AnUnresolvedCastNameRefusesTheGalaxyNamingItsField(string field) { - var cast = new TutorialGenerationSettings - { - ProtagonistFaction = _tutorialSettings.ProtagonistFaction, - AntagonistFaction = _tutorialSettings.AntagonistFaction, - BufferFaction = _tutorialSettings.BufferFaction, - QuestFaction = _tutorialSettings.QuestFaction, - NeutralFactions = _tutorialSettings.NeutralFactions, - ZoneCount = _tutorialSettings.ZoneCount, - LinkDensity = _tutorialSettings.LinkDensity - }; - typeof(TutorialGenerationSettings).GetField(field).SetValue(cast, field == nameof(cast.NeutralFactions) ? new[] { "Nonesuch" } : "Nonesuch"); - var scenario = new Scripted(false, _ => { }, generate: galaxy => galaxy.Prelude(cast)); + var cast = TestCasts.Wide; + typeof(GalaxyCast).GetField(field).SetValue(cast, field == nameof(cast.NeutralFactions) ? new[] { "Nonesuch" } : "Nonesuch"); + var scenario = new Scripted(false, _ => { }, generate: stage => stage.Cast(cast)); var refusal = Assert.Throws(() => RunStart.Generate(scenario, Inputs())); Assert.Contains(field, refusal.Message); } - // What a release build lists under New Game is the demo alone; the tutorial and the main galaxy are listed only in + // What a release build lists under New Game is the demo alone; the main galaxy is listed only in // editor and development builds (MainMenu.ShowScenarios), beside the test arenas. [Fact] public void ReleaseBuildsListOnlyTheDemo() { Assert.Equal(new[] { typeof(DemoTerminus) }, Scenarios.Modes.Select(scenario => scenario.GetType())); - Assert.Equal(new[] { typeof(TutorialGalaxy), typeof(MainGalaxy) }, Scenarios.Development.Select(scenario => scenario.GetType())); + Assert.Equal(new[] { typeof(MainGalaxy) }, Scenarios.Development.Select(scenario => scenario.GetType())); } - // The tutorial is the galaxy it was before the demo: its cast, homes, entrance and ownership at a fixed seed, with - // no exit and no boss zone. + // The wide test cast at half influence is the galaxy it was before the prelude was retired: its cast, homes, entrance + // and ownership at a fixed seed, with no exit and no boss zone. Homes, entrance and owners depend on InfluenceOf, so + // an InfluenceScale of 1 or a lost halving fails it. [Fact] - public void TutorialGalaxy_unchanged() + public void CastGalaxyAtHalfInfluenceIsUnchanged() { - var galaxy = RunStart.Generate(new TutorialGalaxy(), Inputs(() => GalaxySeed)); - Assert.Equal(TutorialSeed1, TutorialShape(galaxy)); - Assert.True(galaxy.Exit == null, "the tutorial has no exit"); - Assert.True(galaxy.BossZones.Count == 0, $"the tutorial has {galaxy.BossZones.Count} boss zones"); + var galaxy = RunStart.Generate(new Scripted(false, _ => { }, generate: stage => stage.Cast(TestCasts.Wide)), Inputs(() => GalaxySeed)); + Assert.Equal(WideCastSeed1, CastShape(galaxy)); + Assert.True(galaxy.Exit == null, "a cast galaxy has no exit until its scenario places the gate"); + Assert.True(galaxy.BossZones.Count == 0, $"the cast galaxy has {galaxy.BossZones.Count} boss zones"); } - private static string TutorialShape(Galaxy g) => + private static string CastShape(Galaxy g) => string.Join(",", g.Factions.Select(f => f.Name)) + " | homes " + string.Join(",", g.Factions.Select(f => g.HomeZones.TryGetValue(f, out var z) ? Array.IndexOf(g.Zones, z) : -2)) + " | entrance " + Array.IndexOf(g.Zones, g.Entrance) + @@ -223,6 +215,6 @@ public sealed partial class RunStartTests " | owners " + string.Join(",", g.Zones.Select(z => z.Owner == null ? "-" : z.Owner.ShortName)); // Measured at seed 1 under CultMath 0.3.0 (cultmath-unity-v0.3.0); the noise kernel changed there, which re-rolled the galaxy. - private const string TutorialSeed1 = + private const string WideCastSeed1 = "Miss Terri’s Sugariffic Snack Company,Zhestokost,Lucent Media,Adrasteia,Aeronautics Unlimited,Finch Cybernetics | homes 3,44,40,19,0,30 | entrance 12 | zones 64 | owners AU,AU,Finch,Miss Terri's,Lucent,Zhestokost,-,Lucent,AU,AU,Lucent,Adrasteia,-,Finch,Zhestokost,-,Adrasteia,-,AU,Adrasteia,AU,Zhestokost,Miss Terri's,-,AU,Finch,Miss Terri's,-,Zhestokost,-,Finch,-,-,AU,-,-,-,-,Miss Terri's,AU,Lucent,-,Finch,-,Zhestokost,AU,-,Zhestokost,Adrasteia,Adrasteia,AU,Miss Terri's,Finch,AU,Finch,-,Lucent,Zhestokost,-,AU,Miss Terri's,Zhestokost,-,Lucent"; } diff --git a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs index 6029d3647..7b7182400 100644 --- a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs +++ b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs @@ -48,7 +48,17 @@ public sealed partial class RunStartTests // go of a held weapon it no longer commands (target gone, untracked, another group the pick, Combat ended), where a held gun fired on // until a later step selected its group (the candidate change reverted: d9493bbe). Both together: the digest below. Releasing a beam or a // lock the same way (h7) moved nothing. - private const string TwoAiPinnedDigest = "85e85c46cfc66693c819dd294ad02f3cd0eae5486c8f152a97e2e2787f854274"; + // Repinned an eighth time, once (suite-honest), for the flight-model changes that landed after h6 and never repinned this + // entry (bisected on master, each intended): e0c1daa4e made ThrustScale default 0.1, 845f6c3aa removed drag below top speed, + // ffdba39ac made ThrustScale scale the push only, and 8c5a904cb pinned the fixtures to ThrustScale=1. Pull requests 8 and 9 + // moved the digest and returned it to 52fbb10d, which master already measured before this cut. The authored-cargo and + // ammunition-data blob of this cut moved nothing (52fbb10d measured with it merged in). Fixtures run ThrustScale=1 while play + // uses 0.1, so this digest pins the fight's logic, not the shipped feel. + // Repinned a ninth time, once (scenarios-batch4-minors): the catalog restores the five station-reactor products' quality + // spread (station-reactor-spread), and that blob alone moved the digest (the same tree with the old catalog measured 52fbb10d; + // traced: only Notorious Station moves it, because the zone's station Zenith carries a Notorious Station reactor lot whose + // minted quality changes with the role spread, and Snapshot hashes every zone entity's heat and shield). + private const string TwoAiPinnedDigest = "9c70a3ee234fb3b879f721a4a4abf13dd83bf56fd8733690d356b89b8a392258"; private const float TwoAiSeconds = 60f; [Fact] @@ -255,7 +265,7 @@ public sealed partial class RunStartTests Assert.Equal(first.digest, second.digest); } - private static string HostClass() => + internal static string HostClass() => (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "linux" : RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "windows" : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "osx" : "other") diff --git a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs index 37111b114..e7254fac6 100644 --- a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs +++ b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs @@ -542,7 +542,7 @@ public sealed class DrawnPoseTests : IDisposable var chunk = new ChunkId(w.Belt, 5); var hitpoints = w.Zone.Settings.AsteroidHitpoints.Evaluate(w.Asteroids[5].Size); var unworn = w.Zone.ChunkRadius(chunk); - Assert.False(w.Zone.Wear(chunk, hitpoints * .9f)); + Assert.False(w.Zone.Breaks(chunk, hitpoints * .9f)); Assert.True(w.Zone.ChunkRadius(chunk) < unworn * .5f, "the rock has shrunk to less than half its size"); Assert.Equal(before, Meshes()); } diff --git a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs index c0c04f89c..9557f27a1 100644 --- a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs @@ -5,6 +5,51 @@ using System.Linq; using GameCult.Caching; using Xunit; +// What the calling thread writes to Console while an action runs. Console is process-global and tests run in parallel, so a plain +// SetOut capture also collects other tests' diagnostic prints (the race that failed these tests in full-suite runs): the probe +// keeps only writes made on the thread that runs the action, and the gate keeps two probes from restoring each other's writer. +internal static class ConsoleProbe +{ + private static readonly object Gate = new object(); + + public static string WrittenBy(Action act) + { + Capture(() => { act(); return 0; }, out var output, out _); + return output; + } + + // The action's result with what it wrote to Console.Out and Console.Error on this thread. + public static T Capture(Func act, out string output, out string error) + { + lock (Gate) + { + var (previousOut, previousError) = (Console.Out, Console.Error); + var (probeOut, probeError) = (new ThreadWriter(Environment.CurrentManagedThreadId), new ThreadWriter(Environment.CurrentManagedThreadId)); + Console.SetOut(probeOut); + Console.SetError(probeError); + try { return act(); } + finally + { + Console.SetOut(previousOut); + Console.SetError(previousError); + output = probeOut.Mine.ToString(); + error = probeError.Mine.ToString(); + } + } + } + + private sealed class ThreadWriter : TextWriter + { + private readonly int _thread; + public readonly System.Text.StringBuilder Mine = new System.Text.StringBuilder(); + public ThreadWriter(int thread) => _thread = thread; + public override System.Text.Encoding Encoding => System.Text.Encoding.UTF8; + public override void Write(char value) { if (Environment.CurrentManagedThreadId == _thread) lock (Mine) Mine.Append(value); } + public override void Write(string value) { if (Environment.CurrentManagedThreadId == _thread) lock (Mine) Mine.Append(value); } + public override void Write(char[] buffer, int index, int count) { if (Environment.CurrentManagedThreadId == _thread) lock (Mine) Mine.Append(buffer, index, count); } + } +} + public sealed class EconomyCommandTests { private sealed class Lambda : EconomyBatch @@ -146,10 +191,19 @@ public sealed class EconomyCommandTests public void TheTrialCopyIsRemoved() { using var f = EconomyFixture.Healthy(); - var before = Directory.GetDirectories(Path.GetTempPath(), "aetherdb-economy-*").Length; - Author(f, false, out _, a => Good(f, a, "coal")); - Author(f, true, out _, a => Good(f, a, "tar", lore: "")); - Assert.Equal(before, Directory.GetDirectories(Path.GetTempPath(), "aetherdb-economy-*").Length); + // A private scratch root: the temp folder is shared with every parallel test that runs the command, so counting it races. + var scratchRoot = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-economy-audit-" + Guid.NewGuid().ToString("N"))).FullName; + try + { + foreach (var apply in new[] { false, true }) + { + Flush(f); + var batch = new Lambda(a => Good(f, a, apply ? "tar" : "coal", lore: apply ? "" : "a good")); + EconomyCommand.Author(f.CatalogPath, new EconomyBatch[] { batch }, apply, new StringWriter(), TestCatalog.Registry(), scratchRoot); + } + Assert.Empty(Directory.GetFileSystemEntries(scratchRoot)); + } + finally { Directory.Delete(scratchRoot, true); } } [Fact] @@ -286,17 +340,13 @@ public sealed class EconomyCommandTests using var db = AetherDb.Open(); var expected = new StringWriter(); var expectedCode = EconomyCommand.Report(db.Cache, expected); - var console = new StringWriter(); - var previous = Console.Out; - Console.SetOut(console); var output = new StringWriter(); - int code; - try { code = EconomyCommand.Run(new[] { "report" }, output); } - finally { Console.SetOut(previous); } + int code = 0; + var console = ConsoleProbe.WrittenBy(() => code = EconomyCommand.Run(new[] { "report" }, output)); Assert.Equal(expectedCode, code); Assert.NotEmpty(expected.ToString()); Assert.Equal(expected.ToString(), output.ToString()); - Assert.Empty(console.ToString()); + Assert.Empty(console); } [Fact] @@ -306,17 +356,13 @@ public sealed class EconomyCommandTests var before = File.ReadAllBytes(path); var expected = new StringWriter(); var expectedCode = EconomyCommand.Author(path, new EconomyBatch[] { new Munitions() }, false, expected); - var console = new StringWriter(); - var previous = Console.Out; - Console.SetOut(console); var output = new StringWriter(); - int code; - try { code = EconomyCommand.Run(new[] { "author", "Munitions" }, output); } - finally { Console.SetOut(previous); } + int code = 0; + var console = ConsoleProbe.WrittenBy(() => code = EconomyCommand.Run(new[] { "author", "Munitions" }, output)); Assert.Equal(expectedCode, code); Assert.NotEmpty(expected.ToString()); Assert.Equal(expected.ToString(), output.ToString()); - Assert.Empty(console.ToString()); + Assert.Empty(console); Assert.Equal(before, File.ReadAllBytes(path)); } diff --git a/tests/Aetheria.Shared.Tests/ElementIdBlind.cs b/tests/Aetheria.Shared.Tests/ElementIdBlind.cs new file mode 100644 index 000000000..6c340ea8f --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ElementIdBlind.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections; +using System.Linq; +using System.Reflection; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +// Element ids are minted at random when a record is written, so two writes of the same content differ in exactly those slots. +// A test that asks "is this the same content" compares the bytes with every element id blank. +public static class ElementIdBlind +{ + private static readonly MessagePackSerializerOptions Options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ItemData).Assembly); + + // The document's bytes with every [CultElementId] member blank, on a copy: the document is untouched. + public static byte[] Pack(object document, Type type = null) + { + type ??= document.GetType(); + var copy = MessagePackSerializer.Deserialize(type, MessagePackSerializer.Serialize(type, document, Options), Options); + Blank(copy); + return MessagePackSerializer.Serialize(type, copy, Options); + } + + // A stored payload of the schema, re-encoded with every element id blank. + public static byte[] Payload(CultDocumentRegistry registry, string schemaId, byte[] payload) + { + var type = registry.GetRequiredBySchemaId(schemaId).DocumentType; + var value = MessagePackSerializer.Deserialize(type, payload, Options); + Blank(value); + return MessagePackSerializer.Serialize(type, value, Options); + } + + private static void Blank(object value) + { + if (value == null || value is string || value.GetType().IsPrimitive || value.GetType().IsEnum) return; + if (value is IEnumerable items && !(value is string)) + { + foreach (var item in items) Blank(item); + return; + } + for (var type = value.GetType(); type != null && type != typeof(object); type = type.BaseType) + foreach (var member in type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + { + if (member is FieldInfo field) + { + if (field.GetCustomAttribute() != null) field.SetValue(value, ""); + else if (!field.FieldType.IsPrimitive && field.GetCustomAttribute() == null && field.GetCustomAttribute() != null) + Blank(field.GetValue(value)); + } + else if (member is PropertyInfo property && property.GetIndexParameters().Length == 0 && property.GetCustomAttribute() != null) + { + if (property.GetCustomAttribute() != null) property.SetValue(value, ""); + else Blank(property.GetValue(value)); + } + } + } +} diff --git a/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs new file mode 100644 index 000000000..682b20409 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching; +using Xunit; + +// CultLib 3.0 requires element ids and reads the stores written before it (2.0 and older), which carry none. +// The shipped GameData stores are those stores, byte for byte: they have never been rewritten under the new pin. +// Upgrading is one-way: once a store is written under the new pin it holds element ids, and an older pin can read it only by +// dropping them (CultLib #98). Readers upgrade before writers. +public class ElementIdUpgradeTests +{ + private static string Shipped => Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Aetheria.cc"); + + [Fact] + public async Task AStoreWrittenBeforeElementIdsOpensMintsThemOnceAndKeepsEveryRecord() + { + using var directory = new TempDirectory(); + var copy = Path.Combine(directory.Path, "Aetheria.cc"); + File.Copy(Shipped, copy); + + int records, minted; + using (var cache = AetheriaStores.Open(copy, catalogWritable: true, registry: TestCatalog.Registry())) + { + records = cache.AllStoredDocuments.Count(); + Assert.True(records > 0); + minted = cache.MintElementIds(); + Assert.True(minted > 0, "the shipped catalog predates element ids; opening it must have minted some"); + Assert.Equal(0, cache.MintElementIds()); + await cache.FlushAsync(); + } + + using var reopened = AetheriaStores.Open(copy, registry: TestCatalog.Registry()); + Assert.Equal(records, reopened.AllStoredDocuments.Count()); + Assert.Equal(0, reopened.MintElementIds()); + foreach (var hull in reopened.GetAll()) + { + var ids = hull.Hardpoints.Select(hardpoint => hardpoint.Id).ToArray(); + Assert.All(ids, id => Assert.False(string.IsNullOrEmpty(id))); + Assert.Equal(ids.Length, ids.Distinct().Count()); + } + } + + // Upgrading assigns ids and changes nothing else: every record of the old-format file decodes, once the id members are + // blank, to the same bytes before and after the mint, flush and reopen. + [Fact] + public async Task UpgradingKeepsEveryFieldOfEveryRecordAndOnlyAddsIds() + { + using var directory = new TempDirectory(); + var copy = Path.Combine(directory.Path, "Aetheria.cc"); + File.Copy(Shipped, copy); + var registry = TestCatalog.Registry(); + Dictionary Content(string path) => + GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).Records + .ToDictionary(record => record.Key, record => record.SchemaId + ":" + Convert.ToHexString(ElementIdBlind.Payload(registry, record.SchemaId, record.Payload))); + var before = Content(copy); + + using (var cache = AetheriaStores.Open(copy, catalogWritable: true, registry: TestCatalog.Registry())) + { + Assert.True(cache.MintElementIds() > 0); + await cache.FlushAsync(); + } + + var after = Content(copy); + Assert.Equal(before.Count, after.Count); + foreach (var record in before) Assert.True(after[record.Key] == record.Value, $"{record.Key} changed content when its element ids were minted"); + } + + [Fact] + public void EveryShippedModPackageStillLoads() + { + var packages = Directory.GetDirectories(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Mods")); + Assert.NotEmpty(packages); + foreach (var package in packages) + { + var (hull, visual, _) = ShipAuthoringStore.Load(Path.Combine(package, "ship.cc")); + Assert.NotNull(hull); + Assert.NotNull(visual); + } + } + + // A package whose file still holds a retired slot reads but cannot be written over (CultSchemaConflictException). + [Fact] + public void EveryShippedModPackageCanBeWrittenOver() + { + foreach (var package in Directory.GetDirectories(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Mods"))) + { + using var directory = new TempDirectory(); + var copy = Path.Combine(directory.Path, "ship.cc"); + File.Copy(Path.Combine(package, "ship.cc"), copy); + var (hull, visual, products) = ShipAuthoringStore.Load(copy); + using (var cache = ShipAuthoringStore.Open(copy, writable: true)) + { + ShipAuthoringStore.Write(cache, hull, visual); + foreach (var product in products) ShipAuthoringStore.WriteProduct(cache, visual.Id, product); + cache.FlushAsync().GetAwaiter().GetResult(); + } + Assert.Equal(visual.Id, ShipAuthoringStore.Load(copy).Visual.Id); + } + } + + // The tool that regenerated the shipped packages: a dry run touches nothing, apply keeps every record's content. + [Fact] + public void RegenerateDryRunLeavesTheFileAndApplyKeepsTheContent() + { + using var directory = new TempDirectory(); + var copy = Path.Combine(directory.Path, "ship.cc"); + File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "tests", "fixtures", "mods", "aetheria.wren", "ship.cc"), copy); + var bytes = File.ReadAllBytes(copy); + var (hull, visual, products) = ShipAuthoringStore.Load(copy); + + Assert.Equal(0, ShipAuthoringCommands.Run(new[] { "regenerate", copy })); + Assert.Equal(bytes, File.ReadAllBytes(copy)); + Assert.Equal(0, ShipAuthoringCommands.Run(new[] { "regenerate", copy, "apply" })); + + var (hull2, visual2, products2) = ShipAuthoringStore.Load(copy); + Assert.Equal(ElementIdBlind.Pack(hull), ElementIdBlind.Pack(hull2)); + Assert.Equal(ElementIdBlind.Pack(visual), ElementIdBlind.Pack(visual2)); + Assert.Equal(products.Length, products2.Length); + Assert.Equal(new[] { copy }, Directory.GetFiles(directory.Path).Where(file => !file.EndsWith(".lock")).ToArray()); + } +} diff --git a/tests/Aetheria.Shared.Tests/EmissionTests.cs b/tests/Aetheria.Shared.Tests/EmissionTests.cs index 831f6f520..68ee5854d 100644 --- a/tests/Aetheria.Shared.Tests/EmissionTests.cs +++ b/tests/Aetheria.Shared.Tests/EmissionTests.cs @@ -281,7 +281,7 @@ public sealed partial class ContactRevealTests var reader = new MessagePackReader(sensor); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(5, reader.ReadInt32()); - Assert.Equal(14, reader.ReadArrayHeader()); + Assert.Equal(38, reader.ReadArrayHeader()); for (var slot = 0; slot < 13; slot++) reader.Skip(); Assert.Equal(2f, MessagePackSerializer.Deserialize(ref reader, EmissionWire).Min); Assert.Equal(2f, JObject.Parse(JsonConvert.SerializeObject(new SensorData { InterceptFactor = Const(2) }))["interceptFactor"].ToObject().Min); @@ -291,7 +291,7 @@ public sealed partial class ContactRevealTests reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); reader.Skip(); // the arm's union index - Assert.Equal(37, reader.ReadArrayHeader()); // 35 and 36 are the weapon base's EffectiveRange and DamageAtMaxRange + Assert.Equal(38, reader.ReadArrayHeader()); // 35 and 36 are the weapon base's EffectiveRange and DamageAtMaxRange, 37 the element id for (var slot = 0; slot < 34; slot++) reader.Skip(); Assert.Equal(3f, MessagePackSerializer.Deserialize(ref reader, EmissionWire).Min); Assert.Equal(3f, JObject.Parse(JsonConvert.SerializeObject(new LauncherData { InterceptFactor = Const(3) }))["interceptFactor"].ToObject().Min); diff --git a/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs index 991af3b44..7ec6abaf5 100644 --- a/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs @@ -234,6 +234,7 @@ public sealed class FireControlCut6cTests : IDisposable // Targeting Maker, so IsAvailable rejects Targeting Maker's products by allegiance. var game = new SavedGame { + InfluenceScale = 1, Factions = new[] { maker }, Relationships = new[] { FactionRelationship.Neutral }, HomeZones = new Dictionary { { 0, 0 } }, diff --git a/tests/Aetheria.Shared.Tests/FlightTests.cs b/tests/Aetheria.Shared.Tests/FlightTests.cs index 1cb2f9c48..a50b02d13 100644 --- a/tests/Aetheria.Shared.Tests/FlightTests.cs +++ b/tests/Aetheria.Shared.Tests/FlightTests.cs @@ -941,8 +941,8 @@ public sealed class FlightTests : IDisposable Assert.Equal(turns, turn != 0f); } - // Faction.Doctrine rides at wire slot 17; slot 16 is reserved for Relations; BossLoadout rides at 22, which sets the array's length. - // Kills: the key moved. + // Faction.Relations rides at wire slot 16 and Faction.Doctrine at 17; BossLoadout rides at 22, which sets the array's length. + // Kills: either key moved. [Fact] public void TheFactionDoctrineRidesAtWireSlot17() { @@ -952,11 +952,25 @@ public sealed class FlightTests : IDisposable CultDocumentMessagePackSerialization.OptionsFor(typeof(Faction).Assembly))); Assert.Equal(23, slots.Length); // 19 is Assembly, 21 is Places, 22 is BossLoadout - Assert.Null(slots[16]); + Assert.Empty(Assert.IsAssignableFrom(slots[16])); // 16 is Relations, none authored here var doctrine = Assert.IsType(slots[17]); Assert.Equal(6f, Convert.ToSingle(doctrine[1])); } + // A faction's relations survive the wire with the regarded faction and the stance. Kills: a wrong key or a field the wire leaves out. + [Fact] + public void ARelationsMapRoundTrips() + { + var regarded = new CultRecordRef(new CultRecordKey("faction:regarded")); + var faction = new Faction { Name = "Grudging", Relations = { [regarded] = FactionRelationship.Hated } }; + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(Faction).Assembly); + + var back = MessagePack.MessagePackSerializer.Deserialize(MessagePack.MessagePackSerializer.Serialize(faction, options), options); + + Assert.Equal(FactionRelationship.Hated, Assert.Single(back.Relations).Value); + Assert.Equal(regarded.Key, Assert.Single(back.Relations).Key.Key); + } + // A cast faction that already has a doctrine keeps it, whatever it holds: one that differs in its engagement and one // that differs only below it. Kills: the keep tested on the engagement alone, or on any one field. [Fact] diff --git a/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs new file mode 100644 index 000000000..6d5341ae9 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs @@ -0,0 +1,163 @@ +using System.Collections.Generic; +using System.Linq; +using CultMath; +using Xunit; +using static CultMath.math; + +// Hardpoint gear holds the hardpoint it was seated in across save and reload: an origin two hardpoints accept is +// resolved by the item's saved Rotation (HardpointData.Rotation), not by hardpoint declaration order. +public sealed partial class RunStartTests +{ + // Two disjoint ballistic hardpoints, A (None, cell (6,5)) and B (Reversed, cell (5,5)). The edge gun's single cell is + // (1,0): origin (5,5) puts it at (6,5) unturned and at (5,5) turned 180 degrees, so both hardpoints take it there. + private (HullData hull, HardpointData a, HardpointData b) TwinMountHull(string name) + { + var a = Mount(HardpointType.Ballistic, 6, 5, rotation: ItemRotation.None); + var b = Mount(HardpointType.Ballistic, 5, 5, rotation: ItemRotation.Reversed); + return (ScratchHull(name, 12, a, b), a, b); + } + + [Fact] + public void AnOriginTwoHardpointsAcceptReloadsIntoTheHardpointItHeld() + { + var (hull, _, b) = TwinMountHull("Origin Twin Mounts"); + var filler = ScratchGear("Origin Filler", HardpointType.Ballistic, 1, 1); + var edge = ScratchGear("Origin Edge Gun", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + Assert.True(entity.TryEquip(Instance(filler), int2(6, 5))); + Assert.True(entity.TryEquip(Instance(edge), int2(5, 5))); + var held = entity.Equipment.Single(i => i.Data == edge); + Assert.Same(b, held.Hardpoint); + Assert.Equal(ItemRotation.Reversed, held.EquippableItem.Rotation); + // Un-equip the filler as a player would, then save and reload. + entity.TryUnequip(entity.Equipment.Single(i => i.Data == filler)); + + var reloaded = EntitySerializer.Unpack(_items, null, EntitySerializer.Pack(entity)); + var after = reloaded.Equipment.Single(i => i.Data == edge); + Assert.Equal(1, reloaded.HullData.Hardpoints.IndexOf(after.Hardpoint)); + } + + [Fact] + public void ReloadKeepsTheFirstHardpointToo() + { + var (hull, _, _) = TwinMountHull("Origin Twin Mounts First"); + var edge = ScratchGear("Origin Edge Gun First", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + Assert.True(entity.TryEquip(Instance(edge), int2(5, 5))); + Assert.Equal(ItemRotation.None, entity.Equipment.Single(i => i.Data == edge).EquippableItem.Rotation); + + var reloaded = EntitySerializer.Unpack(_items, null, EntitySerializer.Pack(entity)); + var after = reloaded.Equipment.Single(i => i.Data == edge); + Assert.Equal(0, reloaded.HullData.Hardpoints.IndexOf(after.Hardpoint)); + } + + [Fact] + public void AnItemWhoseRotationNamesNoAcceptingHardpointStillSeats() + { + var (hull, a, _) = TwinMountHull("Origin Twin Mounts Stray"); + var edge = ScratchGear("Origin Edge Gun Stray", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + var item = Instance(edge); + item.Rotation = ItemRotation.Clockwise; + Assert.True(entity.ItemFits(item, int2(5, 5))); + Assert.True(entity.TryEquip(item, int2(5, 5))); + var held = entity.Equipment.Single(i => i.Data == edge); + Assert.Same(a, held.Hardpoint); + Assert.Equal(ItemRotation.None, held.EquippableItem.Rotation); + } + + // A probe reports; only TryEquip seats. The probe used to turn the item to the hardpoint it found, so the same item + // probed twice could resolve differently, and a failed or merely previewed placement left it turned. + [Fact] + public void AProbeLeavesTheItemsRotationAlone() + { + var (hull, a, b) = TwinMountHull("Origin Twin Mounts Probe"); + var edge = ScratchGear("Origin Edge Gun Probe", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + var item = Instance(edge); + item.Rotation = ItemRotation.Clockwise; + + Assert.True(entity.ItemFits(item, int2(5, 5))); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + Assert.True(entity.ItemFits(item, int2(5, 5), out var seated)); + Assert.Equal(ItemRotation.None, seated); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + Assert.True(entity.TryFindSpace(item, out _)); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + Assert.False(entity.ItemFits(item, int2(0, 0), out var unseated)); + Assert.Equal(ItemRotation.Clockwise, unseated); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + + Assert.True(entity.TryEquip(item, int2(5, 5))); + var held = entity.Equipment.Single(i => i.Data == edge); + Assert.Same(a, held.Hardpoint); + Assert.Equal(ItemRotation.None, held.EquippableItem.Rotation); + + var reversed = Instance(edge); + reversed.Rotation = ItemRotation.Reversed; + var fresh = BareHull(hull); + Assert.True(fresh.ItemFits(reversed, int2(5, 5), out var first)); + Assert.True(fresh.ItemFits(reversed, int2(5, 5), out var second)); + Assert.Equal(ItemRotation.Reversed, first); + Assert.Equal(first, second); + Assert.Equal(b.Rotation, first); + } + + // A deployed entity takes no gear, so no probe reports a fit or a seat on one (the out overload's own guard). + // Kills: a probe that ignores the deployed state and offers a placement TryEquip would then refuse. + [Fact] + public void ADeployedEntityTakesNoProbe() + { + var (hull, _, _) = TwinMountHull("Origin Twin Mounts Deployed"); + var edge = ScratchGear("Origin Edge Gun Deployed", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + var item = Instance(edge); + item.Rotation = ItemRotation.Clockwise; + Assert.True(entity.ItemFits(item, int2(5, 5), out _)); + + var zone = Arena(false); + entity.Zone = zone; + zone.Admit(entity, piloted: false); + Assert.False(entity.ItemFits(item, int2(5, 5), out var seated)); + Assert.Equal(ItemRotation.Clockwise, seated); + Assert.False(entity.ItemFits(item, int2(5, 5))); + Assert.False(entity.TryEquip(item, int2(5, 5))); + } +} + +// The shipped catalog authors no origin that two differently turned hardpoints of one type both take. The fit rule alone +// over-approximates what Entity.HardpointAt sees (occupancy only removes candidates), so zero here is stricter than needed. +public sealed class ShippedHardpointOriginTests +{ + [Fact] + public void TheShippedCatalogHasNoAmbiguousOrigin() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var designs = cache.GetAll().Where(d => !(d is HullData) && d.HardpointType != HardpointType.Tool).ToArray(); + var ambiguous = new List(); + var pairs = 0; + var probes = 0; + foreach (var hull in cache.GetAll()) + for (var i = 0; i < hull.Hardpoints.Count; i++) + for (var j = i + 1; j < hull.Hardpoints.Count; j++) + { + var a = hull.Hardpoints[i]; + var b = hull.Hardpoints[j]; + if (a.Type != b.Type || a.Rotation == b.Rotation) continue; + pairs++; + foreach (var design in designs.Where(d => d.HardpointType == a.Type)) + for (var x = -20; x < hull.Shape.Width; x++) + for (var y = -20; y < hull.Shape.Height; y++) + { + var origin = int2(x, y); + probes++; + if (a.TakesAt(design, origin - a.Position) && b.TakesAt(design, origin - b.Position)) + ambiguous.Add($"{hull.Name} {design.Name} at ({x},{y}): hardpoints {i} and {j}"); + } + } + System.Console.WriteLine($"ShippedHardpointOriginTests visited {pairs} same-type different-rotation pairs"); + // A scan that visits nothing would pass; the catalog has such pairs today, so losing them must fail loudly. + Assert.True(pairs > 0 && probes > 0, $"the scan visited {pairs} pairs and {probes} origins"); + Assert.True(ambiguous.Count == 0, $"{ambiguous.Count} ambiguous origins: " + string.Join("; ", ambiguous.Take(10))); + } +} diff --git a/tests/Aetheria.Shared.Tests/HardpointOwnershipTests.cs b/tests/Aetheria.Shared.Tests/HardpointOwnershipTests.cs index 2b8fa2270..1ddc1d10b 100644 --- a/tests/Aetheria.Shared.Tests/HardpointOwnershipTests.cs +++ b/tests/Aetheria.Shared.Tests/HardpointOwnershipTests.cs @@ -142,6 +142,65 @@ public sealed partial class RunStartTests Assert.Null(entity.EquippedHull.Hardpoint); } + private static Shape Bar(int width) + { + var bar = new Shape(width, 1); + foreach (var cell in bar.AllCoordinates) bar[cell] = true; + return bar; + } + + // Scenarios batch-4 minor: dragging an equipped gun within its own hardpoint. The UI asks ItemFits about the dragged + // item at its current and nudged origin, then TryUnequip and TryEquip at the target. The gun's own cells are not + // occupied against itself, so the nudge that overlaps its current cells is accepted and the sequence lands there. + [Fact] + public void AnEquippedGunCanBeMovedWithinItsOwnHardpoint() + { + var hull = ScratchHull("Minor Drag Mount", 9, Mount(HardpointType.Ballistic, 1, 1, Bar(3))); + var gun = ScratchGear("Minor Drag Gun", HardpointType.Ballistic, Bar(2)); + var entity = BareHull(hull); + var unit = Instance(gun); + Assert.True(entity.TryEquip(unit, int2(1, 1))); + var equipped = entity.Equipment.Single(i => i.Data == gun); + + Assert.True(entity.ItemFits(unit, int2(1, 1)), "its current origin"); + Assert.True(entity.ItemFits(unit, int2(2, 1)), "nudged one cell, overlapping its own cells"); + + Assert.NotNull(entity.TryUnequip(equipped)); + Assert.True(entity.TryEquip(unit, int2(2, 1))); + Assert.Equal(int2(2, 1), entity.Equipment.Single(i => i.Data == gun).Position); + Assert.Same(hull.Hardpoints[0], entity.Equipment.Single(i => i.Data == gun).Hardpoint); + } + + // Ignoring the item's own cells does not ignore anyone else's: a second hardpoint item cannot share the hardpoint, + // and TryEquip never treats an item as its own occupant, so equipping an equipped item again is refused. + [Fact] + public void MovingAnEquippedItemStillRespectsOtherOccupantsAndTryEquipStaysStrict() + { + var hull = ScratchHull("Minor Drag Strict", 9, Mount(HardpointType.Ballistic, 1, 1, Bar(4))); + var gun = ScratchGear("Minor Strict Gun", HardpointType.Ballistic, Bar(2)); + var other = ScratchGear("Minor Strict Other", HardpointType.Ballistic, Bar(1)); + var entity = BareHull(hull); + var unit = Instance(gun); + Assert.True(entity.TryEquip(unit, int2(1, 1))); + Assert.False(entity.TryEquip(Instance(other), int2(3, 1)), "the hardpoint holds one hardpoint item"); + Assert.False(entity.TryEquip(unit, int2(2, 1)), "TryEquip is strict: no duplicate of an equipped item"); + Assert.Single(entity.Equipment, i => i.Data == gun); + } + + // A tool dragged within its own cells is judged the same way. + [Fact] + public void AnEquippedToolCanBeMovedOverItsOwnCells() + { + var hull = ScratchHull("Minor Drag Tool Hull", 9); + var tool = ScratchGear("Minor Drag Tool", HardpointType.Tool, Bar(2)); + var entity = BareHull(hull); + var unit = Instance(tool); + Assert.True(entity.TryEquip(unit, int2(1, 1))); + Assert.True(entity.ItemFits(unit, int2(2, 1)), "nudged over its own cell"); + Assert.False(entity.TryEquip(unit, int2(2, 1)), "TryEquip never sees an item as its own occupant"); + Assert.Single(entity.Equipment, i => i.Data == tool); + } + // The design's cells, turned to a rotation, moved so the lowest x and y are zero. Written here from the cells alone // (the game's turn directions, up to translation), so it is not Shape.Rotate checking itself. private static HashSet<(int x, int y)> Normalized(IEnumerable cells, ItemRotation rotation) diff --git a/tests/Aetheria.Shared.Tests/HaulFeedTests.cs b/tests/Aetheria.Shared.Tests/HaulFeedTests.cs new file mode 100644 index 000000000..34eb8a3db --- /dev/null +++ b/tests/Aetheria.Shared.Tests/HaulFeedTests.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using GameCult.Caching; +using UniRx; +using Xunit; + +// Zone.CargoGained and HaulFeed (aetheria-release mining 6): Extract and TryPickUp publish what entered a hold, once; the feed +// words it and counts the hold. Fixtures are Mining Cut 5a's rig. +public sealed class HaulFeedTests : IDisposable +{ + private readonly MiningCut5aTests _five = new MiningCut5aTests(); + private readonly MiningCut4bTests _rigs = new MiningCut4bTests(); + + public void Dispose() + { + _five.Dispose(); + _rigs.Dispose(); + } + + // The 5a rig: a rock of 4 units, the shooter holding one bay of the given size; the event log records every gain. + private (MiningCut4bTests.Rig Rig, EquippedCargoBay Bay, List Gains) Mining(int w, int h, params (SimpleCommodityData, float)[] ores) + { + var kind = MiningCut3Tests.Kind("Asteroid", 20f); + var rig = _rigs.Build(damage: 1000f, fuse: null, blastRadius: 0f, precision: 1000f, rockSize: .5f, velocity: 0f, kind: kind, galaxySeed: 0); + MiningCut5aTests.Stock(rig.Scene, kind, ores); + var bay = MiningCut5aTests.Bay(rig.Scene, rig.Shooter, w, h, "Hold"); + var gains = new List(); + rig.Zone.CargoGained.Subscribe(gains.Add); + return (rig, bay, gains); + } + + private static CultMath.Random Dice(MiningCut4bTests.Rig rig, uint n) => SimulationDice.For(rig.Zone.DropSeed, SimulationDice.OreStream, n); + + private static void Break(MiningCut4bTests.Rig rig) + { + for (var shot = 0; shot < 40 && rig.Zone.ChunkExists(rig.Rock); shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + MiningCut4bTests.Run(rig, .05f); + } + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + } + + [Fact] + public void AnExtractionPublishesWhatWasStoredAndWhatFloated() + { + // Room for everything. + var (rig, bay, gains) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + Break(rig); + var gain = Assert.Single(gains); + Assert.Equal((GainKind.Mined, 4, 0), (gain.Kind, gain.Stored, gain.Adrift)); + Assert.Same(rig.Shooter, gain.Taker); + Assert.Equal(4, MiningCut5aTests.Units(bay, "Rock", rig.Scene)); + Assert.NotEqual(0, gain.Lot); + + // A full hold: everything floats. + var (full, fullBay, fullGains) = Mining(1, 1, (MiningCut5aTests.Commodity("Grit", maxStack: 1), 1f)); + Assert.True(fullBay.TryStore(new SimpleCommodity { Data = full.Scene.Cache.RefOf(full.Scene.Cache.GetByName("Grit")), Quantity = 1 })); + Break(full); + var overflow = Assert.Single(fullGains); + Assert.Equal((0, 4), (overflow.Stored, overflow.Adrift)); + Assert.Equal(4, MiningCut5aTests.Units(full.Zone.FloatingItems.Select(f => f.Item), "Grit", full.Scene)); + + // A partial store: the hold takes two of four. + var (part, partBay, partGains) = Mining(1, 1, (MiningCut5aTests.Commodity("Grit", maxStack: 2), 1f)); + Break(part); + var split = Assert.Single(partGains); + Assert.Equal((2, 2), (split.Stored, split.Adrift)); + Assert.Equal(2, MiningCut5aTests.Units(partBay, "Grit", part.Scene)); + Assert.Equal(2, MiningCut5aTests.Units(part.Zone.FloatingItems.Select(f => f.Item), "Grit", part.Scene)); + } + + [Fact] + public void AGoneShooterPublishesEverythingAdrift() + { + var (rig, _, gains) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + rig.Shooter.HeatstrokeDeath.OnNext(UniRx.Unit.Default); + var at = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + FireControl.Extract(rig.Zone, rig.Rock, rig.Zone.Wear(rig.Rock, 1e6f), rig.Shooter, Dice(rig, 1)); + var gain = Assert.Single(gains); + Assert.Equal((0, 4), (gain.Stored, gain.Adrift)); + } + + [Fact] + public void AMineAndANullShooterPublishNothing() + { + var (rig, _, gains) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + FireControl.Extract(rig.Zone, rig.Rock, rig.Zone.Wear(rig.Rock, 1e6f), null, Dice(rig, 1)); + Assert.Empty(gains); + Assert.Empty(rig.Zone.FloatingItems); + } + + [Fact] + public void AMergeIntoAnExistingStackStillPublishes() + { + var (rig, bay, gains) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + var chunk = rig.Rock; + FireControl.Extract(rig.Zone, chunk, rig.Zone.Wear(chunk, 1e6f), rig.Shooter, Dice(rig, 1)); + var keys = bay.Cargo.Keys.ToArray(); + // Same rock field and index, same ore, so the same lot: the second extraction merges and writes no Cargo key. + FireControl.Extract(rig.Zone, chunk, 40f, rig.Shooter, Dice(rig, 2)); + Assert.Equal(keys, bay.Cargo.Keys.ToArray()); + Assert.Equal(2, gains.Count); + Assert.Equal(gains[0].Lot, gains[1].Lot); + Assert.True(gains[1].Stored > 0); + } + + [Fact] + public void EveryOreOfOneExtractionPublishesOnce() + { + var (rig, _, gains) = Mining(8, 8, (MiningCut5aTests.Commodity("Rock"), 1f), (MiningCut5aTests.Commodity("Gold"), 1f)); + rig.Zone.Settings.AsteroidYield = new ExponentialLerp { Minimum = 400f, Maximum = 400f, Exponent = 1f }; + FireControl.Extract(rig.Zone, rig.Rock, rig.Zone.Wear(rig.Rock, 1e6f), rig.Shooter, Dice(rig, 3)); + Assert.Equal(2, gains.Count); + Assert.Equal(2, gains.Select(g => g.Lot).Distinct().Count()); + Assert.All(gains, g => Assert.True(g.Stored + g.Adrift > 0)); + } + + [Fact] + public void APickupPublishesCollected() + { + var grit = MiningCut5aTests.Commodity("Grit", maxStack: 2); + var (rig, _, gains) = Mining(1, 1, (grit, 1f)); + Break(rig); + gains.Clear(); + var floating = rig.Zone.FloatingItems.First(); + var quantity = ((SimpleCommodity) floating.Item).Quantity; + + // A taker with no room is refused and publishes nothing. + var packed = new Ship(rig.Scene.Items, rig.Zone, MiningCut3Tests.Mint(rig.Scene, rig.Scene.Hull), new EntitySettings()); + rig.Zone.Admit(packed, piloted: false); + Assert.False(rig.Zone.TryPickUp(packed, floating.Id)); + Assert.Empty(gains); + + var taker = new Ship(rig.Scene.Items, rig.Zone, MiningCut3Tests.Mint(rig.Scene, rig.Scene.Hull), new EntitySettings()); + rig.Zone.Admit(taker, piloted: false); + MiningCut5aTests.Bay(rig.Scene, taker, 4, 4, "Taker"); + Assert.True(rig.Zone.TryPickUp(taker, floating.Id)); + var gain = Assert.Single(gains); + Assert.Equal((GainKind.Collected, quantity, 0), (gain.Kind, gain.Stored, gain.Adrift)); + Assert.Same(taker, gain.Taker); + } + + [Fact] + public void APickupThatMergesAndSpillsReportsTheWholeStack() + { + var grit = MiningCut5aTests.Commodity("Grit", maxStack: 4); + var (rig, _, gains) = Mining(1, 1, (grit, 1f)); + var taker = new Ship(rig.Scene.Items, rig.Zone, MiningCut3Tests.Mint(rig.Scene, rig.Scene.Hull), new EntitySettings()); + rig.Zone.Admit(taker, piloted: false); + var bay = MiningCut5aTests.Bay(rig.Scene, taker, 2, 1, "Taker"); + var design = rig.Scene.Cache.RefOf(grit); + Assert.True(bay.TryStore(new SimpleCommodity { Data = design, Lot = 7, Quantity = 3 })); + gains.Clear(); + var floating = rig.Zone.Release(new SimpleCommodity { Data = design, Lot = 7, Quantity = 4 }, new float2(0, 0), new float2(0, 0)); + Assert.True(rig.Zone.TryPickUp(taker, floating.Id)); + Assert.Equal(7, MiningCut5aTests.Units(bay, "Grit", rig.Scene)); + Assert.Equal((GainKind.Collected, 4, 0), (Assert.Single(gains).Kind, gains[0].Stored, gains[0].Adrift)); + } + + [Fact] + public void TheLineNamesWhatWasTakenAndWhatFloated() + { + var (rig, bay, _) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + var items = rig.Scene.Items; + var design = rig.Scene.Cache.RefOf(rig.Scene.Cache.GetByName("Rock")); + var fill = HaulFeed.HoldFill(rig.Shooter.CargoBays); + var hold = $"hold {fill.used}/{fill.total}"; + + var clean = HaulFeed.Line(new CargoGain { Taker = rig.Shooter, Design = design, Stored = 3, Kind = GainKind.Mined }, items); + Assert.Contains("3", clean); + Assert.Contains("Rock", clean); + Assert.Contains(hold, clean); + Assert.DoesNotContain("adrift", clean); + + var spill = HaulFeed.Line(new CargoGain { Taker = rig.Shooter, Design = design, Stored = 1, Adrift = 2, Kind = GainKind.Mined }, items); + Assert.Contains("2 adrift", spill); + Assert.Contains("Rock", spill); + var collected = HaulFeed.Line(new CargoGain { Taker = rig.Shooter, Design = design, Stored = 2, Kind = GainKind.Collected }, items); + Assert.DoesNotContain("adrift", collected); + Assert.Contains("Collected 2", collected); + Assert.Contains(hold, collected); + } + + [Fact] + public void HoldFillCountsOccupiedCellsAcrossBays() + { + var (rig, bay, _) = Mining(2, 2, (MiningCut5aTests.Commodity("Rock"), 1f)); + var second = MiningCut5aTests.Bay(rig.Scene, rig.Shooter, 3, 1, "Aft"); + Assert.Equal((0, 7), HaulFeed.HoldFill(new[] { bay, second })); + var rock = rig.Scene.Cache.GetByName("Rock"); + Assert.True(bay.TryStore(new SimpleCommodity { Data = rig.Scene.Cache.RefOf(rock), Quantity = 1 })); + Assert.True(second.TryStore(new SimpleCommodity { Data = rig.Scene.Cache.RefOf(rock), Quantity = 1 })); + Assert.Equal((2, 7), HaulFeed.HoldFill(new[] { bay, second })); + } +} diff --git a/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs b/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs index b2a01e356..2d44b8ebb 100644 --- a/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs +++ b/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs @@ -444,4 +444,112 @@ public sealed class IffAndCombatTests : IDisposable Assert.Empty(eligible); } + + // Two cached factions (Relations are read through the catalog's keys), with A regarding B as given when it is given, and a + // ship of each in the world's one ownerless zone. + private (Ship a, Ship b) Rivals(ItemManager items, Zone zone, FactionRelationship? aRegardsB) + { + var a = new Faction { Name = "A" }; + var b = new Faction { Name = "B" }; + items.ItemData.Upsert(a); + var bRef = items.ItemData.Upsert(b); + if (aRegardsB.HasValue) + { + a.Relations[bRef] = aRegardsB.Value; + items.ItemData.Upsert(a); + } + return (NewShip(items, zone, a), NewShip(items, zone, b)); + } + + // Hated is kill on sight in any zone, owned or not, once the claim is received with the track; it is directed, so B's stance + // toward A reads B's map. Kills: no Hated branch; reading the regarded side's map. + [Fact] + public void HatedIsKillOnSightInAnOwnerlessZone() + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, FactionRelationship.Hated); + + Assert.False(a.IsHostileTo(b)); // untracked: no claim to hate + + Detect(a, b); + Detect(b, a); + + Assert.True(a.IsHostileTo(b)); + Assert.True(a.EntityHostility[b]); + Assert.False(b.IsHostileTo(a)); + Assert.False(b.EntityHostility[a]); + } + + // The ladder below Hated governs presence in owned space, not fire. Kills: treating Hostile or worse as kill on sight. + [Theory] + [InlineData(FactionRelationship.Hostile)] + [InlineData(FactionRelationship.Neutral)] + [InlineData(FactionRelationship.Beloved)] + public void ARelationShortOfHatedIsNotKillOnSight(FactionRelationship relationship) + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, relationship); + + Detect(a, b); + Detect(b, a); + + Assert.False(a.IsHostileTo(b)); + Assert.False(b.IsHostileTo(a)); + } + + // An IFF override is the observer's own word and outranks what its faction holds. Kills: the relation branch placed before the override. + [Fact] + public void AnOverrideOutranksARelation() + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, FactionRelationship.Hated); + Detect(a, b); + Assert.True(a.IsHostileTo(b)); + + a.SetIff(b, false); + + Assert.False(a.IsHostileTo(b)); + Assert.False(a.EntityHostility[b]); + } + + // A faction the catalog does not hold has no key, so it is regarded Neutral and nothing throws. Kills: RefOf in the lookup. + [Fact] + public void AFactionOutsideTheCacheIsRegardedNeutral() + { + var (items, zone) = BuildWorld(); + var a = new Faction { Name = "A" }; + items.ItemData.Upsert(a); + a.Relations[items.ItemData.Upsert(new Faction { Name = "Elsewhere" })] = FactionRelationship.Hated; + items.ItemData.Upsert(a); + var ship = NewShip(items, zone, a); + var stranger = NewShip(items, zone, new Faction { Name = "Stranger" }); + + Detect(ship, stranger); + + Assert.False(ship.IsHostileTo(stranger)); + } + + // Stance follows the faction the contact claimed when it was tracked, not the faction it flies now. Kills: reading other.Faction + // instead of the telemetry claim. + [Fact] + public void StanceFollowsTheClaimNotTheLiveFaction() + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, FactionRelationship.Hated); + var other = new Faction { Name = "C" }; + items.ItemData.Upsert(other); + var neutral = NewShip(items, zone, other); + + Detect(a, b); + Detect(a, neutral); + Assert.True(a.IsHostileTo(b)); + Assert.False(a.IsHostileTo(neutral)); + + var hated = b.Faction; + b.Faction = other; // each keeps what it claimed when tracked, until it is claimed again + neutral.Faction = hated; + + Assert.True(a.IsHostileTo(b)); + Assert.False(a.IsHostileTo(neutral)); + } } diff --git a/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs b/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs index e2d453f51..8dbc47873 100644 --- a/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs @@ -22,7 +22,7 @@ public sealed class InspectionScannerCommandTests : IDisposable private readonly string[] _shippedProducts; private static byte[] Pack(GearData design) => - MessagePackSerializer.Serialize(design, CultDocumentMessagePackSerialization.OptionsFor(typeof(GearData).Assembly)); + ElementIdBlind.Pack(design, typeof(GearData)); private static string Describe(CultCache cache, FactionProductData product) => $"{cache.Get(product.Design).Name} | {product.Name} | {cache.Get(product.Manufacturer).ShortName} | {product.Description} | " + diff --git a/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs b/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs index 90c1d3873..47cc9a29e 100644 --- a/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs @@ -22,7 +22,7 @@ public sealed class LaunchSuppressorCommandTests : IDisposable private readonly string[] _shippedProducts; private static byte[] Pack(GearData design) => - MessagePackSerializer.Serialize(design, CultDocumentMessagePackSerialization.OptionsFor(typeof(GearData).Assembly)); + ElementIdBlind.Pack(design, typeof(GearData)); private static string Describe(CultCache cache, FactionProductData product) => $"{cache.Get(product.Design).Name} | {product.Name} | {cache.Get(product.Manufacturer).ShortName} | {product.Description} | " + diff --git a/tests/Aetheria.Shared.Tests/LaunchSuppressorTests.cs b/tests/Aetheria.Shared.Tests/LaunchSuppressorTests.cs index eb2ed3ab8..d3dd3ae03 100644 --- a/tests/Aetheria.Shared.Tests/LaunchSuppressorTests.cs +++ b/tests/Aetheria.Shared.Tests/LaunchSuppressorTests.cs @@ -299,7 +299,7 @@ public sealed partial class ContactRevealTests var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(49, reader.ReadInt32()); // loot-2 holds 48; a key reused across branches would collide on the wire - Assert.Equal(4, reader.ReadArrayHeader()); // Group is key 0, then the three stats + Assert.Equal(38, reader.ReadArrayHeader()); // array-format union: the base's element id sits at key 37, so every behavior row is 38 long; Group is key 0, then the three stats var back = Assert.IsType(MessagePackSerializer.Deserialize(bytes, options)); Assert.Equal(.25f, back.Factor.Min); diff --git a/tests/Aetheria.Shared.Tests/ListenerTests.cs b/tests/Aetheria.Shared.Tests/ListenerTests.cs index 9fe4abf81..1bf1059ae 100644 --- a/tests/Aetheria.Shared.Tests/ListenerTests.cs +++ b/tests/Aetheria.Shared.Tests/ListenerTests.cs @@ -203,7 +203,7 @@ public sealed partial class ContactRevealTests var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(50, reader.ReadInt32()); - Assert.Equal(2, reader.ReadArrayHeader()); // Group is key 0, then Multiple + Assert.Equal(38, reader.ReadArrayHeader()); // array-format union: the base's element id sits at key 37, so every behavior row is 38 long; Group is key 0, then Multiple var back = Assert.IsType(MessagePackSerializer.Deserialize(bytes, options)); Assert.Equal(2.5f, back.Multiple.Min); diff --git a/tests/Aetheria.Shared.Tests/LoadoutTests.cs b/tests/Aetheria.Shared.Tests/LoadoutTests.cs index 3697d7345..4a114637e 100644 --- a/tests/Aetheria.Shared.Tests/LoadoutTests.cs +++ b/tests/Aetheria.Shared.Tests/LoadoutTests.cs @@ -494,6 +494,7 @@ public sealed class LoadoutTests : IDisposable var game = new SavedGame { + InfluenceScale = 1, Factions = Array.Empty>(), Relationships = Array.Empty(), HomeZones = new Dictionary(), diff --git a/tests/Aetheria.Shared.Tests/MiningCut2Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut2Tests.cs index 54fc99972..7716e3c9a 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut2Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut2Tests.cs @@ -134,9 +134,9 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); // Several partial hits under the threshold: still there, still shrinking. - Assert.False(f.Zone.Wear(chunk, hp * 0.3f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.3f)); Assert.True(f.Zone.ChunkExists(chunk)); - Assert.False(f.Zone.Wear(chunk, hp * 0.3f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.3f)); Assert.True(f.Zone.ChunkExists(chunk)); var before = f.Zone.ChunkRadius(chunk); @@ -147,11 +147,11 @@ public sealed class MiningCut2Tests : IDisposable // break condition as strictly greater-than, not greater-or-equal (today's behaviour, kept deliberately // -- see Zone.Wear's own comment). Equal-to-hitpoints must not break the chunk. var remaining = hp - hp * 0.6f; - Assert.False(f.Zone.Wear(chunk, remaining)); + Assert.False(f.Zone.Breaks(chunk, remaining)); Assert.True(f.Zone.ChunkExists(chunk), "damage exactly equal to hitpoints must not break the chunk"); // One more point of damage tips it over. - Assert.True(f.Zone.Wear(chunk, 0.01f)); + Assert.True(f.Zone.Breaks(chunk, 0.01f)); Assert.False(f.Zone.ChunkExists(chunk)); Assert.Equal(0f, f.Zone.ChunkRadius(chunk)); } @@ -165,7 +165,7 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); Assert.False(f.Zone.ChunkExists(chunk)); // Uneven steps that sum to just under the authored respawn time: still broken. @@ -188,13 +188,13 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsB[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsB[index].Size); - Assert.True(f.Zone.Wear(chunk, hp * 1.5f)); + Assert.True(f.Zone.Breaks(chunk, hp * 1.5f)); f.Zone.Update(respawn + 1f); Assert.True(f.Zone.ChunkExists(chunk)); // A hit well under hitpoints, on the freshly respawned chunk, must not break it -- if the old damage // (or the old broken state) leaked through, this hit alone would already be over any stale threshold. - Assert.False(f.Zone.Wear(chunk, hp * 0.4f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.4f)); Assert.True(f.Zone.ChunkExists(chunk)); var radius = f.Zone.ChunkRadius(chunk); Assert.True(radius > 0f && radius < f.Zone.AsteroidBelts[f.BeltB].UndamagedSize(index, f.Settings)); @@ -211,7 +211,7 @@ public sealed class MiningCut2Tests : IDisposable var chunkA1 = new ChunkId(f.BeltA, 1); var hpA0 = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[0].Size); - Assert.True(f.Zone.Wear(chunkA0, hpA0 + 1f)); + Assert.True(f.Zone.Breaks(chunkA0, hpA0 + 1f)); Assert.False(f.Zone.ChunkExists(chunkA0)); Assert.True(f.Zone.ChunkExists(chunkB0), "a different field at the same index must be unaffected"); @@ -230,8 +230,8 @@ public sealed class MiningCut2Tests : IDisposable var hpDamaged = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[4].Size); var hpBroken = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsB[3].Size); - Assert.False(f.Zone.Wear(damaged, hpDamaged * 0.45f)); - Assert.True(f.Zone.Wear(broken, hpBroken + 5f)); + Assert.False(f.Zone.Breaks(damaged, hpDamaged * 0.45f)); + Assert.True(f.Zone.Breaks(broken, hpBroken + 5f)); f.Zone.Update(1.3f); var damagedRadiusBefore = f.Zone.ChunkRadius(damaged); @@ -255,7 +255,7 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[6].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[6].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn + 2f); Assert.True(f.Zone.ChunkExists(chunk), "sanity: this chunk must have respawned before packing"); @@ -333,20 +333,20 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); Assert.False(f.Zone.ChunkExists(chunk)); // A hit well under hitpoints, inside the respawn window: must not break it (it is already broken) and // must not touch BrokenUntil. f.Zone.Update(respawn * 0.2f); - Assert.False(f.Zone.Wear(chunk, hp * 0.1f), "a hit on an already-broken chunk did not break it"); + Assert.False(f.Zone.Breaks(chunk, hp * 0.1f), "a hit on an already-broken chunk did not break it"); Assert.False(f.Zone.ChunkExists(chunk), "must still be absent -- the old bug un-broke it here"); Assert.Equal(0f, f.Zone.ChunkRadius(chunk)); // A second hit, this one alone well over hitpoints, inside the same window: still must not break it // (it is already broken) and must not push BrokenUntil further out. f.Zone.Update(respawn * 0.3f); - Assert.False(f.Zone.Wear(chunk, hp + 50f), "a hit on an already-broken chunk did not break it, even when large"); + Assert.False(f.Zone.Breaks(chunk, hp + 50f), "a hit on an already-broken chunk did not break it, even when large"); Assert.False(f.Zone.ChunkExists(chunk)); // Just under the original respawn time (measured from the original break, not from either re-hit): @@ -360,9 +360,9 @@ public sealed class MiningCut2Tests : IDisposable Assert.Equal(f.Zone.AsteroidBelts[f.BeltA].UndamagedSize(index, f.Settings), f.Zone.ChunkRadius(chunk), 4); // Worn again from fresh: breaks on the normal threshold, not one warped by the earlier no-op hits. - Assert.False(f.Zone.Wear(chunk, hp * 0.9f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.9f)); Assert.True(f.Zone.ChunkExists(chunk)); - Assert.True(f.Zone.Wear(chunk, hp * 0.2f)); + Assert.True(f.Zone.Breaks(chunk, hp * 0.2f)); Assert.False(f.Zone.ChunkExists(chunk)); } @@ -377,9 +377,9 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsB[idx].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsB[idx].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn * 0.4f); - Assert.False(f.Zone.Wear(chunk, hp * 0.5f), "re-hit inside the window did not break an already-broken chunk"); + Assert.False(f.Zone.Breaks(chunk, hp * 0.5f), "re-hit inside the window did not break an already-broken chunk"); var pack = f.Zone.PackZone(); var reloaded = new Zone(f.Items, f.Settings, pack, new GalaxyZone { Name = "MiningCut2ReHitReload", Owner = null }, null); @@ -424,7 +424,7 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn); // zone time now equals BrokenUntil exactly, not "respawn plus a margin". Assert.True(f.Zone.ChunkExists(chunk), "must read as respawned the instant zone time reaches BrokenUntil, not strictly after it"); @@ -458,11 +458,11 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn); Assert.True(f.Zone.ChunkExists(chunk)); - Assert.True(f.Zone.Wear(chunk, hp + 1f), "a hit on the instant of respawn breaks the respawned chunk again"); + Assert.True(f.Zone.Breaks(chunk, hp + 1f), "a hit on the instant of respawn breaks the respawned chunk again"); Assert.False(f.Zone.ChunkExists(chunk)); } @@ -477,9 +477,9 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn + 1f); - Assert.False(f.Zone.Wear(chunk, hp * 0.3f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.3f)); var packed = f.Zone.PackZone().ChunkWear.Find(w => w.Field.Equals(chunk.Field) && w.Index == index); Assert.NotNull(packed); @@ -501,12 +501,12 @@ public sealed class MiningCut2Tests : IDisposable var undamaged = f.Zone.ChunkPose(f.BeltA, index).w; Assert.Equal(f.Zone.AsteroidBelts[f.BeltA].UndamagedSize(index, f.Settings), undamaged, 4); - Assert.False(f.Zone.Wear(chunk, hp * 0.6f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.6f)); var worn = f.Zone.ChunkPose(f.BeltA, index).w; Assert.Equal(f.Zone.ChunkRadius(chunk), worn, 4); Assert.True(worn < undamaged, "a worn chunk is smaller than an untouched one"); - Assert.True(f.Zone.Wear(chunk, hp)); + Assert.True(f.Zone.Breaks(chunk, hp)); Assert.Equal(0f, f.Zone.ChunkPose(f.BeltA, index).w); } } @@ -520,3 +520,15 @@ internal static class MiningCut2TestExtensions return list; } } + +internal static class ChunkWearTestExtensions +{ + // Wears the chunk and reports whether that hit broke it: Zone.Wear returns the damage absorbed, and a break is + // ChunkExists going from true to false. + public static bool Breaks(this Zone zone, ChunkId chunk, float damage) + { + var there = zone.ChunkExists(chunk); + zone.Wear(chunk, damage); + return there && !zone.ChunkExists(chunk); + } +} diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index 5ac322c01..5051a3b8d 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -24,6 +24,9 @@ public sealed partial class MiningCut3Tests : IDisposable private readonly List _caches = new List(); private int _fixtureCount; + // A run seed for the scenes built next: nonzero gives the zone a galaxy carrying it (so Zone.DropSeed differs by it). + internal uint GalaxySeed; + public MiningCut3Tests() => Directory.CreateDirectory(_root); public void Dispose() @@ -32,7 +35,7 @@ public sealed partial class MiningCut3Tests : IDisposable Directory.Delete(_root, true); } - private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + internal static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; private static GameplaySettings GameSettings() => new GameplaySettings { @@ -49,13 +52,15 @@ public sealed partial class MiningCut3Tests : IDisposable // Every sun carries a well (the belts circle in it, c = 9), one sun whose light reaches 1000 units, and the chunk // curves MiningCut2Tests uses, so sizes and wear vary over the fixture's range. - private static PlanetSettings PlanetSettings(float lightRadius = 1000f) => new PlanetSettings + internal static PlanetSettings PlanetSettings(float lightRadius = 1000f) => new PlanetSettings { WellStrength = new ExponentialCurve { Constant = 9f }, RocheLimit = new ExponentialCurve { Constant = 1f }, AsteroidSize = new ExponentialLerp { Minimum = 2f, Maximum = 9f, Exponent = 1.7f }, AsteroidHitpoints = new ExponentialLerp { Minimum = 20f, Maximum = 220f, Exponent = 1.6f }, AsteroidRespawnTime = new ExponentialLerp { Minimum = 8f, Maximum = 96f, Exponent = 1.2f }, + AsteroidYield = new ExponentialLerp { Minimum = 2f, Maximum = 6f, Exponent = 1f }, + ChunkCompositionVariance = .5f, BodyRadius = new ExponentialCurve(), LightRadius = new ExponentialCurve { Constant = lightRadius } }; @@ -66,7 +71,7 @@ public sealed partial class MiningCut3Tests : IDisposable Keys = new[] { new float4(0, 1, 0, 0), new float4(1, .3f, 0, 0) } }; - private sealed class Scene + internal sealed class Scene { public CultCache Cache; public ItemManager Items; @@ -81,16 +86,16 @@ public sealed partial class MiningCut3Tests : IDisposable // A belt around the sun: its chunks orbit the origin at their own distances, so at zone time 0 a chunk of // phase p sits at distance × (cos 2πp, sin 2πp). `kind` null leaves the belt kindless, for the zone to assign. - private sealed class BeltSpec + internal sealed class BeltSpec { public Asteroid[] Asteroids; public FieldKindData Kind; } - private static Asteroid Rock(float distance, float phase = 0f, float size = .5f) => + internal static Asteroid Rock(float distance, float phase = 0f, float size = .5f) => new Asteroid { Distance = distance, Phase = phase, Size = size, RotationSpeed = .1f }; - private Scene BuildScene(FieldKindData[] kinds = null, params BeltSpec[] belts) => BuildSceneAt(float2.zero, kinds, belts); + internal Scene BuildScene(FieldKindData[] kinds = null, params BeltSpec[] belts) => BuildSceneAt(float2.zero, kinds, belts); // The same scene with its sun, and so every belt centre, at `sunAt`. private Scene BuildSceneAt(float2 sunAt, FieldKindData[] kinds, params BeltSpec[] belts) => @@ -161,14 +166,15 @@ public sealed partial class MiningCut3Tests : IDisposable pack.Planets.Add(new CultRecordRef(key)); scene.Belts.Add(key); } - scene.Zone = new Zone(items, PlanetSettings(lightRadius), pack, new GalaxyZone { Name = "MiningCut3", Owner = null }, null); + scene.Zone = new Zone(items, PlanetSettings(lightRadius), pack, new GalaxyZone { Name = "MiningCut3", Owner = null }, + GalaxySeed == 0 ? null : RunSeedFixture.Continue(cache, "MiningCut3", GalaxySeed)); return scene; } - private static FieldKindData Kind(string name, float crossSection, float weight = 1f) => + internal static FieldKindData Kind(string name, float crossSection, float weight = 1f) => new FieldKindData { Name = name, CrossSection = crossSection, GenerationWeight = weight }; - private static BeltSpec Belt(FieldKindData kind, params Asteroid[] asteroids) => new BeltSpec { Kind = kind, Asteroids = asteroids }; + internal static BeltSpec Belt(FieldKindData kind, params Asteroid[] asteroids) => new BeltSpec { Kind = kind, Asteroids = asteroids }; // A chunk's planar position now (zone time never advances in these tests). private static float2 At(Scene s, ChunkId chunk) => s.Zone.ChunkPose(chunk.Field, chunk.Index).xy; @@ -180,14 +186,14 @@ public sealed partial class MiningCut3Tests : IDisposable return kind.CrossSection * PI * cells * cells * s.Zone.GetLight(At(s, chunk)); } - private static GearData Gear(string name, BehaviorData behavior) => new GearData + internal static GearData Gear(string name, BehaviorData behavior) => new GearData { Name = name, Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, Behaviors = { behavior } }; - private static EquippableItem Mint(Scene s, ItemData design) => new EquippableItem + internal static EquippableItem Mint(Scene s, ItemData design) => new EquippableItem { Data = s.Cache.RefOf(design), Durability = design is EquippableItemData equippable ? equippable.Durability : 0, @@ -308,9 +314,17 @@ public sealed partial class MiningCut3Tests : IDisposable // ChunkInfo's value is not changed by moving its arithmetic under PassiveInfo: six observers at different // places and bearings, one with a second sensor so the average is live, read the same chunk, and every value - // matches the bits recorded at base 12dfcef5, before the extraction (a different order of the multiplication - // by the chunk's brightness moves them in the last bits). - private static readonly uint[] ChunkInfoAtBase = new uint[] { 1045120030u, 1039274086u, 1030543422u, 1029120970u, 1036363351u, 1035122917u }; + // matches the bits the code before the extraction (base 12dfcef5) gives on the same host class (a different order of + // the multiplication by the chunk's brightness moves them in the last bits). The bits are per host class because + // the sensor's bearing term (acos, curve) is libm arithmetic, which rounds differently on Windows and Linux; replays + // are trusted only on the host class that recorded them (ruling replays-per-host-class). windows-x64 is the recording the + // test was written with; linux-x64 is base 12dfcef5 run on Linux, which gives 1039274088 where Windows gave 1039274086 for + // the second observer, and the current code gives the same bits as that base. + private static readonly System.Collections.Generic.Dictionary ChunkInfoAtBase = new() + { + ["windows-x64"] = new uint[] { 1045120030u, 1039274086u, 1030543422u, 1029120970u, 1036363351u, 1035122917u }, + ["linux-x64"] = new uint[] { 1045120030u, 1039274088u, 1030543422u, 1029120970u, 1036363351u, 1035122917u }, + }; [Fact] public void ChunkInfoIsBitIdenticalToItsValueBeforeTheExtraction() @@ -329,7 +343,9 @@ public sealed partial class MiningCut3Tests : IDisposable Assert.All(values, v => Assert.InRange(v, 1e-4f, .99f)); // a live, unsaturated reading at every place var actual = values.Select(Bits).ToArray(); - Assert.True(actual.SequenceEqual(ChunkInfoAtBase), "ChunkInfo bits: " + string.Join(",", actual)); + var host = RunStartTests.HostClass(); + Assert.True(ChunkInfoAtBase.TryGetValue(host, out var pinned), $"ChunkInfo bits: host class {host} has no recording; measured " + string.Join(",", actual)); + Assert.True(actual.SequenceEqual(pinned), $"ChunkInfo bits on {host}: " + string.Join(",", actual) + " pinned " + string.Join(",", pinned)); } // A chunk outside every sun's light is dark: no visibility, no info, and it cannot be picked, while a lit @@ -406,7 +422,7 @@ public sealed partial class MiningCut3Tests : IDisposable var whole = s.Zone.ChunkVisibility(chunk); var hitpoints = PlanetSettings().AsteroidHitpoints.Evaluate(.5f); - Assert.False(s.Zone.Wear(chunk, hitpoints * .5f)); + Assert.False(s.Zone.Breaks(chunk, hitpoints * .5f)); var worn = s.Zone.ChunkVisibility(chunk); Assert.InRange(worn, whole * .05f, whole * .95f); Assert.Equal(ExpectedVisibility(s, chunk, kind), worn, 4); @@ -423,7 +439,7 @@ public sealed partial class MiningCut3Tests : IDisposable Tick((observer, eyeAt)); Assert.True(observer.ChunkVisible(chunk)); - Assert.True(s.Zone.Wear(chunk, PlanetSettings().AsteroidHitpoints.Evaluate(.5f) * 2f)); + Assert.True(s.Zone.Breaks(chunk, PlanetSettings().AsteroidHitpoints.Evaluate(.5f) * 2f)); Assert.Equal(0f, s.Zone.ChunkVisibility(chunk)); Assert.Equal(0f, observer.ChunkInfo(chunk)); Assert.False(observer.SetTarget(chunk)); @@ -477,7 +493,7 @@ public sealed partial class MiningCut3Tests : IDisposable var centre = float2(400, -250); // off the origin, so a query that ignored the belt centre would disagree var s = BuildSceneAt(centre, new[] { kind }, Belt(kind, rocks)); var belt = s.Belts[0]; - Assert.True(s.Zone.Wear(new ChunkId(belt, 5), 1e6f)); // broken + Assert.True(s.Zone.Breaks(new ChunkId(belt, 5), 1e6f)); // broken var found = new List(); var sawSome = false; @@ -545,7 +561,7 @@ public sealed partial class MiningCut3Tests : IDisposable Assert.True(watcher.SetTarget(second)); Tick((watcher, eyeAt)); Assert.False(watcher.Target.Value.IsNone); - Assert.True(s.Zone.Wear(second, 1e6f)); + Assert.True(s.Zone.Breaks(second, 1e6f)); Tick((watcher, eyeAt)); Assert.True(watcher.Target.Value.IsNone); @@ -555,7 +571,7 @@ public sealed partial class MiningCut3Tests : IDisposable var third = new ChunkId(s.Belts[0], 2); Assert.True(docked.SetTarget(third)); docked.Deactivate(); - Assert.True(s.Zone.Wear(third, 1e6f)); + Assert.True(s.Zone.Breaks(third, 1e6f)); docked.Activate(); Assert.True(docked.Target.Value.IsNone); } @@ -814,14 +830,14 @@ public sealed partial class MiningCut3Tests : IDisposable Galaxy galaxy; try { - galaxy = new Galaxy(RestoredHullsTests.TutorialGalaxySettings(), RestoredHullsTests.TutorialBackgroundSettings(), - cache, new PlayerSettings(), new DirectoryInfo(dir), _ => { }, null, seed); + galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, + cache, _ => { }, null, seed); } catch (Exception) { continue; } // Galaxy's own seed-dependent flakiness (RestoredHullsTests) var items = new ItemManager(1u, cache, new ProvenanceLedger(), GameSettings(), _ => { }); foreach (var zone in galaxy.Zones.Take(4)) { - var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); + var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, entranceStation: zone == galaxy.Entrance); foreach (var body in pack.Planets) { if (!(cache.Get(body) is AsteroidBeltData belt)) continue; @@ -858,13 +874,13 @@ public sealed partial class MiningCut3Tests : IDisposable Galaxy galaxy; try { - galaxy = new Galaxy(RestoredHullsTests.TutorialGalaxySettings(), RestoredHullsTests.TutorialBackgroundSettings(), - cache, new PlayerSettings(), new DirectoryInfo(dir), _ => { }, null, seed); + galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, + cache, _ => { }, null, seed); } catch (Exception) { return null; } var items = new ItemManager(1u, cache, new ProvenanceLedger(), GameSettings(), _ => { }); return galaxy.Zones.Take(6).SelectMany(zone => - ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance) + ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, entranceStation: zone == galaxy.Entrance) .Planets.Select(body => cache.Get(body)).OfType().Select(belt => cache.Get(belt.Kind).Name)) .ToArray(); } diff --git a/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs new file mode 100644 index 000000000..49fc75886 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs @@ -0,0 +1,279 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using UniRx; +using Xunit; +using static CultMath.math; +using float2 = CultMath.float2; +using float3 = CultMath.float3; + +// Mining cut 4a (docs/mining-cut-refresh.md, Q10 = A): a blast's disc is shared by area over whatever it covers, hull +// cells or rocks, through FireControl.Detonate; each worn rock publishes one absorb on Zone.ChunkCapabilities. Reuses +// MiningCut3Tests' belt fixture (a partial of that class), so a filter on these tests names the methods below. +public sealed partial class MiningCut3Tests +{ + // A one-rock belt: the rock at phase 0 sits on +x of the belt centre, `size` its authored size. + private (Scene scene, ChunkId rock) OneRock(float size = .5f, float distance = 200f) + { + var kind = Kind("Asteroid", 4f); + var s = BuildScene(new[] { kind }, Belt(kind, Rock(distance, 0f, size))); + return (s, new ChunkId(s.Belts[0], 0)); + } + + private static List Absorbs(Scene s, List subs) + { + var list = new List(); + subs.Add(s.Zone.ChunkCapabilities.Absorb.Subscribe(list.Add)); + return list; + } + + // The area of a disc at the origin of radius r1 and a disc at (d, 0) of radius r2, by midpoint integration of the + // chord overlap -- no formula of the code under test. + private static double NumericLens(double d, double r1, double r2) + { + var lo = Math.Max(-r1, d - r2); + var hi = Math.Min(r1, d + r2); + if (hi <= lo) return 0; + const int n = 400000; + var h = (hi - lo) / n; + var area = 0.0; + for (var i = 0; i < n; i++) + { + var x = lo + (i + .5) * h; + var a = Math.Sqrt(Math.Max(0, r1 * r1 - x * x)); + var b = Math.Sqrt(Math.Max(0, r2 * r2 - (x - d) * (x - d))); + area += 2 * Math.Min(a, b) * h; + } + return area; + } + + // The area of a disc centred (cx, cy) of radius r inside the axis-aligned rectangle, by the same integration. + private static double NumericDiscInRect(double cx, double cy, double r, double x0, double x1, double y0, double y1) + { + var lo = Math.Max(cx - r, x0); + var hi = Math.Min(cx + r, x1); + if (hi <= lo) return 0; + const int n = 400000; + var h = (hi - lo) / n; + var area = 0.0; + for (var i = 0; i < n; i++) + { + var x = lo + (i + .5) * h; + var half = Math.Sqrt(Math.Max(0, r * r - (x - cx) * (x - cx))); + area += Math.Max(0, Math.Min(cy + half, y1) - Math.Max(cy - half, y0)) * h; + } + return area; + } + + [Theory] + [InlineData(5f, 3f, 4f)] + [InlineData(1f, 3f, 4f)] + [InlineData(6.5f, 3f, 4f)] + [InlineData(2.5f, 2f, 5f)] + [InlineData(3f, 3f, 3f)] + public void CircleCircleOverlapIsTheLens(float d, float r1, float r2) + { + var expected = NumericLens(d, r1, r2); + Assert.Equal(expected, FireControl.CircleCircleOverlap(d, r1, r2), 3); + Assert.Equal(expected, FireControl.CircleCircleOverlap(d, r2, r1), 3); + } + + [Fact] + public void CircleCircleOverlapIsExactAtTheLimits() + { + Assert.Equal(0f, FireControl.CircleCircleOverlap(7f, 3f, 4f)); // tangent + Assert.Equal(0f, FireControl.CircleCircleOverlap(8f, 3f, 4f)); // disjoint + Assert.Equal(PI * 9f, FireControl.CircleCircleOverlap(1f, 3f, 4f), 3); // contained: the smaller disc + Assert.Equal(PI * 9f, FireControl.CircleCircleOverlap(0f, 4f, 3f), 3); // concentric + Assert.Equal(PI * 9f, FireControl.CircleCircleOverlap(1f, 3f, 4f), 3); + Assert.Equal(0f, FireControl.CircleCircleOverlap(0f, 0f, 3f)); + } + + [Fact] + public void ABlastBesideAnUntargetedRockWearsIt() + { + var (s, rock) = OneRock(); + var at = At(s, rock); + var radius = 5f; + var offset = 3f; + var undamaged = s.Zone.ChunkRadius(rock); + FireControl.Detonate(s.Zone, at + float2(offset, 0), radius, 10f, DamageType.Kinetic); + + var share = (float) (10.0 * NumericLens(offset, radius, undamaged) / (Math.PI * radius * radius)); + Assert.True(share > 0f); + Assert.Equal(s.Zone.AsteroidBelts[rock.Field].DamagedSize(rock.Index, share, s.Zone.Settings), s.Zone.ChunkRadius(rock), 3); + } + + [Fact] + public void ABlastSharesItsDiscOverCellsAndRocksByArea() + { + var (s, rock) = OneRock(); + var rockAt = At(s, rock); + var rockRadius = s.Zone.ChunkRadius(rock); + var ship = SpawnShip(s, rockAt + float2(-12f, 0f)); + var radius = 6f; + var blast = rockAt + float2(-5.5f, 0f); + var damage = 1f; + var subs = new List(); + var hullAbsorbs = new List(); + subs.Add(ship.Capabilities.Absorb.Subscribe(hullAbsorbs.Add)); + var rockAbsorbs = Absorbs(s, subs); + + FireControl.Detonate(s.Zone, blast, radius, damage, DamageType.Kinetic); + foreach (var sub in subs) sub.Dispose(); + + // The hull is a 5 x 5 block of 2-unit cells about its position; the rock a disc; the two do not overlap. + var p = ship.Position.xz; + var area = Math.PI * radius * radius; + var hullArea = NumericDiscInRect(blast.x, blast.y, radius, p.x - 5, p.x + 5, p.y - 5, p.y + 5); + var rockArea = NumericLens(length(rockAt - blast), radius, rockRadius); + Assert.True(hullArea > 0 && rockArea > 0 && hullArea + rockArea < area, "fixture: both covered, some of the disc lost"); + var hull = Assert.Single(hullAbsorbs); + var worn = Assert.Single(rockAbsorbs); + Assert.Equal(damage * hullArea / area, hull.Magnitude, 4); + Assert.Equal(damage * rockArea / area, worn.Magnitude, 4); + var lost = damage * (area - hullArea - rockArea) / area; + Assert.Equal(damage, hull.Magnitude + worn.Magnitude + lost, 4); + } + + [Fact] + public void ARockWhoseCentreIsOutsideTheBlastIsStillWorn() + { + // The widest rock (size 1, radius 9) and a small blast: the blast radius 3 plus the rock's 9 exceeds the + // 8 between them, yet the centre is far outside the blast disc. + var (s, rock) = OneRock(size: 1f); + var at = At(s, rock); + var radius = 3f; + Assert.Equal(9f, s.Zone.ChunkRadius(rock), 3); + var subs = new List(); + var absorbs = Absorbs(s, subs); + FireControl.Detonate(s.Zone, at + float2(8f, 0f), radius, 10f, DamageType.Kinetic); + subs.ForEach(x => x.Dispose()); + + var worn = Assert.Single(absorbs); + Assert.Equal(10.0 * NumericLens(8, radius, 9) / (Math.PI * radius * radius), worn.Magnitude, 4); + Assert.True(s.Zone.ChunkRadius(rock) < 9f); + } + + [Fact] + public void ATangentOrDistantBlastWearsNothing() + { + var (s, rock) = OneRock(); + var at = At(s, rock); + var radius = s.Zone.ChunkRadius(rock); + var subs = new List(); + var absorbs = Absorbs(s, subs); + FireControl.Detonate(s.Zone, at + float2(2f * radius, 0f), radius, 10f, DamageType.Kinetic); + FireControl.Detonate(s.Zone, at + float2(60f, 0f), 5f, 10f, DamageType.Kinetic); + subs.ForEach(x => x.Dispose()); + + Assert.Empty(absorbs); + Assert.Equal(radius, s.Zone.ChunkRadius(rock)); + } + + [Fact] + public void ABrokenRockTakesNothingAndPublishesNothing() + { + var (s, rock) = OneRock(); + var at = At(s, rock); + Assert.True(s.Zone.Breaks(rock, 1e6f)); + var subs = new List(); + var absorbs = Absorbs(s, subs); + FireControl.Detonate(s.Zone, at, 8f, 10f, DamageType.Kinetic); + subs.ForEach(x => x.Dispose()); + + Assert.Empty(absorbs); + Assert.False(s.Zone.ChunkExists(rock)); + Assert.Equal(0f, s.Zone.ChunkRadius(rock)); + } + + [Fact] + public void EachWornRockPublishesOneAbsorb() + { + var kind = Kind("Asteroid", 4f); + // Two rocks side by side and a third out of reach, listed out of order of their distance. + var s = BuildScene(new[] { kind }, Belt(kind, Rock(200f, 0f, .5f), Rock(300f, 0f, .5f), Rock(205f, 0f, .5f))); + var a = new ChunkId(s.Belts[0], 0); + var b = new ChunkId(s.Belts[0], 2); + var far = new ChunkId(s.Belts[0], 1); + var blast = (At(s, a) + At(s, b)) / 2f; + var radius = 8f; + var damage = 10f; + var seen = new List<(AbsorbEvent e, float aRadius, float bRadius)>(); + using var sub = s.Zone.ChunkCapabilities.Absorb.Subscribe(e => seen.Add((e, s.Zone.ChunkRadius(a), s.Zone.ChunkRadius(b)))); + var undamagedA = s.Zone.ChunkRadius(a); + var undamagedB = s.Zone.ChunkRadius(b); + + FireControl.Detonate(s.Zone, blast, radius, damage, DamageType.Kinetic); + + Assert.Equal(2, seen.Count); + Assert.All(seen, x => Assert.Equal(AbsorbLayer.Hull, x.e.Layer)); + Assert.All(seen, x => Assert.Equal(0f, x.e.Position.y)); + // Walked in index order; each absorb lands before its own rock's wear, and the first rock's wear is already + // done when the second is published. + Assert.Equal(undamagedA, seen[0].aRadius); + Assert.Equal(undamagedB, seen[0].bRadius); + Assert.True(seen[1].aRadius < undamagedA); + Assert.Equal(undamagedB, seen[1].bRadius); + Assert.Equal(damage * NumericLens(length(At(s, a) - blast), radius, undamagedA) / (Math.PI * radius * radius), seen[0].e.Magnitude, 4); + Assert.Equal(damage * NumericLens(length(At(s, b) - blast), radius, undamagedB) / (Math.PI * radius * radius), seen[1].e.Magnitude, 4); + // The direction runs from the blast out through the rock. + var away = normalize(At(s, a) - blast); + Assert.Equal(away.x, seen[0].e.Direction.x, 4); + Assert.Equal(away.y, seen[0].e.Direction.z, 4); + Assert.Equal(s.Zone.AsteroidBelts[far.Field].UndamagedSize(far.Index, s.Zone.Settings), s.Zone.ChunkRadius(far)); + } + + // The walk is fixed: (field ordinal, index), whatever order the targeting index yields. Two belts, rocks scattered + // so the index's own order is not the sorted one; the absorbs come in sorted order. + [Fact] + public void RocksAreWornInFieldThenIndexOrder() + { + var kind = Kind("Asteroid", 4f); + var s = BuildScene(new[] { kind }, + Belt(kind, Rock(200f, .7f, .5f), Rock(200f, .1f, .5f), Rock(200f, .4f, .5f)), + Belt(kind, Rock(200f, .9f, .5f), Rock(200f, .2f, .5f))); + var rocks = new[] { 0, 1, 2 }.Select(i => new ChunkId(s.Belts[0], i)).Concat(new[] { 0, 1 }.Select(i => new ChunkId(s.Belts[1], i))).ToList(); + var blast = float2.zero; + var seen = new List(); + using var sub = s.Zone.ChunkCapabilities.Absorb.Subscribe(seen.Add); + + FireControl.Detonate(s.Zone, blast, 400f, 1000f, DamageType.Kinetic); + + Assert.Equal(rocks.Count, seen.Count); + var expected = rocks.OrderBy(r => r.Field.Value, StringComparer.Ordinal).ThenBy(r => r.Index).ToList(); + for (var i = 0; i < expected.Count; i++) + { + var away = normalize(At(s, expected[i]) - blast); + Assert.Equal(away.x, seen[i].Direction.x, 3); + Assert.Equal(away.y, seen[i].Direction.z, 3); + } + } + + [Fact] + public void AMineBlastWearsRocks() + { + var (s, rock) = OneRock(); + var at = At(s, rock); + var undamaged = s.Zone.ChunkRadius(rock); + var absorbs = new List(); + using var sub = s.Zone.ChunkCapabilities.Absorb.Subscribe(absorbs.Add); + s.Zone.Lay(new Mine + { + Id = s.Zone.NextBodyId(), Body = new KinematicBody { Position = at + float2(2f, 0f), Velocity = float2.zero }, + ArmingDelay = 0f, FuseDelay = 100f, Lifetime = 0f, BlastRadius = 6f, Damage = 10f, + DamageType = DamageType.Kinetic, Layer = null, LayerFaction = null + }); + + s.Zone.Update(.001f); + + Assert.Empty(s.Zone.Mines); + Assert.Single(absorbs); + Assert.True(s.Zone.ChunkRadius(rock) < undamaged); + } +} diff --git a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs new file mode 100644 index 000000000..abf4f0dc1 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs @@ -0,0 +1,459 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using UniRx; +using Xunit; +using static CultMath.math; +using float2 = CultMath.float2; +using float3 = CultMath.float3; + +// Mining Cut 4b (docs/mining-cut-refresh.md, Q12 = A): a shot at a rock goes through FireControl's one fire path +// and wears it; the rock is a disc. The fixture is MiningCut3Tests' belt scene: a shooter at the origin, one rock +// straight ahead (+z, phase .25) at `Distance`, a gun and a targeting system fitted on the shooter. +public sealed class MiningCut4bTests : IDisposable +{ + private const float Distance = 100f; + private readonly MiningCut3Tests _fixtures = new MiningCut3Tests(); + + public void Dispose() => _fixtures.Dispose(); + + internal sealed class Rig + { + public MiningCut3Tests.Scene Scene; + public Zone Zone => Scene.Zone; + public Ship Shooter; + public EquippedItem GunItem; + public Weapon Gun; + public ChunkId Rock; + public List Resolved = new List(); + } + + private static InstantWeaponData Behavior(bool launcher, float damage, float velocity, float spread, float effective = float.PositiveInfinity) + { + InstantWeaponData data = launcher ? new LockWeaponData + { + LockSpeed = MiningCut3Tests.Constant(1000), SensorImpact = MiningCut3Tests.Constant(1), LockAngle = MiningCut3Tests.Constant(180), + DirectionImpact = MiningCut3Tests.Constant(1), Decay = MiningCut3Tests.Constant(1) + } : new InstantWeaponData(); + data.Damage = MiningCut3Tests.Constant(damage); + data.Range = MiningCut3Tests.Constant(500f); + data.MinRange = MiningCut3Tests.Constant(0); + data.EffectiveRange = MiningCut3Tests.Constant(effective); + data.DamageAtMaxRange = 0f; + data.Velocity = MiningCut3Tests.Constant(velocity); + data.Spread = MiningCut3Tests.Constant(spread); + data.DamageSpread = MiningCut3Tests.Constant(0); + data.Penetration = MiningCut3Tests.Constant(0); + data.Count = MiningCut3Tests.Constant(1); + data.BurstTime = MiningCut3Tests.Constant(0); + data.Cooldown = MiningCut3Tests.Constant(1000); + return data; + } + + // `precision` 1 gives sigma 1 cell; accuracy 1 and a resolution that asks little of the info make PSensor 1. + internal Rig Build(bool sensor = true, bool launcher = false, float damage = 10f, float velocity = 0f, float spread = 0f, + float precision = 1f, float effective = float.PositiveInfinity, WeaponFuse? fuse = null, float blastRadius = 0f, + float rockSize = 0f, float crossSection = 20f, bool target = true, float tracking = 1000000f, FieldKindData kind = null, uint galaxySeed = 0) + { + _fixtures.GalaxySeed = galaxySeed; + kind ??= MiningCut3Tests.Kind("Asteroid", crossSection); + var scene = _fixtures.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, MiningCut3Tests.Rock(Distance, .25f, rockSize))); + var gear = MiningCut3Tests.Gear("Targeting", new TargetingSystemData + { + Accuracy = MiningCut3Tests.Constant(1f), Resolution = MiningCut3Tests.Constant(1000f), + Precision = MiningCut3Tests.Constant(precision), Tracking = MiningCut3Tests.Constant(tracking) + }); + scene.Cache.Upsert(gear); + var gun = new WeaponItemData + { + Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Fuse = fuse, BlastRadius = blastRadius, + Behaviors = { Behavior(launcher, damage, velocity, spread, effective) } + }; + scene.Cache.Upsert(gun); + + var shape = new Shape(5, 5); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var hull = new HullData + { + Name = "Gunship", HullType = HullType.Ship, Shape = shape, Durability = 10, Mass = 1000, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } } + }; + scene.Cache.Upsert(hull); + var shooter = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, hull), new EntitySettings()); + if (sensor) Assert.True(shooter.TryEquip(MiningCut3Tests.Mint(scene, scene.Eye)), "eye"); + Assert.True(shooter.TryEquip(MiningCut3Tests.Mint(scene, gear)), "targeting"); + var minted = MiningCut3Tests.Mint(scene, gun); + Assert.True(shooter.TryEquip(minted, new int2(0, 0)), "gun"); + scene.Zone.Admit(shooter, piloted: false); + shooter.Position = float3.zero; + shooter.Direction = float2(0, 1); + shooter.Aim = float3(0, 0, 1); + + shooter.Update(.05f); // the fitted sensor becomes active on its first tick; zone time does not advance + shooter.Position = float3.zero; + shooter.Velocity = float2.zero; + var item = shooter.Equipment.Single(x => x.EquippableItem == minted); + var rig = new Rig + { + Scene = scene, Shooter = shooter, GunItem = item, Gun = (Weapon) item.Behaviors.Single(b => b is Weapon), + Rock = new ChunkId(scene.Belts[0], 0) + }; + scene.Zone.ShotResolved.Subscribe(outcome => rig.Resolved.Add(outcome)); + if (target && sensor) Assert.True(shooter.SetTarget(rig.Rock), "target"); + return rig; + } + + private static float Phi(double z) => (float) (.5 * (1 + erf((float) (z / Math.Sqrt(2))))); + + // The rock's radius in cells is the one the zone reports, sigma the targeting system's (floored at half a cell). + private static float Disc(Rig rig) + { + var sigma = max(1f / FireControl.Precision(rig.Shooter), .5f); + var radius = rig.Zone.ChunkCells(rig.Rock); + return Phi(radius / sigma) - Phi(-radius / sigma); + } + + // PSensor as the rule states it, for a gear that wants only the detection threshold plus a thousandth of the rest. + private static float Sensor(Rig rig, float info) + { + var th = rig.Scene.Items.GameplaySettings.TargetDetectionInfoThreshold; + return saturate(unlerp(th, th + (1f - th) / 1000f, info)); + } + + // ==== one fire path ==== + + // Accuracy, PSensor, PSpread, Sigma and PMount price a rock exactly as a ship at equal range, precision and info: + // a two-cell ship (span 2, centre-aimed) and a rock one cell in radius (span 2) are the same disc to the gun, and + // an unauthored gun follows anything, so the mount is 1 for both. + [Fact] + public void ARockShotUsesTheSameFactors() + { + var rig = Build(spread: 4f, precision: 1f, crossSection: 1f); + var s = rig.Scene; + Assert.Equal(1f, rig.Zone.ChunkCells(rig.Rock), 4); + var info = rig.Shooter.ChunkInfo(rig.Rock); + Assert.True(info > .11f && info < 1f, $"the rock's info {info} should be visible and unsaturated"); + + var hull = new HullData { Name = "Pair", HullType = HullType.Ship, Shape = new Shape(2, 2), Durability = 10, Mass = 1000 }; + foreach (var cell in hull.Shape.AllCoordinates) hull.Shape[cell] = true; + s.Cache.Upsert(hull); + var at = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + var ship = new Ship(s.Items, rig.Zone, MiningCut3Tests.Mint(s, hull), new EntitySettings()); + rig.Zone.Admit(ship, piloted: false); + ship.Position = float3(at.x, 0, at.y); + ship.Direction = float2(0, 1); + rig.Shooter.EntityInfoGathered[ship] = info; + rig.Shooter.VisibleEntities.Add(ship); + + var rock = FireControl.HitProbability(rig.Gun, rig.Shooter, rig.Rock); + var vessel = FireControl.HitProbability(rig.Gun, rig.Shooter, ship); + Assert.InRange(rock, .05f, .99f); + Assert.Equal(vessel, rock, 4); + } + + [Fact] + public void AnUnseenRockCannotBeFiredOn() + { + var blind = Build(sensor: false); + Assert.False(FireControl.Designated(blind.Gun, blind.Shooter, blind.Rock, out var range)); + Assert.Equal(Distance, range, 2); + Assert.Equal(0f, FireControl.HitProbability(blind.Gun, blind.Shooter, blind.Rock)); + Assert.False(FireControl.Solve(blind.Gun, blind.GunItem, blind.Shooter, blind.Rock).Designated); + + var sighted = Build(); + Assert.True(FireControl.Designated(sighted.Gun, sighted.Shooter, sighted.Rock, out _)); + Assert.True(FireControl.HitProbability(sighted.Gun, sighted.Shooter, sighted.Rock) > 0f); + } + + // Q12 = A: a launcher (a LockWeapon) is never designated on a rock, locked or not. + [Fact] + public void LaunchersCannotFireOnARock() + { + var launcher = Build(launcher: true); + Assert.False(FireControl.Designated(launcher.Gun, launcher.Shooter, launcher.Rock, out _)); + Assert.Equal(0f, FireControl.HitProbability(launcher.Gun, launcher.Shooter, launcher.Rock)); + var plain = Build(); + Assert.True(FireControl.Designated(plain.Gun, plain.Shooter, plain.Rock, out _)); + } + + // POnHull is the closed form Phi(R/sigma) - Phi(-R/sigma): a zero-spread gun with a full sensor reading is priced by the + // disc alone. + [Fact] + public void DiscMassIsTheClosedForm() + { + var rig = Build(spread: 0f, precision: 1f, rockSize: .5f); + var info = rig.Shooter.ChunkInfo(rig.Rock); + var expected = Sensor(rig, info) * Disc(rig); + Assert.InRange(Disc(rig), .5f, .99f); + Assert.Equal(expected, FireControl.HitProbability(rig.Gun, rig.Shooter, rig.Rock), 4); + } + + // Commit's price at fire time is the forecast: for a rock still at the instant it is fired at, one price. + [Fact] + public void TheForecastIsTheCommitPriceForARock() + { + var rig = Build(spread: 4f, precision: 1f, velocity: 50f); + var forecast = FireControl.HitProbability(rig.Gun, rig.Shooter, rig.Rock); + var id = FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Assert.True(rig.Zone.TryGetShot(id, out var shot)); + Assert.Equal(rig.Rock, shot.Chunk); + Assert.Null(shot.Target); + Assert.Equal(forecast, FireControl.CommitProbability(shot, shot.FireTime, out _), 4); + } + + // ==== resolution ==== + + internal static void Run(Rig rig, float seconds) + { + for (var elapsed = 0f; elapsed < seconds; elapsed += .01f) rig.Zone.Update(.01f); + } + + // A rock hit has no lane and no shield. Hits wear the rock by the shot's Damage after the falloff, and each + // publishes one absorb on the zone's ChunkCapabilities at the rock's surface facing the shot. + [Fact] + public void DirectHitsWearTheRock() + { + var rig = Build(damage: 3f, rockSize: .5f, precision: 1000f, effective: 50f); + var absorbs = new List(); + var surface = new List(); + rig.Zone.ChunkCapabilities.Absorb.Subscribe(e => + { + absorbs.Add(e); + var centre = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + surface.Add(length(float2(e.Position.x, e.Position.z) - centre) - rig.Zone.ChunkRadius(rig.Rock)); + }); + var before = rig.Zone.ChunkRadius(rig.Rock); + var factor = WeaponData.RangeFactor(0f, 50f, 500f, 0f, Distance); + Assert.InRange(factor, .01f, .99f); + + for (var shot = 0; shot < 12; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + + var hits = rig.Resolved.Count(o => o.Hit); + Assert.InRange(hits, 1, 12); + Assert.Equal(hits, absorbs.Count); + Assert.All(rig.Resolved.Where(o => o.Hit), o => { Assert.Equal(0, o.Cell.x); Assert.Equal(0, o.Cell.y); Assert.False(o.Shielded); }); + Assert.All(absorbs, e => Assert.Equal(3f * factor, e.Magnitude, 2)); + Assert.All(surface, d => Assert.True(abs(d) < 1e-3f, $"absorb was {d} off the rock's surface")); + Assert.All(absorbs, e => Assert.Equal(AbsorbLayer.Hull, e.Layer)); + var hp = MiningCut3Tests.PlanetSettings().AsteroidHitpoints.Evaluate(.5f); + var expected = MiningCut3Tests.PlanetSettings().AsteroidSize.Evaluate((hp - hits * 3f * factor) / hp * .5f); + Assert.Equal(expected, rig.Zone.ChunkRadius(rig.Rock), 3); + Assert.True(rig.Zone.ChunkRadius(rig.Rock) < before); + } + + // A contact round that hits a rock detonates at its centre as it arrives, through Detonate: a bystander beside it + // takes the blast from the rock's centre, not from the muzzle or from a lane. + [Fact] + public void AContactRoundAtARockDetonatesAtItsCentre() + { + var rig = Build(damage: 10f, fuse: WeaponFuse.Contact, blastRadius: 6f, precision: 1000f, rockSize: .5f); + var s = rig.Scene; + var at = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + var bystander = new Ship(s.Items, rig.Zone, MiningCut3Tests.Mint(s, s.Hull), new EntitySettings()); + rig.Zone.Admit(bystander, piloted: false); + bystander.Position = float3(at.x + 3f, 0, at.y); + var burstAt = new List(); + bystander.Capabilities.Absorb.Subscribe(e => + { + var centre = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + burstAt.Add(length(float2(e.Position.x, e.Position.z) - centre)); + }); + + for (var shot = 0; shot < 12; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + + Assert.InRange(rig.Resolved.Count(o => o.Hit), 1, 12); + Assert.NotEmpty(burstAt); + Assert.All(burstAt, d => Assert.True(d < 1e-2f, $"blast was {d} from the rock's centre")); + } + + // A rock that no longer exists when its round arrives, broken in flight, resolves as a miss, like a target that + // left the zone: nothing is worn and nothing absorbs. + [Fact] + public void ARockThatBreaksMidFlightIsAMiss() + { + var rig = Build(velocity: 50f, precision: 1000f); + var absorbs = 0; + rig.Zone.ChunkCapabilities.Absorb.Subscribe(_ => absorbs++); + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Assert.Empty(rig.Resolved); + + Assert.True(rig.Zone.Breaks(rig.Rock, 1e6f)); + Run(rig, 2.5f); + + var outcome = Assert.Single(rig.Resolved); + Assert.Equal(ShotResult.Miss, outcome.Result); + Assert.Equal(0, absorbs); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + } + + // The shot's own dice: two zones built alike roll the same sequence of outcomes for the same shot ids. + [Fact] + public void RockDiceAreTheShotsOwn() + { + List Roll() + { + var rig = Build(precision: 1f); + for (var shot = 0; shot < 20; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + return rig.Resolved.Select(o => o.Result).ToList(); + } + + var first = Roll(); + var second = Roll(); + Assert.Equal(20, first.Count); + Assert.Contains(ShotResult.Hit, first); + Assert.Contains(ShotResult.Miss, first); + Assert.Equal(first, second); + } + + // A rock's velocity is the pose function's derivative, derived on every read. + [Fact] + public void ARockMovesAtItsPoseVelocity() + { + var rig = Build(); + var velocity = rig.Zone.ChunkVelocity(rig.Rock); + var ahead = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index, rig.Zone.Time + .5).xy; + var now = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + Assert.True(length(velocity) > 1f); + Assert.True(length(velocity * .5f - (ahead - now)) < .05f * length(ahead - now)); + } + + // A rock is not a Ship: its evasion is 0, so Tracking (the metres of deviation a shooter forgives) never + // discounts the price of a rock. The same rock priced by a tight and by a loose tracker reads one price. + [Fact] + public void ARockEvadesNothing() + { + var tight = Build(spread: 4f, precision: 1f, tracking: 10f); + var loose = Build(spread: 4f, precision: 1f, tracking: 1000000f); + var tightPrice = FireControl.HitProbability(tight.Gun, tight.Shooter, tight.Rock); + var loosePrice = FireControl.HitProbability(loose.Gun, loose.Shooter, loose.Rock); + Assert.InRange(loosePrice, .05f, .99f); + Assert.Equal(loosePrice, tightPrice, 5); + } + + // The lead is the intercept of the rock's pose velocity: the point is where the rock will be when a round of the + // gun's velocity gets there, derived here from the time of flight, not from the code under test. + [Fact] + public void AMovingRockIsLeadAtItsPoseVelocity() + { + var rig = Build(velocity: 50f); + var velocity = rig.Zone.ChunkVelocity(rig.Rock); + var now = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + Assert.True(length(velocity) > 1f); + + var point = FireControl.PredictedIntercept(rig.Gun, rig.Shooter, rig.Rock); + + var flight = length(point.xz - rig.Shooter.Position.xz) / 50f; + var there = now + velocity * flight; + Assert.True(length(point.xz - now) > .5f, "the aim leads the rock"); + Assert.Equal(there.x, point.x, 2); + Assert.Equal(there.y, point.z, 2); + } + + // A rock that breaks after its round committed a hit resolves as a miss through Step's gone rule: the frozen + // outcome says Hit, so only that rule stops the round from absorbing on, and wearing, a rock that is gone. + [Fact] + public void ARockThatBreaksAfterCommitIsAMissNotAFrozenHit() + { + var rig = Build(velocity: 50f, precision: 1000f); + var committed = new List(); + rig.Zone.ShotCommitted.Subscribe(committed.Add); + var absorbs = 0; + rig.Zone.ChunkCapabilities.Absorb.Subscribe(_ => absorbs++); + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + for (var waited = 0f; committed.Count == 0 && waited < 3f; waited += .01f) rig.Zone.Update(.01f); + var frozen = Assert.Single(committed); + Assert.True(frozen.Hit, "fixture: the commit rolled a hit"); + Assert.Empty(rig.Resolved); + + Assert.True(rig.Zone.Breaks(rig.Rock, 1e6f)); + Run(rig, 2.5f); + + var outcome = Assert.Single(rig.Resolved); + Assert.False(outcome.Hit); + Assert.Equal(0, absorbs); + } + + private static void Wear(Rig rig, WeaponFuse fuse, int shots, out int hits, out List absorbs, out float worn) + { + var seen = new List(); + rig.Zone.ChunkCapabilities.Absorb.Subscribe(seen.Add); + for (var shot = 0; shot < shots; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + hits = rig.Resolved.Count(o => o.Hit); + absorbs = seen; + worn = seen.Sum(e => e.Magnitude); + } + + // A contact round that hits a rock wears it exactly once, by the blast's share through Detonate: one absorb per hit, + // and the rock's wear is the sum of those absorbs' magnitudes, with no Damage added on top. + [Fact] + public void AContactRoundWearsARockExactlyOnce() + { + var rig = Build(damage: 10f, fuse: WeaponFuse.Contact, blastRadius: 6f, precision: 1000f, rockSize: .5f); + Wear(rig, WeaponFuse.Contact, 12, out var hits, out var absorbs, out var worn); + + Assert.InRange(hits, 1, 12); + Assert.Equal(hits, absorbs.Count); + var belt = rig.Zone.AsteroidBelts[rig.Rock.Field]; + Assert.True(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(belt.DamagedSize(rig.Rock.Index, worn, rig.Zone.Settings), rig.Zone.ChunkRadius(rig.Rock), 3); + } + + // The same for a proximity round, which detonates at its burst point hit or miss: one absorb per resolved round + // that covers the rock, and no wear beyond them. + [Fact] + public void AProximityRoundWearsARockExactlyOnce() + { + var rig = Build(damage: 10f, fuse: WeaponFuse.Proximity, blastRadius: 6f, precision: 1000f, rockSize: .5f); + Wear(rig, WeaponFuse.Proximity, 12, out _, out var absorbs, out var worn); + + Assert.Equal(12, rig.Resolved.Count); + Assert.NotEmpty(absorbs); + var belt = rig.Zone.AsteroidBelts[rig.Rock.Field]; + Assert.True(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(belt.DamagedSize(rig.Rock.Index, worn, rig.Zone.Settings), rig.Zone.ChunkRadius(rig.Rock), 3); + } + + // A rock's absorb has one height rule whoever reports it: a direct hit and a blast both publish at height 0, not at + // the shooter's. + [Fact] + public void ARockAbsorbHasOneHeightRule() + { + var rig = Build(damage: 3f, rockSize: .5f, precision: 1000f); + rig.Shooter.Position = float3(0, 7, 0); + var heights = new List(); + rig.Zone.ChunkCapabilities.Absorb.Subscribe(e => heights.Add(e.Position.y)); + for (var shot = 0; shot < 6; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + var direct = heights.Count; + FireControl.Detonate(rig.Zone, rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy, 5f, 3f, DamageType.Kinetic); + + Assert.True(direct > 0 && heights.Count > direct); + Assert.All(heights, h => Assert.Equal(0f, h)); + } +} diff --git a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs new file mode 100644 index 000000000..04f02164d --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs @@ -0,0 +1,311 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; +using static CultMath.math; + +// Mining Cut 5a (docs/mining-cut-refresh.md): a worn rock pays the shooter in ore at the wear site, from the shot's own +// dice; what does not fit in the hold floats at the rock. The fixtures are Cut 3's belt scene and Cut 4b's rig. +public sealed class MiningCut5aTests : IDisposable +{ + private readonly MiningCut4bTests _rigs = new MiningCut4bTests(); + private readonly MiningCut3Tests _scenes = new MiningCut3Tests(); + + public void Dispose() + { + _rigs.Dispose(); + _scenes.Dispose(); + } + + internal static SimpleCommodityData Commodity(string name, int maxStack = 100) => + new SimpleCommodityData { Name = name, Shape = new Shape(), Price = 5, MaxStack = maxStack }; + + // Registers the ores and the kind's yields in the scene's catalog (the kind refs need the stored commodities). + internal static void Stock(MiningCut3Tests.Scene scene, FieldKindData kind, params (SimpleCommodityData Ore, float Abundance)[] yields) + { + kind.Yields.Clear(); + foreach (var (ore, abundance) in yields) + { + scene.Cache.Upsert(ore); + kind.Yields.Add(new FieldYield { Commodity = scene.Cache.RefOf(ore), Abundance = abundance }); + } + scene.Cache.Upsert(kind); + } + + internal static EquippedCargoBay Bay(MiningCut3Tests.Scene scene, Ship ship, int width, int height, string name) + { + var shape = new Shape(width, height); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var data = new CargoBayData { Name = name, Shape = new Shape(), InteriorShape = shape, Price = 1, Durability = 4 }; + scene.Cache.Upsert(data); + var bay = new EquippedCargoBay(scene.Items, MiningCut3Tests.Mint(scene, data), new int2(1, 1), ship, name); + ship.CargoBays.Add(bay); + return bay; + } + + internal static int Units(IEnumerable items, string ore, MiningCut3Tests.Scene scene) => + items.OfType().Where(c => scene.Items.GetData(c).Name == ore).Sum(c => c.Quantity); + + internal static int Units(EquippedCargoBay bay, string ore, MiningCut3Tests.Scene scene) => Units(bay.Cargo.Keys, ore, scene); + + // A rig whose rock (size .5: 4 units, whole) yields `ores`, shooter holding one bay. + private (MiningCut4bTests.Rig Rig, EquippedCargoBay Bay) Mining(int bayWidth = 4, int bayHeight = 4, float damage = 1000f, + WeaponFuse? fuse = null, float velocity = 0f, uint galaxySeed = 0, float rockSize = .5f, params (SimpleCommodityData, float)[] ores) + { + var kind = MiningCut3Tests.Kind("Asteroid", 20f); + var rig = _rigs.Build(damage: damage, fuse: fuse, blastRadius: fuse == null ? 0f : 6f, precision: 1000f, rockSize: rockSize, velocity: velocity, kind: kind, galaxySeed: galaxySeed); + Stock(rig.Scene, kind, ores.Length > 0 ? ores : new[] { (Commodity("Rock"), 1f) }); + return (rig, Bay(rig.Scene, rig.Shooter, bayWidth, bayHeight, "Hold")); + } + + private static int Hits(MiningCut4bTests.Rig rig, int cap = 40) + { + for (var shot = 0; shot < cap && !rig.Resolved.Any(o => o.Hit); shot++) + { + // A broken rock cannot be targeted again: the first hit ends the loop. + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + MiningCut4bTests.Run(rig, .05f); + } + return rig.Resolved.Count(o => o.Hit); + } + + private static float Hitpoints(MiningCut4bTests.Rig rig) => + rig.Zone.Settings.AsteroidHitpoints.Evaluate(rig.Zone.AsteroidBelts[rig.Rock.Field].Data.Asteroids[rig.Rock.Index].Size); + + [Fact] + public void WearReturnsWhatTheRockAbsorbed() + { + var (rig, _) = Mining(); + var hp = Hitpoints(rig); + Assert.Equal(hp * .3f, rig.Zone.Wear(rig.Rock, hp * .3f), 3); + // The breaking hit absorbs only what the rock had left. + Assert.Equal(hp * .7f, rig.Zone.Wear(rig.Rock, hp * 5f), 3); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(0f, rig.Zone.Wear(rig.Rock, hp)); + } + + // Units owed are absorbed/hitpoints x AsteroidYield(size): a rock pays its whole yield however many hits break it, so + // the mean over many rocks does not depend on how the damage arrives. + [Fact] + public void ARockYieldsItsAuthoredTotalWhateverBreaksIt() + { + const int rocks = 300; + var ore = Commodity("Rock"); + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + var scene = _scenes.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, + Enumerable.Range(0, rocks).Select(i => MiningCut3Tests.Rock(150f + i * .1f, i / (float) rocks, .3f)).ToArray())); + Stock(scene, kind, (ore, 1f)); + var ship = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, scene.Hull), new EntitySettings()); + scene.Zone.Admit(ship, piloted: false); + var bay = Bay(scene, ship, 8, 8, "Hold"); + var settings = scene.Zone.Settings; + var hp = settings.AsteroidHitpoints.Evaluate(.3f); + var owed = settings.AsteroidYield.Evaluate(.3f); + + uint ordinal = 0; + void Hit(int rock, float fraction) => + FireControl.Extract(scene.Zone, new ChunkId(scene.Belts[0], rock), scene.Zone.Wear(new ChunkId(scene.Belts[0], rock), hp * fraction), + ship, SimulationDice.For(scene.Zone.DropSeed, SimulationDice.OreStream, ++ordinal)); + + for (var rock = 0; rock < rocks / 2; rock++) Hit(rock, 2f); + var wholeHits = Units(bay.Cargo.Keys.Concat(scene.Zone.FloatingItems.Select(f => f.Item)), "Rock", scene); + for (var rock = rocks / 2; rock < rocks; rock++) for (var part = 0; part < 4; part++) Hit(rock, .25f); + var total = Units(bay.Cargo.Keys.Concat(scene.Zone.FloatingItems.Select(f => f.Item)), "Rock", scene); + var quartered = total - wholeHits; + + // owed = 3.2 per rock; 150 rocks: mean 480, sigma about 4.9 whole, 4.9 quartered. + Assert.InRange(wholeHits, 480 - 30, 480 + 30); + Assert.InRange(quartered, 480 - 30, 480 + 30); + Assert.Equal(3.2f, owed, 3); + } + + [Fact] + public void ADirectHitPaysTheShooter() + { + var (rig, bay) = Mining(ores: new[] { (Commodity("Rock"), 1f), (Commodity("Gold"), 1f) }); + var yields = FieldKinds.Yield(rig.Zone.AsteroidBelts[rig.Rock.Field].Data.Kind, default, rig.Scene.Cache); + Assert.Equal(2, yields.Length); + Assert.Equal(1, Hits(rig)); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(4, Units(bay, "Rock", rig.Scene) + Units(bay, "Gold", rig.Scene)); + Assert.Empty(rig.Zone.FloatingItems); + } + + [Fact] + public void ABlastPaysTheShooter() + { + var (rig, bay) = Mining(fuse: WeaponFuse.Contact, ores: new[] { (Commodity("Rock"), 1f) }); + Hits(rig); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(4, Units(bay, "Rock", rig.Scene)); + } + + [Fact] + public void AMineWearsButYieldsNothing() + { + var (rig, bay) = Mining(); + var at = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + FireControl.Detonate(rig.Zone, at, 6f, 1000f, DamageType.Kinetic); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Empty(bay.Cargo); + Assert.Empty(rig.Zone.FloatingItems); + } + + // Ruling mining-overflow-floats: what the hold cannot take floats at the rock, where another ship can pick it up. + [Fact] + public void AFullHoldReleasesTheOverflow() + { + var grit = Commodity("Grit", maxStack: 2); + var (rig, bay) = Mining(bayWidth: 1, bayHeight: 1, ores: new[] { (grit, 1f) }); + Hits(rig); + + Assert.Equal(2, Units(bay, "Grit", rig.Scene)); + var floating = Assert.Single(rig.Zone.FloatingItems); + Assert.Equal(2, Assert.IsType(floating.Item).Quantity); + var rock = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + Assert.True(length(floating.Body.Position - rock) < 1f, "the overflow leaves from the rock"); + + var taker = new Ship(rig.Scene.Items, rig.Zone, MiningCut3Tests.Mint(rig.Scene, rig.Scene.Hull), new EntitySettings()); + rig.Zone.Admit(taker, piloted: false); + var takerBay = Bay(rig.Scene, taker, 4, 4, "Taker"); + Assert.True(rig.Zone.TryPickUp(taker, floating.Id)); + Assert.Equal(2, Units(takerBay, "Grit", rig.Scene)); + } + + [Fact] + public void AGoneShooterReleasesEverything() + { + var (rig, bay) = Mining(velocity: 50f); + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + rig.Shooter.HeatstrokeDeath.OnNext(UniRx.Unit.Default); + MiningCut4bTests.Run(rig, 3f); + + Assert.Empty(bay.Cargo); + Assert.Equal(4, Units(rig.Zone.FloatingItems.Select(f => f.Item), "Rock", rig.Scene)); + } + + // Two zones of one pack share every key, so the same rocks wear in each: the ore is a function of the dice alone. + private (MiningCut3Tests.Scene Scene, Func NewZone, Ship Shooter) Field(int rocks, float size, float variance = .5f, float yield = 4f) + { + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + var scene = _scenes.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, + Enumerable.Range(0, rocks).Select(i => MiningCut3Tests.Rock(150f + i, i / (float) rocks, size)).ToArray())); + Stock(scene, kind, (Commodity("Rock"), 1f), (Commodity("Gold"), 1f)); + var ship = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, scene.Hull), new EntitySettings()); + Zone NewZone() + { + var settings = MiningCut3Tests.PlanetSettings(); + settings.ChunkCompositionVariance = variance; + settings.AsteroidYield = new ExponentialLerp { Minimum = yield, Maximum = yield, Exponent = 1f }; + return new Zone(scene.Items, settings, scene.Pack, new GalaxyZone { Name = "MiningCut3", Owner = null }, null); + } + return (scene, NewZone, ship); + } + + // Every rock broken once; the shooter is not in the zone, so everything floats and the floats are the record. + private static (int Rock, int Gold)[] Break(MiningCut3Tests.Scene scene, Zone zone, Ship ship, int rocks, uint seed) => + Enumerable.Range(0, rocks).Select(rock => + { + var chunk = new ChunkId(scene.Belts[0], rock); + var before = zone.FloatingItems.Select(f => f.Item).ToArray(); + FireControl.Extract(zone, chunk, zone.Wear(chunk, 1e6f), ship, SimulationDice.For(seed, SimulationDice.OreStream, (uint) rock)); + var added = zone.FloatingItems.Select(f => f.Item).Except(before).ToArray(); + return (Units(added, "Rock", scene), Units(added, "Gold", scene)); + }).ToArray(); + + [Fact] + public void TheSameShotGivesTheSameOre() + { + var (scene, newZone, ship) = Field(20, .5f); + var first = Break(scene, newZone(), ship, 20, 11); + Assert.Equal(first, Break(scene, newZone(), ship, 20, 11)); + Assert.NotEqual(first, Break(scene, newZone(), ship, 20, 12)); + } + + // Composition is derived from the rock's identity every call: variance 0 reads the kind's ratio, variance above 0 gives + // rocks different mixes, and nothing stores it (a second zone of the pack reads the same mixes from the dice and keys). + [Fact] + public void CompositionVariesByRockAndIsDerived() + { + var (scene, even, ship) = Field(12, 1f, variance: 0f, yield: 600f); + // Equal weights, 600 units a rock: even splits within sampling noise (sigma about 12). + Assert.All(Break(scene, even(), ship, 12, 5), m => Assert.InRange(m.Rock, 240, 360)); + + var (scene2, varied, ship2) = Field(12, 1f, variance: 2f, yield: 600f); + var mixes = Break(scene2, varied(), ship2, 12, 5).Select(m => m.Rock).ToArray(); + Assert.True(mixes.Max() - mixes.Min() > 100, "rocks differ in mix when variance is above zero"); + Assert.Equal(mixes, Break(scene2, varied(), ship2, 12, 5).Select(m => m.Rock)); + } + + // ==== the shot's own dice: ShotId and the zone's DropSeed key the ore ==== + + // A rig whose rock outlives many shots and pays hundreds of units a hit, three ores, so a changed key shows in the mix. The rock is + // wider than the blast, so every blast wears it by the same share and only the dice can tell two shots apart. + private (MiningCut4bTests.Rig Rig, EquippedCargoBay Bay) Rich(WeaponFuse? fuse, float damage, uint galaxySeed = 0) + { + var (rig, bay) = Mining(bayWidth: 8, bayHeight: 8, damage: damage, fuse: fuse, galaxySeed: galaxySeed, rockSize: 1f, + ores: new[] { (Commodity("Rock"), 1f), (Commodity("Gold"), 1f), (Commodity("Ice"), 1f) }); + rig.Zone.Settings.AsteroidYield = new ExponentialLerp { Minimum = 6000f, Maximum = 6000f, Exponent = 1f }; + // Composition hashes the belt's record key, which differs per scene; variance 0 leaves the dice alone to vary the ore. + rig.Zone.Settings.ChunkCompositionVariance = 0f; + return (rig, bay); + } + + // Fires until `hits` shots have landed, returning each landed shot's payout (bay and floats together) as (Rock, Gold, Ice). + private static (int, int, int)[] Payouts(MiningCut4bTests.Rig rig, EquippedCargoBay bay, int hits) + { + IEnumerable Held() => bay.Cargo.Keys.Concat(rig.Zone.FloatingItems.Select(f => f.Item)); + var paid = new List<(int, int, int)>(); + var before = (0, 0, 0); + for (var shot = 0; shot < 100 && paid.Count < hits; shot++) + { + var landed = rig.Resolved.Count(o => o.Hit); + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + MiningCut4bTests.Run(rig, .05f); + if (rig.Resolved.Count(o => o.Hit) == landed) continue; + Assert.True(rig.Zone.ChunkExists(rig.Rock), "the rock must outlive the shots under test"); + var held = Held().ToArray(); + var now = (Units(held, "Rock", rig.Scene), Units(held, "Gold", rig.Scene), Units(held, "Ice", rig.Scene)); + paid.Add((now.Item1 - before.Item1, now.Item2 - before.Item2, now.Item3 - before.Item3)); + before = now; + } + Assert.Equal(hits, paid.Count); + return paid.ToArray(); + } + + // Which ore lands in which slot follows each scene's catalog keys, so scenes compare by the multiset of counts. + private static int[][] Mix(IEnumerable<(int, int, int)> paid) => paid.Select(p => new[] { p.Item1, p.Item2, p.Item3 }.OrderBy(n => n).ToArray()).ToArray(); + + [Theory] + [InlineData(null, 8f)] + [InlineData(WeaponFuse.Contact, 40f)] + public void TwoShotsInOneZonePayDifferentOre(WeaponFuse? fuse, float damage) + { + var (rig, bay) = Rich(fuse, damage); + var paid = Payouts(rig, bay, 2); + Assert.All(paid, p => Assert.True(p.Item1 + p.Item2 + p.Item3 > 100, "a shot pays hundreds of units")); + Assert.NotEqual(paid[0], paid[1]); + } + + [Theory] + [InlineData(null, 8f)] + [InlineData(WeaponFuse.Contact, 40f)] + public void ADifferentRunSeedPaysDifferentOreForTheSameShot(WeaponFuse? fuse, float damage) + { + var (a, bayA) = Rich(fuse, damage, galaxySeed: 7); + var (b, bayB) = Rich(fuse, damage, galaxySeed: 8); + Assert.NotEqual(a.Zone.DropSeed, b.Zone.DropSeed); + Assert.Equal(a.Zone.CombatSeed, b.Zone.CombatSeed); + Assert.NotEqual(Mix(Payouts(a, bayA, 1)), Mix(Payouts(b, bayB, 1))); + // The same seed repeats it. + var (c, bayC) = Rich(fuse, damage, galaxySeed: 7); + var (d, bayD) = Rich(fuse, damage, galaxySeed: 7); + Assert.Equal(Mix(Payouts(c, bayC, 1)), Mix(Payouts(d, bayD, 1))); + } +} diff --git a/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs new file mode 100644 index 000000000..5165a0f1e --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs @@ -0,0 +1,348 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using Xunit; + +// Mining Cut 5b (docs/mining-cut-refresh.md, Cut 5, Q6b = A): a mined unit carries an Extracted lot naming the zone, the belt +// and the ore; stacks merge, split, restore and save by lot. Fixtures are Cut 3's belt scene and Cut 5a's bay and stock helpers. +public sealed class MiningCut5bTests : IDisposable +{ + private readonly MiningCut3Tests _scenes = new MiningCut3Tests(); + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-mining5b-" + Guid.NewGuid().ToString("N")); + private uint _ordinal; + + public MiningCut5bTests() => Directory.CreateDirectory(_root); + + public void Dispose() + { + _scenes.Dispose(); + Directory.Delete(_root, true); + } + + private sealed class Field + { + public MiningCut3Tests.Scene Scene; + public Galaxy Galaxy; + public SimpleCommodityData Ore; + } + + // Two belts of rocks (size .5: 4 whole units a rock), one ore, in a galaxy of three zones. + private Field Build() + { + var ore = MiningCut5aTests.Commodity("Rock"); + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + var scene = _scenes.BuildScene(new[] { kind }, + MiningCut3Tests.Belt(kind, MiningCut3Tests.Rock(150f, 0f), MiningCut3Tests.Rock(155f, .3f)), + MiningCut3Tests.Belt(kind, MiningCut3Tests.Rock(160f, .6f))); + MiningCut5aTests.Stock(scene, kind, (ore, 1f)); + var game = new SavedGame + { + InfluenceScale = 1, + Seed = 5, Factions = new CultRecordRef[0], Relationships = new FactionRelationship[0], + HomeZones = new Dictionary(), BossZones = new Dictionary(), DiscoveredZones = new[] { 0 }, + ActionBarBindings = new SavedActionBarBinding[0], Entrance = 0, Exit = -1 + }; + var zones = Enumerable.Range(0, 3) + .Select(i => new SavedZone { Name = $"Z{i}", AdjacentZones = new int[0], Factions = new int[0], Owner = -1 }).ToArray(); + RunSave.Commit(scene.Cache, game, zones, new ProvenanceLedger()); + return new Field { Scene = scene, Galaxy = new Galaxy(scene.Cache, scene.Cache.GetGlobal(), _ => { }), Ore = ore }; + } + + private static Zone ZoneOf(Field f, int index) + { + var settings = MiningCut3Tests.PlanetSettings(); + settings.AsteroidYield = new ExponentialLerp { Minimum = 4f, Maximum = 4f, Exponent = 1f }; + return index < 0 + ? new Zone(f.Scene.Items, settings, f.Scene.Pack, new GalaxyZone { Name = "Lone", Owner = null }, null) + : new Zone(f.Scene.Items, settings, f.Scene.Pack, f.Galaxy.Zones[index], f.Galaxy); + } + + private Ship Shooter(Field f, Zone zone) + { + var ship = new Ship(f.Scene.Items, zone, MiningCut3Tests.Mint(f.Scene, f.Scene.Hull), new EntitySettings()); + zone.Admit(ship, piloted: false); + return ship; + } + + private void Mine(Field f, Zone zone, Ship ship, int belt, int rock) + { + var chunk = new ChunkId(f.Scene.Belts[belt], rock); + FireControl.Extract(zone, chunk, zone.Wear(chunk, 1e6f), ship, SimulationDice.For(zone.DropSeed, SimulationDice.OreStream, ++_ordinal)); + } + + private static SimpleCommodity[] Stacks(EquippedCargoBay bay) => bay.Cargo.Keys.OfType().OrderBy(s => s.Lot).ToArray(); + + [Fact] + public void MinedUnitsCarryAnExtractedLotNamingZoneBeltAndOre() + { + var f = Build(); + var zone = ZoneOf(f, 2); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 1, 0); + + var stack = Assert.Single(Stacks(bay)); + Assert.Equal(4, stack.Quantity); + Assert.NotEqual(0, stack.Lot); + var lot = f.Scene.Items.GetLot(stack); + var origin = Assert.IsType(lot.Origin); + Assert.Equal(2, origin.Zone); + Assert.Equal(f.Scene.Belts[1], origin.Body.Key); + Assert.Equal(stack.Data.Key, origin.Commodity.Key); + Assert.Equal(stack.Data.Key, lot.Design.Key); + Assert.Equal(1f, lot.Quality); + Assert.Equal(default, lot.Product); + } + + [Fact] + public void AZoneWithNoGalaxyIsMinus1() + { + var f = Build(); + var zone = ZoneOf(f, -1); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + Assert.Equal(-1, Assert.IsType(f.Scene.Items.GetLot(Assert.Single(Stacks(bay))).Origin).Zone); + } + + [Fact] + public void UnitsFromOneSourceStack_UnitsFromTwoSourcesDoNot() + { + var f = Build(); + var zone = ZoneOf(f, 1); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + Mine(f, zone, ship, 0, 1); + var one = Assert.Single(Stacks(bay)); + Assert.Equal(8, one.Quantity); + + Mine(f, zone, ship, 1, 0); + var stacks = Stacks(bay); + Assert.Equal(new[] { 8, 4 }, stacks.Select(s => s.Quantity)); + Assert.NotEqual(stacks[0].Lot, stacks[1].Lot); + Assert.Equal(2, f.Scene.Items.Lots.Lots.Values.Count(l => l.Origin is Extracted)); + // Two lots of one ore still total one commodity for the market and the hold. + Assert.Equal(12, MiningCut5aTests.Units(bay, "Rock", f.Scene)); + } + + // TryFindSpace and the at-coordinate store both look for a stack to top up: a stack of another lot is not one. + [Fact] + public void ASearchAndAStoreIgnoreAStackOfAnotherLot() + { + var f = Build(); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 1, 1, "Hold"); + var key = new CultRecordRef(f.Scene.Cache.RefOf(f.Ore).Key); + SimpleCommodity Units(int lot, int quantity) => new SimpleCommodity { Data = key, Lot = lot, Quantity = quantity }; + + Assert.True(bay.TryStore(Units(7, 90))); + Assert.False(bay.TryFindSpace(Units(8, 5), out _)); + Assert.True(bay.TryFindSpace(Units(7, 5), out _)); + var other = Units(8, 5); + Assert.False(bay.TryStore(other, new int2(0, 0))); + Assert.Equal(90, Assert.Single(bay.Cargo.Keys.OfType()).Quantity); + Assert.Equal(5, other.Quantity); + Assert.True(bay.TryStore(Units(7, 5), new int2(0, 0))); + Assert.Equal(95, Assert.Single(bay.Cargo.Keys.OfType()).Quantity); + } + + [Fact] + public void ASplitStackKeepsItsLot() + { + var f = Build(); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + var stack = Assert.Single(Stacks(bay)); + + var part = bay.Remove(stack, 3); + Assert.Equal(3, part.Quantity); + Assert.Equal(stack.Lot, part.Lot); + Assert.NotEqual(0, part.Lot); + Assert.Equal(1, stack.Quantity); + } + + // A saved stack above its design's MaxStack comes back as several stacks, every one of the saved lot. + [Fact] + public void ARestoredOversizeStackKeepsItsLot() + { + var f = Build(); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + for (var rock = 0; rock < 2; rock++) Mine(f, zone, ship, 0, rock); + var lot = Assert.Single(Stacks(bay)).Lot; + + var pack = EntitySerializer.Pack(ship); + f.Ore.MaxStack = 3; + var restored = EntitySerializer.Unpack(f.Scene.Items, zone, pack); + + var stacks = restored.CargoBays.SelectMany(Stacks).ToArray(); + Assert.Equal(8, stacks.Sum(s => s.Quantity)); + Assert.True(stacks.Length >= 3); + Assert.All(stacks, s => Assert.Equal(lot, s.Lot)); + } + + private CultCache Open() => AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), Path.Combine(_root, "run.cc"), Path.Combine(_root, "player.cc")); + + private static ShipPack PackHolding(int hullLot, params ItemInstance[] stacks) => new ShipPack + { + Name = "ship", Hull = new EquippableItem { Lot = hullLot }, + Equipment = Array.Empty<(int2, EquippableItem)>(), CargoBays = Array.Empty<(int2, EquippableItem)>(), + DockingBays = Array.Empty<(int2, EquippableItem)>(), + CargoContents = new[] { stacks.Select((s, i) => (new int2(i, 0), s)).ToArray() }, + DockingBayContents = Array.Empty<(int2, ItemInstance)[]>(), Children = Array.Empty(), + Temperature = new float[0, 0], Armor = new float[0, 0], Conductivity = new bool2[0, 0], + DockingBayAssignments = Array.Empty(), Settings = new EntitySettings(), WeaponGroups = Array.Empty() + }; + + // The ship's hull is a crafted item and roots like any other, so the fixture gives it a lot of its own. + private int _hullLot; + + // The ledger as the run file holds it after a save of ships holding `held`. + private ProvenanceLedger SaveAndReload(ProvenanceLedger live, params ItemInstance[] held) + { + _hullLot = live.Add(new Lot { Design = default, Origin = new Attributed(), Quality = 1f, Roles = new List() }); + using (var cache = AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), catalogWritable: true)) + { + cache.Commit(batch => batch.Upsert(new VerseGrammar { Revision = 1 })); + } + using (var cache = Open()) + { + var game = new SavedGame + { + InfluenceScale = 1, + Factions = new CultRecordRef[0], Relationships = new FactionRelationship[0], + HomeZones = new Dictionary(), BossZones = new Dictionary(), DiscoveredZones = new[] { 0 }, + ActionBarBindings = new SavedActionBarBinding[0], Exit = -1 + }; + var zone = new SavedZone + { + Name = "Zone 0", AdjacentZones = Array.Empty(), Factions = Array.Empty(), Owner = -1, + Contents = new ZonePack { Entities = new List { PackHolding(_hullLot, held) } } + }; + RunSave.Commit(cache, game, new[] { zone }, live); + } + using (var cache = Open()) return RunSave.Lots(cache); + } + + // An ore the draw never picks mints no lot: the ledger gains nothing for it, only for the ore that was drawn. + [Fact] + public void AnOreThatDrawsZeroUnitsMintsNoLot() + { + var f = Build(); + var dud = MiningCut5aTests.Commodity("Dud"); + MiningCut5aTests.Stock(f.Scene, f.Scene.Kinds[0], (f.Ore, 1f), (dud, 1e-12f)); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + var before = f.Scene.Items.Lots.Lots.Count; + Mine(f, zone, ship, 0, 0); + + Assert.Equal(4, MiningCut5aTests.Units(bay, "Rock", f.Scene)); + Assert.Equal(0, MiningCut5aTests.Units(bay, "Dud", f.Scene)); + Assert.Equal(before + 1, f.Scene.Items.Lots.Lots.Count); + Assert.Equal(1, f.Scene.Items.Lots.Lots.Values.Count(l => l.Origin is Extracted)); + } + + // A crafted item with no lot is corruption and the save says so; a SimpleCommodity at Lot 0 is ordinary stock. + [Fact] + public void ACraftedItemAtLotZeroFailsTheSaveLoudly() + { + var f = Build(); + var crafted = new EquippableItem { Data = f.Scene.Cache.RefOf(f.Scene.Hull), Lot = 0 }; + var thrown = Assert.Throws(() => SaveAndReload(new ProvenanceLedger(), crafted)); + Assert.Contains("Lot 0 is not in the provenance ledger", thrown.Message); + + var stock = new SimpleCommodity { Data = new CultRecordRef(f.Scene.Cache.RefOf(f.Ore).Key), Quantity = 3, Lot = 0 }; + var savedStock = SaveAndReload(new ProvenanceLedger(), stock); + Assert.Equal(new[] { _hullLot }, savedStock.Lots.Keys); + } + + [Fact] + public void AMinedStackSurvivesSaveGc() + { + var f = Build(); + var zone = ZoneOf(f, 1); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + Mine(f, zone, ship, 1, 0); + var held = Stacks(bay); + Assert.Equal(2, held.Length); + // A third lot nobody holds: floated and gone, or never collected. + var orphan = f.Scene.Items.ExtractedLot(1, new CultRecordKey("elsewhere"), f.Ore); + + var saved = SaveAndReload(f.Scene.Items.Lots, held); + + Assert.Equal(held.Select(s => s.Lot).Append(_hullLot).OrderBy(i => i), saved.Lots.Keys.OrderBy(i => i)); + Assert.DoesNotContain(orphan, saved.Lots.Keys); + var origin = Assert.IsType(saved[held[0].Lot].Origin); + Assert.Equal(1, origin.Zone); + Assert.Equal(f.Scene.Belts[0], origin.Body.Key); + } + + [Fact] + public void TheLotIndexIsRebuiltOnContinue() + { + var f = Build(); + var zone = ZoneOf(f, 1); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + var held = Assert.Single(Stacks(bay)); + + var saved = SaveAndReload(f.Scene.Items.Lots, held); + var continued = new ItemManager(1u, f.Scene.Cache, saved, RunSaveTests.TestSettings(), _ => { }); + + Assert.Equal(held.Lot, continued.ExtractedLot(1, f.Scene.Belts[0], f.Ore)); + Assert.Equal(2, saved.Lots.Count); // the mined lot and the hull + var next = continued.ExtractedLot(1, f.Scene.Belts[1], f.Ore); + Assert.NotEqual(held.Lot, next); + Assert.Equal(3, saved.Lots.Count); + // Zone and ore tell lots apart as the belt does. + Assert.NotEqual(next, continued.ExtractedLot(2, f.Scene.Belts[1], f.Ore)); + } + + // A save from before the field reached SimpleCommodity: Data, Rotation, Quantity and nothing else. + [Fact] + public void OldSavesReadLotZero() + { + var f = Build(); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ItemInstance).Assembly); + var key = new CultRecordRef(f.Scene.Cache.RefOf(f.Ore).Key); + var buffer = new System.Buffers.ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteArrayHeader(2); + writer.Write(0); // Union(0, SimpleCommodity) + writer.WriteArrayHeader(3); + MessagePackSerializer.Serialize(ref writer, key, options); + MessagePackSerializer.Serialize(ref writer, ItemRotation.None, options); + writer.Write(7); + writer.Flush(); + + var old = Assert.IsType(MessagePackSerializer.Deserialize(buffer.WrittenMemory, options)); + Assert.Equal(7, old.Quantity); + Assert.Equal(0, old.Lot); + Assert.Equal(key.Key, old.Data.Key); + + // A lot rides the wire; a Lot-0 stack is no root, so the old stack saves no lot. + var back = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize( + new SimpleCommodity { Data = key, Quantity = 2, Lot = 9 }, options), options); + Assert.Equal(9, back.Lot); + var savedOld = SaveAndReload(new ProvenanceLedger(), old); + Assert.Equal(new[] { _hullLot }, savedOld.Lots.Keys); // the hull only + } +} diff --git a/tests/Aetheria.Shared.Tests/MiningIndexTests.cs b/tests/Aetheria.Shared.Tests/MiningIndexTests.cs index e47f9a4a1..a90f8343b 100644 --- a/tests/Aetheria.Shared.Tests/MiningIndexTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningIndexTests.cs @@ -70,7 +70,7 @@ public sealed partial class MiningCut3Tests var centre = float2(-300, 820); var s = BuildSceneAt(centre, 5000f, 1234.5, null, new[] { kind }, Belt(kind, Annulus(rng, 3000, 200f, 900f)), Belt(kind, Annulus(rng, 700, 1000f, 1060f))); - for (var i = 0; i < 40; i++) Assert.True(s.Zone.Wear(new ChunkId(s.Belts[0], i * 73), 1e6f)); + for (var i = 0; i < 40; i++) Assert.True(s.Zone.Breaks(new ChunkId(s.Belts[0], i * 73), 1e6f)); var found = new List(); var nonEmpty = 0; diff --git a/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs b/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs index 374f9292e..e492b5835 100644 --- a/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs @@ -546,4 +546,130 @@ public sealed partial class MiningCut3Tests Assert.Equal(order[i % order.Count], observer.Target.Value); } } + + private static float2 Polar(float2 at, float distance, float angle) => at + distance * float2(cos(angle), sin(angle)); + + // Both presses, from nothing and from every target, visit `order` and wrap. + private static void AssertPressesWalk(Ship observer, List order) + { + observer.SetTarget(TargetRef.None); + for (var i = 0; i <= order.Count; i++) + { + Assert.True(observer.TargetNext()); + Assert.Equal(order[i % order.Count], observer.Target.Value); + } + observer.SetTarget(TargetRef.None); + for (var i = 0; i <= order.Count; i++) + { + Assert.True(observer.TargetPrevious()); + Assert.Equal(order[order.Count - 1 - i % order.Count], observer.Target.Value); + } + for (var i = 0; i < order.Count; i++) + { + observer.SetTarget(order[i]); + Assert.True(observer.TargetNext()); + Assert.Equal(order[(i + 1) % order.Count], observer.Target.Value); + observer.SetTarget(order[i]); + Assert.True(observer.TargetPrevious()); + Assert.Equal(order[(i + order.Count - 1) % order.Count], observer.Target.Value); + } + } + + // Ships keep their distance order for both presses at every range: the key is the distance itself past 1000 too, + // not a function that clamps or bends there. Ships stand on both sides of 1000, many thousand units out, each a + // distinct distance and admitted in an order unlike the distance order, so a key that ties or inverts any two + // falls back on zone order and shows. + [Fact] + public void ShipsPastAThousandUnitsAreOrderedByDistanceBothWays() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + var distances = new[] { 1800f, 700f, 2400f, 1200f, 400f, 4000f, 999f, 1500f, 1001f, 150f, 3100f, 1100f }; + for (var i = 0; i < distances.Length; i++) Sight(s, observer, Polar(at, distances[i], i * 1.9f)); + var order = ByDistance(s, observer, 120f); + Assert.True(order.Count(t => t.Chunk.HasValue) >= 8 && order.Count(t => t.Entity != null) == distances.Length, $"degenerate: {order.Count} candidates"); + var ships = order.Where(t => t.Entity != null).Select(t => length(t.Entity.Position.xz - at)).ToList(); + Assert.Equal(ships.OrderBy(d => d).ToList(), ships); + Assert.Equal(ships.Distinct().Count(), ships.Count); + AssertPressesWalk(observer, order); + } + + // The pilot's instruments bound the pick at every range: undetected ships stand from a few units out to well + // past the farthest seen one, on every bearing, among the seen ships, so a press that offers undetected ships + // within any window of distance (or only once the zone is crowded) offers one here. Every press walks the + // detected order, and the reticle aimed straight at each hidden ship still takes a detected target. + [Fact] + public void ShipsTheObserverHasNotDetectedAreNeverPickedAtAnyDistance() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + foreach (var (distance, i) in new[] { 60f, 300f, 800f, 1300f, 2000f }.Select((d, i) => (d, i))) Sight(s, observer, Polar(at, distance, i * 1.3f + .4f)); + var hidden = new List(); + for (var i = 0; i < 48; i++) + hidden.Add(Unseen(s, Polar(at, 2f * MathF.Pow(1.18f, i), i * 2.4f))); + var order = ByDistance(s, observer, 120f); + Assert.True(order.Count > 5 && order.Count(t => t.Entity != null) == 5, $"degenerate: {order.Count} candidates"); + Assert.All(hidden, h => Assert.DoesNotContain(h, order)); + var farthest = hidden.Max(h => length(h.Entity.Position.xz - at)); + Assert.True(farthest > 4000f && hidden.Count(h => length(h.Entity.Position.xz - at) is > 100f and < 2500f) > 10, "the hidden ships do not sweep the window"); + + AssertPressesWalk(observer, order); + foreach (var h in hidden) + { + var to = h.Entity.Position.xz - at; + observer.Aim = float3(to.x, 0, to.y); + observer.SetTarget(TargetRef.None); + Assert.True(observer.TargetUnderReticle()); + Assert.DoesNotContain(observer.Target.Value, hidden); + Assert.Contains(observer.Target.Value, order); + } + } + + // The distance key stays the distance far beyond the clamps a fixture reaching 4000 can see: ships stand out to + // 8000 units, several within any one quantum or round-number cap (4600 and 4900, 5200 and 5300, 7960, 7975 and 7990), + // and are admitted farthest first, so zone order is the exact reverse of distance order and any tie (a clamp, a + // coarse bucket, a cap on either key) shows as a swapped pair. + [Fact] + public void ShipsOutToEightThousandUnitsAreOrderedByDistanceBothWaysWhenAdmittedFarthestFirst() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + var distances = new[] { 7990f, 7975f, 7960f, 7900f, 7000f, 6100f, 5300f, 5200f, 4900f, 4600f, 4000f, 3600f, 3100f, 2900f, 1500f, 700f }; + for (var i = 0; i < distances.Length; i++) Sight(s, observer, Polar(at, distances[i], i * 1.9f)); + var order = ByDistance(s, observer, 120f); + Assert.True(order.Count(t => t.Chunk.HasValue) >= 8 && order.Count(t => t.Entity != null) == distances.Length, $"degenerate: {order.Count} candidates"); + var ships = order.Where(t => t.Entity != null).Select(t => length(t.Entity.Position.xz - at)).ToList(); + Assert.Equal(ships.OrderBy(d => d).ToList(), ships); + Assert.Equal(ships.Distinct().Count(), ships.Count); + Assert.True(ships.Last() > 7900f); + AssertPressesWalk(observer, order); + } + + // The same pins in a crowded zone: far more than 60 entities stand in it, ships the observer has not detected + // among them out to 8000 units, so a leak or a bent key gated on the zone's size shows here. + [Fact] + public void ShipsTheObserverHasNotDetectedAreNeverPickedInACrowdedZone() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + var seen = new[] { 6200f, 4700f, 2500f, 900f, 120f, 5400f }; + for (var i = 0; i < seen.Length; i++) Sight(s, observer, Polar(at, seen[i], i * 1.3f + .4f)); + var hidden = new List(); + for (var i = 0; i < 110; i++) + hidden.Add(Unseen(s, Polar(at, 3f * MathF.Pow(1.0885f, i), i * 2.4f))); + var order = ByDistance(s, observer, 120f); + Assert.True(s.Zone.Entities.Count > 100, $"zone holds {s.Zone.Entities.Count}"); + Assert.True(order.Count > seen.Length && order.Count(t => t.Entity != null) == seen.Length, $"degenerate: {order.Count} candidates"); + Assert.All(hidden, h => Assert.DoesNotContain(h, order)); + Assert.True(hidden.Max(h => length(h.Entity.Position.xz - at)) > 7500f, "the hidden ships do not reach the far window"); + AssertPressesWalk(observer, order); + foreach (var h in hidden.Where((_, i) => i % 3 == 0)) + { + var to = h.Entity.Position.xz - at; + observer.Aim = float3(to.x, 0, to.y); + observer.SetTarget(TargetRef.None); + Assert.True(observer.TargetUnderReticle()); + Assert.DoesNotContain(observer.Target.Value, hidden); + } + } } diff --git a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs index 7a399587f..ffe29bbc1 100644 --- a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs +++ b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs @@ -251,13 +251,12 @@ public sealed class OrbitsFromFieldTests : IDisposable cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes); cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var tutorial = authored.Read("TutorialGenerationSettings"); - var galaxy = new Galaxy(tutorial, authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var tutorial = TestCasts.Wide; + var galaxy = new Galaxy(tutorial, authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); var pack = ZoneGenerator.GenerateZone(items, authored.Read("ZoneSettings"), authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, - galaxy.IsPrelude, false); + true, false); var zone = new Zone(items, authored.Read("PlanetSettings"), pack, galaxy.Entrance, galaxy); var hosting = zone.Planets.Values.Select(body => body.Orbit.Key).ToHashSet(); diff --git a/tests/Aetheria.Shared.Tests/OreGeographyTests.cs b/tests/Aetheria.Shared.Tests/OreGeographyTests.cs index 20c1e9043..764ec66c0 100644 --- a/tests/Aetheria.Shared.Tests/OreGeographyTests.cs +++ b/tests/Aetheria.Shared.Tests/OreGeographyTests.cs @@ -128,14 +128,14 @@ public sealed class OreGeographyTests : IDisposable return reached; } - private static Galaxy Build(CultCache cache, bool prelude, uint seed, TutorialGenerationSettings cast = null) => prelude - ? new Galaxy(cast ?? Authored.Read("TutorialGenerationSettings"), Authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed) + private static Galaxy Build(CultCache cache, bool prelude, uint seed, GalaxyCast cast = null) => prelude + ? new Galaxy(cast ?? TestCasts.Wide, Authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed) : new Galaxy(Authored.Read("SectorGenerationSettings"), Authored.Read("SectorBackgroundSettings"), cache, _ => { }, null, seed); // Galaxy refuses some seeds (RestoredHullsTests calls it seed-dependent flakiness); those are skipped. - private static Galaxy TryBuild(CultCache cache, bool prelude, uint seed, TutorialGenerationSettings cast = null) + private static Galaxy TryBuild(CultCache cache, bool prelude, uint seed, GalaxyCast cast = null) { try { return Build(cache, prelude, seed, cast); } catch (Exception) { return null; } @@ -151,14 +151,14 @@ public sealed class OreGeographyTests : IDisposable Enumerable.Range(1, (int) last).Select(seed => SharedGalaxy(prelude, (uint) seed)).Where(galaxy => galaxy != null); // The demo's cast: the same fixed cast, with the province size chosen. - private static TutorialGenerationSettings Cast(int provinceZones) + private static GalaxyCast Cast(int provinceZones) { var cast = DemoTerminus.Cast; - return new TutorialGenerationSettings + return new GalaxyCast { ProtagonistFaction = cast.ProtagonistFaction, AntagonistFaction = cast.AntagonistFaction, BufferFaction = cast.BufferFaction, NeutralFactions = cast.NeutralFactions, QuestFaction = cast.QuestFaction, ZoneCount = cast.ZoneCount, LinkDensity = cast.LinkDensity, - ProvinceZones = provinceZones + ProvinceZones = provinceZones, InfluenceScale = cast.InfluenceScale }; } @@ -929,7 +929,7 @@ public sealed class OreGeographyTests : IDisposable { foreach (var zone in galaxy.Zones.Take(zones)) { - var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); + var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, entranceStation: zone == galaxy.Entrance); foreach (var belt in pack.Planets.Select(body => cache.Get(body)).OfType()) yield return (belt, zone, pack); } diff --git a/tests/Aetheria.Shared.Tests/PaintModeTests.cs b/tests/Aetheria.Shared.Tests/PaintModeTests.cs index 89b6fb39f..ab195813f 100644 --- a/tests/Aetheria.Shared.Tests/PaintModeTests.cs +++ b/tests/Aetheria.Shared.Tests/PaintModeTests.cs @@ -724,7 +724,7 @@ public sealed class PaintModeTests : IDisposable var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(5, reader.ReadInt32()); - Assert.Equal(14, reader.ReadArrayHeader()); + Assert.Equal(38, reader.ReadArrayHeader()); for (var slot = 0; slot < 12; slot++) reader.Skip(); Assert.Equal(90f, MessagePackSerializer.Deserialize(ref reader, WireOptions).Min); diff --git a/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs b/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs index 9490d049b..0d53a1706 100644 --- a/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs +++ b/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs @@ -30,8 +30,8 @@ public sealed class PlaceNamesTests : IDisposable } private static Galaxy Build(CultCache cache, bool prelude, uint seed) => prelude - ? new Galaxy(Authored.Read("TutorialGenerationSettings"), Authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed) + ? new Galaxy(TestCasts.Wide, Authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed) : new Galaxy(Authored.Read("SectorGenerationSettings"), Authored.Read("SectorBackgroundSettings"), cache, _ => { }, null, seed); diff --git a/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs b/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs index 76ad7c2f8..768bc8a14 100644 --- a/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs +++ b/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs @@ -128,6 +128,7 @@ public sealed class ProductChoiceTests : IDisposable var outZ = cache.GetByName("OutZ"); var game = new SavedGame { + InfluenceScale = 1, // Alpha's headquarters are in zone 0 and Zeta's in zone 1. Factions = new[] { cache.RefOf(outA), cache.RefOf(outZ), cache.RefOf(cache.GetByName("Alpha")), cache.RefOf(cache.GetByName("Zeta")) }, Relationships = new[] { FactionRelationship.Neutral, FactionRelationship.Neutral, FactionRelationship.Neutral, FactionRelationship.Neutral }, diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index 121d468b3..f33e11a46 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -61,9 +61,10 @@ public sealed class RestoredHullsTests } internal static CultCache OpenCatalog() => OpenReadOnlyRealCatalog(TestCatalog.Repo); + internal static CultCache OpenCatalogWithFixtures() => OpenReadOnlyRealCatalog(TestCatalog.RepoWithFixtures); - // Shared tutorial-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out - // so every test that needs a real tutorial Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds + // Shared cast-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out + // so every test that needs a real cast Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds // -- builds it the same way instead of re-inlining the same ~20 fields. internal static PlanetSettings AuthoredPlanetSettings() => AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read("PlanetSettings"); @@ -87,18 +88,6 @@ public sealed class RestoredHullsTests NameData = new string[0], }; - internal static TutorialGenerationSettings TutorialGalaxySettings() => new TutorialGenerationSettings - { - ProtagonistFaction = "Miss", AntagonistFaction = "Zhe", BufferFaction = "Luc", - NeutralFactions = new[] { "Aero", "Finch" }, QuestFaction = "Adras", LinkDensity = .5f, ZoneCount = 64, - }; - - internal static SectorBackgroundSettings TutorialBackgroundSettings() => new SectorBackgroundSettings - { - NoiseAmplitude = 1, NoiseOffset = .3f, NoiseGain = .7f, NoiseLacunarity = 2, NoiseFrequency = .1f, - NoisePosition = 536.5106f, CloudExponent = 10, CloudAmplitude = .01f, - }; - // A station's orbit is a copy of its source planet's own (Parent, Distance) (ZoneGenerator.CreateLagrangeOrbit), // so it always matches that one planet. It matches MORE than one planet only when the source planet shares its // distance with a sibling under the same parent -- exactly what ZoneGenerator's potentialLagrangePoints filter @@ -158,10 +147,10 @@ public sealed class RestoredHullsTests var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); for (var seed = 1u; seed <= 64u; seed++) { - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed); foreach (var zone in galaxy.Zones.Where(z => !ReferenceEquals(z, galaxy.Entrance))) { - var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: false, ambient: false)); + var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, entranceStation: false, ambient: false)); if (orbits.Length > 0 && !HasGenuineLagrangeCandidate(orbits)) return (seed, zone.Name); } } @@ -379,8 +368,8 @@ public sealed class RestoredHullsTests public void EntranceZoneAlwaysGetsADockedStationAcrossSeeds() { var zoneSettings = TutorialZoneSettings(); - var tutorialSettings = TutorialGalaxySettings(); - var background = TutorialBackgroundSettings(); + var tutorialSettings = TestCasts.Wide; + var background = TestCasts.Background; var gameData = TestCatalog.Repo; var sawGenuineLagrangeOrbit = false; for (uint seed = 1; seed <= 25; seed++) @@ -389,10 +378,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(tutorialSettings, background, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(tutorialSettings, background, cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var dockedStation = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -412,15 +401,15 @@ public sealed class RestoredHullsTests // Cut 1 fix batch 3 (F6, N1): a per-seed strengthening of the "across seeds" test above. That test only // requires a genuine Lagrange orbit at least once in 25 seeds; it says nothing about a seed where a genuine // candidate DID exist but the station landed on the widened fallback anyway (which the widening condition's - // own isTutorialEntrance-and-empty-candidates guard should make impossible). This pins the normal case + // own entranceStationEntrance-and-empty-candidates guard should make impossible). This pins the normal case // directly, seed by seed: whenever the entrance zone actually has a genuine (non-rosette) Lagrange candidate, // its station must be seated on one. [Fact] public void EntranceStationSitsOnAGenuineLagrangeOrbitWheneverOneExists() { var zoneSettings = TutorialZoneSettings(); - var tutorialSettings = TutorialGalaxySettings(); - var background = TutorialBackgroundSettings(); + var tutorialSettings = TestCasts.Wide; + var background = TestCasts.Background; var gameData = TestCatalog.Repo; var sawGenuineCandidate = false; for (uint seed = 1; seed <= 25; seed++) @@ -429,10 +418,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(tutorialSettings, background, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(tutorialSettings, background, cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var planetOrbits = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Where(o => o.Parent.IsSet()).ToArray(); var hasGenuineCandidate = planetOrbits.Any(o => planetOrbits.Count(c => c.Parent.Key.Equals(o.Parent.Key) && abs(c.Distance - o.Distance) < .1f) == 1); @@ -467,7 +456,7 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); var zoneSettings = TutorialZoneSettings(); @@ -477,7 +466,7 @@ public sealed class RestoredHullsTests zoneSettings.SubZoneCount = new ExponentialLerp { Exponent = 1, Minimum = 0, Maximum = 0 }; Assert.Throws(() => - ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true)); + ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true)); } finally { @@ -502,7 +491,7 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); var zoneSettings = TutorialZoneSettings(); @@ -511,7 +500,7 @@ public sealed class RestoredHullsTests zoneSettings.SatelliteCreationProbability = 0; zoneSettings.BinaryCreationProbability = 0; - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var roots = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Count(o => !o.Parent.IsSet()); Assert.True(roots > 1, $"this fixture no longer produces a multi-root entrance (only {roots} root); it no longer tests the fragmented-topology case."); @@ -541,8 +530,8 @@ public sealed class RestoredHullsTests public void EntranceStationPhaseDiffersFromEveryPlanetAtItsOwnDistanceAcrossSeeds() { var zoneSettings = TutorialZoneSettings(); - var tutorialSettings = TutorialGalaxySettings(); - var background = TutorialBackgroundSettings(); + var tutorialSettings = TestCasts.Wide; + var background = TestCasts.Background; var gameData = TestCatalog.Repo; var checkedAny = false; @@ -552,10 +541,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(tutorialSettings, background, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(tutorialSettings, background, cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var dockedStation = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -687,7 +676,7 @@ public sealed class RestoredHullsTests // real zone from a real galaxy (e.g. one already known to have no Lagrange candidate) and make it the Entrance. private static Galaxy BuildGalaxyWithForcedEntrance(CultCache cache, uint seed, string entranceZoneName) { - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed); var target = galaxy.Zones.Single(z => z.Name == entranceZoneName); var factions = galaxy.Factions; @@ -714,7 +703,7 @@ public sealed class RestoredHullsTests Relationships = factions.Select(f => galaxy.FactionRelationships[f]).ToArray(), DiscoveredZones = Array.Empty(), Background = galaxy.Background, - IsTutorial = true, + InfluenceScale = .5f, }; return new Galaxy(cache, game, _ => { }); } @@ -749,7 +738,7 @@ public sealed class RestoredHullsTests var galaxy = BuildGalaxyWithForcedEntrance(cache, seed, zoneName); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var station = pack.Entities.OfType() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -798,24 +787,24 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - int StationCount(GalaxyZone zone, bool isTutorial) => - ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial) + int StationCount(GalaxyZone zone, bool entranceStation) => + ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, entranceStation) .Entities.OfType() .Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); // (a) A non-entrance tutorial zone that naturally rolls zero stations keeps that roll under - // isTutorial: true -- the floor must not leak past the galaxy.Entrance reference check. - // The zone is chosen by its natural roll: zero stations without the tutorial floor (isTutorial: false). - var otherZone = galaxy.Zones.First(z => !ReferenceEquals(z, galaxy.Entrance) && StationCount(z, isTutorial: false) == 0); + // entranceStation: true -- the floor must not leak past the galaxy.Entrance reference check. + // The zone is chosen by its natural roll: zero stations without the tutorial floor (entranceStation: false). + var otherZone = galaxy.Zones.First(z => !ReferenceEquals(z, galaxy.Entrance) && StationCount(z, entranceStation: false) == 0); Assert.NotSame(galaxy.Entrance, otherZone); - Assert.Equal(0, StationCount(otherZone, isTutorial: true)); + Assert.Equal(0, StationCount(otherZone, entranceStation: true)); - // (b) The entrance zone itself, generated for a non-tutorial game (isTutorial: false), keeps its - // natural roll too -- the floor must not leak past the isTutorial flag either. - Assert.Equal(0, StationCount(galaxy.Entrance, isTutorial: false)); + // (b) The entrance zone itself, generated for a non-tutorial game (entranceStation: false), keeps its + // natural roll too -- the floor must not leak past the entranceStation flag either. + Assert.Equal(0, StationCount(galaxy.Entrance, entranceStation: false)); } finally { @@ -826,7 +815,7 @@ public sealed class RestoredHullsTests // Cut 1 fix batch 2 (Soul's finding #2, baseStationCount): the entrance override raises stationCount (the // orbit-selection floor) but must not also raise the enemyCount roll, which is keyed to baseStationCount // (the pre-override value) precisely so the forced station doesn't buy the zone an extra enemy. Seed 1's - // entrance zone rolls baseStationCount 0 (confirmed via the isTutorial: false StationCount == 0 above) and + // entrance zone rolls baseStationCount 0 (confirmed via the entranceStation: false StationCount == 0 above) and // the override raises stationCount to 1; this pins the resulting ship count at the value baseStationCount // produces. It must fail if the enemy-count formula is changed to add stationCount instead (it would add a // ship instead of zero). @@ -838,10 +827,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var stationCount = pack.Entities.OfType().Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); // Soul's finding (this cut's fix batch 3): pack.Entities.OfType().Count() also counts the // zone's neutral wanderers (ZoneGenerator.cs's own EligibleWandererFactions spawn, keyed to @@ -868,12 +857,12 @@ public sealed class RestoredHullsTests // here by boosting one faction's presence there (HomeZone distance 0, InfluenceDistance 50, so the roll's // floor(rand * (factionPresence+1)) is overwhelmingly likely nonzero) via the same public SavedGame round // trip BuildGalaxyWithForcedEntrance uses, not by touching ZoneGenerator's private roll. Verified directly: - // temporarily widening every zone (dropping ZoneGenerator's isTutorialEntrance guard) turns this fixture's + // temporarily widening every zone (dropping ZoneGenerator's entranceStationEntrance guard) turns this fixture's // station count from 0 into 2, so a natural nonzero roll really is hiding behind the empty candidate set. // Must fail if that guard is dropped for real. private static Galaxy BuildGalaxyWithBoostedPresence(CultCache cache, uint seed, string zoneName) { - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed); var target = galaxy.Zones.Single(z => z.Name == zoneName); var factions = galaxy.Factions; @@ -905,7 +894,7 @@ public sealed class RestoredHullsTests Relationships = factions.Select(f => galaxy.FactionRelationships[f]).ToArray(), DiscoveredZones = Array.Empty(), Background = galaxy.Background, - IsTutorial = true, + InfluenceScale = .5f, }; return new Galaxy(cache, game, _ => { }); } @@ -924,7 +913,7 @@ public sealed class RestoredHullsTests Assert.NotSame(galaxy.Entrance, zone); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, entranceStation: true); // Confirms this fixture still has no genuine (non-rosette) Lagrange candidate -- a regression here // would mean the fixture no longer probes what this test claims to probe. diff --git a/tests/Aetheria.Shared.Tests/RunGoalTests.cs b/tests/Aetheria.Shared.Tests/RunGoalTests.cs index cfdbdb158..6d4646284 100644 --- a/tests/Aetheria.Shared.Tests/RunGoalTests.cs +++ b/tests/Aetheria.Shared.Tests/RunGoalTests.cs @@ -21,7 +21,7 @@ public sealed partial class RunStartTests private ZonePack BossZonePack(Galaxy galaxy, ItemManager items, GalaxyZone zone, bool ambient = true, uint seed = 7) { items.Random = new CultMath.Random(seed); - return ZoneGenerator.GenerateZone(items, _zoneSettings, _planetSettings, galaxy, zone, galaxy.IsPrelude, ambient); + return ZoneGenerator.GenerateZone(items, _zoneSettings, _planetSettings, galaxy, zone, entranceStation: zone == galaxy.Entrance, ambient); } private Zone ZoneOf(Galaxy galaxy, GalaxyZone zone) => @@ -414,6 +414,54 @@ public sealed partial class RunStartTests Assert.False(RunGoal.ExitOpen(ZoneOf(galaxy, zone))); } + // The gate belongs to the exit zone alone. A boss zone that is not the exit spawns its boss and loses it, and that zone's gate + // stays sealed: the exit check, not the boss mark, decides where a gate can open (a MainGalaxy choke-point boss zone is such a zone). + [Fact] + public void Exit_stays_sealed_in_a_non_exit_zone_whose_boss_died() + { + var galaxy = DemoGalaxy(1); + GiveAntagonistABoss(galaxy); + var other = galaxy.Zones.First(zone => zone != galaxy.Exit); + galaxy.BossZones[Zhestokost(galaxy)] = other; + + var zone = ZoneOf(galaxy, other); + Assert.True(zone.Pack.BossSpawned, "the fixture must spawn a boss outside the exit"); + var boss = Assert.Single(zone.Entities, entity => entity.IsBoss); + Assert.False(RunGoal.ExitOpen(zone)); + boss.HeatstrokeDeath.OnNext(Unit.Default); + Assert.False(RunGoal.BossAlive(zone)); + Assert.False(RunGoal.ExitOpen(zone), "a dead boss outside the exit zone opens no gate"); + } + + // The null-boss path through the real spawn loop: the boss zone is the exit, the faction's Loadout resolves, and + // Materialize cannot build it, so no boss is produced and the gate must not read as open. + // Both refusals (no Loadout, unbuildable Loadout) leave BossSpawned false. + [Fact] + public void A_refused_boss_leaves_the_exit_sealed_through_the_spawn_loop() + { + var galaxy = DemoGalaxy(1); + var loadout = GiveAntagonistABoss(galaxy); + var antagonist = Zhestokost(galaxy); + var exitZone = galaxy.Exit; + Assert.Equal(exitZone, galaxy.BossZones[antagonist]); + + // Unbuildable: the Loadout resolves and the entity is null. + loadout.Slots[0].Position = new int2(999, 999); + loadout.Slots[1].Position = new int2(998, 998); + StoreLoadout(loadout); + var unbuildable = ZoneOf(galaxy, exitZone); + Assert.False(unbuildable.Pack.BossSpawned); + Assert.DoesNotContain(unbuildable.Entities, entity => entity.IsBoss); + Assert.False(RunGoal.ExitOpen(unbuildable)); + + // Unresolved: the faction's Loadout is gone, so BossOf returns null. + antagonist.BossLoadout = new CultRecordRef(Loadouts.KeyOf("No Such Loadout")); + var unresolved = ZoneOf(galaxy, exitZone); + Assert.False(unresolved.Pack.BossSpawned); + Assert.DoesNotContain(unresolved.Entities, entity => entity.IsBoss); + Assert.False(RunGoal.ExitOpen(unresolved)); + } + // Continue: the mark is saved with the zone and restored, so a boss alive when the run was saved is alive after. [Fact] public void Boss_mark_survives_continue() diff --git a/tests/Aetheria.Shared.Tests/RunLaunchTests.cs b/tests/Aetheria.Shared.Tests/RunLaunchTests.cs new file mode 100644 index 000000000..1c8b0e380 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/RunLaunchTests.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using Xunit; + +// RunStart.Launch decides whether a start produced a run; the game scene halts on its answer (a failed start clears the +// galaxy, and a scene with no galaxy steps nothing). Kills: a start that throws or returns nothing reading as a run, a +// failure with no reason to show on the menu, a thrown exception that is neither logged nor listed, and a start that +// worked being reported failed. +public sealed class RunLaunchTests +{ + [Fact] + public void AStartThatThrowsIsNoRunAndSaysWhy() + { + var failures = new List(); + var logged = new List(); + var staged = RunStart.Launch(() => throw new InvalidOperationException("the arena would not generate"), failures, logged.Add); + Assert.Null(staged); + Assert.Equal(new[] { "the arena would not generate" }, failures); + Assert.Single(logged); + } + + [Fact] + public void AStartThatReturnsNothingIsNoRunAndKeepsItsOwnReasons() + { + var failures = new List(); + Assert.Null(RunStart.Launch(() => { failures.Add("player: the scenario places no player"); return null; }, failures)); + Assert.Equal(new[] { "player: the scenario places no player" }, failures); + } + + [Fact] + public void AStartThatReturnsNothingAndSaysNothingStillGivesAReason() + { + var failures = new List(); + Assert.Null(RunStart.Launch(() => null, failures)); + Assert.Single(failures); + } + + [Fact] + public void AStartThatStagedIsARunWithNoFailures() + { + var failures = new List(); + var made = new RunStart.Staged(); + Assert.Same(made, RunStart.Launch(() => made, failures)); + Assert.Empty(failures); + } +} diff --git a/tests/Aetheria.Shared.Tests/RunSaveTests.cs b/tests/Aetheria.Shared.Tests/RunSaveTests.cs index 545c1681a..33b139fb9 100644 --- a/tests/Aetheria.Shared.Tests/RunSaveTests.cs +++ b/tests/Aetheria.Shared.Tests/RunSaveTests.cs @@ -458,6 +458,7 @@ public sealed class RunSaveTests : IDisposable var game = new SavedGame { + InfluenceScale = 1, Factions = Array.Empty>(), Relationships = Array.Empty(), HomeZones = new Dictionary(), @@ -841,6 +842,7 @@ public sealed class RunSaveTests : IDisposable // HomeZones lists the factions in reverse of their saved order. private static SavedGame Game(CultCache cache, params Faction[] factions) => new SavedGame { + InfluenceScale = 1, Factions = factions.Select(f => cache.RefOf(f)).ToArray(), Relationships = factions.Select(_ => FactionRelationship.Neutral).ToArray(), HomeZones = factions.Select((_, i) => factions.Length - 1 - i).ToDictionary(i => i, _ => 0), diff --git a/tests/Aetheria.Shared.Tests/RunSeedFixture.cs b/tests/Aetheria.Shared.Tests/RunSeedFixture.cs index 0152584b7..2f4acf413 100644 --- a/tests/Aetheria.Shared.Tests/RunSeedFixture.cs +++ b/tests/Aetheria.Shared.Tests/RunSeedFixture.cs @@ -9,6 +9,7 @@ internal static class RunSeedFixture { var game = new SavedGame { + InfluenceScale = 1, Seed = seed, Factions = new CultRecordRef[0], Relationships = new FactionRelationship[0], diff --git a/tests/Aetheria.Shared.Tests/RunStartGearTests.cs b/tests/Aetheria.Shared.Tests/RunStartGearTests.cs index 2d0e1fb67..9abaae4a6 100644 --- a/tests/Aetheria.Shared.Tests/RunStartGearTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartGearTests.cs @@ -79,9 +79,9 @@ public sealed partial class RunStartTests } [Fact] - public void APreludeNoLongerOffersEverything() + public void ACastGalaxyNoLongerOffersEverything() { - Assert.True(_galaxy.IsPrelude); + Assert.Equal(.5f, _galaxy.InfluenceScale); var (absentProduct, _) = AbsentMaker("AbsentToPrelude"); var generator = GeneratorFor(_galaxy, "PreludeLoner"); Assert.False(generator.IsAvailable(absentProduct)); diff --git a/tests/Aetheria.Shared.Tests/RunStartTests.cs b/tests/Aetheria.Shared.Tests/RunStartTests.cs index efd17eb71..3ea2f2fdc 100644 --- a/tests/Aetheria.Shared.Tests/RunStartTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartTests.cs @@ -17,7 +17,7 @@ using float2 = CultMath.float2; using float3 = CultMath.float3; // RunStart owns what a new run starts with, and Zone.Admit is the one admission into a zone (docs/scenarios-cut.md, -// 2.2 and R). Every test stages into a real arena: the entrance zone of a prelude galaxy at a fixed seed, built from a +// 2.2 and R). Every test stages into a real arena: the entrance zone of a cast galaxy at a fixed seed, built from a // scratch copy of the catalog the game boots (TestCatalog) and the authored settings (Assets/Resources/Settings.asset). public sealed partial class RunStartTests : IDisposable { @@ -31,7 +31,6 @@ public sealed partial class RunStartTests : IDisposable private readonly PlanetSettings _planetSettings; private readonly string _startingHull; private readonly Faction _protagonist; - private readonly TutorialGenerationSettings _tutorialSettings; public RunStartTests() { @@ -49,10 +48,9 @@ public sealed partial class RunStartTests : IDisposable var authored = AuthoredSettings.Load(repo); _zoneSettings = authored.Read("ZoneSettings"); _planetSettings = authored.Read("PlanetSettings"); - var tutorial = _tutorialSettings = authored.Read("TutorialGenerationSettings"); - _galaxy = new Galaxy(tutorial, authored.Read("TutorialBackgroundSettings"), - _cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, GalaxySeed); + var tutorial = TestCasts.Wide; + _galaxy = new Galaxy(tutorial, authored.Read("CastBackgroundSettings"), + _cache, _ => { }, null, GalaxySeed); _items = new ItemManager(1u, _cache, new ProvenanceLedger(), RestoredHullsTests.PinnedFlight(authored.Read("GameplaySettings")), _ => { }); _protagonist = _galaxy.ResolveFaction(tutorial.ProtagonistFaction); @@ -125,11 +123,11 @@ public sealed partial class RunStartTests : IDisposable var background = authored.Read("SectorBackgroundSettings"); var sector = authored.Read("SectorGenerationSettings"); sector.ZoneCount = 8; - var tutorial = authored.Read("TutorialGenerationSettings"); + var tutorial = TestCasts.Wide; var main = Assert.Throws(() => new Galaxy(sector, background, _cache, _ => { }, null, 0)); var prelude = Assert.Throws(() => - new Galaxy(tutorial, background, _cache, new PlayerSettings(), new DirectoryInfo(_root), _ => { }, null, 0)); + new Galaxy(tutorial, background, _cache, _ => { }, null, 0)); foreach (var refusal in new[] { main, prelude }) { Assert.Equal("seed", refusal.ParamName); @@ -161,7 +159,7 @@ public sealed partial class RunStartTests : IDisposable public void EveryFactionsStationsCarryOnlyGearItCanReachIncludingAHeaterAndAReactor() { var galaxy = MainSectorGalaxy(); - Assert.False(galaxy.IsPrelude); + Assert.Equal(1f, galaxy.InfluenceScale); var zone = Arena(true); foreach (var faction in galaxy.Factions) { diff --git a/tests/Aetheria.Shared.Tests/ScannerTests.cs b/tests/Aetheria.Shared.Tests/ScannerTests.cs index b470d2ae0..7184659b2 100644 --- a/tests/Aetheria.Shared.Tests/ScannerTests.cs +++ b/tests/Aetheria.Shared.Tests/ScannerTests.cs @@ -484,7 +484,7 @@ public sealed partial class ContactRevealTests var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(51, reader.ReadInt32()); // sensor-catalog holds 50; a key reused across branches would collide on the wire - Assert.Equal(4, reader.ReadArrayHeader()); // Group is key 0, then the three stats + Assert.Equal(38, reader.ReadArrayHeader()); // array-format union: the base's element id sits at key 37, so every behavior row is 38 long; Group is key 0, then the three stats reader.Skip(); Assert.Equal(200f, MessagePackSerializer.Deserialize(ref reader, options).Min); // key 1 Range Assert.Equal(2f, MessagePackSerializer.Deserialize(ref reader, options).Min); // key 2 ScanTime diff --git a/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs new file mode 100644 index 000000000..43dec542a --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs @@ -0,0 +1,102 @@ +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// How much ammunition a staged scenario really spends over a run (ruling ballistics-real-ammo): the crates a scenario authors are pinned to +// this measurement, not to an estimate. A run is RunSeconds of continuous play: the player holds every ammunition-drawing weapon down with its +// hostile-or-flank hull standing in weapon range, an AI shooter fires on its own, and every hull keeps its armour so no shooter or target leaves +// the run early. The draw is counted in crates (one reload per crate) and each drawn crate is put back, so the count is not capped by the stock. +public sealed partial class RunStartTests +{ + // Ceiling of the window: a shooter holding every gun down dies of heat at ~250-270 s, so the draws are bounded by heat death, not by this. + public const float RunSeconds = 600f; + + // Crates each armed entity of the scenario draws over the run, keyed by (index in the stage's entities, -1 for the player; ammunition name), + // and the crates each held when the run began. + private (Dictionary<(int, string), int> drawn, Dictionary<(int, string), int> stocked) RunAmmunition(Scenario scenario, bool playerFires, bool standNearHostile) + { + var (_, arena, staged, failures) = Launch(scenario, Inputs(() => GalaxySeed)); + Assert.Empty(failures); + arena.Update(0); + var shooters = staged.Entities.Select((entity, index) => (entity, index)).Append((staged.Player, -1)) + .Where(s => s.Item1.Weapons.Any(weapon => weapon.WeaponData.AmmoType.IsSet())).ToList(); + var drawn = new Dictionary<(int, string), int>(); + var stocked = new Dictionary<(int, string), int>(); + var held = new Dictionary<(int, string), int>(); + string NameOf(CultRecordKey key) => _items.ItemData.Get(key).Name; + foreach (var (entity, index) in shooters) + foreach (var key in entity.Weapons.Where(weapon => weapon.WeaponData.AmmoType.IsSet()).Select(weapon => weapon.WeaponData.AmmoType.Key).Distinct()) + { + stocked[(index, NameOf(key))] = entity.CountItemsInCargo(key); + // A shooter with no crate cannot reload at all, so a run could not show what it would draw: it is given one to start. + if (stocked[(index, NameOf(key))] == 0) + entity.CargoBays.First().TryStore(new SimpleCommodity { Data = new CultRecordRef(key), Quantity = 1 }); + drawn[(index, NameOf(key))] = 0; + held[(index, NameOf(key))] = entity.CountItemsInCargo(key); + } + var everyone = staged.Entities.Append(staged.Player).ToList(); + var player = staged.Player; + var sound = everyone.SelectMany(entity => entity.Equipment).ToDictionary(item => item, item => item.EquippableItem.Durability); + var hostile = standNearHostile ? staged.Entities.First(entity => player.IsHostileTo(entity)) : null; + for (var tick = 0; tick < System.MathF.Round(RunSeconds / SimClock.GameStep); tick++) + { + foreach (var entity in everyone) + for (var x = 0; x < entity.Armor.GetLength(0); x++) + for (var y = 0; y < entity.Armor.GetLength(1); y++) + entity.Armor[x, y] = entity.MaxArmor[x, y]; + foreach (var (item, durability) in sound) item.EquippableItem.Durability = durability; + if (hostile != null) player.Position = hostile.Position + CultMath.math.float3(-200, 0, 0); + if (playerFires) + foreach (var weapon in player.Weapons.Where(weapon => weapon.WeaponData.AmmoType.IsSet())) weapon.Activate(); + arena.Update(SimClock.GameStep); + foreach (var (entity, index) in shooters) + foreach (var key in entity.Weapons.Where(weapon => weapon.WeaponData.AmmoType.IsSet()).Select(weapon => weapon.WeaponData.AmmoType.Key).Distinct()) + { + var slot = (index, NameOf(key)); + var spent = held[slot] - entity.CountItemsInCargo(key); + if (spent <= 0) continue; + drawn[slot] += spent; + for (var crate = 0; crate < spent; crate++) + entity.CargoBays.First().TryStore(new SimpleCommodity { Data = new CultRecordRef(key), Quantity = 1 }); + } + } + return (drawn, stocked); + } + + // The most crates each shooter draws in any of the modes, and what it was stocked with. + private List<(int shooter, string ammo, int drawn, int stocked)> WorstRun(Scenario scenario, params (bool playerFires, bool standNearHostile)[] modes) + { + var worst = new Dictionary<(int, string), (int drawn, int stocked)>(); + foreach (var (fires, near) in modes) + { + var (drawn, stocked) = RunAmmunition(scenario, fires, near); + foreach (var slot in drawn.Keys) + worst[slot] = (System.Math.Max(drawn[slot], worst.TryGetValue(slot, out var seen) ? seen.drawn : 0), stocked[slot]); + } + return worst.Select(kv => (kv.Key.Item1, kv.Key.Item2, kv.Value.drawn, kv.Value.stocked)).ToList(); + } + + // Arcs, run to its end twice: the player holding every gun down, and the player standing in the hostile turret's range while the turret + // shoots. Kills: a crate count nobody measured (the turret's 30 and the player's none were estimates), a scenario shooter stocked below + // what a run draws so its guns go silent, and a harness that measures nothing. + [Fact] + public void ArcsStocksEveryShooterForARun() + { + var run = WorstRun(new Arcs(), (true, false), (false, true)); + Assert.Contains(run, r => r.shooter == 2 && r.ammo == "Ammo" && r.drawn > 0); + Assert.Contains(run, r => r.shooter == -1 && r.ammo == "Ammo" && r.drawn > 0); + Assert.All(run, r => Assert.True(r.stocked >= r.drawn, $"Arcs shooter {r.shooter} drew {r.drawn} {r.ammo} over a run and was stocked {r.stocked}")); + } + + // Pursuit, the player holding every gun down and the pursuer shooting back, then the player idle. Kills: as above, for the Mine Launcher's + // crates and the pursuer's. + [Fact] + public void PursuitStocksEveryShooterForARun() + { + var run = WorstRun(new Pursuit(), (true, false), (false, false)); + Assert.Contains(run, r => r.shooter == -1 && r.ammo == "Mines" && r.drawn > 0); + Assert.Contains(run, r => r.shooter == 0 && r.ammo == "Ammo" && r.drawn > 0); + Assert.All(run, r => Assert.True(r.stocked >= r.drawn, $"Pursuit shooter {r.shooter} drew {r.drawn} {r.ammo} over a run and was stocked {r.stocked}")); + } +} diff --git a/tests/Aetheria.Shared.Tests/ScenarioAmmunitionTests.cs b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionTests.cs new file mode 100644 index 000000000..740e793a2 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionTests.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Linq; +using UniRx; +using Xunit; + +// Scenarios that author a weapon's ammunition-fed crates in a hold (ruling ballistics-real-ammo): the staged hold is what the weapon reloads from, so a +// scenario whose check rests on a weapon firing past its first magazine states the crates it needs. Each test launches through the production path. +public sealed partial class RunStartTests +{ + // The Arcs turret fits two Light Machine Guns of a hundred rounds and a bay of Ammo: its hold holds what the scenario states, and across a minute + // in range of the player it fires past both first magazines, each reload taking a crate. Kills: a turret fit without a bay or with no authored + // crates (silent after one magazine), and Cargo failing to admit a commodity. + [Fact] + public void TheArcsTurretKeepsFiringPastItsFirstMagazine() + { + var (_, arena, staged, failures) = Launch(new Arcs(), Inputs(() => GalaxySeed)); + Assert.Empty(failures); + var player = staged.Player; + var turret = Assert.IsType(staged.Entities[2]); + var guns = turret.Weapons.ToList(); + Assert.Equal(2, guns.Count); + var ammo = guns[0].WeaponData.AmmoType.Key; + Assert.Equal(Arcs.TurretAmmoCrates, turret.CountItemsInCargo(ammo)); + + // The guns are Auto weapons: they fire on a hostile inside their range (400 m) with no pilot. The player starts 775 m off, so it flies up to 200 m. + arena.Update(0); + player.Position = turret.Position + new CultMath.float3(-200, 0, 0); + var shots = 0; + using var sub = arena.ShotCommitted.Subscribe(outcome => { if (ReferenceEquals(outcome.Source, turret)) shots++; }); + for (var tick = 0; tick < System.MathF.Round(60f / SimClock.GameStep); tick++) arena.Update(SimClock.GameStep); + + var firstMagazines = guns.Sum(gun => gun.WeaponData.MagazineSize); + Assert.True(shots > firstMagazines, $"the turret fired {shots} rounds, no more than its two first magazines of {firstMagazines}"); + Assert.True(turret.CountItemsInCargo(ammo) < Arcs.TurretAmmoCrates, "the turret reloaded without taking a crate"); + } + + // The Pursuit player's Mine Launcher draws its magazine of six from crates of Mines it carries beside the consumables: it lays past six, and the + // crate count falls by one per reload. Kills: authored cargo with no Mines (at most six mines), a reload that takes no crate. + [Fact] + public void ThePursuitPlayerLaysMoreThanOneMagazineOfMinesFromItsCrates() + { + var (_, arena, staged, failures) = Launch(new Pursuit(), Inputs(() => GalaxySeed)); + Assert.Empty(failures); + var player = staged.Player; + var launcher = player.Weapons.Single(weapon => weapon.WeaponData is MineLayerData); + var mines = launcher.WeaponData.AmmoType.Key; + Assert.Equal(Pursuit.MineCrates, player.CountItemsInCargo(mines)); + Assert.Equal(3, HeldOf(player, "Coolant Vent")); + + arena.Update(0); + var laid = 0; + using var sub = arena.Mines.ObserveAdd().Subscribe(_ => laid++); + var reloaded = new List(); + var last = Pursuit.MineCrates; + for (var tick = 0; tick < System.MathF.Round(120f / SimClock.GameStep) && laid <= 18; tick++) + { + launcher.Activate(); + arena.Update(SimClock.GameStep); + var crates = player.CountItemsInCargo(mines); + if (crates != last) { reloaded.Add(last - crates); last = crates; } + } + + Assert.True(laid > launcher.WeaponData.MagazineSize, $"the player laid {laid} mines, no more than one magazine of {launcher.WeaponData.MagazineSize}"); + Assert.NotEmpty(reloaded); + Assert.All(reloaded, step => Assert.Equal(1, step)); + } +} diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 7303931f0..f7a8f6a78 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -17,7 +17,7 @@ using float2 = CultMath.float2; using float3 = CultMath.float3; // Scenarios S2 (docs/scenarios-cut.md, R): every new run is a scenario. The fixture is RunStartTests': a scratch copy -// of the shipped catalog, the authored settings and a prelude galaxy at a fixed seed. +// of the shipped catalog, the authored settings and a cast galaxy at a fixed seed. public sealed partial class RunStartTests { // A test's own scenario: a script given inline, staged into the fixture's arena or launched whole. @@ -33,7 +33,7 @@ public sealed partial class RunStartTests _ambient = ambient; _stage = stage; _seed = seed; - _generate = generate ?? (galaxy => galaxy.Prelude()); + _generate = generate ?? (stage => stage.Cast(TestCasts.Wide)); } public override string Name => "Scripted"; @@ -54,9 +54,8 @@ public sealed partial class RunStartTests return new GalaxyStage( authored.Read("SectorGenerationSettings"), authored.Read("SectorBackgroundSettings"), - authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), - _cache, new PlayerSettings(), Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, clock); + authored.Read("CastBackgroundSettings"), + _cache, _ => { }, null, clock); } // What MainMenu.Launch and StartGame do with a scenario: its galaxy, its arena, then staging. beforeStaging stands in @@ -67,14 +66,14 @@ public sealed partial class RunStartTests var arena = new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, galaxy, scenario), galaxy.Entrance, galaxy); beforeStaging?.Invoke(); var failures = new List(); - var staged = RunStart.Stage(_items, arena, scenario, _startingHull, _tutorialSettings, failures); + var staged = RunStart.Stage(_items, arena, scenario, _startingHull, failures); return (galaxy, arena, staged, failures); } private RunStart.Staged Stage(Zone zone, Scenario scenario) { var failures = new List(); - var staged = RunStart.Stage(_items, zone, scenario, _startingHull, _tutorialSettings, failures); + var staged = RunStart.Stage(_items, zone, scenario, _startingHull, failures); Assert.True(failures.Count == 0, string.Join("; ", failures)); Assert.NotNull(staged); return staged; @@ -86,7 +85,7 @@ public sealed partial class RunStartTests var entities = zone.Entities.ToList(); var agents = zone.Agents.ToList(); var failures = new List(); - Assert.Null(RunStart.Stage(_items, zone, scenario, _startingHull, _tutorialSettings, failures)); + Assert.Null(RunStart.Stage(_items, zone, scenario, _startingHull, failures)); SafeAssert.Unchanged(zone, entities, agents); return failures; } @@ -123,26 +122,25 @@ public sealed partial class RunStartTests Assert.Equal(1234, poor.Credits); } - // The two game modes are what New Game did: the tutorial a prelude galaxy and a starting-hull ship of the - // protagonist faction at the entrance's origin; the main galaxy a main galaxy and a starting-hull ship there. Both - // arenas keep their generated ships. + // The two game modes are what New Game did: the demo a cast galaxy at half influence and a starting-hull ship at the + // entrance's origin; the main galaxy a main galaxy at full influence and a starting-hull ship there. Both arenas + // keep their generated ships. [Fact] public void ModesMatchOldNewGame() { Assert.Equal("Longinus", _startingHull); - var tutorial = Launch(new TutorialGalaxy(), Inputs(() => GalaxySeed)); - Assert.Empty(tutorial.failures); - Assert.True(tutorial.galaxy.IsPrelude, "the tutorial is a prelude galaxy"); - Assert.Equal(_startingHull, tutorial.staged.Player.HullData.Name); - Assert.Same(tutorial.galaxy.ResolveFaction(_tutorialSettings.ProtagonistFaction), tutorial.staged.Player.Faction); - Assert.Equal(float3.zero, tutorial.staged.Player.Position); - Assert.Empty(tutorial.staged.Entities); - Assert.Contains(tutorial.arena.Pack.Entities, entity => entity is ShipPack { IsPlayerShip: false }); + var demo = Launch(new DemoTerminus(), Inputs(() => GalaxySeed)); + Assert.Empty(demo.failures); + Assert.Equal(.5f, demo.galaxy.InfluenceScale); + Assert.Equal(_startingHull, demo.staged.Player.HullData.Name); + Assert.Equal(float3.zero, demo.staged.Player.Position); + Assert.Empty(demo.staged.Entities); + Assert.Contains(demo.arena.Pack.Entities, entity => entity is ShipPack { IsPlayerShip: false }); var main = Launch(new MainGalaxy(), Inputs(() => GalaxySeed)); Assert.Empty(main.failures); - Assert.False(main.galaxy.IsPrelude, "the main galaxy is not a prelude"); + Assert.Equal(1f, main.galaxy.InfluenceScale); Assert.Equal(_startingHull, main.staged.Player.HullData.Name); Assert.Equal(float3.zero, main.staged.Player.Position); Assert.Empty(main.staged.Entities); @@ -209,12 +207,12 @@ public sealed partial class RunStartTests Assert.NotEqual(Layout(a), Layout(b)); } - // Generating a galaxy writes nothing a later one reads: a prelude leaves the catalog's faction influence as authored. + // Generating a galaxy writes nothing a later one reads: a cast galaxy leaves the catalog's faction influence as authored. [Fact] public void AGalaxyLeavesTheCatalogsFactionsAsAuthored() { var authored = _cache.GetAll().ToDictionary(faction => faction, faction => faction.InfluenceDistance); - RunStart.Generate(new TutorialGalaxy(), Inputs()); + RunStart.Generate(new DemoTerminus(), Inputs()); RunStart.Generate(new MainGalaxy(), Inputs()); Assert.All(authored, pair => Assert.Equal(pair.Value, pair.Key.InfluenceDistance)); } @@ -233,7 +231,7 @@ public sealed partial class RunStartTests [InlineData(34u, false)] public void EveryZoneIsLinked(uint seed, bool prelude) { - var galaxy = RunStart.Generate(new Scripted(true, _ => { }, seed, stage => prelude ? stage.Prelude() : stage.Main()), Inputs()); + var galaxy = RunStart.Generate(new Scripted(true, _ => { }, seed, stage => prelude ? stage.Cast(TestCasts.Wide) : stage.Main()), Inputs()); Assert.All(galaxy.Zones, zone => Assert.Equal(galaxy.Zones.Length, zone.Distance.Count)); var positions = galaxy.Zones.Select(zone => zone.Position).ToArray(); @@ -401,6 +399,142 @@ public sealed partial class RunStartTests Assert.Equal(0, AgentsOf(zone, neutral)); } + // A summon places into a running zone through the stage's admission (ruling ifl-ships-in-demo-as-tactical-view): after a run + // has started and stepped, a piloted generated ship that approaches the player is a member with one agent, and its pilot + // knows the player by the sensors' own path. It holds no stance either way (ruling summons-follow-faction-logic: the faction + // rule decides). Kills: a summon that skips the pilot or the knowledge seed, or that writes any override. + [Fact] + public void ASummonJoinsARunningZone() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + for (var tick = 0; tick < 20; tick++) zone.Update(.1f); + + var failures = new List(); + var summoned = ZoneStage.Summon(_items, zone, stage => + { + var placed = stage.Place(stage.Generated("Longinus"), float2(400, 0), piloted: true); + stage.Approach(placed, player); + }, failures); + + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var raider = Assert.Single(summoned); + SafeAssert.In(zone, raider, "the summoned ship is admitted"); + Assert.Equal(1, AgentsOf(zone, raider)); + Assert.Null(raider.IffOverride(player)); + Assert.Null(player.IffOverride(raider)); + Assert.Equal((_items.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f, raider.EntityInfoGathered[player]); + for (var tick = 0; tick < 20; tick++) zone.Update(.1f); + Assert.Equal(1, AgentsOf(zone, raider)); + } + + // A summon writes no pin, so the grudge a provocation raises still lands (an override already held is never replaced: + // Entity.Provoke). Kills: any stance written at summon, which blocks the formation from fighting back. + [Fact] + public void ASummonedShipAnswersAProvocation() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var failures = new List(); + var placed = Assert.Single(ZoneStage.Summon(_items, zone, stage => + stage.Place(stage.Generated("Longinus"), float2(400, 0), piloted: true), failures)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + + placed.Provoke(player); + + Assert.True(placed.IsHostileTo(player), "a provoked summon did not turn on its attacker"); + } + + // A run-start script's Hostile is the only authored stance: written both ways with the player. Neutral is the absence of + // an override, not a pin to false. Kills: Neutral writing false; a Hostile written one way only. + [Fact] + public void ANeutralPlacementWritesNoOverride() + { + var staged = Stage(Arena(true), new Scripted(true, stage => + { + stage.Player(stage.Bare("Djinni"), float2(0, 0)); + stage.Place(stage.Generated("Longinus"), float2(300, 0), stance: ScenarioStance.Hostile, piloted: true); + stage.Place(stage.Bare("Longinus"), float2(-300, 0), stance: ScenarioStance.Neutral); + })); + var player = staged.Player; + var hostile = staged.Entities[0]; + var neutral = staged.Entities[1]; + + Assert.Null(neutral.IffOverride(player)); + Assert.Null(player.IffOverride(neutral)); + Assert.True(hostile.IffOverride(player) == true && player.IffOverride(hostile) == true, "hostile both ways"); + } + + // A summon naming a design the catalog lacks admits nothing, and names it. Kills: admitting before the failure check. + [Fact] + public void ARefusedSummonAdmitsNothing() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var entities = zone.Entities.ToList(); + var agents = zone.Agents.ToList(); + var failures = new List(); + + var summoned = ZoneStage.Summon(_items, zone, stage => + { + stage.Place(stage.Generated("Longinus"), float2(400, 0), piloted: true); + stage.Place(stage.Bare("No Such Hull"), float2(-400, 0)); + }, failures); + + Assert.Null(summoned); + Assert.Contains(failures, failure => failure.Contains("No Such Hull")); + SafeAssert.Unchanged(zone, entities, agents); + } + + // A refused summon leaves the item stream and the lot ledger (which a run save persists) where they were, so a refusal is neither + // a draw nor a mint. Kills: a summon that keeps the draws or the lots of the fits it built before refusing. + [Fact] + public void ARefusedSummonLeavesTheItemStream() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var before = _items.Random; + var nextLot = _items.Lots.NextLot; + var lots = _items.Lots.Lots.Keys.ToList(); + var failures = new List(); + + Assert.Null(ZoneStage.Summon(_items, zone, stage => + { + stage.Place(stage.Generated("Longinus"), float2(400, 0)); + stage.Place(stage.Bare("No Such Hull"), float2(-400, 0)); + }, failures)); + + var after = _items.Random; + Assert.Equal(before.NextUInt(), after.NextUInt()); + Assert.Equal(nextLot, _items.Lots.NextLot); + Assert.Equal(lots.OrderBy(id => id), _items.Lots.Lots.Keys.OrderBy(id => id)); + } + + // A faction's boss is the zone generator's to place (boss-hulls-exclusive): a preset naming the loadout Loadouts.BossOf + // returns is refused, through a summon as through a run start. Kills: a Preset that places any catalog loadout. + [Fact] + public void APresetCannotPlaceAFactionsBoss() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var boss = _cache.GetAll().Select(faction => Loadouts.BossOf(_cache, faction, out _)).First(loadout => loadout != null); + var entities = zone.Entities.ToList(); + var agents = zone.Agents.ToList(); + var failures = new List(); + + Assert.Null(ZoneStage.Summon(_items, zone, stage => + stage.Place(stage.Preset(boss.Name), float2(400, 0), piloted: true), failures)); + + Assert.Contains(failures, failure => failure.Contains(boss.Name) && failure.Contains("boss")); + SafeAssert.Unchanged(zone, entities, agents); + var started = Refused(Arena(true), new Scripted(true, stage => + { + stage.Player(stage.Bare("Djinni"), float2(0, 0)); + stage.Place(stage.Preset(boss.Name), float2(400, 0)); + })); + Assert.Contains(started, failure => failure.Contains("boss")); + } + // A stance lasts the sitting: the player docking and undocking leaves it standing both ways. It goes with an entity // gone for good: once an entity is destroyed, the player holds no stance toward it. [Fact] @@ -438,7 +572,7 @@ public sealed partial class RunStartTests public void UndockingAdmitsWithNoAgent() { var zone = Arena(true); - var player = Stage(zone, new TutorialGalaxy()).Player; + var player = Stage(zone, new Scripted(false, stage => stage.Player(stage.Generated(stage.StartingHull), float2(0, 0)))).Player; var station = zone.Entities.First(entity => entity is OrbitalEntity && entity.DockingBays.Count > 0); var agents = zone.Agents.Count; @@ -617,18 +751,69 @@ public sealed partial class RunStartTests Assert.Empty(UnsoldAndUnplaced(runs)); } - // Whether a run is the prelude is the galaxy's fact (Galaxy.IsPrelude); a save records it with no second owner. + // How far influence reaches is the galaxy's fact (Galaxy.InfluenceScale); a save records it with no second owner, and + // a save without one (written before it existed) is refused by name rather than read as full influence. [Fact] - public void SaveReadsPrelude() + public void InfluenceScaleRoundTripsAndOldSavesAreRefused() { var arena = Arena(true); - var (prelude, _) = RunSave.Capture(_cache, _galaxy, arena, null, new SavedActionBarBinding[0], 0); - Assert.True(prelude.IsTutorial); - + var (demo, _) = RunSave.Capture(_cache, _galaxy, arena, null, new SavedActionBarBinding[0], 0); + Assert.Equal(.5f, demo.InfluenceScale); var (main, _) = RunSave.Capture(_cache, MainSectorGalaxy(), arena, null, new SavedActionBarBinding[0], 0); - Assert.False(main.IsTutorial); + Assert.Equal(1f, main.InfluenceScale); + + var old = Assert.Throws(() => new Galaxy(_cache, new SavedGame + { + Zones = demo.Zones, Factions = demo.Factions, HomeZones = demo.HomeZones, BossZones = demo.BossZones, + Entrance = demo.Entrance, Exit = demo.Exit, DiscoveredZones = demo.DiscoveredZones, Background = demo.Background, + Relationships = demo.Relationships, Standings = demo.Standings, Seed = demo.Seed, + InfluenceScale = 0, + }, _ => { })); + Assert.Contains(nameof(SavedGame.InfluenceScale), old.Message); } + // The halving is the cast's: InfluenceOf scales a faction's authored distance by the galaxy's InfluenceScale, rounding up. + [Fact] + public void InfluenceOfMatchesTheHalving() + { + var half = _galaxy; + var full = MainSectorGalaxy(); + var faction = _cache.GetAll().First(); + var authored = faction.InfluenceDistance; + try + { + for (var distance = 0; distance <= 10; distance++) + { + faction.InfluenceDistance = distance; + Assert.Equal((distance + 1) / 2, half.InfluenceOf(faction)); + Assert.Equal(distance, full.InfluenceOf(faction)); + } + } + finally { faction.InfluenceDistance = authored; } + } + + // Whether the arena gets a forced entrance station is the scenario's declaration, not the galaxy's. At a seed whose + // natural roll is zero stations, a scenario declaring one gets a docking station and the same arena generated without + // the declaration gets none. + [Fact] + public void EntranceStationIsTheScenariosDeclaration() + { + Assert.True(new DemoTerminus().EntranceStation); + Assert.False(new MainGalaxy().EntranceStation); + + var natural = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, _galaxy, _galaxy.Entrance, entranceStation: false, ambient: false); + var forced = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, _galaxy, _galaxy.Entrance, entranceStation: true, ambient: false); + Assert.Equal(0, StationsOf(natural)); + Assert.True(StationsOf(forced) >= 1); + + // Through RunStart, the scenario's declaration is what reaches the generator. + Assert.True(StationsOf(RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new DemoTerminus())) >= 1); + Assert.Equal(0, StationsOf(RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new MainGalaxy()))); + } + + private int StationsOf(ZonePack pack) => + pack.Entities.OfType().Count(entity => (_cache.Get(entity.Hull.Data) as HullData)?.HullType == HullType.Station); + // PlayerSettings Key 2, the never-written tutorial flag, is retired: a player.cc written with it still loads, every other field intact. [Fact] public void OldPlayerSettingsLoad() @@ -672,4 +857,39 @@ public sealed partial class RunStartTests stale.Add(scenario.Name + " names " + retired); Assert.True(stale.Count == 0, "scenario briefs naming gear the catalog no longer has: " + string.Join("; ", stale)); } + + // The ruling's played case: nothing but the catalog's Relations makes two NPC factions fight. Two piloted ships of the cast's + // Zhe and Luc sit 400 apart in the arena; with Luc's record Hated toward Zhe the Zhestokost ship is hit or gone inside 60 s, + // and without it both keep full armor. Kills: no Hated branch; the relation read from the wrong side; a scenario stance doing + // the work. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TwoFactionsFightByRelationAlone(bool hated) + { + var zhe = _galaxy.ResolveFaction("Zhe"); + var luc = _galaxy.ResolveFaction("Luc"); + if (hated) + { + luc.Relations ??= new Dictionary, FactionRelationship>(); + luc.Relations[_cache.RefOf(zhe)] = FactionRelationship.Hated; + } + Entity zheShip = null, lucShip = null; + var (_, arena, _, failures) = Launch(new Scripted(false, stage => + { + stage.Player(stage.Bare("Djinni"), float2(0, 0)); + zheShip = stage.Place(stage.Generated("Longinus", zhe), float2(2000, 0), piloted: true); + lucShip = stage.Place(stage.Generated("Longinus", luc), float2(2000, 400), piloted: true); + })); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + Assert.Same(zhe, zheShip.Faction); + Assert.Same(luc, lucShip.Faction); + + for (var tick = 0; tick < 600; tick++) arena.Update(.1f); + + bool Intact(Entity ship) => arena.Entities.Contains(ship) && + ship.Armor.Cast().Sum() >= ship.MaxArmor.Cast().Sum(); + Assert.Equal(!hated, Intact(zheShip)); + if (!hated) Assert.True(Intact(lucShip)); + } } diff --git a/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs index 850e83dfd..7ed2b84be 100644 --- a/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs @@ -180,24 +180,20 @@ public sealed class ShipAuthoringTests Assert.IsAssignableFrom(pull.InnerException); } - // A store header with a nil format stamp is refused by the runtime with NotSupportedException; Load names the file. + // A store header with a nil format stamp is refused by the runtime with CultStoreUnreadableException; Load names the file. [Fact] public void LoadNamesTheFileWhoseFormatStampIsNil() { using var directory = new TempDirectory(); var path = Path.Combine(directory.Path, "nilstamp.cc"); - File.WriteAllBytes(path, CultDocumentMessagePackSerialization.SerializeSnapshot(new CultPersistedStoreSnapshot - { - FormatVersion = null, - SchemaCatalog = Array.Empty(), - Records = Array.Empty(), - })); + // The runtime no longer writes a store without a format stamp, so the header is spelled by hand: [nil, [], []]. + File.WriteAllBytes(path, new byte[] { 0x93, 0xC0, 0x90, 0x90 }); var error = Assert.Throws(() => ShipAuthoringStore.Load(path)); Assert.Contains(path, error.Message); - Assert.IsType(error.InnerException); + Assert.IsType(error.InnerException); } - // A store format this runtime does not know is refused on read with NotSupportedException from the attach; Load names the file. + // A store format this runtime does not know is refused on read with CultStoreUnreadableException from the attach; Load names the file. [Fact] public async Task LoadNamesTheFileWhoseStoreFormatIsNewer() { @@ -213,7 +209,7 @@ public sealed class ShipAuthoringTests File.WriteAllBytes(path, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot)); var error = Assert.Throws(() => ShipAuthoringStore.Load(path)); Assert.Contains(path, error.Message); - Assert.IsType(error.InnerException); + Assert.IsType(error.InnerException); } // Decodes one record's payload of the named schema to its slot array, lets the edit change it, and stores it again. diff --git a/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs new file mode 100644 index 000000000..e3af827dc --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs @@ -0,0 +1,188 @@ +using System; +using System.IO; +using System.Linq; +using Newtonsoft.Json.Linq; +using Xunit; + +// A directional thruster's emitter mesh is the surface its exhaust is born from, along each triangle's normal, so every +// normal must face the exhaust, opposite the push (ShipModCatalog.BindExhaust). A closed box fires both ways: the operator +// saw the same thrusters firing whichever way the ship strafed. A ring thruster is a class of its own with its own rule and +// is not exercised here. +public sealed class ShipEmitterExhaustTests : IDisposable +{ + private readonly TempDirectory _directory = new TempDirectory(); + + public void Dispose() => _directory.Dispose(); + + private string Thruster => Path.Combine(_directory.Path, "mod.skiff", "ship.cc"); + + // The fixture thruster's hardpoint Rotation is None, so its exhaust leaves toward glTF's +Z; its emitter, one quad + // wound to face +Z, is the one-sided emitter the generator writes. + private void Write(Action tweak = null, string from = null, string to = null) + { + ShipFixture.WritePackage(_directory.Path, "mod.skiff", tweak: tweak); + if (from == null) return; + var json = ShipFixture.GlbJson(ShipFixture.Nodes); + Assert.Contains(from, json); + File.WriteAllBytes(Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"), ShipFixture.Glb(json.Replace(from, to), ShipFixture.MeshBytes())); + } + + private static void Reversed(ShipParts ship) => ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "thruster.port").Rotation = ItemRotation.Reversed; + + [Fact] + public void AOneSidedEmitterFacingItsExhaustIsAccepted() + { + Write(); + Assert.Equal("mod.skiff", ShipModCatalog.ReadPackage(Thruster).Visual.Id); + } + + [Fact] + public void AClosedBoxEmitterIsRefusedNamingItsAnchor() + { + Write(from: @"""name"":""thruster-port"",""mesh"":1", to: @"""name"":""thruster-port"",""mesh"":0"); + var message = Assert.Throws(() => ShipModCatalog.ReadPackage(Thruster)).Message; + Assert.Contains("thruster emitter thruster.port", message); + Assert.Contains("one-sided", message); + } + + [Fact] + public void AnEmitterFacingTheWrongWayIsRefused() + { + // The same quad toward +Z under a thruster that now faces aft: its exhaust would leave along the push. + Write(Reversed); + Assert.Contains("thruster emitter thruster.port", Assert.Throws(() => ShipModCatalog.ReadPackage(Thruster)).Message); + } + + [Fact] + public void TheNodesTurnDecidesWhichWayTheEmitterFaces() + { + // Turned half a circle about Y, the quad's +Z becomes -Z: the exhaust of an aft-facing thruster. + Write(Reversed, from: @"""name"":""thruster-port"",""mesh"":1", to: @"""name"":""thruster-port"",""mesh"":1,""rotation"":[0,1,0,0]"); + Assert.Equal("mod.skiff", ShipModCatalog.ReadPackage(Thruster).Visual.Id); + } + + [Fact] + public void TheShippedAndFixturePackagesPass() + { + var root = RunStartTests.FindRepoRoot(); + foreach (var ship in new[] { Path.Combine("GameData", "Mods", "aetheria.nakovalnya"), Path.Combine("tests", "fixtures", "mods", "aetheria.wren") }) + Assert.NotNull(ShipModCatalog.ReadPackage(Path.Combine(root, ship, "ship.cc"))); + } + + // The fixture package whose thruster node carries a mesh of the test's own (a third mesh appended to the BIN chunk), with + // optional vertex normals, an edit to the node, and an edit to the primitive. The thruster's Rotation is None: the exhaust + // leaves toward +Z and the push is -Z. + private string WriteCustom(float[] positions, ushort[] indices, float[] normals = null, Action node = null, Action primitive = null) + { + ShipFixture.WritePackage(_directory.Path, "mod.skiff"); + var json = JObject.Parse(ShipFixture.GlbJson(ShipFixture.Nodes)); + var bin = ShipFixture.MeshBytes().ToList(); + int View(byte[] bytes) + { + while (bin.Count % 4 != 0) bin.Add(0); + ((JArray)json["bufferViews"]).Add(new JObject { ["buffer"] = 0, ["byteOffset"] = bin.Count, ["byteLength"] = bytes.Length }); + bin.AddRange(bytes); + return ((JArray)json["bufferViews"]).Count - 1; + } + int Accessor(int view, int component, int count, string type) + { + ((JArray)json["accessors"]).Add(new JObject { ["bufferView"] = view, ["componentType"] = component, ["count"] = count, ["type"] = type }); + return ((JArray)json["accessors"]).Count - 1; + } + var attributes = new JObject { ["POSITION"] = Accessor(View(positions.SelectMany(BitConverter.GetBytes).ToArray()), 5126, positions.Length / 3, "VEC3") }; + if (normals != null) attributes["NORMAL"] = Accessor(View(normals.SelectMany(BitConverter.GetBytes).ToArray()), 5126, normals.Length / 3, "VEC3"); + var made = new JObject { ["attributes"] = attributes, ["indices"] = Accessor(View(indices.SelectMany(BitConverter.GetBytes).ToArray()), 5123, indices.Length, "SCALAR") }; + primitive?.Invoke(made); + ((JArray)json["meshes"]).Add(new JObject { ["primitives"] = new JArray(made) }); + var thruster = json["nodes"].Single(n => (string)n["name"] == "thruster-port"); + thruster["mesh"] = ((JArray)json["meshes"]).Count - 1; + node?.Invoke((JObject)thruster); + json["buffers"][0]["byteLength"] = bin.Count + (4 - bin.Count % 4) % 4; + File.WriteAllBytes(Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"), ShipFixture.Glb(json.ToString(Newtonsoft.Json.Formatting.None), bin.ToArray())); + return Thruster; + } + + private static readonly ushort[] Quad = { 0, 1, 2, 0, 2, 3 }; + + // A unit quad with counter-clockwise normal n (in the XZ plane's span: n = (sin a, 0, cos a)), a measured from +Z. + private static float[] Plane(double degrees) + { + var (s, c) = (Math.Sin(degrees * Math.PI / 180), Math.Cos(degrees * Math.PI / 180)); + var t = new[] { (float)c, 0f, (float)-s }; + return new[] { 0f, 0f, 0f, t[0], 0f, t[2], t[0], 1f, t[2], 0f, 1f, 0f }; + } + + private static float[] Repeat(float x, float y, float z) => Enumerable.Repeat(new[] { x, y, z }, 4).SelectMany(v => v).ToArray(); + + private bool Accepts(string ship) + { + try { ShipModCatalog.ReadPackage(ship); return true; } + catch (InvalidOperationException error) when (error.Message.Contains("thruster emitter thruster.port")) { return false; } + } + + [Theory] + [InlineData(0, true), InlineData(60, true), InlineData(-60, true), InlineData(89, true), InlineData(-89, true), + InlineData(91, false), InlineData(-91, false), InlineData(120, false), InlineData(180, false)] + public void ATiltedEmitterIsJudgedByItsDotWithThePush(double degrees, bool accepted) => + Assert.Equal(accepted, Accepts(WriteCustom(Plane(degrees), Quad))); + + [Fact] + public void VertexNormalsThatContradictTheWindingAreRefused() + { + // Unity's Mesh Renderer shape emits along the vertex normals, so a face wound toward the exhaust is not enough. + Assert.True(Accepts(WriteCustom(Plane(0), Quad, Repeat(0, 0, 1)))); + Assert.False(Accepts(WriteCustom(Plane(0), Quad, Repeat(0, 0, -1)))); + Assert.False(Accepts(WriteCustom(Plane(0), Quad, Repeat(1, 0, 0)))); + } + + [Fact] + public void AMirroredNodeFlipsTheWindingAndIsJudgedByWhatItDrawsNotWhatItIsWound() + { + // Scaled -1 in X the quad's winding reverses in the world, so glTF's front face is the other one. + Action mirror = node => node["scale"] = new JArray(-1, 1, 1); + Assert.True(Accepts(WriteCustom(Plane(0), Quad, node: mirror))); + Assert.False(Accepts(WriteCustom(Plane(180), Quad, node: mirror))); + } + + [Fact] + public void VertexNormalsFollowTheInverseTransposeUnderNonUniformScale() + { + // A quarter turn's eighth about Y over a stretch of 4 in X: the plane with local normal (1,0,1) keeps a normal toward + // +Z (0.75 of it), where transforming the normal like a position would send it toward -Z. + Action stretched = node => { node["scale"] = new JArray(4, 1, 1); node["rotation"] = new JArray(0, 0.3826834f, 0, 0.9238795f); }; + var tangent = (float)(1 / Math.Sqrt(2)); + var positions = new[] { 0f, 0f, 0f, tangent, 0f, -tangent, tangent, 1f, -tangent, 0f, 1f, 0f }; + Assert.True(Accepts(WriteCustom(positions, Quad, Repeat(tangent, 0, tangent), stretched))); + } + + [Fact] + public void OnlyExtensionsThatHideGeometryAreRefused() + { + Assert.True(Accepts(WriteCustom(Plane(0), Quad, primitive: p => p["extensions"] = JObject.Parse(@"{""KHR_materials_variants"":{""mappings"":[]}}")))); + var compressed = WriteCustom(Plane(0), Quad, primitive: p => p["extensions"] = JObject.Parse(@"{""KHR_draco_mesh_compression"":{""bufferView"":0,""attributes"":{""POSITION"":0}}}")); + Assert.Contains("compressed by KHR_draco_mesh_compression", Assert.Throws(() => ShipModCatalog.ReadPackage(compressed)).Message); + } + + [Fact] + public void ASidewaysEmitterWhoseNormalIsPerpendicularToThePushIsRefused() => + // Normal exactly +X, dot with the push exactly 0: the rule is non-negative, so it fires along the axis it is not meant to. + Assert.False(Accepts(WriteCustom(new[] { 0f, 0f, 0f, 0f, 1f, 0f, 0f, 1f, 1f, 0f, 0f, 1f }, Quad))); + + [Theory] + [InlineData("KHR_draco_mesh_compression"), InlineData("EXT_meshopt_compression")] + public void AnAccessorWhoseBufferViewIsCompressedIsRefused(string extension) + { + // The compression sits on the bufferView, not the primitive: the accessor's bytes are not positions. + var path = WriteCustom(Plane(0), Quad); + var glb = Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"); + var bytes = File.ReadAllBytes(glb); + var length = (int)BitConverter.ToUInt32(bytes, 12); + var json = JObject.Parse(System.Text.Encoding.UTF8.GetString(bytes, 20, length)); + var views = (JArray)json["bufferViews"]; + var positions = (int)json["accessors"][(int)json["meshes"].Last["primitives"][0]["attributes"]["POSITION"]]["bufferView"]; + views[positions]["extensions"] = JObject.Parse("{\"" + extension + "\":{}}"); + var bin = bytes.Skip(28 + length).ToArray(); + File.WriteAllBytes(glb, ShipFixture.Glb(json.ToString(Newtonsoft.Json.Formatting.None), bin)); + Assert.Contains("compressed by " + extension, Assert.Throws(() => ShipModCatalog.ReadPackage(path)).Message); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipFixture.cs b/tests/Aetheria.Shared.Tests/ShipFixture.cs index 9f2e1c75f..ac41ece2f 100644 --- a/tests/Aetheria.Shared.Tests/ShipFixture.cs +++ b/tests/Aetheria.Shared.Tests/ShipFixture.cs @@ -22,22 +22,33 @@ internal static class ShipFixture 1, 0, 0, 0, 1, 0, 0, 0, 1 }; - public static byte[] MeshBytes() => Tetrahedron.SelectMany(BitConverter.GetBytes).ToArray(); + // One-sided quad in the z = 0 plane, wound counter-clockwise seen from +Z, so its normal is +Z (glTF's nose): the emitter + // of a thruster whose Rotation is None, which faces its exhaust ahead. Four vertices and six 16-bit indices follow the + // tetrahedron in the BIN chunk. + private static readonly float[] Quad = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 }; + private static readonly ushort[] QuadIndices = { 0, 1, 2, 0, 2, 3 }; + + public static byte[] MeshBytes() => + Tetrahedron.SelectMany(BitConverter.GetBytes).Concat(Quad.SelectMany(BitConverter.GetBytes)).Concat(QuadIndices.SelectMany(BitConverter.GetBytes)).ToArray(); + + // The model's geometry as glTF JSON members (meshes, accessors, bufferViews, buffers) over MeshBytes: mesh 0 is the + // tetrahedron, mesh 1 the quad. + public static string Geometry => + @"""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]},{""primitives"":[{""attributes"":{""POSITION"":1},""indices"":2}]}]," + + @"""accessors"":[{""bufferView"":0,""componentType"":5126,""count"":12,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,1]}," + + @"{""bufferView"":1,""componentType"":5126,""count"":4,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,0]}," + + @"{""bufferView"":2,""componentType"":5123,""count"":6,""type"":""SCALAR""}]," + + $@"""bufferViews"":[{{""buffer"":0,""byteLength"":144}},{{""buffer"":0,""byteOffset"":144,""byteLength"":48}},{{""buffer"":0,""byteOffset"":192,""byteLength"":12}}],""buffers"":[{{""byteLength"":{MeshBytes().Length}}}]"; // The GLB carries a glTF scene naming every node: glTFast instantiates a scene, and a scene-less file has none. // Nodes in meshNodes (default MeshNodes) get the shared tetrahedron mesh, whose vertices live in the BIN chunk (MeshBytes). public static string GlbJson(string[] nodes, string[] meshNodes = null) { meshNodes ??= MeshNodes; - var length = MeshBytes().Length; - var mesh = nodes.Any(meshNodes.Contains) - ? @",""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}]," + - @"""accessors"":[{""bufferView"":0,""componentType"":5126,""count"":12,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,1]}]," + - $@"""bufferViews"":[{{""buffer"":0,""byteLength"":{length}}}],""buffers"":[{{""byteLength"":{length}}}]" - : ""; + var mesh = nodes.Any(meshNodes.Contains) ? "," + Geometry : ""; return @"{""asset"":{""version"":""2.0""},""scene"":0,""scenes"":[{""nodes"":[" + string.Join(",", nodes.Select((_, index) => index)) + @"]}]" + mesh + @",""nodes"":[" + string.Join(",", nodes.Select(node => - $@"{{""name"":""{node}""{(meshNodes.Contains(node) ? @",""mesh"":0" : "")},""extras"":{{""aetheria.id"":""{node}""}}}}")) + "]}"; + $@"{{""name"":""{node}""{(meshNodes.Contains(node) ? node.StartsWith("thruster") ? @",""mesh"":1" : @",""mesh"":0" : "")},""extras"":{{""aetheria.id"":""{node}""}}}}")) + "]}"; } public static byte[] Glb(string json, byte[] bin = null) diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index 3def3e6dd..5a4f38093 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -49,6 +49,137 @@ public sealed class ShipModCatalogTests : IDisposable AssertOnlyTheDerivedFile(); } + // A maker (by name) the shipped catalog holds, made on first use. + private CultRecordKey Maker(string name) + { + using var cache = AetheriaStores.Open(Shipped, catalogWritable: true); + var existing = cache.GetAll().FirstOrDefault(faction => faction.Name == name); + var key = existing != null ? cache.RefOf(existing).Key : cache.Upsert(new Faction { Name = name, ShortName = name.Substring(0, 3).ToUpperInvariant() }).Key; + cache.FlushAsync().Wait(); + return key; + } + + // A shipped product line a package's product can bin. + private CultRecordKey ShippedLine(string name, bool notOffered) + { + var maker = Maker("Acme"); + using var cache = AetheriaStores.Open(Shipped, catalogWritable: true); + var hull = cache.Upsert(new HullData { Name = name + " hull", Shape = ShipAuthoringTests.Fixture().Hull.Shape, Price = 10 }); + var line = cache.Upsert(new FactionProductData + { + Name = name, + Design = new CultRecordRef(hull.Key), + Manufacturer = new CultRecordRef(maker), + NotOffered = notOffered + }); + cache.FlushAsync().Wait(); + return line.Key; + } + + // One product of a package: its maker, whether it is itself off the market, and the line it bins, if any. + private sealed record Sale(string Maker, bool NotOffered = false, CultRecordKey? Bin = null); + + // A priced package selling the given products through the one product writer, with or without schematic lines + // (`lines` null leaves the record's SchematicLines null). + private void PricedPackage(string id, bool? lines, params Sale[] sales) + { + var makers = sales.Select(sale => Maker(sale.Maker)).ToArray(); + WritePackage(id, id, tweak: ship => + { + ship.Hull.Price = 100; + if (lines == false) ship.Visual.SchematicLines = new List(); + if (lines == null) ship.Visual.SchematicLines = null; + }); + using var cache = ShipAuthoringStore.Open(Path.Combine(Mods, id, "ship.cc"), writable: true); + for (var n = 0; n < sales.Length; n++) + ShipAuthoringStore.WriteProduct(cache, id, new FactionProductData + { + Name = $"{id} product {n}", + Design = new CultRecordRef(ShipModCatalog.HullKey(id)), + Manufacturer = new CultRecordRef(makers[n]), + NotOffered = sales[n].NotOffered, + Bin = sales[n].Bin is { } line ? new ProductBin { Line = new CultRecordRef(line), Floor = 1f } : null + }); + cache.FlushAsync().Wait(); + } + + private static string Excluded(ShipModCatalog.Composition composition, string package) => + composition.Excluded.SingleOrDefault(entry => entry.Package == package)?.Reason; + + // An offered hull is drawn by its schematic lines (ShipModVisual.BuildLineMesh builds nothing from none), so one without any + // is left out of the catalog with its reason; an offered hull with lines and an unoffered stand-in without them both compose. + [Fact] + public void ComposeExcludesAnOfferedHullWithoutSchematicLinesAndKeepsTheRest() + { + PricedPackage("mod.offeredbare", lines: false, new Sale("Acme")); + PricedPackage("mod.offeredlined", lines: true, new Sale("Acme")); + PricedPackage("mod.standin", lines: false, new Sale("Acme", NotOffered: true)); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.offeredlined", "mod.standin" }, composition.Included.OrderBy(id => id, StringComparer.Ordinal)); + var excluded = Assert.Single(composition.Excluded); + Assert.Equal("mod.offeredbare", excluded.Package); + Assert.Contains("mod.offeredbare", excluded.Reason); + Assert.Contains("no schematic", excluded.Reason); + } + + // A hull is offered when any product of it is, and a binned product is offered only if its line is (ruling bin-inherits-line-offered): + // the verdict is IsOffered's, not a read of the product's own NotOffered. + [Fact] + public void OfferedNessComesFromAnyProductAndFromTheBinsLine() + { + var offeredLine = ShippedLine("Offered Line", notOffered: false); + var closedLine = ShippedLine("Closed Line", notOffered: true); + PricedPackage("mod.binoffered", lines: false, new Sale("Acme", Bin: offeredLine)); + PricedPackage("mod.binclosed", lines: false, new Sale("Acme", Bin: closedLine)); + PricedPackage("mod.oneoftwo", lines: false, new Sale("Acme", NotOffered: true), new Sale("Rival")); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Contains("no schematic", Excluded(composition, "mod.binoffered")); + Assert.Null(Excluded(composition, "mod.binclosed")); + Assert.Contains("no schematic", Excluded(composition, "mod.oneoftwo")); + Assert.Equal(new[] { "mod.binclosed" }, composition.Included); + } + + [Fact] + public void ANullSchematicIsNoSchematicWhenOffered() + { + PricedPackage("mod.nulled", lines: null, new Sale("Acme")); + PricedPackage("mod.nulledstandin", lines: null, new Sale("Acme", NotOffered: true)); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Contains("no schematic", Excluded(composition, "mod.nulled")); + Assert.Equal(new[] { "mod.nulledstandin" }, composition.Included); + } + + // A bin's line is a shipped product or one of the package's own, never another package's and never nothing: the catalog read + // refuses such a bin at boot, so compose leaves the package out and the derived catalog opens. + [Fact] + public void ComposeExcludesAPackageWhoseBinNamesNoShippedOrOwnLine() + { + var shipped = ShippedLine("Shipped Line", notOffered: false); + var maker = Maker("Acme"); + PricedPackage("mod.lined", lines: true, new Sale("Acme")); + PricedPackage("mod.cross", lines: false, new Sale("Rival", Bin: ShipModCatalog.ProductKey("mod.lined", maker))); + PricedPackage("mod.nothing", lines: true, new Sale("Acme", Bin: new CultRecordKey("product:nowhere"))); + PricedPackage("mod.shippedbin", lines: true, new Sale("Acme", Bin: shipped)); + PricedPackage("mod.ownbin", lines: true, new Sale("Acme"), new Sale("Rival", Bin: ShipModCatalog.ProductKey("mod.ownbin", maker))); + + PricedPackage("mod.binofbin", lines: true, new Sale("Acme", Bin: shipped), new Sale("Rival", Bin: ShipModCatalog.ProductKey("mod.binofbin", maker))); + + var (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.binofbin", "mod.cross", "mod.nothing" }, excluded.Select(entry => entry.Package).OrderBy(id => id, StringComparer.Ordinal)); + Assert.All(excluded, entry => Assert.Contains("bins a line", entry.Reason)); + Assert.Equal(Derived, catalog); + using var cache = AetheriaStores.Open(Derived); + Assert.Contains("mod.ownbin product 1", cache.GetAll().Select(product => product.Name)); + Assert.DoesNotContain("mod.cross product 0", cache.GetAll().Select(product => product.Name)); + } + // A package's station kind is checked per package: a bad one is left out, named with its reason, and the derived catalog // still opens. The shipped catalog's own check is unchanged. [Fact] @@ -328,6 +459,54 @@ public sealed class ShipModCatalogTests : IDisposable Assert.Contains("GLB", excluded.Reason); } + // Bind is the one verdict on whether a mod hull exists: a package whose GLB names a node mesh the importer cannot build + // (dangling or negative index, no meshes array, non-integer index, no POSITION on any one primitive, non-triangle mode, skinned node, no primitives) never reaches the boot catalog, so Preload has nothing left to refuse on file facts. + [Fact] + public void ABootCatalogHoldsNoHullTheImporterCannotBuild() + { + WritePackage("mod.good", hullName: "Good"); + var broken = new Dictionary + { + ["mod.dangling"] = (@"{""name"":""collider"",""mesh"":0", @"{""name"":""collider"",""mesh"":7"), + ["mod.nopos"] = (@"""attributes"":{""POSITION"":0}", @"""attributes"":{}"), + ["mod.skinned"] = (@"{""name"":""map"",""mesh"":0", @"{""name"":""map"",""mesh"":0,""skin"":0"), + ["mod.noprims"] = (@"""primitives"":[{""attributes"":{""POSITION"":0}}]", @"""primitives"":[]"), + ["mod.onebad"] = (@"""primitives"":[{""attributes"":{""POSITION"":0}}]", @"""primitives"":[{""attributes"":{""POSITION"":0}},{""attributes"":{}}]"), + ["mod.points"] = (@"""attributes"":{""POSITION"":0}}", @"""attributes"":{""POSITION"":0},""mode"":0}"), + ["mod.negative"] = (@"""mesh"":0", @"""mesh"":-1"), + ["mod.nomeshes"] = (@"""meshes"":", @"""other"":"), + ["mod.fractional"] = (@"""mesh"":0", @"""mesh"":0.0") + }; + foreach (var (package, (from, to)) in broken) + { + WritePackage(package, hullName: package.Substring(4)); + var json = ShipFixture.GlbJson(FixtureNodes); + Assert.Contains(from, json); + File.WriteAllBytes(Path.Combine(Mods, package, "skiff.glb"), ShipFixture.Glb(json.Replace(from, to), ShipFixture.MeshBytes())); + } + + var (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods); + + Assert.Equal(Derived, catalog); + Assert.Equal(broken.Keys.OrderBy(name => name, StringComparer.Ordinal), excluded.Select(e => e.Package).OrderBy(name => name, StringComparer.Ordinal)); + Assert.All(excluded, e => Assert.Contains("needs a mesh", e.Reason)); + using var cache = AetheriaStores.Open(catalog); + var hulls = cache.GetAll().Where(hull => hull.Visual.IsSet()).ToArray(); + Assert.Equal(new[] { "Good" }, hulls.Select(hull => hull.Name)); + var keys = cache.AllStoredDocuments.Select(record => record.Key.Value).ToHashSet(); + foreach (var package in broken.Keys) + { + Assert.DoesNotContain(ShipModCatalog.HullKey(package).Value, keys); + Assert.DoesNotContain(ShipModCatalog.AuthoringKey(package).Value, keys); + } + // Preload's own two steps over file facts, run headlessly: neither may refuse a hull the catalog holds. + foreach (var hull in hulls) + { + var package = ShipModCatalog.PackageOf(cache, hull, Mods); + ShipModPlan.Build(package.Hull, package.Visual); + } + } + // The game's boot: a bad package is named and the rest boot; with none left, the shipped catalog boots. [Fact] public void TheBootCatalogSurvivesBadPackages() @@ -546,20 +725,17 @@ public sealed class ShipModCatalogTests : IDisposable private static (int Code, string Output, string Error) Run(params string[] args) { - var (output, error) = (new StringWriter(), new StringWriter()); - var (previousOut, previousError) = (Console.Out, Console.Error); - Console.SetOut(output); - Console.SetError(error); - try { return (ShipAuthoringCommands.Run(args), output.ToString(), error.ToString()); } - finally { Console.SetOut(previousOut); Console.SetError(previousError); } + var code = ConsoleProbe.Capture(() => ShipAuthoringCommands.Run(args), out var output, out var error); + return (code, output, error); } [Fact] public void NodeIdsMapToTheirGlbNodeIndexSkippingNodesWithoutOne() { var path = Write("nodes.glb", ShipFixture.Glb(@"{""asset"":{""version"":""2.0""},""nodes"":[ - {""name"":""plain""},{""extras"":{""aetheria.id"":""a""}},{""extras"":{}},{""extras"":{""aetheria.id"":""""}},{""mesh"":0,""extras"":{""aetheria.id"":""b""}}]}")); - Assert.Equal(new Dictionary { ["a"] = (1, false, -1, true), ["b"] = (4, true, -1, true) }, ShipModCatalog.ReadNodeIds(path)); + {""name"":""plain""},{""extras"":{""aetheria.id"":""a""}},{""extras"":{}},{""extras"":{""aetheria.id"":""""}},{""mesh"":0,""extras"":{""aetheria.id"":""b""}},{""mesh"":7,""extras"":{""aetheria.id"":""c""}}], + ""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}]}")); + Assert.Equal(new Dictionary { ["a"] = (1, false, -1, true), ["b"] = (4, true, -1, true), ["c"] = (5, false, -1, true) }, ShipModCatalog.ReadNodeIds(path)); } [Fact] @@ -628,7 +804,8 @@ public sealed class ShipModCatalogTests : IDisposable ShipModCatalog.Compose(Shipped, second, secondMods); ShipModCatalog.Compose(Shipped, Path.Combine(_directory.Path, "Derived3", "Aetheria.modded.cc"), firstMods); - Assert.Equal(Records(Derived), Records(second)); + // Two packages written separately carry separately minted ids: same content, ids blank. + Assert.Equal(Records(Derived, blindMods: true), Records(second, blindMods: true)); Assert.Equal(Records(Derived), Records(Path.Combine(_directory.Path, "Derived3", "Aetheria.modded.cc"))); Assert.Contains(ShipModCatalog.HullKey("mod.c").Value, Records(Derived).Keys); } @@ -797,10 +974,15 @@ public sealed class ShipModCatalogTests : IDisposable ShipModCatalog.PackageOf(cache, hull, Mods)).Message); } - // Every stored record's key, schema and payload bytes. StoredAt is a write timestamp, not record content. - private static Dictionary Records(string path) => + // Every stored record's key, schema and payload bytes. StoredAt is a write timestamp, not record content. The shipped + // catalog holds no element ids, so each open mints new random ones for the records Compose copies from it; those are + // always compared with ids blank. A mod package's records carry the ids its ship.cc persisted and are compared as stored, + // unless the two sides are packages written separately (blindMods), where each write minted its own. + private static Dictionary Records(string path, bool blindMods = false) => GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).Records - .ToDictionary(record => record.Key, record => record.SchemaId + ":" + Convert.ToHexString(record.Payload)); + .ToDictionary(record => record.Key, record => record.SchemaId + ":" + Convert.ToHexString( + !blindMods && ShipModCatalog.IsModKey(new CultRecordKey(record.Key)) ? record.Payload + : ElementIdBlind.Payload(TestCatalog.Registry(), record.SchemaId, record.Payload))); private void AssertOnlyTheDerivedFile() { diff --git a/tests/Aetheria.Shared.Tests/ShipProductTests.cs b/tests/Aetheria.Shared.Tests/ShipProductTests.cs index 343f35082..638f408b6 100644 --- a/tests/Aetheria.Shared.Tests/ShipProductTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -99,6 +99,39 @@ public sealed class ShipProductTests : IDisposable } } + // validate gives the verdict compose gives: an offered hull with no schematic lines is refused, an unoffered one is not. + [Fact] + public void ValidateRefusesAnOfferedHullWithoutSchematicLinesAsComposeDoes() + { + Environment.CurrentDirectory = _root.Path; + string Bare(string id, bool offered, bool nullLines = false, CultRecordKey? bin = null) + { + var directory = ShipFixture.WritePackage(Mods, id, id, tweak: ship => { ship.Hull.Price = 100; ship.Visual.SchematicLines = nullLines ? null : new List(); }); + var path = Path.Combine(directory, "ship.cc"); + using var cache = ShipAuthoringStore.Open(path, writable: true); + var product = Product(id + " product", _acme, id); + product.NotOffered = !offered; + if (bin is { } line) product.Bin = new ProductBin { Line = new CultRecordRef(line), Floor = 1f }; + ShipAuthoringStore.WriteProduct(cache, id, product); + cache.FlushAsync().Wait(); + return path; + } + + var (code, _, error) = Run("validate", Bare("mod.offered", offered: true)); + Assert.Equal(1, code); + Assert.Contains("no schematic", error); + Assert.Equal(0, Run("validate", Bare("mod.standin", offered: false)).Item1); + // A null SchematicLines is no schematic, as for compose. + var (nullCode, _, nullError) = Run("validate", Bare("mod.nulled", offered: true, nullLines: true)); + Assert.Equal(1, nullCode); + Assert.Contains("no schematic", nullError); + // A bin naming no shipped product and no product of the package is refused, as compose excludes it. + var (binCode, _, binError) = Run("validate", Bare("mod.badbin", offered: true, bin: new CultRecordKey("product:nowhere"))); + Assert.Equal(1, binCode); + Assert.Contains("bins a line", binError); + Assert.Equal(new[] { "mod.standin" }, ShipModCatalog.Compose(Shipped, Derived, Mods).Included); + } + [Fact] public void APackageWithAnUnknownMakerIsExcluded() { @@ -247,12 +280,8 @@ public sealed class ShipProductTests : IDisposable private static (int Code, string Output, string Error) Run(params string[] args) { - var (output, error) = (new StringWriter(), new StringWriter()); - var (previousOut, previousError) = (Console.Out, Console.Error); - Console.SetOut(output); - Console.SetError(error); - try { return (ShipAuthoringCommands.Run(args), output.ToString(), error.ToString()); } - finally { Console.SetOut(previousOut); Console.SetError(previousError); } + var code = ConsoleProbe.Capture(() => ShipAuthoringCommands.Run(args), out var output, out var error); + return (code, output, error); } [Fact] @@ -335,7 +364,7 @@ public sealed class ShipProductTests : IDisposable var path = Package("mod.skiff", "Skiffhull", 0); var bare = Path.Combine(ShipFixture.WritePackage(Mods, "mod.bare", "Barehull", tweak: ship => ship.Hull.Behaviors.Clear()), "ship.cc"); var twin = Path.Combine(ShipFixture.WritePackage(Mods, "mod.twin", "Twinhull", - tweak: ship => ship.Hull.Behaviors.Add(ship.Hull.Behaviors.OfType().First())), "ship.cc"); + tweak: ship => ship.Hull.Behaviors.Add(new VelocityLimitData())), "ship.cc"); void RefusedAndUntouched(string file, params string[] flags) { var before = File.ReadAllBytes(file); diff --git a/tests/Aetheria.Shared.Tests/ShipRigTests.cs b/tests/Aetheria.Shared.Tests/ShipRigTests.cs index 4bed1989b..657a2f03b 100644 --- a/tests/Aetheria.Shared.Tests/ShipRigTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipRigTests.cs @@ -209,13 +209,13 @@ public sealed class ShipRigTests : IDisposable private static string GlbJson(Node[] nodes) { - var text = new StringBuilder(@"{""asset"":{""version"":""2.0""},""meshes"":[{""primitives"":[]}],""nodes"":["); + var text = new StringBuilder(@"{""asset"":{""version"":""2.0""}," + ShipFixture.Geometry + @",""nodes"":["); for (var index = 0; index < nodes.Length; index++) { var node = nodes[index]; var kids = Enumerable.Range(0, nodes.Length).Where(child => nodes[child].Parent == node.Name).ToArray(); text.Append(index > 0 ? "," : "").Append($@"{{""name"":""{node.Name}"""); - if (node.Mesh) text.Append(@",""mesh"":0"); + if (node.Mesh) text.Append(node.Name.StartsWith("thruster") ? @",""mesh"":1" : @",""mesh"":0"); if (node.Id != null) text.Append($@",""extras"":{{""aetheria.id"":""{node.Id}""}}"); if (kids.Length > 0) text.Append(@",""children"":[" + string.Join(",", kids) + "]"); text.Append('}'); @@ -238,7 +238,7 @@ public sealed class ShipRigTests : IDisposable ship.Visual.Anchors.Single(anchor => anchor.Id == "gun").Joint = "wrist"; tweak?.Invoke(ship); }); - File.WriteAllBytes(Path.Combine(directory, "skiff.glb"), ShipFixture.Glb(GlbJson(nodes ?? RigNodes))); + File.WriteAllBytes(Path.Combine(directory, "skiff.glb"), ShipFixture.Glb(GlbJson(nodes ?? RigNodes), ShipFixture.MeshBytes())); return Path.Combine(directory, "ship.cc"); } @@ -348,7 +348,7 @@ public sealed class ShipRigTests : IDisposable public void NodeParentsAreTheNearestTaggedAncestorAndRootsHaveNone() { var path = Path.Combine(_directory.Path, "rig.glb"); - File.WriteAllBytes(path, ShipFixture.Glb(GlbJson(RigNodes))); + File.WriteAllBytes(path, ShipFixture.Glb(GlbJson(RigNodes), ShipFixture.MeshBytes())); var nodes = ShipModCatalog.ReadNodeIds(path); Assert.Equal(-1, nodes["arm"].Parent); Assert.Equal((int)nodes["arm"].Index, nodes["elbow"].Parent); @@ -833,7 +833,7 @@ public sealed class ShipRigTests : IDisposable var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HardpointData).Assembly); var hardpoint = new HardpointData { Type = HardpointType.Thruster, Shape = new Shape(), Transform = "t", FiringArc = 40f, Row = "left" }; var fields = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(hardpoint, options), options); - Assert.Equal(8, fields.Length); + Assert.Equal(9, fields.Length); Assert.Equal(40f, Convert.ToSingle(fields[6])); Assert.Equal("left", fields[7]); Assert.Null(MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(new HardpointData { Shape = new Shape() }, options), options)[7]); @@ -842,7 +842,7 @@ public sealed class ShipRigTests : IDisposable thruster.Thrust.Max = 5f; thruster.Slew.Max = 90f; var slew = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(thruster, options), options); - Assert.Equal(7, slew.Length); + Assert.Equal(38, slew.Length); // the behavior base's element id is key 37 Assert.Equal(MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(thruster.Slew, options), options), MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(slew[6], options), options)); Assert.NotEqual(MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(thruster.Thrust, options), options), diff --git a/tests/Aetheria.Shared.Tests/SignatureTests.cs b/tests/Aetheria.Shared.Tests/SignatureTests.cs index 50d0bc824..21bdd7644 100644 --- a/tests/Aetheria.Shared.Tests/SignatureTests.cs +++ b/tests/Aetheria.Shared.Tests/SignatureTests.cs @@ -501,7 +501,7 @@ public sealed class SignatureTests : IDisposable var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(22, reader.ReadInt32()); - Assert.Equal(4, reader.ReadArrayHeader()); + Assert.Equal(38, reader.ReadArrayHeader()); reader.Skip(); // Group Assert.Equal(1f, MessagePackSerializer.Deserialize(ref reader, Options).Min); Assert.Equal(2f, MessagePackSerializer.Deserialize(ref reader, Options).Min); diff --git a/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs b/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs index 40a47eec6..83013d766 100644 --- a/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs @@ -21,7 +21,7 @@ public sealed class SmokeRoundsCommandTests : IDisposable private readonly Dictionary _shipped = new Dictionary(); private static byte[] Pack(WeaponItemData design) => - MessagePackSerializer.Serialize(design, CultDocumentMessagePackSerialization.OptionsFor(typeof(WeaponItemData).Assembly)); + ElementIdBlind.Pack(design, typeof(WeaponItemData)); public SmokeRoundsCommandTests() { diff --git a/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs b/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs new file mode 100644 index 000000000..3e00ba91b --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs @@ -0,0 +1,66 @@ +using System.Linq; +using System.Text.RegularExpressions; +using GameCult.Caching; +using Xunit; + +// A station kind's description is what a player and a planner read of what it does; the recipes at the kind are what it does. +public sealed class StationKindDescriptionTests +{ + // Every good the shipped catalog extracts at a station kind (a commodity recipe with no inputs; a gear recipe is a design on offer, not raw) is named in that kind's description. + // Kills: a kind that gains an extraction recipe (Diamond at mining, Ammonia at volatiles) while its description still lists the old set. + [Fact] + public void EveryRawGoodAKindExtractsIsNamedInItsDescription() + { + using var db = AetherDb.Open(); + var cache = db.Cache; + var unnamed = cache.GetAll().Where(recipe => recipe.Inputs.Count == 0 && recipe.StationKind.IsSet()) + .Select(recipe => (Kind: cache.Get(recipe.StationKind), Output: cache.Get(recipe.Output))) + .Where(pair => pair.Kind != null && (pair.Output is SimpleCommodityData || pair.Output is CompoundCommodityData) && !pair.Kind.Description.Contains(pair.Output.Name)) + .Select(pair => $"{pair.Kind.Name} extracts {pair.Output.Name}, which its description omits") + .Distinct().OrderBy(line => line).ToList(); + Assert.True(unnamed.Count == 0, string.Join("\n", unnamed)); + } + + // The two kinds the rule was cut for, by name, so the rule cannot pass by the catalog having lost the recipes. + [Fact] + public void MiningExtractsDiamondAndVolatilesAmmonia() + { + using var db = AetherDb.Open(); + var cache = db.Cache; + string Extracted(string kindId) => string.Join(",", cache.GetAll() + .Where(recipe => recipe.Inputs.Count == 0 && recipe.StationKind.IsSet() && recipe.StationKind.Key.Equals(StationKindData.KeyOf(kindId))) + .Select(recipe => cache.Get(recipe.Output).Name)); + Assert.Contains("Diamond", Extracted("mining")); + Assert.Contains("Ammonia", Extracted("volatiles")); + Assert.Contains("Diamond", cache.Get(StationKindData.KeyOf("mining")).Description); + Assert.Contains("Ammonia", cache.Get(StationKindData.KeyOf("volatiles")).Description); + } + + // Kills: a station-kind description naming a commodity no recipe yields or consumes (Uranium, Hydrogen, Bacteria, Fungi and + // Animal Products were named by the shipped descriptions with no recipe behind them). + [Fact] + public void EveryCommodityAStationKindNamesIsMadeOrTakenByARecipe() + { + using var db = AetherDb.Open(); + var c = db.Cache; + var used = c.GetAll().SelectMany(r => r.Inputs.Select(i => i.Commodity.Key.Value).Append(r.Output.Key.Value)).ToHashSet(); + var commodities = c.GetAll().ToArray(); + Assert.True(commodities.Length >= 20 && used.Count >= 20, $"fixture: the catalog holds its commodities and recipes ({commodities.Length}, {used.Count})"); + var kinds = c.GetAll().ToArray(); + Assert.True(kinds.Length >= 17, $"fixture: the catalog holds its station kinds ({kinds.Length})"); + var orphans = from kind in kinds + from good in commodities + where Regex.IsMatch(kind.Description ?? "", @"\b" + Regex.Escape(good.Name) + @"\b") && !used.Contains(c.RefOf(good).Key.Value) + select $"{kind.Name} names {good.Name}"; + Assert.True(!orphans.Any(), string.Join("\n", orphans)); + } + + // Kills: the fresh-catalog text and the shipped catalog saying different things about the same kind. + [Fact] + public void TheShippedDescriptionsAreTheAuthoredTable() + { + using var db = AetherDb.Open(); + foreach (var id in new[] { "mining", "volatiles", "agriculture", "habitat-support", "power" }) + Assert.Equal(StationKindsCatalog.DescriptionOf(id), db.Cache.Get(StationKindData.KeyOf(id)).Description); + } +} diff --git a/tests/Aetheria.Shared.Tests/StationKindTests.cs b/tests/Aetheria.Shared.Tests/StationKindTests.cs index 02db0c081..dc28fd955 100644 --- a/tests/Aetheria.Shared.Tests/StationKindTests.cs +++ b/tests/Aetheria.Shared.Tests/StationKindTests.cs @@ -352,11 +352,10 @@ public sealed class StationKindTests : IDisposable stock?.Invoke(w); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); var dir = Path.Combine(_root, "galaxy" + _worlds++); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), w.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, 3); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), w.Cache, _ => { }, null, 3); var pack = ZoneGenerator.GenerateZone(w.Items, authored.Read("ZoneSettings"), - authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, galaxy.IsPrelude, true); + authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, true, true); Assert.NotEmpty(pack.Entities.OfType()); return pack.Orbits.Select(orbit => w.Cache.Get(orbit)).Select(orbit => (orbit.Distance, orbit.Phase)).ToArray(); } @@ -376,11 +375,10 @@ public sealed class StationKindTests : IDisposable foreach (var faction in new[] { w.Au, w.Zh, w.Lucent }) foreach (var kind in new[] { "mining", "shipyard", "depot", "power" }) w.Sell(faction, kind); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), w.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "galaxy" + _worlds++, "Narrative")), _ => { }, null, 3); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), w.Cache, _ => { }, null, 3); return galaxy.Zones.Take(8).SelectMany(zone => ZoneGenerator.GenerateZone(w.Items, authored.Read("ZoneSettings"), - authored.Read("PlanetSettings"), galaxy, zone, zone == galaxy.Entrance && galaxy.IsPrelude, true) + authored.Read("PlanetSettings"), galaxy, zone, true, true) .Entities.OfType().Where(e => e.Kind.IsSet()).Select(e => e.Kind.Key.Value)).ToArray(); } var first = Kinds(); @@ -397,15 +395,14 @@ public sealed class StationKindTests : IDisposable w.StandIn("depot", w.Lucent, "power"); w.StandIn("depot", w.Zh, "power"); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), w.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "zones", "Narrative")), _ => { }, null, 5); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), w.Cache, _ => { }, null, 5); var stations = 0; var fallbacks = 0; foreach (var galaxyZone in galaxy.Zones.Take(8)) { var pack = ZoneGenerator.GenerateZone(w.Items, authored.Read("ZoneSettings"), - authored.Read("PlanetSettings"), galaxy, galaxyZone, galaxyZone == galaxy.Entrance && galaxy.IsPrelude, true); + authored.Read("PlanetSettings"), galaxy, galaxyZone, true, true); foreach (var station in pack.Entities.OfType().Where(e => w.HullOf(e).HullType == HullType.Station)) { stations++; @@ -473,11 +470,10 @@ public sealed class StationKindTests : IDisposable } var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), world.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "galaxy" + _worlds++, "Narrative")), _ => { }, null, 5); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), world.Cache, _ => { }, null, 5); var entrance = ZoneGenerator.GenerateZone(world.Items, authored.Read("ZoneSettings"), - authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, galaxy.IsPrelude, true); + authored.Read("PlanetSettings"), galaxy, galaxy.Entrance, true, true); Assert.Contains(entrance.Entities.OfType(), e => world.HullOf(e).HullType == HullType.Station); } diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index b265ead4d..33441e369 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -52,10 +52,9 @@ public sealed class StationPlacementTests : IDisposable cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); var settings = authored.Read("GameplaySettings"); - var galaxy = new Galaxy(authored.Read("TutorialGenerationSettings"), - authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), settings, _ => { }); stock?.Invoke(items); foreach (var galaxyZone in entranceOnly ? new[] { galaxy.Entrance } : galaxy.Zones.Take(zonesPerSeed)) @@ -65,7 +64,7 @@ public sealed class StationPlacementTests : IDisposable var zoneSettings = authored.Read("ZoneSettings"); tune?.Invoke(zoneSettings); var pack = ZoneGenerator.GenerateZone(items, zoneSettings, authored.Read("PlanetSettings"), galaxy, galaxyZone, - galaxyZone == galaxy.Entrance && galaxy.IsPrelude, true); + true, true); var zone = new Zone(items, authored.Read("PlanetSettings"), pack, galaxyZone, galaxy); zone.Update(.02f); yield return new Built(seed, zone, items); diff --git a/tests/Aetheria.Shared.Tests/StationReactorSpreadTests.cs b/tests/Aetheria.Shared.Tests/StationReactorSpreadTests.cs new file mode 100644 index 000000000..41161975a --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationReactorSpreadTests.cs @@ -0,0 +1,99 @@ +using System; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// station-reactor-spread (aetheria-release follow-up scenarios-batch4-minors): a station reactor's product keeps the +// quality spread of the reactor product it was scaled from. The mint reads a product's Roles (Mean, StandardDeviation) per +// design role, and a role missing or left at the unauthored default draws a flat .5 / .15 instead of the maker's spread. +public sealed class StationReactorSpreadTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-station-spread-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public StationReactorSpreadTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + // Read the way the mint does (ItemManager.Mint): the product's own Roles, matched by role name. + [Fact] + public void ShippedStationReactorProductsCarryTheirSourcesSpread() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var products = cache.GetAll().ToArray(); + FactionProductData Find(string name, string maker) => + products.Single(p => p.Name == name && cache.Get(p.Manufacturer)?.ShortName == maker); + + foreach (var (stationName, sourceName, maker) in StationReactorSpreadCommand.Rows) + { + var station = Find(stationName, maker); + var source = Find(sourceName, maker); + Assert.NotEmpty(station.Roles); + foreach (var role in station.Roles) + { + var from = source.Roles.Single(r => r.Role == role.Role); + Assert.Equal(from.Mean, role.Mean); + Assert.Equal(from.StandardDeviation, role.StandardDeviation); + } + Assert.Contains(station.Roles, r => r.Mean != .5f || r.StandardDeviation != .15f); + } + } + + private void Seed() + { + using var cache = AetheriaStores.Open(Catalog, catalogWritable: true); + cache.Upsert(new VerseGrammar { Revision = 1 }); + var maker = cache.Upsert(new Faction { Name = "Maker", ShortName = "M" }); + var gear = cache.Upsert(new GearData { Name = "Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10 }); + var design = new CultRecordRef(gear.Key); + cache.Upsert(new FactionProductData + { + Name = "Source", Design = design, Manufacturer = maker, + Roles = { new ProductRole { Role = "core", Mean = .7f, StandardDeviation = .05f }, new ProductRole { Role = "regulator", Mean = .3f, StandardDeviation = .2f } } + }); + cache.Upsert(new FactionProductData + { + Name = "Source Station", Design = design, Manufacturer = maker, + Roles = { new ProductRole { Role = "core" }, new ProductRole { Role = "regulator", Mean = .9f, StandardDeviation = .01f } } + }); + cache.FlushAsync().Wait(); + } + + private static readonly (string Station, string Source, string Maker)[] Fixture = { ("Source Station", "Source", "M") }; + + private string Run(bool apply) + { + using var cache = AetheriaStores.Open(Catalog, catalogWritable: apply); + var output = new StringWriter(); + Assert.Equal(0, StationReactorSpreadCommand.Run(cache, apply, output, Fixture)); + cache.FlushAsync().Wait(); + return output.ToString(); + } + + private ProductRole RoleOf(string role) + { + using var cache = AetheriaStores.Open(Catalog); + return cache.GetAll().Single(p => p.Name == "Source Station").Roles.Single(r => r.Role == role); + } + + // A role at the unauthored default takes the source's pair, a role tuned in Studio is kept, a dry run writes nothing, + // and a second apply has nothing to do. + [Fact] + public void CopiesOnlyUnauthoredRolesAndReplaysToNothing() + { + Seed(); + var before = File.ReadAllBytes(Catalog); + Assert.Contains("core", Run(apply: false)); + Assert.Equal(before, File.ReadAllBytes(Catalog)); + + Run(apply: true); + Assert.Equal(.7f, RoleOf("core").Mean, 3); + Assert.Equal(.05f, RoleOf("core").StandardDeviation, 3); + Assert.Equal(.9f, RoleOf("regulator").Mean, 3); + Assert.Equal(.01f, RoleOf("regulator").StandardDeviation, 3); + + var written = File.ReadAllBytes(Catalog); + Assert.Contains("No changes", Run(apply: true)); + Assert.Equal(written, File.ReadAllBytes(Catalog)); + } +} diff --git a/tests/Aetheria.Shared.Tests/StationServicesTests.cs b/tests/Aetheria.Shared.Tests/StationServicesTests.cs index 2bf4d3c2f..3821a22b4 100644 --- a/tests/Aetheria.Shared.Tests/StationServicesTests.cs +++ b/tests/Aetheria.Shared.Tests/StationServicesTests.cs @@ -175,6 +175,46 @@ public sealed class StationServicesTests : IDisposable Assert.Contains(ore, open.Cargo.Keys); } + // The market absorbs a sold commodity (aetheria-release:ruling:station-market-absorbs-sold-commodity): a full hold + // stores what fits, the rest is taken, and the full price is paid; a hold with no room at all still pays. + [Fact] + public void TrySell_commodity_is_paid_in_full_when_the_station_hold_is_full() + { + var from = Ship().CargoBays.Single(); + var ore = Ore(10); + Assert.True(from.TryStore(ore)); + var station = Station(); + while (station.CargoBays[0].TryStore(Mint("Gun"))) { } + var credits = 0; + Assert.True(StationServices.TrySell(from, station, ore, ref credits)); + Assert.Equal(35, credits); + Assert.Empty(from.Cargo.Keys.OfType()); + Assert.Empty(station.CargoBays[0].Cargo.Keys.OfType()); + } + + // A commodity the seller does not hold sells for nothing: not one never stored, and not a stale copy of a stack the sale + // already took. The held stack is untouched, and no credit is paid. + [Fact] + public void TrySell_commodity_not_in_the_hold_pays_nothing() + { + var from = Ship().CargoBays.Single(); + var held = Ore(10); + Assert.True(from.TryStore(held)); + var station = Station(); + var credits = 500; + + Assert.False(StationServices.TrySell(from, station, Ore(10), ref credits)); + Assert.Equal(500, credits); + Assert.Empty(station.CargoBays.Single().Cargo.Keys.OfType()); + Assert.Equal(10, Assert.Single(from.Cargo.Keys.OfType()).Quantity); + + Assert.True(StationServices.TrySell(from, station, held, ref credits)); + var paid = credits; + Assert.False(StationServices.TrySell(from, station, held, ref credits)); + Assert.Equal(paid, credits); + Assert.Equal(10, station.CargoBays.Single().Cargo.Keys.OfType().Sum(c => c.Quantity)); + } + [Fact] public void Repair_restores_and_charges() { @@ -465,4 +505,86 @@ public sealed class StationServicesTests : IDisposable Assert.Equal(BuyResult.Bought, StationServices.TryBuy(_items, ore, 10, ref credits, () => true)); Assert.Equal(0, credits); } + + private SimpleCommodity Mined(int quantity) + { + var data = _cache.GetByName("Ore"); + return new SimpleCommodity { Data = _cache.RefOf(data), Quantity = quantity, Lot = _items.ExtractedLot(0, default, data) }; + } + + [Fact] + public void SellOreSellsOnlyMinedStacks() + { + var ship = Ship(); + var bay = ship.CargoBays.Single(); + var mined = Mined(10); + var staged = Ore(5); + var gun = Mint("Gun"); + Assert.True(bay.TryStore(mined)); + Assert.True(bay.TryStore(staged)); + Assert.True(bay.TryStore(gun)); + var station = Station(); + var value = StationServices.OreValue(_items, ship.CargoBays); + Assert.Equal(StationServices.SellPrice(_items, mined), value); + Assert.True(value > 0); + + var credits = 100; + Assert.Equal(10, StationServices.TrySellOre(ship.CargoBays, station, ref credits)); + Assert.Equal(100 + value, credits); + Assert.DoesNotContain(mined, bay.Cargo.Keys); + Assert.Contains(staged, bay.Cargo.Keys); + Assert.Contains(gun, bay.Cargo.Keys); + } + + [Fact] + public void SellOreLeavesALottedCommodityThatWasNotExtracted() + { + var ship = Ship(); + var bay = ship.CargoBays.Single(); + var data = _cache.GetByName("Ore"); + var lot = _items.Lots.Add(new Lot { Design = _cache.RefOf(data), Origin = new Attributed(), Quality = 1 }); + Assert.NotEqual(0, lot); + var traded = new SimpleCommodity { Data = _cache.RefOf(data), Quantity = 6, Lot = lot }; + Assert.True(bay.TryStore(traded)); + var credits = 100; + Assert.Equal(0, StationServices.OreValue(_items, ship.CargoBays)); + Assert.Equal(0, StationServices.TrySellOre(ship.CargoBays, Station(), ref credits)); + Assert.Equal(100, credits); + Assert.Contains(traded, bay.Cargo.Keys); + } + + [Fact] + public void SellOreAcrossBaysAndShips() + { + var one = Ship(); + var two = Ship(); + var bays = one.CargoBays.Concat(two.CargoBays).ToArray(); + Assert.True(one.CargoBays.Single().TryStore(Mined(30))); + Assert.True(two.CargoBays.Single().TryStore(Mined(40))); + var station = Station(); + // Fill the station's bay so nothing more fits: the market absorbs the sale at full price all the same. + for (var i = 0; i < 20; i++) station.CargoBays.Single().TryStore(Ore(100)); + var value = StationServices.OreValue(_items, bays); + Assert.Equal(StationServices.SellPrice(_items, Ore(70)), value); + + var credits = 0; + Assert.Equal(70, StationServices.TrySellOre(bays, station, ref credits)); + Assert.Equal(value, credits); + Assert.All(bays, bay => Assert.Empty(bay.Cargo.Keys.OfType())); + } + + [Fact] + public void SellOreWithNoOreChangesNothing() + { + var ship = Ship(); + var bay = ship.CargoBays.Single(); + Assert.True(bay.TryStore(Ore(5))); + Assert.True(bay.TryStore(Mint("Gun"))); + var held = bay.Cargo.Count; + var credits = 100; + Assert.Equal(0, StationServices.OreValue(_items, ship.CargoBays)); + Assert.Equal(0, StationServices.TrySellOre(ship.CargoBays, Station(), ref credits)); + Assert.Equal(100, credits); + Assert.Equal(held, bay.Cargo.Count); + } } diff --git a/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs new file mode 100644 index 000000000..39842e4f0 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs @@ -0,0 +1,253 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using Xunit; + +// Substance clean break (aetheria-release:ruling:clean-break-from-substance, cut remove-sbsar-files). The 41 .sbsar +// files, their importer and the SUBSTANCE_PLUGIN_ENABLED define are gone, and nothing that survives may point into +// them. Headless: no Unity is open, so a dangling GUID is caught here instead of rendering pink in the editor. +public sealed class SubstanceCleanBreakTests +{ + // Every guid the removed tree owned, captured from the .meta files before deletion: the 41 .sbsar.meta, the two + // folder metas (Assets/Materials/Substance.meta, Substance/Metal.meta) and the importer script guid + // (43a8bbf6..., the `script:` line of every .sbsar.meta, whose plugin was already absent). + private static readonly string[] Tombstones = + { + "06833951ebae4cc45ad88d58cb5571de", + "06d6a565d43fba5409712ce9a10bfbef", + "07f679eadba9fb14abac26b1e165f7d5", + "092bdd8d243488141aeab5bb0d72429a", + "09aee558716a08d4c9806b9b4273a209", + "0b5dfc86c0681a3459a57d197804191b", + "0be5fb1df83ac8e499a3f6a060041e49", + "130f566ffa0b2424fbb47de2194c136a", + "180b85899b4b1f848b348230339ce984", + "1c858fec5b74c7c46b1712494192b6b5", + "26a894e543f3ed44893b1620707ca62c", + "2b42584452fe0cc4fa4e8a115230b156", + "2be0f689f5b01be4aa1032bc86f15eab", + "2e9a9dbacde66a446852af882f33e9e2", + "43a8bbf65be290d44ba52b94476242b9", + "4e39297ae4fe9ee4b803c04eabb69da7", + "50192727b92e0af4cbe5c773bec3537f", + "504c7bfe0d50ff64a88b8eac2ceb46f8", + "53adf8e53222e6f4791d7bf2110fb70c", + "58e16b7dbc1c31f4585e11544cdce127", + "6b2eb94965ca27542b8627d3521f5b5b", + "7363fcc4a3c41a349b29de7ec34555be", + "7de1c11cf7591ec48bdb53e9818172f5", + "8249e9ffcbd97c84d8ce73343e156c82", + "885e680924fc12c439a842a2142d4b78", + "9458f33b8e7e51a42aa19686b9779d82", + "9aa51bbe4dd46874a906608c34a739e4", + "9d0963470d3545a4e932ed4ea95b9d62", + "9fc901afb8a434e46b9405eaec2df5a4", + "a1d39ea984432bf44b4a0686afe2bf1a", + "a74970be876d3554ea0f279f39314c9c", + "afbd691d0ea2a5a47b5a43b244593a56", + "b2bec4b400153d745b2915f1c43e5c96", + "b7e648471e9dfc44490bd41973711541", + "c00b5a4f1e4743a4ca59b8030251f900", + "c5f2177e1f35daa499f4d7e0b7f3370a", + "ca8f080ab60226e4097841eee2bfa8db", + "cbc61995a46604441ab9de4f1c68e290", + "d15fc45ed0000934d946b5f271f637ef", + "ddc6970cc883b9845bdadc91983130c2", + "deb7e15e5f95294498d18869d9f11302", + "e7758cad28ae98f478940e55222419a6", + "ea7457b9a4f0bcb43becaa33de541cbd", + "ef9a54b8dacea9f44be70da43472f701", + }; + + private static readonly string[] PrefabsAndMetasEditedByTheCut = + { + "Assets/Content/Prefabs/Turrets/Turret.prefab", "Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab", + "Assets/Prefabs/RPG/Pickups/Hexahedron.prefab", "Assets/Prefabs/RPG/Pickups/Icosahedron.prefab", + "Assets/Prefabs/RPG/Pickups/Octahedron.prefab", "Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab", + "Assets/Models/Zenith_Blender.fbx.meta", + }; + + // A material reference (main object fileID 2100000). Script guids in the same files resolve to Unity packages, + // which have no .meta under Assets/, so only material slots are checked. + private static readonly Regex MaterialRef = new(@"fileID:\s*2100000,\s*guid:\s*([0-9a-f]{32})", RegexOptions.Compiled); + + private static readonly string[] ExcludedDirs = { ".git", "node_modules", ".voidbot" }; + + private static readonly string[] RepointedMaterials = + { + "Assets/Materials/Steel.mat", "Assets/Materials/Aluminium brushed.mat", "Assets/Materials/Silver.mat", + "Assets/Materials/Steel parkerized.mat", "Assets/Materials/Cockpit.mat", "Assets/Materials/Metal 003.mat", + "Assets/Materials/Car Paint Red.mat", "Assets/Materials/Car Paint Magenta.mat", + "Assets/Materials/Car Paint White.mat", "Assets/Materials/Car Paint White Small.mat", + "Assets/Materials/Radiators.mat", "Assets/Materials/Station Lights.mat", "Assets/Materials/Mine Glow.mat", + "Assets/Models/Discobolus/Discobolus Marble.mat", "Assets/Materials/Pickup Trim.mat", + }; + + private static IEnumerable Walk(string dir) + { + foreach (var file in Directory.EnumerateFiles(dir)) yield return file; + foreach (var sub in Directory.EnumerateDirectories(dir)) + if (!ExcludedDirs.Contains(Path.GetFileName(sub))) + foreach (var file in Walk(sub)) yield return file; + } + + // A checkout that holds Git LFS pointers instead of content cannot be scanned. The guards that read LFS-tracked + // files fail loudly here: skipping would pass vacuously, and a failure says "smudge the LFS objects first". + private static bool IsLfsPointer(string path) + { + using var stream = File.OpenRead(path); + var head = new byte[48]; + var n = stream.Read(head, 0, head.Length); + return Encoding.ASCII.GetString(head, 0, n).StartsWith("version https://git-lfs", StringComparison.Ordinal); + } + + private static string ReadTextOrFailOnPointer(string path) + { + Assert.False(IsLfsPointer(path), $"{path} is an LFS pointer, not content: this guard cannot see inside it. Run `git lfs pull`."); + return File.ReadAllText(path, Encoding.Latin1); + } + + // Everything is scanned except known binary media (a denylist, so an unlisted serialized type is still read) and, + // for unlisted extensions, files with a NUL byte in the first 8 KiB. The extension check comes first because an + // LFS pointer for a texture is itself text and says nothing about what the object holds. + private static readonly string[] BinaryExtensions = + { + ".png", ".jpg", ".jpeg", ".tga", ".tif", ".tiff", ".psd", ".bmp", ".gif", ".exr", ".hdr", ".dds", ".wav", ".mp3", + ".ogg", ".mp4", ".fbx", ".glb", ".blend", ".ttf", ".otf", ".dll", ".so", ".pdb", ".msgpack", ".zip", ".bank", + }; + + private static bool LooksBinary(string path) + { + if (BinaryExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase)) return true; + using var stream = File.OpenRead(path); + var buf = new byte[8192]; + var n = stream.Read(buf, 0, buf.Length); + return Array.IndexOf(buf, (byte)0, 0, n) >= 0; + } + + private static Dictionary GuidToMeta(string root) + { + var map = new Dictionary(); + foreach (var meta in Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*.meta", SearchOption.AllDirectories)) + { + var guid = File.ReadLines(meta).FirstOrDefault(l => l.StartsWith("guid: "))?.Substring("guid: ".Length).Trim(); + if (guid == null) continue; + // A .meta whose asset is gone still carries the guid, so resolution must look beside it: the asset is the + // .meta path minus ".meta". Directory metas resolve to a folder. + var asset = meta.Substring(0, meta.Length - ".meta".Length); + if (File.Exists(asset) || Directory.Exists(asset)) map[guid] = Path.GetRelativePath(root, meta).Replace('\\', '/'); + } + return map; + } + + [Fact] + public void NoSbsarFileOrMetaRemains() + { + var root = RestoredHullsTests.FindRepoRoot(); + var stray = Walk(root).Where(f => f.EndsWith(".sbsar", StringComparison.OrdinalIgnoreCase) + || f.EndsWith(".sbsar.meta", StringComparison.OrdinalIgnoreCase)) + .Select(f => Path.GetRelativePath(root, f)).ToList(); + Assert.True(stray.Count == 0, $"{stray.Count} Substance archive files remain, first: {stray.FirstOrDefault()}"); + Assert.False(Directory.Exists(Path.Combine(root, "Assets", "Materials", "Substance"))); + } + + [Fact] + public void NoSurvivingFileNamesARemovedSubstanceGuid() + { + var root = RestoredHullsTests.FindRepoRoot(); + var files = new[] { "Assets", "Packages", "ProjectSettings" } + .Select(d => Path.Combine(root, d)).Where(Directory.Exists) + .SelectMany(Walk) + .Concat(Directory.Exists(Path.Combine(root, "GameData")) + ? Directory.EnumerateFiles(Path.Combine(root, "GameData"), "*.cc") : Enumerable.Empty()) + .Where(f => f.EndsWith(".cc") || !LooksBinary(f)) + .ToList(); + var pointers = files.Where(IsLfsPointer).Select(f => Path.GetRelativePath(root, f)).ToList(); + Assert.True(pointers.Count == 0, + $"{pointers.Count} scanned files are LFS pointers, not content (first: {pointers.FirstOrDefault()}); run `git lfs pull`."); + var hits = new List(); + foreach (var file in files) + { + var lines = File.ReadAllText(file, Encoding.Latin1).Split('\n'); + for (var i = 0; i < lines.Length; i++) + foreach (var guid in Tombstones) + if (lines[i].Contains(guid, StringComparison.Ordinal)) + hits.Add($"{Path.GetRelativePath(root, file)}:{i + 1} names {guid}"); + } + Assert.True(hits.Count == 0, $"{hits.Count} references to removed Substance guids:\n" + string.Join("\n", hits.Take(40))); + } + + [Fact] + public void NoSubstanceBuildSurface() + { + var root = RestoredHullsTests.FindRepoRoot(); + Assert.DoesNotContain("SUBSTANCE", ReadTextOrFailOnPointer(Path.Combine(root, "ProjectSettings", "ProjectSettings.asset")), StringComparison.Ordinal); + foreach (var name in new[] { "manifest.json", "packages-lock.json" }) + { + var text = File.ReadAllText(Path.Combine(root, "Packages", name)); + Assert.DoesNotContain("substance", text, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("allegorithmic", text, StringComparison.OrdinalIgnoreCase); + } + Assert.DoesNotContain("sbsar", File.ReadAllText(Path.Combine(root, ".gitattributes")), StringComparison.OrdinalIgnoreCase); + Assert.False(Directory.Exists(Path.Combine(root, "Assets", "Allegorithmic"))); + } + + [Fact] + public void EveryReplacementTextureResolves() + { + var root = RestoredHullsTests.FindRepoRoot(); + var guidToMeta = GuidToMeta(root); + + var texture = new Regex(@"m_Texture:\s*\{fileID:\s*(-?\d+)(?:,\s*guid:\s*([0-9a-f]{32}))?", RegexOptions.Compiled); + var problems = new List(); + foreach (var rel in RepointedMaterials) + { + var path = Path.Combine(root, rel); + if (!File.Exists(path)) { problems.Add($"{rel} does not exist"); continue; } + var text = File.ReadAllText(path); + var start = text.IndexOf("m_TexEnvs:", StringComparison.Ordinal); + var end = text.IndexOf("m_Floats:", StringComparison.Ordinal); + Assert.True(start >= 0 && end > start, $"{rel} has no m_TexEnvs section"); + foreach (Match m in texture.Matches(text.Substring(start, end - start))) + { + if (m.Groups[1].Value == "0") continue; + if (!m.Groups[2].Success) { problems.Add($"{rel} has a nonzero texture fileID with no guid: {m.Value}"); continue; } + var guid = m.Groups[2].Value; + if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel} names {guid}, which has no .meta and asset under Assets/"); + else if (meta.StartsWith("Assets/Materials/Substance", StringComparison.Ordinal)) problems.Add($"{rel} names {guid} inside the removed Substance tree"); + else if (!File.ReadLines(Path.Combine(root, meta)).Any(l => l.StartsWith("TextureImporter:", StringComparison.Ordinal))) + problems.Add($"{rel} texture slot names {guid} ({meta}), which is not a TextureImporter asset"); + } + } + Assert.True(problems.Count == 0, string.Join("\n", problems)); + } + + [Fact] + public void EveryRepointedPrefabAndFbxSlotResolves() + { + var root = RestoredHullsTests.FindRepoRoot(); + var guidToMeta = GuidToMeta(root); + var problems = new List(); + foreach (var rel in PrefabsAndMetasEditedByTheCut) + { + var path = Path.Combine(root, rel); + if (!File.Exists(path)) { problems.Add($"{rel} does not exist"); continue; } + var lines = ReadTextOrFailOnPointer(path).Split('\n'); + for (var i = 0; i < lines.Length; i++) + foreach (Match m in MaterialRef.Matches(lines[i])) + { + var guid = m.Groups[1].Value; + if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel}:{i + 1} names {guid}, which has no .meta and asset under Assets/"); + else if (!meta.EndsWith(".mat.meta", StringComparison.Ordinal)) problems.Add($"{rel}:{i + 1} material slot names {guid} ({meta}), which is not a .mat"); + } + } + Assert.True(problems.Count == 0, string.Join("\n", problems.Take(40))); + } +} diff --git a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs index 37eafc01a..d1f9f73de 100644 --- a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs +++ b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs @@ -181,10 +181,9 @@ public sealed class SunsNeverGreenTests : IDisposable cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes); cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var tutorial = authored.Read("TutorialGenerationSettings"); - var galaxy = new Galaxy(tutorial, authored.Read("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var tutorial = TestCasts.Wide; + var galaxy = new Galaxy(tutorial, authored.Read("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); var zoneSettings = authored.Read("ZoneSettings"); adjust(zoneSettings); diff --git a/tests/Aetheria.Shared.Tests/TestCasts.cs b/tests/Aetheria.Shared.Tests/TestCasts.cs new file mode 100644 index 000000000..05759557c --- /dev/null +++ b/tests/Aetheria.Shared.Tests/TestCasts.cs @@ -0,0 +1,18 @@ +// The two fixtures every cast-galaxy test builds from: the values the retired Settings.asset block held (Miss, Zhe, Luc, +// Aero and Finch, Adras, 64 zones, half influence), so every test galaxy is what it was. A test fixture is not new +// faction material (ruling miss-terris-belongs-to-emily-r3). +internal static class TestCasts +{ + internal static GalaxyCast Wide => new GalaxyCast + { + ProtagonistFaction = "Miss", AntagonistFaction = "Zhe", BufferFaction = "Luc", + NeutralFactions = new[] { "Aero", "Finch" }, QuestFaction = "Adras", LinkDensity = .5f, ZoneCount = 64, + InfluenceScale = .5f, + }; + + internal static SectorBackgroundSettings Background => new SectorBackgroundSettings + { + NoiseAmplitude = 1, NoiseOffset = .3f, NoiseGain = .7f, NoiseLacunarity = 2, NoiseFrequency = .1f, + NoisePosition = 536.5106f, CloudExponent = 10, CloudAmplitude = .01f, + }; +} diff --git a/tests/Aetheria.Shared.Tests/TestCatalog.cs b/tests/Aetheria.Shared.Tests/TestCatalog.cs index 60d41c996..2561406f2 100644 --- a/tests/Aetheria.Shared.Tests/TestCatalog.cs +++ b/tests/Aetheria.Shared.Tests/TestCatalog.cs @@ -18,6 +18,12 @@ internal static class TestCatalog // The repo's catalog with its first-party packages composed in, resolved once per test process. public static string Repo => Shared.Value; + private static readonly Lazy SharedWithFixtures = new Lazy(() => ForRepoWithFixtures(RunStartTests.FindRepoRoot())); + + // The repo's catalog with its first-party packages and the test fixture packages (tests/fixtures/mods) composed in. For a + // test whose subject is a fixture package; Repo is the catalog the game ships. + public static string RepoWithFixtures => SharedWithFixtures.Value; + // The shipped assembly's own [CultDocument] types and nothing the test assembly registers (CultDocumentRegistry.ForTypes // does not re-scan the AppDomain), so this assembly's fixture documents never become catalog globals the real catalog // must hold. The one registry every test that opens a real catalog, and the composition behind Repo, uses. @@ -34,6 +40,21 @@ internal static class TestCatalog return Resolve(Path.Combine(repoRoot, "GameData", "Aetheria.cc"), Path.Combine(repoRoot, "GameData", "Mods"), work); } + // ForRepo over a mods root assembled from GameData/Mods and tests/fixtures/mods, copied into the per-call temp directory. + public static string ForRepoWithFixtures(string repoRoot) + { + var work = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetheria-testcatalog-" + Guid.NewGuid().ToString("N"))).FullName; + AppDomain.CurrentDomain.ProcessExit += (_, _) => { try { Directory.Delete(work, true); } catch (IOException) { } }; + var mods = Path.Combine(work, "Mods"); + foreach (var root in new[] { Path.Combine(repoRoot, "GameData", "Mods"), Path.Combine(repoRoot, "tests", "fixtures", "mods") }) + foreach (var package in Directory.GetDirectories(root)) + { + var target = Directory.CreateDirectory(Path.Combine(mods, Path.GetFileName(package))).FullName; + foreach (var file in Directory.GetFiles(package)) File.Copy(file, Path.Combine(target, Path.GetFileName(file))); + } + return Resolve(Path.Combine(repoRoot, "GameData", "Aetheria.cc"), mods, work); + } + public static string Resolve(string shippedCatalog, string modsRoot, string workDir) { // Every directory under the first-party tree is a package. The game treats a directory without a ship.cc as not a diff --git a/tests/Aetheria.Shared.Tests/VapourCloudTests.cs b/tests/Aetheria.Shared.Tests/VapourCloudTests.cs index 6945de2a8..3cd4ab34a 100644 --- a/tests/Aetheria.Shared.Tests/VapourCloudTests.cs +++ b/tests/Aetheria.Shared.Tests/VapourCloudTests.cs @@ -419,7 +419,7 @@ public sealed class VapourCloudTests : IDisposable var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(42, reader.ReadInt32()); - Assert.Equal(4, reader.ReadArrayHeader()); + Assert.Equal(38, reader.ReadArrayHeader()); reader.Skip(); Assert.Equal(1f, MessagePackSerializer.Deserialize(ref reader, options).Min); Assert.Equal(2f, MessagePackSerializer.Deserialize(ref reader, options).Min); diff --git a/tests/Aetheria.Shared.Tests/WrenPackageTests.cs b/tests/Aetheria.Shared.Tests/WrenPackageTests.cs index bb95cbb55..3395d7f32 100644 --- a/tests/Aetheria.Shared.Tests/WrenPackageTests.cs +++ b/tests/Aetheria.Shared.Tests/WrenPackageTests.cs @@ -5,7 +5,7 @@ using Xunit; using static CultMath.math; using Random = CultMath.Random; -// GameData/Mods/aetheria.wren: a first-party package written by `ship-authoring starter --like Djinni`, then priced and given +// tests/fixtures/mods/aetheria.wren: a test fixture package, not shipped with the game, written by `ship-authoring starter --like Djinni`, then priced and given // an unoffered Aeronautics Unlimited product by `ship-authoring price` and `product`; its model is the starter's boxed // stand-in. It is the pipeline's proof from a hull package on disk to a ship that flies in the headless simulation: the // package composes into the catalog, its mounts take catalog gear, and the fitted ship moves under thrust. `fly` cannot @@ -19,7 +19,7 @@ public sealed class WrenPackageTests [Fact] public void TheStarterPackageIsInTheComposedCatalogWithTheStatsOfItsLike() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var hull = Wren(cache); var like = cache.GetByName("Djinni"); Assert.NotNull(hull); @@ -34,7 +34,7 @@ public sealed class WrenPackageTests [Fact] public void TheStarterIsMadeButNeverOffered() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var hull = Wren(cache); var product = Assert.Single(cache.GetAll(), p => p.Design.Key.Equals(ShipModCatalog.HullKey(Id))); Assert.Equal("Aeronautics Unlimited", cache.Get(product.Manufacturer).Name); @@ -47,7 +47,7 @@ public sealed class WrenPackageTests [Fact] public void EveryMountTakesACatalogDesign() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var designs = cache.GetAll().ToArray(); var bare = Wren(cache).Hardpoints.Where(hardpoint => !designs.Any(hardpoint.Takes)).Select(hardpoint => $"{hardpoint.Transform} ({hardpoint.Type})").ToArray(); // No shield design fits a 1x1 yet (hardpoint-fit lists Djinni's 4-cell shield with none either); every other mount does. @@ -57,7 +57,7 @@ public sealed class WrenPackageTests [Fact] public void TheStarterFliesUnderThrust() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var ship = RestoredHullsTests.BuildThrustedShip(cache, "Wren"); var start = ship.Velocity; ship.MovementDirection = float2(0, 1); diff --git a/tests/fixtures/mods/aetheria.wren/ship.cc b/tests/fixtures/mods/aetheria.wren/ship.cc new file mode 100644 index 000000000..71b71ef5a --- /dev/null +++ b/tests/fixtures/mods/aetheria.wren/ship.cc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:096ea08f7fe85b44c343b57dfbc84fd82b2ec1d450cc1eb49efc3c238f9a9678 +size 10528 diff --git a/tests/fixtures/mods/aetheria.wren/ship.glb b/tests/fixtures/mods/aetheria.wren/ship.glb new file mode 100644 index 000000000..08f3e5c7e --- /dev/null +++ b/tests/fixtures/mods/aetheria.wren/ship.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3980ea88075b07bece2f64f315fde34bb7214ae0c9fb40d766556e12bb4b8a5a +size 5872 diff --git a/tools/AetherDb/Economy/DemoOre.cs b/tools/AetherDb/Economy/DemoOre.cs new file mode 100644 index 000000000..df2a2aff2 --- /dev/null +++ b/tools/AetherDb/Economy/DemoOre.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +// Interim ore sheet (ruling mining-demo-ore-minimal-yields-now): the Asteroid field kind yields Rock, New Metals and Gold, and those +// three can be held (a 1x1 shape, a mass) and are sold (a price). The economy ores batch may rewrite the yields by element id. +// Prices are ruling mining-demo-ore-prices-gear-scale, gear-scale so the mine, sell, repair loop closes: a retune is an edit here and a rerun. +// Munitions and MunitionsFeed never rewrite these three commodities, so rerunning them does not clobber this sheet. +public sealed class DemoOre : EconomyBatch +{ + private const int RockPrice = 200; + private const int NewMetalsPrice = 1000; + private const int GoldPrice = 5000; + + // Authored element ids (the cache takes a hand-written id only as 12 lowercase hex): asteroid-rock, asteroid-new-metals, asteroid-gold. + private const string RockId = "a57e0c000001"; + private const string NewMetalsId = "a57e0c000002"; + private const string GoldId = "a57e0c000003"; + + public override void Author(EconomyAuthor author) + { + author.Edit("Rock", o => { o.Shape = new Shape(); o.Price = RockPrice; }); + author.Edit("New Metals", o => { o.Shape = new Shape(); o.Price = NewMetalsPrice; o.Mass = 2; }); + author.Edit("Gold", o => { o.Shape = new Shape(); o.Price = GoldPrice; }); + + var kinds = author.Catalog.GetAll().Where(k => k.Name == "Asteroid").ToArray(); + if (kinds.Length != 1) throw new InvalidOperationException($"{kinds.Length} field kinds are named 'Asteroid'; the ore sheet needs exactly one."); + var asteroid = kinds[0]; + asteroid.Yields = new List + { + Yield(author, "Rock", 6, RockId), + Yield(author, "New Metals", 3, NewMetalsId), + Yield(author, "Gold", 1, GoldId) + }; + author.Put(asteroid, author.Catalog.RefOf(asteroid).Key); + } + + private static FieldYield Yield(EconomyAuthor author, string name, float abundance, string id) + { + var item = author.Catalog.GetAll().Single(i => i.Name == name); + return new FieldYield { Commodity = new CultRecordRef(author.Catalog.RefOf(item).Key), Abundance = abundance, Regional = false, Id = id }; + } +} diff --git a/tools/AetherDb/Economy/StationKindDescriptions.cs b/tools/AetherDb/Economy/StationKindDescriptions.cs new file mode 100644 index 000000000..746847e2e --- /dev/null +++ b/tools/AetherDb/Economy/StationKindDescriptions.cs @@ -0,0 +1,27 @@ +using System; +using GameCult.Caching; + +// Economy content: station-kind descriptions that name only goods the recipe graph makes or takes. The station-round bench wrote +// descriptions naming Uranium, Hydrogen, Bacteria, Fungi and Animal Products, none of which any recipe yields or consumes; this +// restates the five kinds that named them (mining, volatiles, agriculture, habitat-support, power) as StationKindsCatalog.Table +// has them, so a catalog authored fresh says the same thing. Sets the description whatever it was, so a rerun converges. +public sealed class StationKindDescriptions : EconomyBatch +{ + public override void Author(EconomyAuthor author) + { + foreach (var (id, description) in new[] + { + ("mining", StationKindsCatalog.DescriptionOf("mining")), + ("volatiles", StationKindsCatalog.DescriptionOf("volatiles")), + ("agriculture", StationKindsCatalog.DescriptionOf("agriculture")), + ("habitat-support", StationKindsCatalog.DescriptionOf("habitat-support")), + ("power", StationKindsCatalog.DescriptionOf("power")), + }) + { + var key = StationKindData.KeyOf(id); + var kind = author.Catalog.Get(key) ?? throw new InvalidOperationException($"The catalog holds no station kind '{id}'."); + kind.Description = description; + author.Put(kind, key); + } + } +} diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index 244fc4279..83349a1c0 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -45,6 +45,10 @@ public sealed class EconomyAuthor private void Write(Type type, object document, CultRecordKey key) { if (!_touched.Contains(key.Value)) _touched.Add(key.Value); + // A cache refuses to write one type onto a key another type holds (write ownership by written type): a batch that turns + // a compound good into a raw one removes the old record first. + var held = _catalog.Get(key); + if (held != null && held.GetType() != type) _catalog.Remove(key); _catalog.UpsertAsync(type, document, key).GetAwaiter().GetResult(); } } @@ -107,15 +111,16 @@ public static class EconomyCommand // atomically, so a refusal leaves Aetheria.cc byte-identical. A batch is compiled code and is reviewed as code: it is trusted not // to touch the real file, and the command refuses by name if the file changed under it. Added, changed and unchanged are read by // comparing the original and the copy on disk. A shape fault the batches introduce (present after, absent before, by rule and - // record) refuses; faults the catalog already held print and do not. - public static int Author(string catalogPath, IReadOnlyList batches, bool apply, TextWriter output, CultDocumentRegistry registry = null) + // record) refuses; faults the catalog already held print and do not. The trial copy lives under scratchRoot (the temp folder unless a caller + // that audits it names a private one). + public static int Author(string catalogPath, IReadOnlyList batches, bool apply, TextWriter output, CultDocumentRegistry registry = null, string scratchRoot = null) { if (apply && new FileInfo(catalogPath).IsReadOnly) { output.WriteLine("The batches are refused: Aetheria.cc is read-only. Clear the read-only flag, or check it out, and run again. The catalog is unchanged."); return 1; } - var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-economy-" + Guid.NewGuid().ToString("N"))).FullName; + var scratch = Directory.CreateDirectory(Path.Combine(scratchRoot ?? Path.GetTempPath(), "aetherdb-economy-" + Guid.NewGuid().ToString("N"))).FullName; try { var trial = Path.Combine(scratch, "Aetheria.cc"); diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 5d3d18e93..39e4284ff 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -59,6 +59,7 @@ public static class Program case "inspection-scanner": return InspectionScannerCatalog(args.Contains("apply")); case "product-lines": return ProductLinesCommand.Run(args.Skip(1).ToArray()); case "minor-power-factions": return MinorPowerFactionsCommand.Run(args.Skip(1).ToArray()); + case "station-reactor-spread": return StationReactorSpreadCommand.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); case "assembly-from-maker": return AssemblyFromMakerCommand.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); case "place-names": Console.OutputEncoding = new System.Text.UTF8Encoding(false); @@ -559,7 +560,7 @@ public static class Program private static int SettingsDump() { var authored = AuthoredSettings.Load(AetherDb.FindRoot()); - authored.Dump("TutorialGenerationSettings", 2); + authored.Dump("CastBackgroundSettings", 2); Console.WriteLine(); authored.Dump("GameplaySettings", 2); return 0; @@ -571,15 +572,10 @@ public static class Program { var authored = AuthoredSettings.Load(AetherDb.FindRoot()); - var tutorial = authored.Read("TutorialGenerationSettings"); - var background = authored.Read("TutorialBackgroundSettings"); + var background = authored.Read("CastBackgroundSettings"); var zones = authored.Read("ZoneSettings"); var gameplay = authored.Read("GameplaySettings"); - Console.WriteLine($"tutorial: protagonist {tutorial.ProtagonistFaction}, antagonist {tutorial.AntagonistFaction}, " + - $"buffer {tutorial.BufferFaction}, quest {tutorial.QuestFaction}, " + - $"neutrals [{string.Join(", ", tutorial.NeutralFactions ?? new string[0])}], " + - $"{tutorial.ZoneCount} zones, link density {tutorial.LinkDensity}"); Console.WriteLine($"background: frequency {background.NoiseFrequency}, amplitude {background.NoiseAmplitude}, " + $"cloud exponent {background.CloudExponent}, density at centre {background.CloudDensity(new float2(.5f)):0.000}"); Console.WriteLine($"zones: sun mass {zones.SunMass}, planet mass {zones.PlanetMass}, satellite passes {zones.SatellitePasses}, " + @@ -599,8 +595,6 @@ public static class Program else if (gameplay.Tiers.Any(t => string.IsNullOrEmpty(t.Name) || t.Quality <= 0)) missing.Add("GameplaySettings.Tiers (a tier parsed without a name or quality)"); if (gameplay.DefaultEntitySettings == null) missing.Add("GameplaySettings.DefaultEntitySettings"); if (gameplay.QualityPriceModifier == null || gameplay.QualityPriceModifier.Maximum <= 0) missing.Add("GameplaySettings.QualityPriceModifier"); - if (tutorial.NeutralFactions == null || tutorial.NeutralFactions.Length != 2) missing.Add($"TutorialGenerationSettings.NeutralFactions (expected 2, got {tutorial.NeutralFactions?.Length ?? 0})"); - if (string.IsNullOrEmpty(tutorial.ProtagonistFaction)) missing.Add("TutorialGenerationSettings.ProtagonistFaction"); Console.WriteLine($"\n{authored.Unplaced.Count} fields in the asset had nowhere to go"); foreach (var field in authored.Unplaced.Take(20)) Console.WriteLine($" {field}"); diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs index 841da957e..3b3ea9051 100644 --- a/tools/AetherDb/ShipAuthoringCommands.cs +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -1,4 +1,5 @@ using GameCult.Caching; +using GameCult.Caching.MessagePack; using System; using System.Collections.Generic; using System.Globalization; @@ -8,7 +9,7 @@ using System.Linq; // Uses the existing database executable; mod authoring does not earn another binary target. public static class ShipAuthoringCommands { - private const string Usage = "ship-authoring create [--like ] | starter --like | inspect | centre | validate | product (--name [--description ] [--not-offered] | --remove) | price | stats [--mass m] [--durability d] [--armor a] [--drag x] [--top-speed v] | compose "; + private const string Usage = "ship-authoring create [--like ] | starter --like | regenerate [apply] | inspect | centre | validate | product (--name [--description ] [--not-offered] | --remove) | price | stats [--mass m] [--durability d] [--armor a] [--drag x] [--top-speed v] | compose "; private static readonly string[] StatFlags = { "--mass", "--durability", "--armor", "--drag", "--top-speed" }; @@ -52,6 +53,10 @@ public static class ShipAuthoringCommands var judged = model != null && File.Exists(model) ? "records and model" : "records only, no model yet"; if (judged == "records and model") ShipModCatalog.ReadPackage(args[1]); else ShipAuthoringStore.ValidateLoaded(hull, ship, products); + // Compose's verdict on a package's bins and its offered hull's schematic; the author sees it here, before compose. + // A package with no products has no bin and is never offered, so the shipped catalog is opened for none. + using var catalog = products.Length > 0 ? AetherDb.Open().Cache : null; + if (ShipModCatalog.MarketFault(catalog, ship, products) is { } fault) throw new InvalidOperationException(fault); Console.WriteLine($"{ship.Id}: {hull.Name}, {hull.Hardpoints.Count} hardpoints, {ship.Anchors.Count} anchors, {ship.SchematicLines.Count} lines ({judged})"); return 0; } @@ -84,6 +89,39 @@ public static class ShipAuthoringCommands Console.WriteLine($"Wrote a flyable starter package {path}; replace its stand-in model through Blender and Package, then set price and product."); return 0; } + if (args[0] == "regenerate" && (args.Length == 2 || args.Length == 3 && args[2] == "apply")) + { + // A package written before a record dropped a persisted slot cannot be written over (CultSchemaConflictException, + // retired slots stay read-only). Its decoded records go into a fresh file under today's schema, which must read + // back identical, and the fresh file replaces the old only with `apply`. Retired slots are the only content lost. + var (hull, ship, products) = ShipAuthoringStore.Load(args[1]); + var fresh = Path.GetFullPath(args[1]) + ".regenerating"; + File.Delete(fresh); + try + { + using (var cache = ShipAuthoringStore.Open(fresh, writable: true)) + { + ShipAuthoringStore.Write(cache, hull, ship); + foreach (var product in products) ShipAuthoringStore.WriteProduct(cache, ship.Id, product); + cache.FlushAsync().Wait(); + } + var (hull2, ship2, products2) = ShipAuthoringStore.Load(fresh); + ShipAuthoringStore.ValidateLoaded(hull2, ship2, products2); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + byte[] Pack(T value) => MessagePack.MessagePackSerializer.Serialize(value, options); + var same = Pack(hull).AsSpan().SequenceEqual(Pack(hull2)) && Pack(ship).AsSpan().SequenceEqual(Pack(ship2)) && + products.Length == products2.Length && + products.OrderBy(p => p.Manufacturer.Key.Value, StringComparer.Ordinal).Zip( + products2.OrderBy(p => p.Manufacturer.Key.Value, StringComparer.Ordinal), + (a, b) => Pack(a).AsSpan().SequenceEqual(Pack(b))).All(equal => equal); + if (!same) throw new InvalidOperationException($"{ship.Id}: the regenerated file does not read back as the records that went in; {args[1]} is untouched."); + Console.WriteLine($"{ship.Id}: {new FileInfo(args[1]).Length} bytes -> {new FileInfo(fresh).Length} bytes, {hull.Hardpoints.Count} hardpoints, {ship.Anchors.Count} anchors, {products.Length} products read back identical."); + if (args.Length == 3) File.Move(fresh, args[1], overwrite: true); + else Console.WriteLine("Dry run; add apply to replace the file."); + } + finally { File.Delete(fresh); File.Delete(fresh + ".lock"); } + return 0; + } if (args[0] == "price" && args.Length == 3) { // Judged before the file is touched: a refusal leaves it byte-identical. diff --git a/tools/AetherDb/ShipStarterCommand.cs b/tools/AetherDb/ShipStarterCommand.cs index 2a502a1f5..ebb3f4682 100644 --- a/tools/AetherDb/ShipStarterCommand.cs +++ b/tools/AetherDb/ShipStarterCommand.cs @@ -25,6 +25,9 @@ public static class ShipStarterCommand public float3 Position; // Box half-extents; null for an empty node. Scale is the node scale, used by the shield envelope. public float3? Half; + // A directional thruster emitter has one face, the (axis, sign) its exhaust leaves by in the Blender frame; a box with all six + // would fire exhaust both ways along the push. These drives push toward the bow (Reversed), so the exhaust leaves aft, +Y. + public (int Axis, int Sign)? Face; public float3? Scale; } @@ -43,8 +46,8 @@ public static class ShipStarterCommand new Part { Id = "collider", Role = "hull-collider", Half = new float3(3f, 5f, 1f) }, new Part { Id = "shield", Role = "shield", Scale = new float3(4f, 6f, 2.5f) }, new Part { Id = "tractor", Role = "tractor", Position = new float3(0f, -5f, 0f) }, - new Part { Id = "thruster.port", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(0, 0), Size = new int2(2, 1), Position = new float3(2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, - new Part { Id = "thruster.starboard", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(2, 0), Size = new int2(2, 1), Position = new float3(-2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, + new Part { Id = "thruster.port", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(0, 0), Size = new int2(2, 1), Position = new float3(2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f), Face = (1, 1) }, + new Part { Id = "thruster.starboard", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(2, 0), Size = new int2(2, 1), Position = new float3(-2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f), Face = (1, 1) }, new Part { Id = "radiator", Role = "radiator-mesh", Mount = HardpointType.Radiator, Cell = new int2(1, 1), Size = new int2(2, 1), Position = new float3(0f, 2f, 1.1f), Half = new float3(1.5f, .8f, .08f) }, new Part { Id = "gun.port", Role = "weapon-mount", Mount = HardpointType.Energy, Cell = new int2(0, 5), Position = new float3(1.8f, -3f, 1.1f) }, new Part { Id = "gun.port.muzzle", Role = "weapon-muzzle", Parent = "gun.port", Position = new float3(1.8f, -4f, 1.1f) }, @@ -125,8 +128,8 @@ public static class ShipStarterCommand var positions = new List(); var normals = new List(); var indices = new List(); - // Six faces, outward normals, in the Blender frame; Gltf() turns each into glTF's. - foreach (var (axis, sign) in new[] { (0, 1), (0, -1), (1, 1), (1, -1), (2, 1), (2, -1) }) + // Six faces (one for a thruster emitter), outward normals, in the Blender frame; Gltf() turns each into glTF's. + foreach (var (axis, sign) in part.Face != null ? new[] { part.Face.Value } : new[] { (0, 1), (0, -1), (1, 1), (1, -1), (2, 1), (2, -1) }) { var u = (axis + 1) % 3; var v = (axis + 2) % 3; diff --git a/tools/AetherDb/StationKindsCatalog.cs b/tools/AetherDb/StationKindsCatalog.cs index a450d2ff7..51d865f57 100644 --- a/tools/AetherDb/StationKindsCatalog.cs +++ b/tools/AetherDb/StationKindsCatalog.cs @@ -14,25 +14,28 @@ public static class StationKindsCatalog private static readonly (string id, string name, string description)[] Table = { - ("mining", "Mining Station", "Extracts ore (Rock, New Metals, Gold, Uranium, Potassium) from bodies and belts; consumes tools and food."), - ("volatiles", "Volatiles Station", "Skims Hydrogen, Methane and Water from gas giants and ice; consumes tools."), - ("agriculture", "Agriculture Station", "Grows Organics (Algae, Fungi, Bacteria, Animal Products) from Water and Potassium; feeds residential."), + ("mining", "Mining Station", "Extracts ore (Rock, New Metals, Gold, Potassium) and Diamond from bodies and belts; consumes tools and food."), + ("volatiles", "Volatiles Station", "Skims Methane, Ammonia and Water from gas giants and ice; consumes tools."), + ("agriculture", "Agriculture Station", "Grows Algae from Water and Potassium; feeds residential."), ("processing", "Processing Station", "Refines ore and volatiles into Metals, Alloys and Compounds."), ("fabrication", "Fabrication Station", "Turns Alloys and Compounds into Manufacturing compounds, Assemblies, gear, Ammo and consumer goods."), ("shipyard", "Shipyard", "Assembles hulls from Assemblies and Alloys."), ("depot", "Depot", "Stores and dispatches stock; loads haulers and tenders."), ("trade-hub", "Trade Hub", "Exchanges every bloc's goods between haulers and takes a cut; produces nothing."), ("residential", "Residential Station", "A bloom: consumes food, water, Wearables, Consumables and Luxuries; supplies crews."), - ("habitat-support", "Habitat Support Station", "Air, water recycling, life support and medicine for nearby habitats; consumes Bacteria, Water, Compounds."), + ("habitat-support", "Habitat Support Station", "Air, water recycling, life support and medicine for nearby habitats; consumes Water and Compounds."), ("urban", "Urban Station", "Dense city and services: market, media, repair; consumes luxuries and food."), ("administrative", "Administrative Station", "Issues quotas, contracts and security; consumes luxuries."), - ("power", "Power Station", "Makes reactor fuel, reservoirs and capacitors from Uranium and Hydrogen."), + ("power", "Power Station", "Generates and distributes power for nearby stations."), ("research", "Research Station", "Certification, compute, prototypes; consumes Assemblies."), ("salvage", "Salvage Station", "Breaks wrecks into Metals and second-hand gear."), ("black-market", "Black Market", "Buys anything, fences stolen cargo."), ("waystation", "Waystation", "Fuel, repair and medicine along a corridor."), }; + // A kind's authored description: the one text a fresh catalog gets and an economy batch restates. + public static string DescriptionOf(string id) => Table.Single(row => row.id == id).description; + public static int Run(CultCache cache, bool apply, TextWriter output) { var held = cache.GetAll().Select(kind => cache.RefOf(kind).Key.Value).ToHashSet(StringComparer.Ordinal); diff --git a/tools/AetherDb/StationReactorSpreadCommand.cs b/tools/AetherDb/StationReactorSpreadCommand.cs new file mode 100644 index 000000000..6f7064fb3 --- /dev/null +++ b/tools/AetherDb/StationReactorSpreadCommand.cs @@ -0,0 +1,82 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; + +// station-reactor-spread [apply] (aetheria-release follow-up scenarios-batch4-minors): the per-manufacturer station reactors +// (f458206c7) were authored as scaled copies of each maker's largest reactor, but their products were authored with a bare +// ProductRole { Role } for each role, which is the .5 / .15 default, so they lost the source product's quality spread. This +// gives each station product the Mean and StandardDeviation the source product holds for the same role. It writes only a role +// still at the default pair, so a spread tuned in Studio survives every replay, and a second apply has nothing to do. Replays +// before assembly-from-maker (which derives from role means) when that command has an unauthored maker to fill. Dry run +// unless apply. +public static class StationReactorSpreadCommand +{ + // The role pair an unauthored ProductRole carries (ProductRole's field defaults). + private static readonly ProductRole Unauthored = new ProductRole(); + + // (station product, source product, maker short name): the source is the maker's product of the reactor the station + // design was scaled from. + public static readonly (string Station, string Source, string Maker)[] Rows = + { + ("Steadfast Station", "Steadfast", "R&D"), + ("Manhattan Station", "Manhattan", "Zhestokost"), + ("Notorious Station", "Notorious", "Lucent"), + ("Vulcan Station", "Vulcan", "AU"), + ("MoveOnPro Station", "MoveOnPro", "NiteLife"), + }; + + public static int Run(CultCache cache, bool apply, TextWriter output, (string Station, string Source, string Maker)[] rows = null) + { + var products = cache.GetAll().ToArray(); + FactionProductData Find(string name, string maker) + { + var found = products.Where(p => p.Name == name && cache.Get(p.Manufacturer)?.ShortName == maker).ToArray(); + if (found.Length != 1) throw new InvalidOperationException($"Station reactor row \"{name}\" by {maker}: {found.Length} products match."); + return found[0]; + } + + var changed = new List(); + foreach (var (stationName, sourceName, maker) in rows ?? Rows) + { + var station = Find(stationName, maker); + var source = Find(sourceName, maker); + foreach (var role in station.Roles) + { + var from = source.Roles.SingleOrDefault(r => r.Role == role.Role) + ?? throw new InvalidOperationException($"\"{sourceName}\" holds no \"{role.Role}\" role to copy to \"{stationName}\"."); + if (role.Mean != Unauthored.Mean || role.StandardDeviation != Unauthored.StandardDeviation) continue; + if (from.Mean == role.Mean && from.StandardDeviation == role.StandardDeviation) continue; + output.WriteLine($"{stationName} ({maker}) {role.Role}: {role.Mean:0.###}±{role.StandardDeviation:0.###} -> {from.Mean:0.###}±{from.StandardDeviation:0.###}"); + role.Mean = from.Mean; + role.StandardDeviation = from.StandardDeviation; + if (!changed.Contains(station)) changed.Add(station); + } + } + + if (changed.Count == 0) + { + output.WriteLine("No changes."); + return 0; + } + + if (!apply) + { + output.WriteLine($"\nDry run. Pass \"apply\" to write {changed.Count} products."); + return 0; + } + + foreach (var product in changed) CultRecordRefs.Validate(product); + cache.Commit(batch => + { + foreach (var product in changed) batch.Upsert(typeof(FactionProductData), product, cache.RefOf(product).Key); + }); + output.WriteLine($"\nWrote {changed.Count} products in Aetheria.cc"); + return 0; + } +} diff --git a/tools/blender/aetheria_ships/hull_source.py b/tools/blender/aetheria_ships/hull_source.py index 2d6d0ca16..4c7771e94 100644 --- a/tools/blender/aetheria_ships/hull_source.py +++ b/tools/blender/aetheria_ships/hull_source.py @@ -14,7 +14,8 @@ with it (a hull that redefines or shadows an included language fails a check): lines ECHO line = [layer, cyclic, [[x, y, z], ...]] one line per kit part that draws one, points in the Ship Root frame (lowpoly.scad lp_line under lp_at frames); layer is one of KIT_LAYERS the zone's geometry, OFF; a donor's zone is named ":" - emit:, rad: the mesh of a thruster-emitter or radiator-mesh anchor + emit:, rad: the mesh of a thruster-emitter or radiator-mesh anchor; build() keeps of an emitter only the triangles + that face its exhaust (exhaust_face), so a closed box an author draws becomes its one exhaust-facing side marks OFF, a tiny cube at the first point of each kit line, drawn through the frame the geometry is drawn in (lp_line) Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. build() also takes the hull's HullData.HullType ("Ship", @@ -183,6 +184,28 @@ def parse_off(text): return Mesh(vertices, tuple(triangles)) +def exhaust_face(mesh, yaw): + """The part of a thruster emitter's mesh that faces its exhaust, which leaves the way the anchor faces (its yaw: 0 the nose, + -Y; 90 port, +X): the triangles whose outward normal lies within 60 degrees of it, with the vertices they use. The + exhaust of a thruster is born along each triangle's normal of this mesh, so an emitter with a triangle facing the + other way fires along the push too: a directional thruster's emitter is one-sided. The hull source draws the surface + in whatever solid is convenient (a thin box); the closed sides drop here, and a mesh with no side facing the exhaust + is left empty, which the emitter-has-a-mesh check refuses. A future ring thruster, whose exhaust leaves radially, is a + different emitter with its own rule and does not come through here.""" + facing = (math.sin(math.radians(yaw)), -math.cos(math.radians(yaw))) + kept = [] + for a, b, c in mesh.triangles: + pa, pb, pc = mesh.vertices[a], mesh.vertices[b], mesh.vertices[c] + u, v = [pb[i] - pa[i] for i in range(3)], [pc[i] - pa[i] for i in range(3)] + normal = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) + length = math.sqrt(sum(n * n for n in normal)) + if length > 0 and (normal[0] * facing[0] + normal[1] * facing[1]) / length > 0.5: + kept.append((a, b, c)) + used = sorted({i for tri in kept for i in tri}) + renumber = {old: new for new, old in enumerate(used)} + return Mesh(tuple(mesh.vertices[i] for i in used), tuple(tuple(renumber[i] for i in tri) for tri in kept)) + + def parse_echoes(text, name): """The values of every 'ECHO: = ' line. OpenSCAD prints JSON-compatible values.""" values = [] @@ -439,6 +462,13 @@ def build(runner, library, hull_type, projector): if len(set(ids)) != len(ids) or any(a.role not in ANCHOR_ROLES for a in anchors): raise HullSourceError("The hull source's anchors repeat an id or name a role a hull source does not make") anchor_meshes = {a.id: parse_off(runner(MESH_ROLES[a.role] + a.id)[0]) for a in anchors if a.role in MESH_ROLES} + for a in anchors: + if a.role == "thruster-emitter": + # The hardpoint Rotation the catalog gate judges the emitter against is one of four directions, so the one authority + # for which way an emitter faces is a quarter turn; a source that turns one otherwise is refused here, not rounded. + if abs(a.yaw / 90 - round(a.yaw / 90)) > 1e-6: + raise HullSourceError("The hull source turns a thruster emitter by something other than a quarter turn") + anchor_meshes[a.id] = exhaust_face(anchor_meshes[a.id], a.yaw) kit_lines = read_lines(runner("lines")[1]) judge = donor or own body_zone = f"{donor.faction}:{donor.body}" if donor else own.body diff --git a/tools/blender/tests/smoke_hull_source.py b/tools/blender/tests/smoke_hull_source.py index a3676b0c7..3916eeefa 100644 --- a/tools/blender/tests/smoke_hull_source.py +++ b/tools/blender/tests/smoke_hull_source.py @@ -167,6 +167,8 @@ def make_ship(scene, fixture, ship_id, extent, length, rows): bpy.ops.aetheria.add_ship_hardpoint() hp = state.hardpoints[len(state.hardpoints) - 1] hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint = mount_id, kind, x, y, "#" + if kind == THRUSTER: + hp.rotation = "2" # Reversed: the hull sources' drives sit at the stern, their emitters yawed 180 so the exhaust leaves aft result, message = run(bpy.ops.aetheria.save_ship_layout) require(result == {"FINISHED"}, f"Save was refused: {message}") package = MODS / ship_id @@ -586,7 +588,7 @@ def shared_ids_refused(scene, box, collection, ship_id, package, objects, number def check_poses(collection, root, runner): """Every built anchor stands where the hull source says in Ship Root's frame, turned as it says, and the emitter and - radiator meshes are the source's meshes in that frame.""" + radiator meshes are the source's meshes in that frame (an emitter's cut to the side that faces its exhaust).""" inverse = root.matrix_world.inverted() for anchor in hull_source.read_anchors(runner("anchors")[1]): obj = bpy.data.objects[anchor.id] @@ -599,7 +601,10 @@ def check_poses(collection, root, runner): f"{anchor.id} is turned {math.degrees(turn):.1f} degrees, not {anchor.yaw}") if anchor.role in hull_source.MESH_ROLES: made = sorted(tuple(round(c, 3) for c in (inverse @ obj.matrix_world @ v.co)) for v in obj.data.vertices) - wanted = sorted(tuple(round(c, 3) for c in v) for v in hull_source.parse_off(runner(hull_source.MESH_ROLES[anchor.role] + anchor.id)[0]).vertices) + source = hull_source.parse_off(runner(hull_source.MESH_ROLES[anchor.role] + anchor.id)[0]) + if anchor.role == "thruster-emitter": # Build keeps of an emitter only the side facing its exhaust + source = hull_source.exhaust_face(source, anchor.yaw) + wanted = sorted(tuple(round(c, 3) for c in v) for v in source.vertices) require(len(made) == len(wanted) and all(approx(a, b, 2e-3) for a, b in zip(made, wanted)), f"The mesh of {anchor.id} is not the source's mesh in Ship Root's frame") diff --git a/tools/blender/tests/smoke_mounts.py b/tools/blender/tests/smoke_mounts.py index 53418abb1..ee623537d 100644 --- a/tools/blender/tests/smoke_mounts.py +++ b/tools/blender/tests/smoke_mounts.py @@ -69,6 +69,14 @@ def quad(name, size): return mesh +def exhaust_quad(name, size): + """A thruster emitter for a hardpoint of Rotation None: an upright quad whose one side faces the nose (-Y), the way its exhaust leaves.""" + mesh = bpy.data.meshes.new(name) + half = size / 2 + mesh.from_pydata([(-half, 0, -half), (half, 0, -half), (half, 0, half), (-half, 0, half)], [], [(0, 1, 2, 3)]) + return mesh + + def tetrahedron(name): mesh = bpy.data.meshes.new(name) mesh.from_pydata([(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)], [], [(0, 2, 1), (0, 1, 3), (0, 3, 2), (1, 2, 3)]) @@ -294,7 +302,7 @@ def main(): tag(new_object(collection, "Hull Collider", tetrahedron("Hull Collider"), parent=root), "hull-collider", "collider") tag(new_object(collection, "Shield", None, parent=root), "shield", "shield") tag(new_object(collection, "Tractor", None, (0, 2, 0), root), "tractor", "tractor") - disc = new_object(collection, "Thruster", quad("Thruster", 0.4), (0, 8, 0), root) + disc = new_object(collection, "Thruster", exhaust_quad("Thruster", 0.4), (0, 8, 0), root) tag(disc, "thruster-emitter", "thruster") for mount, kind, x, y in (("thruster", "3", 2, 0), ("reactor.a", "5", 2, 2)): bpy.ops.aetheria.add_ship_hardpoint() diff --git a/tools/blender/tests/smoke_package.py b/tools/blender/tests/smoke_package.py index 886c349e2..6d0322dea 100644 --- a/tools/blender/tests/smoke_package.py +++ b/tools/blender/tests/smoke_package.py @@ -53,6 +53,14 @@ def quad(name, size=1.0): return mesh +def exhaust_quad(name, size): + """A thruster emitter for a hardpoint of Rotation None: an upright quad whose one side faces the nose (-Y), the way its exhaust leaves.""" + mesh = bpy.data.meshes.new(name) + half = size / 2 + mesh.from_pydata([(-half, 0, -half), (half, 0, -half), (half, 0, half), (-half, 0, half)], [], [(0, 1, 2, 3)]) + return mesh + + def tagged(collection, name, data, role=None, anchor_id=None, location=(0, 0, 0), parent=None): obj = bpy.data.objects.new(name, data) obj.location = location @@ -345,7 +353,7 @@ def main(): tagged(ship, "Hull Collider", tetrahedron("Hull Collider"), "hull-collider", "collider") tagged(ship, "Shield", None, "shield", "shield") tagged(ship, "Tractor", None, "tractor", "tractor", (0, 2, 0)) - disc = tagged(ship, "Thruster", quad("Thruster", 0.4), "thruster-emitter", "thruster", (0, -1, 0)) + disc = tagged(ship, "Thruster", exhaust_quad("Thruster", 0.4), "thruster-emitter", "thruster", (0, -1, 0)) gun = tagged(ship, "Gun", None, "weapon-mount", "gun", (1, 0, 0)) tagged(ship, "Gun Muzzle", None, "weapon-muzzle", "gun.muzzle", (0, 0.5, 0), parent=gun) tagged(ship, "Radiator", quad("Radiator", 0.5), "radiator-mesh", "radiator", (-1, 0, 0)) diff --git a/tools/blender/tests/test_hull_source.py b/tools/blender/tests/test_hull_source.py index e77ec11b2..ce78c313f 100644 --- a/tools/blender/tests/test_hull_source.py +++ b/tools/blender/tests/test_hull_source.py @@ -28,7 +28,7 @@ SECRET = "SECRET-NAME-7" # a value a hull source supplies and no refusal may ec def box(x0, x1, y0, y1, z0, z1): """An OFF text for an axis-aligned box: 8 vertices, 6 quads (12 triangles once fanned).""" v = [(x, y, z) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)] - quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] + quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)] # outward, counter-clockwise from outside rows = ["OFF", "8 6 0"] + [f"{x} {y} {z}" for x, y, z in v] + [f"4 {a} {b} {c} {d}" for a, b, c, d in quads] return "\n".join(rows) @@ -339,9 +339,9 @@ class JudgementTests(unittest.TestCase): self.assertEqual(fixture.failed(), ["the triangle count lies inside the brief's budget"], budget) def test_the_budget_counts_the_triangles_of_the_emitter_meshes_too(self): - # 12 + 12 triangles of zones, 12 of the emitter: a budget of 30 holds without the emitter and not with it + # 12 + 12 triangles of zones, 2 of the emitter (its exhaust-facing side): a budget of 25 holds without it and not with it fixture = Fixture() - fixture.parts["brief"] = ("", brief(triangles=(10, 30))) + fixture.parts["brief"] = ("", brief(triangles=(10, 25))) self.assertEqual(fixture.failed(), ["the triangle count lies inside the brief's budget"]) def test_the_length_is_a_range_with_two_ends(self): @@ -385,6 +385,47 @@ class JudgementTests(unittest.TestCase): fixture.parts["emit:Th.A"] = ("", "") self.assertEqual(fixture.failed(), ["every emitter and radiator anchor has a mesh"]) + @staticmethod + def _normals(mesh): + """The unit outward normal of each triangle.""" + out = [] + for a, b, c in mesh.triangles: + pa, pb, pc = (mesh.vertices[i] for i in (a, b, c)) + u, v = [pb[i] - pa[i] for i in range(3)], [pc[i] - pa[i] for i in range(3)] + n = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) + length = sum(x * x for x in n) ** 0.5 + out.append(tuple(round(x / length) for x in n)) + return out + + def test_an_emitter_keeps_only_the_side_that_faces_its_exhaust(self): + # The thin box the hull source draws is closed; its exhaust leaves the way the anchor faces (yaw 180 aft, +Y; yaw 90 + # port, +X; yaw 0 the nose, -Y), and only the triangles facing that way are the emitter. + for yaw, thin, facing in ((180, (5, 5.1, "y"), (0, 1, 0)), (0, (5, 5.1, "y"), (0, -1, 0)), (90, (5, 5.1, "x"), (1, 0, 0))): + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""]) + + echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, -3, 3], 0, "Gun.A"]) + + echo("anchor", ["Th.A", "thruster-emitter", [1, 5, 1], yaw, ""])) + fixture.parts["emit:Th.A"] = (box(5, 5.1, 1, 2, 0.5, 1.5) if thin[2] == "x" else box(0.5, 1.5, 5, 5.1, 0.5, 1.5), "") + mesh = fixture.build().anchor_meshes["Th.A"] + self.assertEqual(len(mesh.triangles), 2, yaw) + self.assertEqual(set(self._normals(mesh)), {facing}, yaw) + + def test_an_emitter_turned_off_a_quarter_turn_is_refused(self): + # The gate knows four directions (a hardpoint Rotation); an emitter yawed 45 degrees has none, so it is not rounded. + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""]) + + echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, -3, 3], 0, "Gun.A"]) + + echo("anchor", ["Th.A", "thruster-emitter", [1, 5, 1], 45, ""])) + with self.assertRaises(hs.HullSourceError): + fixture.build() + + def test_an_emitter_with_no_side_facing_its_exhaust_is_refused(self): + # A single quad that faces the push, not the exhaust, has nothing left once the wrong side is dropped. + fixture = Fixture() + quad_toward_push = "OFF\n4 1 0\n0.5 5 0.5\n1.5 5 0.5\n1.5 5 1.5\n0.5 5 1.5\n4 0 1 2 3" # normal -Y, anchor exhaust +Y + fixture.parts["emit:Th.A"] = (quad_toward_push, "") + self.assertEqual(fixture.failed(), ["every emitter and radiator anchor has a mesh"]) + def test_the_collider_zone_is_the_languages_body(self): self.assertEqual(Fixture().build().body_zone, "primary")