text stringlengths 7 35.3M | id stringlengths 11 185 | metadata dict | __index_level_0__ int64 0 2.14k |
|---|---|---|---|
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &253232877
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 253232878}
- component: {fileID: 253232880}
- component: {fileID: 253232879}
m_Layer: 0
m_Name: WallSideB
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &253232878
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 253232877}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 775, y: 175, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 12
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &253232880
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 253232877}
m_Mesh: {fileID: 4300016, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &253232879
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 253232877}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 66163cf35956a4be08e801b750c26f33, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &444114134
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 444114135}
- component: {fileID: 444114137}
- component: {fileID: 444114136}
m_Layer: 0
m_Name: CenterPitch
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &444114135
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 444114134}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -0.000061035156, y: 1, z: 0.000061035156}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &444114137
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 444114134}
m_Mesh: {fileID: 4300022, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &444114136
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 444114134}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: ff03c5911bd5dfa49a040cf45420a0e4, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &473053727
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 473053728}
m_Layer: 0
m_Name: SideB
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &473053728
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 473053727}
m_LocalRotation: {x: -0, y: -1, z: -0, w: 0.0000021010635}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 1227615309}
- {fileID: 1155121818}
- {fileID: 2049130509}
m_Father: {fileID: 1838648424}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: -180.00002, z: 0}
--- !u!1 &474940249
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 474940250}
- component: {fileID: 474940251}
m_Layer: 0
m_Name: Roof
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &474940250
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 474940249}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 425, z: 0}
m_LocalScale: {x: 100, y: 100, z: 100}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 15
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!65 &474940251
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 474940249}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 30, y: 0.1, z: 16}
m_Center: {x: 0, y: 0, z: 0}
--- !u!1 &615018290
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 615018291}
- component: {fileID: 615018297}
- component: {fileID: 615018296}
- component: {fileID: 615018295}
- component: {fileID: 615018294}
- component: {fileID: 615018293}
- component: {fileID: 615018292}
m_Layer: 0
m_Name: GoalNetBlue
m_TagString: blueGoal
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &615018291
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615018290}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -1650, y: 192.0061, z: -0.000015258789}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 7
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &615018297
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615018290}
m_Mesh: {fileID: 4300006, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &615018296
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615018290}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 69fefdd39d2b34b169e921910bed9c0d, type: 2}
- {fileID: 2100000, guid: daad6e777b6e99a46bbcded7cf6816ee, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!65 &615018295
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615018290}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 200.00024, y: 384.01212, z: 10}
m_Center: {x: 0.00023841858, y: 0, z: -420}
--- !u!65 &615018294
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615018290}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 200.00024, y: 384.01212, z: 10}
m_Center: {x: 0.00023841858, y: 0, z: 420}
--- !u!65 &615018293
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615018290}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 12.737513, y: 384.01212, z: 830}
m_Center: {x: -93.6311, y: 0, z: 0}
--- !u!65 &615018292
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 615018290}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 186.31436, y: 7.4030876, z: 830}
m_Center: {x: 6.8431735, y: 188.3043, z: 0}
--- !u!1 &654598887
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 654598888}
- component: {fileID: 654598890}
- component: {fileID: 654598889}
m_Layer: 0
m_Name: GlassSideB
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &654598888
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 654598887}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -0, y: 272.05, z: -607.00037}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &654598890
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 654598887}
m_Mesh: {fileID: 4300004, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &654598889
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 654598887}
m_Enabled: 1
m_CastShadows: 0
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: ec99cc74da6543b459e71a51834b037d, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &738577471
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 738577472}
- component: {fileID: 738577478}
- component: {fileID: 738577477}
- component: {fileID: 738577476}
- component: {fileID: 738577475}
- component: {fileID: 738577474}
- component: {fileID: 738577473}
m_Layer: 0
m_Name: GoalNetPurple
m_TagString: purpleGoal
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &738577472
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 738577471}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 1647, y: 192.0061, z: -0.000015258789}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 9
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &738577478
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 738577471}
m_Mesh: {fileID: 4300010, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &738577477
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 738577471}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 69fefdd39d2b34b169e921910bed9c0d, type: 2}
- {fileID: 2100000, guid: daad6e777b6e99a46bbcded7cf6816ee, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!65 &738577476
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 738577471}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 200.00047, y: 384.01212, z: 10}
m_Center: {x: -0.00023841858, y: 0, z: -420}
--- !u!65 &738577475
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 738577471}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 200.00047, y: 384.01212, z: 10}
m_Center: {x: -0.00023841858, y: 0, z: 420}
--- !u!65 &738577474
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 738577471}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 10, y: 384.01212, z: 830}
m_Center: {x: 93.6, y: 0, z: 0}
--- !u!65 &738577473
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 738577471}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 200.00047, y: 13.09334, z: 830}
m_Center: {x: -0.00023841858, y: 185.45909, z: 0}
--- !u!1 &922552524
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 922552525}
- component: {fileID: 922552527}
- component: {fileID: 922552526}
m_Layer: 0
m_Name: GoalNetPurpleOuter
m_TagString: purpleGoal
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &922552525
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 922552524}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 1640.98, y: 186.06555, z: -0.50001526}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 10
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &922552527
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 922552524}
m_Mesh: {fileID: 4300012, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &922552526
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 922552524}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: daad6e777b6e99a46bbcded7cf6816ee, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &940293614
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 940293615}
- component: {fileID: 940293616}
m_Layer: 0
m_Name: Side
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &940293615
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 940293614}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 176, z: 775}
m_LocalScale: {x: 100, y: 100, z: 100}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1280034523}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!65 &940293616
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 940293614}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 31, y: 4.5311604, z: 0.4607078}
m_Center: {x: 0, y: 0, z: -0.011573717}
--- !u!1 &1155121817
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1155121818}
- component: {fileID: 1155121819}
m_Layer: 0
m_Name: Wall Angle
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1155121818
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1155121817}
m_LocalRotation: {x: -0, y: 0.49999917, z: -0, w: 0.86602587}
m_LocalPosition: {x: 1446, y: 176, z: 641}
m_LocalScale: {x: 100, y: 100, z: 100}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 473053728}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 60.000004, z: 0}
--- !u!65 &1155121819
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1155121817}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 4.8, y: 4.5311604, z: 0.4607078}
m_Center: {x: 0, y: 0, z: 0}
--- !u!1 &1227615308
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1227615309}
- component: {fileID: 1227615310}
m_Layer: 0
m_Name: Side
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1227615309
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1227615308}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 176, z: 775}
m_LocalScale: {x: 100, y: 100, z: 100}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 473053728}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!65 &1227615310
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1227615308}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 31, y: 4.5311604, z: 0.4607078}
m_Center: {x: 0, y: 0, z: -0.011573717}
--- !u!1 &1280034522
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1280034523}
m_Layer: 0
m_Name: SideA
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1280034523
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1280034522}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 940293615}
- {fileID: 1348508957}
- {fileID: 1681476315}
m_Father: {fileID: 1838648424}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1348508956
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1348508957}
- component: {fileID: 1348508958}
m_Layer: 0
m_Name: Wall Angle
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1348508957
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1348508956}
m_LocalRotation: {x: -0, y: 0.49999917, z: -0, w: 0.86602587}
m_LocalPosition: {x: 1446, y: 176, z: 641}
m_LocalScale: {x: 100, y: 100, z: 100}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1280034523}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 60.000004, z: 0}
--- !u!65 &1348508958
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1348508956}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 4.8, y: 4.5311604, z: 0.4607078}
m_Center: {x: 0, y: 0, z: 0}
--- !u!1 &1358559436
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1358559437}
- component: {fileID: 1358559440}
- component: {fileID: 1358559439}
- component: {fileID: 1358559438}
m_Layer: 0
m_Name: GoalAreaPurple
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1358559437
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1358559436}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 1400, y: 0, z: 0}
m_LocalScale: {x: 300, y: 10, z: 1200}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 13
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &1358559440
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1358559436}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!65 &1358559439
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1358559436}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 0
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!23 &1358559438
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1358559436}
m_Enabled: 0
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1411349252
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1411349253}
- component: {fileID: 1411349256}
- component: {fileID: 1411349255}
- component: {fileID: 1411349254}
m_Layer: 0
m_Name: GoalPurple
m_TagString: purpleGoal
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &1411349253
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1411349252}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 1650, y: -25, z: -0.000015258789}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 6
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &1411349256
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1411349252}
m_Mesh: {fileID: 4300020, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &1411349255
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1411349252}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: b0da1813c36914e678ba57f2790424e1, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!65 &1411349254
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1411349252}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 200, y: 50, z: 850.0001}
m_Center: {x: 0, y: 0, z: 0}
--- !u!1 &1590368732
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1590368733}
- component: {fileID: 1590368737}
- component: {fileID: 1590368736}
- component: {fileID: 1590368735}
- component: {fileID: 1590368734}
m_Layer: 0
m_Name: Field
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &1590368733
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1590368732}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 0.01, y: 0.01, z: 0.01}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 5380420931288637108}
- {fileID: 1838648424}
- {fileID: 444114135}
- {fileID: 1905370727}
- {fileID: 654598888}
- {fileID: 1685058923}
- {fileID: 1411349253}
- {fileID: 615018291}
- {fileID: 1641907511}
- {fileID: 738577472}
- {fileID: 922552525}
- {fileID: 1728133458}
- {fileID: 253232878}
- {fileID: 1358559437}
- {fileID: 1790209494}
- {fileID: 474940250}
m_Father: {fileID: 4558743310993102}
m_RootOrder: 5
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &1590368737
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1590368732}
m_Mesh: {fileID: 4300000, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &1590368736
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1590368732}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: ff03c5911bd5dfa49a040cf45420a0e4, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!65 &1590368735
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1590368732}
m_Material: {fileID: 13400000, guid: 1d7384a79905e47399076985ef6317bb, type: 2}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 3100, y: 100, z: 1500.0001}
m_Center: {x: 0, y: -50, z: 0}
--- !u!215 &1590368734
ReflectionProbe:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1590368732}
m_Enabled: 1
serializedVersion: 2
m_Type: 0
m_Mode: 0
m_RefreshMode: 0
m_TimeSlicingMode: 0
m_Resolution: 512
m_UpdateFrequency: 0
m_BoxSize: {x: 34, y: 15, z: 18}
m_BoxOffset: {x: 0, y: 0, z: 0}
m_NearClip: 0.3
m_FarClip: 1000
m_ShadowDistance: 100
m_ClearFlags: 1
m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_IntensityMultiplier: 1
m_BlendDistance: 1
m_HDR: 1
m_BoxProjection: 0
m_RenderDynamicObjects: 0
m_UseOcclusionCulling: 1
m_Importance: 1
m_CustomBakedTexture: {fileID: 0}
--- !u!1 &1641907510
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1641907511}
- component: {fileID: 1641907513}
- component: {fileID: 1641907512}
m_Layer: 0
m_Name: GoalNetBlueOuter
m_TagString: blueGoal
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &1641907511
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1641907510}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -1643.9795, y: 186.06555, z: 0.49998474}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 8
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &1641907513
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1641907510}
m_Mesh: {fileID: 4300008, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &1641907512
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1641907510}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: daad6e777b6e99a46bbcded7cf6816ee, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1681476314
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1681476315}
- component: {fileID: 1681476316}
m_Layer: 0
m_Name: Wall Angle (1)
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1681476315
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1681476314}
m_LocalRotation: {x: 0, y: -0.5, z: 0, w: 0.8660254}
m_LocalPosition: {x: -1446, y: 176, z: 641}
m_LocalScale: {x: 100, y: 100, z: 100}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1280034523}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: -60, z: 0}
--- !u!65 &1681476316
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1681476314}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 4.8, y: 4.5311604, z: 0.4607078}
m_Center: {x: 0, y: 0, z: 0}
--- !u!1 &1685058922
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1685058923}
- component: {fileID: 1685058926}
- component: {fileID: 1685058925}
- component: {fileID: 1685058924}
m_Layer: 0
m_Name: GoalBlue
m_TagString: blueGoal
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &1685058923
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1685058922}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -1650, y: -25, z: -0.000015258789}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 5
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &1685058926
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1685058922}
m_Mesh: {fileID: 4300018, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &1685058925
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1685058922}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: c9fa44c2c3f8ce74ca39a3355ea42631, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!65 &1685058924
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1685058922}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 200, y: 50, z: 850.0001}
m_Center: {x: 0, y: 0, z: 0}
--- !u!1 &1728133457
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1728133458}
- component: {fileID: 1728133460}
- component: {fileID: 1728133459}
m_Layer: 0
m_Name: WallSideA
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &1728133458
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1728133457}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -774.99994, y: 175, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 11
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &1728133460
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1728133457}
m_Mesh: {fileID: 4300014, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &1728133459
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1728133457}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 66163cf35956a4be08e801b750c26f33, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1790209493
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1790209494}
- component: {fileID: 1790209497}
- component: {fileID: 1790209496}
- component: {fileID: 1790209495}
m_Layer: 0
m_Name: GoalAreaBlue
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1790209494
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1790209493}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -1400, y: 0, z: 0}
m_LocalScale: {x: 300, y: 10, z: 1200}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 14
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &1790209497
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1790209493}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!65 &1790209496
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1790209493}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 0
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!23 &1790209495
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1790209493}
m_Enabled: 0
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1838648423
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1838648424}
m_Layer: 0
m_Name: WallColliders
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1838648424
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1838648423}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 1280034523}
- {fileID: 473053728}
m_Father: {fileID: 1590368733}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1905370726
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1905370727}
- component: {fileID: 1905370729}
- component: {fileID: 1905370728}
m_Layer: 0
m_Name: GlassSideA
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 65
m_IsActive: 1
--- !u!4 &1905370727
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1905370726}
m_LocalRotation: {x: 0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -0, y: 272.05, z: 607.00037}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &1905370729
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1905370726}
m_Mesh: {fileID: 4300002, guid: 02257fc10ef7ad149b5daa123a7df881, type: 3}
--- !u!23 &1905370728
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1905370726}
m_Enabled: 1
m_CastShadows: 0
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: ec99cc74da6543b459e71a51834b037d, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &2049130508
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 2049130509}
- component: {fileID: 2049130510}
m_Layer: 0
m_Name: Wall Angle (1)
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &2049130509
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2049130508}
m_LocalRotation: {x: 0, y: -0.5, z: 0, w: 0.8660254}
m_LocalPosition: {x: -1446, y: 176, z: 641}
m_LocalScale: {x: 100, y: 100, z: 100}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 473053728}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: -60, z: 0}
--- !u!65 &2049130510
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2049130508}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 4.8, y: 4.5311604, z: 0.4607078}
m_Center: {x: 0, y: 0, z: 0}
--- !u!1 &1032056389038868
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4859417942674614}
- component: {fileID: 20622362340627540}
m_Layer: 0
m_Name: AgentCamera
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 0
--- !u!4 &4859417942674614
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1032056389038868}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0.15}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4991109413118678}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!20 &20622362340627540
Camera:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1032056389038868}
m_Enabled: 1
serializedVersion: 2
m_ClearFlags: 2
m_BackGroundColor: {r: 0.46666667, g: 0.5647059, b: 0.60784316, a: 1}
m_projectionMatrixMode: 1
m_GateFitMode: 2
m_FOVAxisMode: 0
m_SensorSize: {x: 36, y: 24}
m_LensShift: {x: 0, y: 0}
m_FocalLength: 50
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.3
far clip plane: 1000
field of view: 60
orthographic: 0
orthographic size: 5
m_Depth: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294950911
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 1
m_AllowMSAA: 1
m_AllowDynamicResolution: 0
m_ForceIntoRT: 0
m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!1 &1083582452036196
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4991109413118678}
- component: {fileID: 33298283473714412}
- component: {fileID: 23549972778301016}
m_Layer: 0
m_Name: AgentCube_Blue
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4991109413118678
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1083582452036196}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 4859417942674614}
- {fileID: 4039980604236862}
- {fileID: 4683691907469924}
- {fileID: 4222051823283070}
- {fileID: 4671048899227928}
m_Father: {fileID: 4444285537983296}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &33298283473714412
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1083582452036196}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23549972778301016
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1083582452036196}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: c9fa44c2c3f8ce74ca39a3355ea42631, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1095606497496374
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4277721046484044}
- component: {fileID: 54348679551516588}
- component: {fileID: 135232974003521068}
- component: {fileID: 114734187185382186}
- component: {fileID: 114492261207303438}
- component: {fileID: 114320493772006642}
- component: {fileID: 9152743230243588598}
- component: {fileID: 9171805407464329310}
m_Layer: 0
m_Name: PurpleGoalie
m_TagString: purpleAgent
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4277721046484044
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1095606497496374}
m_LocalRotation: {x: 0, y: -0.7071068, z: 0, w: 0.7071068}
m_LocalPosition: {x: 4, y: 0.5, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 4540034559941056}
m_Father: {fileID: 4558743310993102}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: -90, z: 0}
--- !u!54 &54348679551516588
Rigidbody:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1095606497496374}
serializedVersion: 2
m_Mass: 50
m_Drag: 3
m_AngularDrag: 0.05
m_UseGravity: 1
m_IsKinematic: 0
m_Interpolate: 0
m_Constraints: 116
m_CollisionDetection: 1
--- !u!135 &135232974003521068
SphereCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1095606497496374}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Radius: 0.5
m_Center: {x: 0, y: 0, z: 0}
--- !u!114 &114734187185382186
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1095606497496374}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5d1c4e0b1822b495aa52bc52839ecb30, type: 3}
m_Name:
m_EditorClassIdentifier:
m_BrainParameters:
VectorObservationSize: 0
NumStackedVectorObservations: 1
m_ActionSpec:
m_NumContinuousActions: 0
BranchSizes: 030000000300000003000000
VectorActionSize: 030000000300000003000000
VectorActionDescriptions: []
VectorActionSpaceType: 0
hasUpgradedBrainParametersWithActionSpec: 1
m_Model: {fileID: 5022602860645237092, guid: b10cdd09f88e542e28a506a90bbf1cf1, type: 3}
m_InferenceDevice: 2
m_BehaviorType: 0
m_BehaviorName: Goalie
TeamId: 1
m_UseChildSensors: 1
m_UseChildActuators: 1
m_DeterministicInference: 0
m_ObservableAttributeHandling: 0
--- !u!114 &114492261207303438
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1095606497496374}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 2a2688ef4a36349f9aa010020c32d198, type: 3}
m_Name:
m_EditorClassIdentifier:
agentParameters:
maxStep: 0
hasUpgradedFromAgentParameters: 1
MaxStep: 0
team: 0
position: 1
agentRb: {fileID: 0}
initialPos: {x: 0, y: 0, z: 0}
rotSign: 0
--- !u!114 &114320493772006642
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1095606497496374}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 6bb6b867a41448888c1cd4f99643ad71, type: 3}
m_Name:
m_EditorClassIdentifier:
m_SensorName: PurpleGoalieRayPerceptionSensor
m_DetectableTags:
- ball
- purpleGoal
- wall
- blueAgent
m_RaysPerDirection: 20
m_MaxRayDegrees: 180
m_SphereCastRadius: 0.5
m_RayLength: 20
m_RayLayerMask:
serializedVersion: 2
m_Bits: 4294967291
m_ObservationStacks: 3
m_AlternatingRayOrder: 1
rayHitColor: {r: 1, g: 0, b: 0, a: 1}
rayMissColor: {r: 1, g: 1, b: 1, a: 1}
m_StartVerticalOffset: 0.5
m_EndVerticalOffset: 0.5
--- !u!114 &9152743230243588598
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1095606497496374}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3a5c9d521e5ef4759a8246a07d52221e, type: 3}
m_Name:
m_EditorClassIdentifier:
DecisionPeriod: 5
TakeActionsBetweenDecisions: 1
--- !u!114 &9171805407464329310
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1095606497496374}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3a6da8f78a394c6ab027688eab81e04d, type: 3}
m_Name:
m_EditorClassIdentifier:
debugCommandLineOverride:
--- !u!1 &1101518129530804
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4904293978873118}
- component: {fileID: 20243662707170704}
m_Layer: 0
m_Name: AgentCamera
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 0
--- !u!4 &4904293978873118
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1101518129530804}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0.15}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4540034559941056}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!20 &20243662707170704
Camera:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1101518129530804}
m_Enabled: 1
serializedVersion: 2
m_ClearFlags: 2
m_BackGroundColor: {r: 0.46666667, g: 0.5647059, b: 0.60784316, a: 1}
m_projectionMatrixMode: 1
m_GateFitMode: 2
m_FOVAxisMode: 0
m_SensorSize: {x: 36, y: 24}
m_LensShift: {x: 0, y: 0}
m_FocalLength: 50
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.3
far clip plane: 1000
field of view: 60
orthographic: 0
orthographic size: 5
m_Depth: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294950911
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 1
m_AllowMSAA: 1
m_AllowDynamicResolution: 0
m_ForceIntoRT: 0
m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!1 &1131626411948014
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4444285537983296}
- component: {fileID: 54609996481602788}
- component: {fileID: 135208952479003512}
- component: {fileID: 114387866097048300}
- component: {fileID: 114850431417842684}
- component: {fileID: 114516244030127556}
- component: {fileID: 404683423509059512}
- component: {fileID: 5776656799174978208}
m_Layer: 0
m_Name: BlueStriker
m_TagString: blueAgent
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4444285537983296
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1131626411948014}
m_LocalRotation: {x: 0, y: 0.7071068, z: 0, w: 0.7071068}
m_LocalPosition: {x: -3.19, y: 0.5, z: 1.2}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 4991109413118678}
- {fileID: 4942358209803819540}
m_Father: {fileID: 4558743310993102}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 90, z: 0}
--- !u!54 &54609996481602788
Rigidbody:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1131626411948014}
serializedVersion: 2
m_Mass: 50
m_Drag: 3
m_AngularDrag: 0.05
m_UseGravity: 1
m_IsKinematic: 0
m_Interpolate: 0
m_Constraints: 116
m_CollisionDetection: 1
--- !u!135 &135208952479003512
SphereCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1131626411948014}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Radius: 0.5
m_Center: {x: 0, y: 0, z: 0}
--- !u!114 &114387866097048300
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1131626411948014}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5d1c4e0b1822b495aa52bc52839ecb30, type: 3}
m_Name:
m_EditorClassIdentifier:
m_BrainParameters:
VectorObservationSize: 0
NumStackedVectorObservations: 1
m_ActionSpec:
m_NumContinuousActions: 0
BranchSizes: 030000000300000003000000
VectorActionSize: 030000000300000003000000
VectorActionDescriptions: []
VectorActionSpaceType: 0
hasUpgradedBrainParametersWithActionSpec: 1
m_Model: {fileID: 5022602860645237092, guid: a58ce15fa237b41b9b12dbdcb2d04dcb, type: 3}
m_InferenceDevice: 2
m_BehaviorType: 0
m_BehaviorName: Striker
TeamId: 0
m_UseChildSensors: 1
m_UseChildActuators: 1
m_DeterministicInference: 0
m_ObservableAttributeHandling: 0
--- !u!114 &114850431417842684
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1131626411948014}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 2a2688ef4a36349f9aa010020c32d198, type: 3}
m_Name:
m_EditorClassIdentifier:
agentParameters:
maxStep: 0
hasUpgradedFromAgentParameters: 1
MaxStep: 0
team: 1
position: 0
agentRb: {fileID: 0}
initialPos: {x: 0, y: 0, z: 0}
rotSign: 0
--- !u!114 &114516244030127556
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1131626411948014}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 6bb6b867a41448888c1cd4f99643ad71, type: 3}
m_Name:
m_EditorClassIdentifier:
m_SensorName: BlueRayPerceptionSensor
m_DetectableTags:
- ball
- purpleGoal
- wall
- blueAgent
- purpleAgent
m_RaysPerDirection: 5
m_MaxRayDegrees: 60
m_SphereCastRadius: 0.5
m_RayLength: 20
m_RayLayerMask:
serializedVersion: 2
m_Bits: 4294967291
m_ObservationStacks: 3
m_AlternatingRayOrder: 1
rayHitColor: {r: 1, g: 0, b: 0, a: 1}
rayMissColor: {r: 1, g: 1, b: 1, a: 1}
m_StartVerticalOffset: 0.5
m_EndVerticalOffset: 0.5
--- !u!114 &404683423509059512
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1131626411948014}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3a5c9d521e5ef4759a8246a07d52221e, type: 3}
m_Name:
m_EditorClassIdentifier:
DecisionPeriod: 5
TakeActionsBetweenDecisions: 1
--- !u!114 &5776656799174978208
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1131626411948014}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3a6da8f78a394c6ab027688eab81e04d, type: 3}
m_Name:
m_EditorClassIdentifier:
debugCommandLineOverride:
--- !u!1 &1141134673700168
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4558743310993102}
- component: {fileID: 5003424191498964318}
m_Layer: 0
m_Name: StrikersVsGoalieField
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4558743310993102
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1141134673700168}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 4540201673231058}
- {fileID: 4867652605555692}
- {fileID: 4444285537983296}
- {fileID: 4277721046484044}
- {fileID: 7843730402782877929}
- {fileID: 1590368733}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &5003424191498964318
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1141134673700168}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 4e397bc3ae78c466a8d44400f5b68e38, type: 3}
m_Name:
m_EditorClassIdentifier:
MaxEnvironmentSteps: 5000
ball: {fileID: 1682753582128710}
ballRb: {fileID: 0}
AgentsList:
- Agent: {fileID: 114850431417842684}
StartingPos: {x: 0, y: 0, z: 0}
StartingRot: {x: 0, y: 0, z: 0, w: 0}
Rb: {fileID: 0}
- Agent: {fileID: 5379409612883756837}
StartingPos: {x: 0, y: 0, z: 0}
StartingRot: {x: 0, y: 0, z: 0, w: 0}
Rb: {fileID: 0}
- Agent: {fileID: 114492261207303438}
StartingPos: {x: 0, y: 0, z: 0}
StartingRot: {x: 0, y: 0, z: 0, w: 0}
Rb: {fileID: 0}
--- !u!1 &1366507812774098
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4266272446237730}
- component: {fileID: 33201643863918062}
- component: {fileID: 23624366765569318}
m_Layer: 0
m_Name: Headband
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4266272446237730
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1366507812774098}
m_LocalRotation: {x: -0, y: -0, z: -0.036135223, w: 0.999347}
m_LocalPosition: {x: 0, y: 0.341, z: 0}
m_LocalScale: {x: 1.0441425, y: 0.19278127, z: 1.0441422}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4540034559941056}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: 0, z: -4.142}
--- !u!33 &33201643863918062
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1366507812774098}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23624366765569318
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1366507812774098}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 04be259c590de46f69db4cbd1da877d5, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1383518430785328
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4867652605555692}
m_Layer: 0
m_Name: Players
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4867652605555692
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1383518430785328}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4558743310993102}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1557392375314408
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4039980604236862}
- component: {fileID: 33462524524189736}
- component: {fileID: 23293559766629696}
m_Layer: 0
m_Name: eye
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4039980604236862
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1557392375314408}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: 0.29999995, y: 0.07399994, z: 0.50040054}
m_LocalScale: {x: 0.29457998, y: 0.29457998, z: 0.29457998}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4991109413118678}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!33 &33462524524189736
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1557392375314408}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23293559766629696
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1557392375314408}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1623838202568698
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4222051823283070}
- component: {fileID: 33079734303900652}
- component: {fileID: 23044742990593156}
m_Layer: 0
m_Name: mouth
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4222051823283070
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1623838202568698}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: 0, y: -0.18299997, z: 0.50040054}
m_LocalScale: {x: 0.27602, y: 0.042489994, z: 0.13891}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4991109413118678}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!33 &33079734303900652
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1623838202568698}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23044742990593156
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1623838202568698}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1682753582128710
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4540201673231058}
- component: {fileID: 33063578823143084}
- component: {fileID: 23962084906832836}
- component: {fileID: 135993924486820224}
- component: {fileID: 114273807544954564}
- component: {fileID: 54100138833592438}
m_Layer: 0
m_Name: Soccer Ball
m_TagString: ball
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4540201673231058
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1682753582128710}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0.5, z: 0}
m_LocalScale: {x: 0.015, y: 0.015, z: 0.015}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4558743310993102}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &33063578823143084
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1682753582128710}
m_Mesh: {fileID: 4300000, guid: 7cb7c129b7ec1fb4293dd40773bdce33, type: 3}
--- !u!23 &23962084906832836
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1682753582128710}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 1644c0cb0c67e314194579be857f87da, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!135 &135993924486820224
SphereCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1682753582128710}
m_Material: {fileID: 13400000, guid: 54ed79b9254e1456587c8cf3849f6dc1, type: 2}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Radius: 41.61146
m_Center: {x: 0, y: 0, z: 0}
--- !u!114 &114273807544954564
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1682753582128710}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 93558b952b37a4b0ebaca3ca6711bcc4, type: 3}
m_Name:
m_EditorClassIdentifier:
area: {fileID: 1141134673700168}
envController: {fileID: 0}
purpleGoalTag: purpleGoal
blueGoalTag: blueGoal
--- !u!54 &54100138833592438
Rigidbody:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1682753582128710}
serializedVersion: 2
m_Mass: 3
m_Drag: 1
m_AngularDrag: 1
m_UseGravity: 1
m_IsKinematic: 0
m_Interpolate: 0
m_Constraints: 4
m_CollisionDetection: 1
--- !u!1 &1817598442362300
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4671048899227928}
- component: {fileID: 33400024424252764}
- component: {fileID: 23876007776278096}
m_Layer: 0
m_Name: Headband
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4671048899227928
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1817598442362300}
m_LocalRotation: {x: -0, y: -0, z: 0.016506119, w: 0.9998638}
m_LocalPosition: {x: 0, y: 0.341, z: 0}
m_LocalScale: {x: 1.0441425, y: 0.19278127, z: 1.0441422}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4991109413118678}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: -179.99998, z: 1.8920001}
--- !u!33 &33400024424252764
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1817598442362300}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23876007776278096
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1817598442362300}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 04be259c590de46f69db4cbd1da877d5, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1836679221278734
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4540034559941056}
- component: {fileID: 33174308205182346}
- component: {fileID: 23344424056921900}
m_Layer: 0
m_Name: AgentCube_Purple
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4540034559941056
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1836679221278734}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 4904293978873118}
- {fileID: 4058002210749422}
- {fileID: 4857307866975302}
- {fileID: 4874120150569100}
- {fileID: 4266272446237730}
m_Father: {fileID: 4277721046484044}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &33174308205182346
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1836679221278734}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23344424056921900
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1836679221278734}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: b0da1813c36914e678ba57f2790424e1, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1841872787705274
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4058002210749422}
- component: {fileID: 33223661134341430}
- component: {fileID: 23837187974122722}
m_Layer: 0
m_Name: eye
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4058002210749422
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1841872787705274}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: 0.29999995, y: 0.07399994, z: 0.50040054}
m_LocalScale: {x: 0.29457998, y: 0.29457998, z: 0.29457998}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4540034559941056}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!33 &33223661134341430
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1841872787705274}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23837187974122722
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1841872787705274}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1931023723143276
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4874120150569100}
- component: {fileID: 33486671041495046}
- component: {fileID: 23179297000275962}
m_Layer: 0
m_Name: mouth
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4874120150569100
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1931023723143276}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: 0, y: -0.18299997, z: 0.50040054}
m_LocalScale: {x: 0.27602, y: 0.042489994, z: 0.13891}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4540034559941056}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!33 &33486671041495046
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1931023723143276}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23179297000275962
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1931023723143276}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1933336248964008
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4857307866975302}
- component: {fileID: 33689349573892708}
- component: {fileID: 23033472357858008}
m_Layer: 0
m_Name: eye
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4857307866975302
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1933336248964008}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: -0.29999995, y: 0.07399994, z: 0.50040054}
m_LocalScale: {x: 0.29457998, y: 0.29457998, z: 0.29457998}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4540034559941056}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!33 &33689349573892708
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1933336248964008}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23033472357858008
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1933336248964008}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1988976889579366
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4683691907469924}
- component: {fileID: 33422890814875164}
- component: {fileID: 23996567852471186}
m_Layer: 0
m_Name: eye
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4683691907469924
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1988976889579366}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: -0.29999995, y: 0.07399994, z: 0.50040054}
m_LocalScale: {x: 0.29457998, y: 0.29457998, z: 0.29457998}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4991109413118678}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!33 &33422890814875164
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1988976889579366}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &23996567852471186
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1988976889579366}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &1897170901855235213
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4942358209803819540}
- component: {fileID: 796105769966339250}
m_Layer: 0
m_Name: BlueReverseRays
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4942358209803819540
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1897170901855235213}
m_LocalRotation: {x: 0, y: 1, z: 0, w: 0}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 4444285537983296}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!114 &796105769966339250
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1897170901855235213}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 6bb6b867a41448888c1cd4f99643ad71, type: 3}
m_Name:
m_EditorClassIdentifier:
m_SensorName: BlueRayPerceptionSensorReverse
m_DetectableTags:
- ball
- purpleGoal
- wall
- blueAgent
- purpleAgent
m_RaysPerDirection: 1
m_MaxRayDegrees: 45
m_SphereCastRadius: 0.5
m_RayLength: 20
m_RayLayerMask:
serializedVersion: 2
m_Bits: 4294967291
m_ObservationStacks: 3
m_AlternatingRayOrder: 1
rayHitColor: {r: 1, g: 0, b: 0, a: 1}
rayMissColor: {r: 1, g: 1, b: 1, a: 1}
m_StartVerticalOffset: 0.5
m_EndVerticalOffset: 0.5
--- !u!1 &2016057044266316337
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 3343797950804926185}
- component: {fileID: 7679702203014927471}
m_Layer: 0
m_Name: AgentCamera
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 0
--- !u!4 &3343797950804926185
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2016057044266316337}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0.15}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 3493354028456101517}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!20 &7679702203014927471
Camera:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2016057044266316337}
m_Enabled: 1
serializedVersion: 2
m_ClearFlags: 2
m_BackGroundColor: {r: 0.46666667, g: 0.5647059, b: 0.60784316, a: 1}
m_projectionMatrixMode: 1
m_GateFitMode: 2
m_FOVAxisMode: 0
m_SensorSize: {x: 36, y: 24}
m_LensShift: {x: 0, y: 0}
m_FocalLength: 50
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.3
far clip plane: 1000
field of view: 60
orthographic: 0
orthographic size: 5
m_Depth: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294950911
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 1
m_AllowMSAA: 1
m_AllowDynamicResolution: 0
m_ForceIntoRT: 0
m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!1 &2329918556726399591
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 3597096365793476057}
- component: {fileID: 3272648336714276914}
- component: {fileID: 6521557456685239880}
m_Layer: 0
m_Name: eye
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &3597096365793476057
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2329918556726399591}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: -0.29999995, y: 0.07399994, z: 0.50040054}
m_LocalScale: {x: 0.29457998, y: 0.29457998, z: 0.29457998}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 3493354028456101517}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!33 &3272648336714276914
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2329918556726399591}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &6521557456685239880
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2329918556726399591}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &2909838886639257826
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 3567543467983998314}
- component: {fileID: 5705175531533507764}
- component: {fileID: 630866108016762318}
m_Layer: 0
m_Name: Headband
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &3567543467983998314
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2909838886639257826}
m_LocalRotation: {x: -0, y: -0, z: 0.016506119, w: 0.9998638}
m_LocalPosition: {x: 0, y: 0.341, z: 0}
m_LocalScale: {x: 1.0441425, y: 0.19278127, z: 1.0441422}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 3493354028456101517}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: -179.99998, z: 1.8920001}
--- !u!33 &5705175531533507764
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2909838886639257826}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &630866108016762318
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2909838886639257826}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 04be259c590de46f69db4cbd1da877d5, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &4407673136905670519
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 8224668928246715092}
- component: {fileID: 217286280874173272}
m_Layer: 0
m_Name: BlueReverseRays (1)
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &8224668928246715092
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4407673136905670519}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 7843730402782877929}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!114 &217286280874173272
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4407673136905670519}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 6bb6b867a41448888c1cd4f99643ad71, type: 3}
m_Name:
m_EditorClassIdentifier:
m_SensorName: BlueRayPerceptionSensorReverse
m_DetectableTags:
- ball
- purpleGoal
- wall
- blueAgent
- purpleAgent
m_RaysPerDirection: 1
m_MaxRayDegrees: 45
m_SphereCastRadius: 0.5
m_RayLength: 20
m_RayLayerMask:
serializedVersion: 2
m_Bits: 4294967291
m_ObservationStacks: 3
m_AlternatingRayOrder: 1
rayHitColor: {r: 1, g: 0, b: 0, a: 1}
rayMissColor: {r: 1, g: 1, b: 1, a: 1}
m_StartVerticalOffset: 0.5
m_EndVerticalOffset: 0.5
--- !u!1 &4599713170205044794
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 6439063416007821090}
- component: {fileID: 4119411769362767890}
- component: {fileID: 304632679239919484}
m_Layer: 0
m_Name: mouth
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &6439063416007821090
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4599713170205044794}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: 0, y: -0.18299997, z: 0.50040054}
m_LocalScale: {x: 0.27602, y: 0.042489994, z: 0.13891}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 3493354028456101517}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!33 &4119411769362767890
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4599713170205044794}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &304632679239919484
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4599713170205044794}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &6007240757639156798
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 3493354028456101517}
- component: {fileID: 6322537730689507644}
- component: {fileID: 4272497041746572966}
m_Layer: 0
m_Name: AgentCube_Blue
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &3493354028456101517
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6007240757639156798}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 3343797950804926185}
- {fileID: 8909689398596890234}
- {fileID: 3597096365793476057}
- {fileID: 6439063416007821090}
- {fileID: 3567543467983998314}
m_Father: {fileID: 7843730402782877929}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &6322537730689507644
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6007240757639156798}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &4272497041746572966
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6007240757639156798}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: c9fa44c2c3f8ce74ca39a3355ea42631, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &7925489420550093475
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 8909689398596890234}
- component: {fileID: 7272623948078999278}
- component: {fileID: 3843749850161548145}
m_Layer: 0
m_Name: eye
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &8909689398596890234
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7925489420550093475}
m_LocalRotation: {x: -0, y: 1, z: -0, w: 0}
m_LocalPosition: {x: 0.29999995, y: 0.07399994, z: 0.50040054}
m_LocalScale: {x: 0.29457998, y: 0.29457998, z: 0.29457998}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 3493354028456101517}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!33 &7272623948078999278
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7925489420550093475}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &3843749850161548145
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7925489420550093475}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: f731be6866ce749fd8349e67ae81f76a, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &8360301818957399454
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 7843730402782877929}
- component: {fileID: 648637983722350212}
- component: {fileID: 559349321895083135}
- component: {fileID: 3316085536305919483}
- component: {fileID: 5379409612883756837}
- component: {fileID: 2562571719799803906}
- component: {fileID: 1018414316889932458}
- component: {fileID: 493348456414434994}
m_Layer: 0
m_Name: BlueStriker (1)
m_TagString: blueAgent
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &7843730402782877929
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8360301818957399454}
m_LocalRotation: {x: 0, y: 0.7071068, z: 0, w: 0.7071068}
m_LocalPosition: {x: -3.19, y: 0.5, z: -1.2}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 3493354028456101517}
- {fileID: 8224668928246715092}
m_Father: {fileID: 4558743310993102}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: 90, z: 0}
--- !u!54 &648637983722350212
Rigidbody:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8360301818957399454}
serializedVersion: 2
m_Mass: 50
m_Drag: 3
m_AngularDrag: 0.05
m_UseGravity: 1
m_IsKinematic: 0
m_Interpolate: 0
m_Constraints: 116
m_CollisionDetection: 1
--- !u!135 &559349321895083135
SphereCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8360301818957399454}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Radius: 0.5
m_Center: {x: 0, y: 0, z: 0}
--- !u!114 &3316085536305919483
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8360301818957399454}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5d1c4e0b1822b495aa52bc52839ecb30, type: 3}
m_Name:
m_EditorClassIdentifier:
m_BrainParameters:
VectorObservationSize: 0
NumStackedVectorObservations: 1
m_ActionSpec:
m_NumContinuousActions: 0
BranchSizes: 030000000300000003000000
VectorActionSize: 030000000300000003000000
VectorActionDescriptions: []
VectorActionSpaceType: 0
hasUpgradedBrainParametersWithActionSpec: 1
m_Model: {fileID: 5022602860645237092, guid: a58ce15fa237b41b9b12dbdcb2d04dcb, type: 3}
m_InferenceDevice: 2
m_BehaviorType: 0
m_BehaviorName: Striker
TeamId: 0
m_UseChildSensors: 1
m_UseChildActuators: 1
m_DeterministicInference: 0
m_ObservableAttributeHandling: 0
--- !u!114 &5379409612883756837
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8360301818957399454}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 2a2688ef4a36349f9aa010020c32d198, type: 3}
m_Name:
m_EditorClassIdentifier:
agentParameters:
maxStep: 0
hasUpgradedFromAgentParameters: 1
MaxStep: 0
team: 1
position: 0
agentRb: {fileID: 0}
initialPos: {x: 0, y: 0, z: 0}
rotSign: 0
--- !u!114 &2562571719799803906
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8360301818957399454}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 6bb6b867a41448888c1cd4f99643ad71, type: 3}
m_Name:
m_EditorClassIdentifier:
m_SensorName: BlueRayPerceptionSensor
m_DetectableTags:
- ball
- purpleGoal
- wall
- blueAgent
- purpleAgent
m_RaysPerDirection: 5
m_MaxRayDegrees: 60
m_SphereCastRadius: 0.5
m_RayLength: 20
m_RayLayerMask:
serializedVersion: 2
m_Bits: 4294967291
m_ObservationStacks: 3
m_AlternatingRayOrder: 1
rayHitColor: {r: 1, g: 0, b: 0, a: 1}
rayMissColor: {r: 1, g: 1, b: 1, a: 1}
m_StartVerticalOffset: 0.5
m_EndVerticalOffset: 0.5
--- !u!114 &1018414316889932458
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8360301818957399454}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3a5c9d521e5ef4759a8246a07d52221e, type: 3}
m_Name:
m_EditorClassIdentifier:
DecisionPeriod: 5
TakeActionsBetweenDecisions: 1
--- !u!114 &493348456414434994
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8360301818957399454}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3a6da8f78a394c6ab027688eab81e04d, type: 3}
m_Name:
m_EditorClassIdentifier:
debugCommandLineOverride:
--- !u!1 &9012161277676694912
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 5380420931288637108}
- component: {fileID: 9218808494928946219}
- component: {fileID: 751017937587398034}
- component: {fileID: 5544574640864840267}
m_Layer: 0
m_Name: BlueGoalBlocker
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &5380420931288637108
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 9012161277676694912}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -1551, y: 155, z: 0}
m_LocalScale: {x: 100, y: 395.9755, z: 791.466}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1590368733}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &9218808494928946219
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 9012161277676694912}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &751017937587398034
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 9012161277676694912}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 66163cf35956a4be08e801b750c26f33, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 1
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!65 &5544574640864840267
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 9012161277676694912}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
| ml-agents/Project/Assets/ML-Agents/Examples/Soccer/Prefabs/StrikersVsGoalieField.prefab/0 | {
"file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Soccer/Prefabs/StrikersVsGoalieField.prefab",
"repo_id": "ml-agents",
"token_count": 53803
} | 1,814 |
fileFormatVersion: 2
guid: f1322978b914041748ae9def364eeef1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/Project/Assets/ML-Agents/Examples/Soccer/TFModels.meta/0 | {
"file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Soccer/TFModels.meta",
"repo_id": "ml-agents",
"token_count": 67
} | 1,815 |
fileFormatVersion: 2
guid: f23c5f09c95ad48768a41974a2f1523c
timeCreated: 1506808980
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/Project/Assets/ML-Agents/Examples/Sorter/Scenes/Sorter.unity.meta/0 | {
"file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Sorter/Scenes/Sorter.unity.meta",
"repo_id": "ml-agents",
"token_count": 78
} | 1,816 |
fileFormatVersion: 2
guid: 618b2484c0fea4a9691069008604eea3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/Project/Assets/ML-Agents/Examples/Walker/Demos.meta/0 | {
"file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Walker/Demos.meta",
"repo_id": "ml-agents",
"token_count": 69
} | 1,817 |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!29 &1
OcclusionCullingSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_OcclusionBakeSettings:
smallestOccluder: 5
smallestHole: 0.25
backfaceThreshold: 100
m_SceneGUID: 00000000000000000000000000000000
m_OcclusionCullingData: {fileID: 0}
--- !u!104 &2
RenderSettings:
m_ObjectHideFlags: 0
serializedVersion: 9
m_Fog: 0
m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}
m_FogMode: 3
m_FogDensity: 0.01
m_LinearFogStart: 0
m_LinearFogEnd: 300
m_AmbientSkyColor: {r: 0.8, g: 0.8, b: 0.8, a: 1}
m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}
m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}
m_AmbientIntensity: 1
m_AmbientMode: 3
m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}
m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}
m_HaloStrength: 0.5
m_FlareStrength: 1
m_FlareFadeSpeed: 3
m_HaloTexture: {fileID: 0}
m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}
m_DefaultReflectionMode: 0
m_DefaultReflectionResolution: 128
m_ReflectionBounces: 1
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.44971168, g: 0.4997775, b: 0.57563686, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 12
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1
m_IndirectOutputScale: 1
m_AlbedoBoost: 1
m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 1
m_LightmapEditorSettings:
serializedVersion: 12
m_Resolution: 2
m_BakeResolution: 40
m_AtlasSize: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 1
m_CompAOExponentDirect: 0
m_ExtractAmbientOcclusion: 0
m_Padding: 2
m_LightmapParameters: {fileID: 0}
m_LightmapsBakeMode: 1
m_TextureCompression: 1
m_FinalGather: 0
m_FinalGatherFiltering: 1
m_FinalGatherRayCount: 256
m_ReflectionCompression: 2
m_MixedBakeMode: 2
m_BakeBackend: 1
m_PVRSampling: 1
m_PVRDirectSampleCount: 32
m_PVRSampleCount: 500
m_PVRBounces: 2
m_PVREnvironmentSampleCount: 500
m_PVREnvironmentReferencePointCount: 2048
m_PVRFilteringMode: 2
m_PVRDenoiserTypeDirect: 0
m_PVRDenoiserTypeIndirect: 0
m_PVRDenoiserTypeAO: 0
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVREnvironmentMIS: 0
m_PVRCulling: 1
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_ExportTrainingData: 0
m_TrainingDataDestination: TrainingData
m_LightProbeSampleCountMultiplier: 4
m_LightingDataAsset: {fileID: 112000002, guid: 79aaf90aa86a141da808b7768b9f1403,
type: 2}
m_LightingSettings: {fileID: 579492083}
--- !u!196 &4
NavMeshSettings:
serializedVersion: 2
m_ObjectHideFlags: 0
m_BuildSettings:
serializedVersion: 2
agentTypeID: 0
agentRadius: 0.5
agentHeight: 2
agentSlope: 45
agentClimb: 0.4
ledgeDropHeight: 0
maxJumpAcrossDistance: 0
minRegionArea: 2
manualCellSize: 0
cellSize: 0.16666667
manualTileSize: 0
tileSize: 256
accuratePlacement: 0
maxJobWorkers: 0
preserveTilesOutsideBounds: 0
debug:
m_Flags: 0
m_NavMeshData: {fileID: 0}
--- !u!1001 &193531851
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 1537121661968964, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_Name
value: Directional_Light
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_RootOrder
value: 1
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalRotation.w
value: 0.8681629
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalRotation.x
value: 0.31598538
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalRotation.y
value: -0.3596048
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalRotation.z
value: 0.13088542
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 40
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: -45
objectReference: {fileID: 0}
- target: {fileID: 4943719350691982, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 5889392e3f05b448a8a06c5def6c2dec, type: 3}
--- !u!1001 &377867948
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget (5)
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 11
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 25.5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 25.5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
--- !u!1001 &500175881
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget (8)
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 12
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 51
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 25.5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
--- !u!850595691 &579492083
LightingSettings:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Settings.lighting
serializedVersion: 4
m_GIWorkflowMode: 1
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 1
m_RealtimeEnvironmentLighting: 1
m_BounceScale: 1
m_AlbedoBoost: 1
m_IndirectOutputScale: 1
m_UsingShadowmask: 1
m_BakeBackend: 1
m_LightmapMaxSize: 1024
m_BakeResolution: 40
m_Padding: 2
m_LightmapCompression: 3
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 1
m_CompAOExponentDirect: 0
m_ExtractAO: 0
m_MixedBakeMode: 2
m_LightmapsBakeMode: 1
m_FilterMode: 1
m_LightmapParameters: {fileID: 15204, guid: 0000000000000000f000000000000000, type: 0}
m_ExportTrainingData: 0
m_TrainingDataDestination: TrainingData
m_RealtimeResolution: 2
m_ForceWhiteAlbedo: 0
m_ForceUpdates: 0
m_FinalGather: 0
m_FinalGatherRayCount: 256
m_FinalGatherFiltering: 1
m_PVRCulling: 1
m_PVRSampling: 1
m_PVRDirectSampleCount: 32
m_PVRSampleCount: 500
m_PVREnvironmentSampleCount: 500
m_PVREnvironmentReferencePointCount: 2048
m_LightProbeSampleCountMultiplier: 4
m_PVRBounces: 2
m_PVRMinBounces: 2
m_PVREnvironmentMIS: 0
m_PVRFilteringMode: 2
m_PVRDenoiserTypeDirect: 0
m_PVRDenoiserTypeIndirect: 0
m_PVRDenoiserTypeAO: 0
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_PVRTiledBaking: 0
--- !u!1001 &753585645
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget (9)
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 14
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 102
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 25.5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
--- !u!1 &781961355
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 781961358}
- component: {fileID: 781961357}
- component: {fileID: 781961356}
m_Layer: 0
m_Name: EventSystem
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &781961356
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 781961355}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 4f231c4fb786f3946a6b90b886c48677, type: 3}
m_Name:
m_EditorClassIdentifier:
m_SendPointerHoverToParent: 1
m_HorizontalAxis: Horizontal
m_VerticalAxis: Vertical
m_SubmitButton: Submit
m_CancelButton: Cancel
m_InputActionsPerSecond: 10
m_RepeatDelay: 0.5
m_ForceModuleActive: 0
--- !u!114 &781961357
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 781961355}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 76c392e42b5098c458856cdf6ecaaaa1, type: 3}
m_Name:
m_EditorClassIdentifier:
m_FirstSelected: {fileID: 0}
m_sendNavigationEvents: 1
m_DragThreshold: 10
--- !u!4 &781961358
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 781961355}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1001 &1079850865
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget (2)
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 7
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 51
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
--- !u!1 &1392866527
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1392866532}
- component: {fileID: 1392866531}
- component: {fileID: 1392866529}
- component: {fileID: 1392866533}
m_Layer: 0
m_Name: Main Camera
m_TagString: MainCamera
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!124 &1392866529
Behaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1392866527}
m_Enabled: 1
--- !u!20 &1392866531
Camera:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1392866527}
m_Enabled: 1
serializedVersion: 2
m_ClearFlags: 2
m_BackGroundColor: {r: 0.46666667, g: 0.5647059, b: 0.60784316, a: 1}
m_projectionMatrixMode: 1
m_GateFitMode: 2
m_FOVAxisMode: 0
m_SensorSize: {x: 36, y: 24}
m_LensShift: {x: 0, y: 0}
m_FocalLength: 50
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.1
far clip plane: 5000
field of view: 60
orthographic: 0
orthographic size: 10
m_Depth: -1
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 1
m_AllowMSAA: 1
m_AllowDynamicResolution: 0
m_ForceIntoRT: 0
m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!4 &1392866532
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1392866527}
m_LocalRotation: {x: 0.14431359, y: -0.60080194, z: 0.111364864, w: 0.778337}
m_LocalPosition: {x: 4.21, y: 2.83, z: -1.43}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 21.006, y: -75.33, z: -0.003}
--- !u!114 &1392866533
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1392866527}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: ec40c70d5160b47cd8deaab79e24892c, type: 3}
m_Name:
m_EditorClassIdentifier:
target: {fileID: 1997371326124021637}
smoothingTime: 0.1
--- !u!1001 &1475071004
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget (6)
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 13
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 76.5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 25.5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
--- !u!1001 &1481808307
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_Pivot.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_Pivot.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_RootOrder
value: 2
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_AnchorMax.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_AnchorMin.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_AnchorMin.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_SizeDelta.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_SizeDelta.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_LocalRotation.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_LocalRotation.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_LocalRotation.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_AnchoredPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 224194346362733190, guid: 3ce107b4a79bc4eef83afde434932a68,
type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 3ce107b4a79bc4eef83afde434932a68, type: 3}
--- !u!1001 &1702385307
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget (4)
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 9
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 102
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
--- !u!1001 &1828383796
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget (7)
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 10
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 25.5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
--- !u!1001 &2023056993
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget (3)
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 8
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 76.5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
--- !u!1001 &2080237570
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget (1)
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 6
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 25.5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
--- !u!1 &2095421678
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 2095421679}
- component: {fileID: 2095421681}
- component: {fileID: 2095421680}
m_Layer: 0
m_Name: WalkerDynamicSettings
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &2095421679
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2095421678}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 2, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &2095421680
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2095421678}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: ec51f47c5ed0478080c449c74fd9c154, type: 3}
m_Name:
m_EditorClassIdentifier:
gravityMultiplier: 1.5
fixedDeltaTime: 0.01333
maximumDeltaTime: 0.15
solverIterations: 12
solverVelocityIterations: 12
reuseCollisionCallbacks: 1
--- !u!114 &2095421681
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2095421678}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3d6f3eab3776b4fb79724ac4216dfd7b, type: 3}
m_Name:
m_EditorClassIdentifier:
--- !u!4 &1997371326124021637 stripped
Transform:
m_CorrespondingSourceObject: {fileID: 1997371326124021637, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
m_PrefabInstance: {fileID: 2709362470382547191}
m_PrefabAsset: {fileID: 0}
--- !u!1001 &2709362470382547191
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6713178126238440196, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_Name
value: PlatformDynamicTarget
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_RootOrder
value: 5
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6718791046026642300, guid: 84359146bf7af47e58c229d877e801d7,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 84359146bf7af47e58c229d877e801d7, type: 3}
| ml-agents/Project/Assets/ML-Agents/Examples/Walker/Scenes/Walker.unity/0 | {
"file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Walker/Scenes/Walker.unity",
"repo_id": "ml-agents",
"token_count": 20596
} | 1,818 |
fileFormatVersion: 2
guid: 1d53e87fe54dd4178b88cc1a23b11731
folderAsset: yes
timeCreated: 1517446674
licenseType: Free
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/Project/Assets/ML-Agents/Examples/WallJump/Scenes.meta/0 | {
"file_path": "ml-agents/Project/Assets/ML-Agents/Examples/WallJump/Scenes.meta",
"repo_id": "ml-agents",
"token_count": 83
} | 1,819 |
fileFormatVersion: 2
guid: 07206274aded54b3991a277fedbaa2b2
folderAsset: yes
timeCreated: 1508478093
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/Project/Assets/ML-Agents/Examples/Worm/Prefabs.meta/0 | {
"file_path": "ml-agents/Project/Assets/ML-Agents/Examples/Worm/Prefabs.meta",
"repo_id": "ml-agents",
"token_count": 73
} | 1,820 |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!29 &1
OcclusionCullingSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_OcclusionBakeSettings:
smallestOccluder: 5
smallestHole: 0.25
backfaceThreshold: 100
m_SceneGUID: 00000000000000000000000000000000
m_OcclusionCullingData: {fileID: 0}
--- !u!104 &2
RenderSettings:
m_ObjectHideFlags: 0
serializedVersion: 9
m_Fog: 0
m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}
m_FogMode: 3
m_FogDensity: 0.01
m_LinearFogStart: 0
m_LinearFogEnd: 300
m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}
m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}
m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}
m_AmbientIntensity: 1
m_AmbientMode: 0
m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}
m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}
m_HaloStrength: 0.5
m_FlareStrength: 1
m_FlareFadeSpeed: 3
m_HaloTexture: {fileID: 0}
m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}
m_DefaultReflectionMode: 0
m_DefaultReflectionResolution: 128
m_ReflectionBounces: 1
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.44657838, g: 0.49641234, b: 0.57481676, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 11
m_GIWorkflowMode: 0
m_GISettings:
serializedVersion: 2
m_BounceScale: 1
m_IndirectOutputScale: 1
m_AlbedoBoost: 1
m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 1
m_LightmapEditorSettings:
serializedVersion: 10
m_Resolution: 2
m_BakeResolution: 40
m_AtlasSize: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 1
m_CompAOExponentDirect: 0
m_Padding: 2
m_LightmapParameters: {fileID: 0}
m_LightmapsBakeMode: 1
m_TextureCompression: 1
m_FinalGather: 0
m_FinalGatherFiltering: 1
m_FinalGatherRayCount: 256
m_ReflectionCompression: 2
m_MixedBakeMode: 2
m_BakeBackend: 1
m_PVRSampling: 1
m_PVRDirectSampleCount: 32
m_PVRSampleCount: 500
m_PVRBounces: 2
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVRFilteringMode: 1
m_PVRCulling: 1
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_ShowResolutionOverlay: 1
m_LightingDataAsset: {fileID: 0}
m_UseShadowmask: 1
--- !u!196 &4
NavMeshSettings:
serializedVersion: 2
m_ObjectHideFlags: 0
m_BuildSettings:
serializedVersion: 2
agentTypeID: 0
agentRadius: 0.5
agentHeight: 2
agentSlope: 45
agentClimb: 0.4
ledgeDropHeight: 0
maxJumpAcrossDistance: 0
minRegionArea: 2
manualCellSize: 0
cellSize: 0.16666667
manualTileSize: 0
tileSize: 256
accuratePlacement: 0
debug:
m_Flags: 0
m_NavMeshData: {fileID: 0}
--- !u!1 &512612610
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 512612611}
m_Layer: 0
m_Name: Ground
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &512612611
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 512612610}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 1242785455}
- {fileID: 577791992}
m_Father: {fileID: 0}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &577791991
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 577791992}
- component: {fileID: 577791995}
- component: {fileID: 577791994}
- component: {fileID: 577791993}
m_Layer: 0
m_Name: Cube (1)
m_TagString: wall
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &577791992
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 577791991}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 4.67, y: 0, z: 0.79}
m_LocalScale: {x: 1, y: 1, z: 11.002}
m_Children: []
m_Father: {fileID: 512612611}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!65 &577791993
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 577791991}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!23 &577791994
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 577791991}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!33 &577791995
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 577791991}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &1242785454
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1242785455}
- component: {fileID: 1242785458}
- component: {fileID: 1242785457}
- component: {fileID: 1242785456}
m_Layer: 0
m_Name: Cube
m_TagString: goal
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1242785455
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1242785454}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 3.31}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 512612611}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!65 &1242785456
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1242785454}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!23 &1242785457
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1242785454}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!33 &1242785458
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1242785454}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &1362333146
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1362333151}
- component: {fileID: 1362333150}
- component: {fileID: 1362333149}
- component: {fileID: 1362333148}
- component: {fileID: 1362333147}
m_Layer: 0
m_Name: GridAgentUnCompressed
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &1362333147
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1362333146}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3a5c9d521e5ef4759a8246a07d52221e, type: 3}
m_Name:
m_EditorClassIdentifier:
DecisionPeriod: 1
TakeActionsBetweenDecisions: 1
--- !u!114 &1362333148
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1362333146}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 801669c0cdece6b40b2e741ad0b119ac, type: 3}
m_Name:
m_EditorClassIdentifier:
Name: GridSensor
CellScaleX: 1
CellScaleZ: 1
GridNumSideX: 16
GridNumSideZ: 16
CellScaleY: 0.01
RotateToAgent: 0
ChannelDepth: 04000000
DetectableObjects:
- goal
- wall
- Player
ObserveMask:
serializedVersion: 2
m_Bits: 307
gridDepthType: 1
rootReference: {fileID: 1362333146}
ObservationPerCell: 4
NumberOfObservations: 1024
ChannelOffsets: 00000000
DebugColors:
- {r: 1, g: 0.0141509175, b: 0.0141509175, a: 0}
- {r: 0, g: 0.050011635, b: 1, a: 0}
- {r: 0.12027997, g: 1, b: 0.08962262, a: 0}
GizmoYOffset: 0
ShowGizmos: 1
CompressionType: 0
--- !u!114 &1362333149
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1362333146}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 88b6042bc9a5d4aa58d931eae49442e5, type: 3}
m_Name:
m_EditorClassIdentifier:
agentParameters:
maxStep: 0
hasUpgradedFromAgentParameters: 1
MaxStep: 0
--- !u!114 &1362333150
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1362333146}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5d1c4e0b1822b495aa52bc52839ecb30, type: 3}
m_Name:
m_EditorClassIdentifier:
m_BrainParameters:
VectorObservationSize: 0
NumStackedVectorObservations: 1
VectorActionSize: 01000000
VectorActionDescriptions: []
VectorActionSpaceType: 0
m_Model: {fileID: 0}
m_InferenceDevice: 0
m_BehaviorType: 0
m_BehaviorName: TestGrid
TeamId: 0
m_UseChildSensors: 1
m_UseChildActuators: 1
m_ObservableAttributeHandling: 0
--- !u!4 &1362333151
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1362333146}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1377910015
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1377910019}
- component: {fileID: 1377910018}
- component: {fileID: 1377910017}
- component: {fileID: 1377910016}
- component: {fileID: 1377910020}
m_Layer: 0
m_Name: GridAgentCompressed
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &1377910016
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1377910015}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 801669c0cdece6b40b2e741ad0b119ac, type: 3}
m_Name:
m_EditorClassIdentifier:
Name: GridSensor
CellScaleX: 1
CellScaleZ: 1
GridNumSideX: 16
GridNumSideZ: 16
CellScaleY: 0.01
RotateToAgent: 0
ChannelDepth: 04000000
DetectableObjects:
- goal
- wall
- Player
ObserveMask:
serializedVersion: 2
m_Bits: 307
gridDepthType: 1
rootReference: {fileID: 1377910015}
ObservationPerCell: 4
NumberOfObservations: 1024
ChannelOffsets: 00000000
DebugColors:
- {r: 1, g: 0.0141509175, b: 0.0141509175, a: 0}
- {r: 0, g: 0.050011635, b: 1, a: 0}
- {r: 0.12027997, g: 1, b: 0.08962262, a: 0}
GizmoYOffset: 0
ShowGizmos: 1
CompressionType: 1
--- !u!114 &1377910017
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1377910015}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 88b6042bc9a5d4aa58d931eae49442e5, type: 3}
m_Name:
m_EditorClassIdentifier:
agentParameters:
maxStep: 0
hasUpgradedFromAgentParameters: 1
MaxStep: 0
--- !u!114 &1377910018
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1377910015}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5d1c4e0b1822b495aa52bc52839ecb30, type: 3}
m_Name:
m_EditorClassIdentifier:
m_BrainParameters:
VectorObservationSize: 0
NumStackedVectorObservations: 1
VectorActionSize: 01000000
VectorActionDescriptions: []
VectorActionSpaceType: 0
m_Model: {fileID: 0}
m_InferenceDevice: 0
m_BehaviorType: 0
m_BehaviorName: TestGrid
TeamId: 0
m_UseChildSensors: 1
m_UseChildActuators: 1
m_ObservableAttributeHandling: 0
--- !u!4 &1377910019
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1377910015}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &1377910020
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1377910015}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 3a5c9d521e5ef4759a8246a07d52221e, type: 3}
m_Name:
m_EditorClassIdentifier:
DecisionPeriod: 1
TakeActionsBetweenDecisions: 1
--- !u!1 &1617557642
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1617557644}
- component: {fileID: 1617557643}
m_Layer: 0
m_Name: Directional Light
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!108 &1617557643
Light:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1617557642}
m_Enabled: 1
serializedVersion: 8
m_Type: 1
m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1}
m_Intensity: 1
m_Range: 10
m_SpotAngle: 30
m_CookieSize: 10
m_Shadows:
m_Type: 2
m_Resolution: -1
m_CustomResolution: -1
m_Strength: 1
m_Bias: 0.05
m_NormalBias: 0.4
m_NearPlane: 0.2
m_Cookie: {fileID: 0}
m_DrawHalo: 0
m_Flare: {fileID: 0}
m_RenderMode: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_Lightmapping: 4
m_LightShadowCasterMode: 0
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!4 &1617557644
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1617557642}
m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}
m_LocalPosition: {x: 0, y: 3, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}
--- !u!1 &1634604112
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1634604115}
- component: {fileID: 1634604114}
- component: {fileID: 1634604113}
m_Layer: 0
m_Name: Main Camera
m_TagString: MainCamera
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!81 &1634604113
AudioListener:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1634604112}
m_Enabled: 1
--- !u!20 &1634604114
Camera:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1634604112}
m_Enabled: 1
serializedVersion: 2
m_ClearFlags: 1
m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}
m_projectionMatrixMode: 1
m_SensorSize: {x: 36, y: 24}
m_LensShift: {x: 0, y: 0}
m_GateFitMode: 2
m_FocalLength: 50
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.3
far clip plane: 1000
field of view: 60
orthographic: 0
orthographic size: 5
m_Depth: -1
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 1
m_AllowMSAA: 1
m_AllowDynamicResolution: 0
m_ForceIntoRT: 0
m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!4 &1634604115
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1634604112}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 1, z: -10}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
| ml-agents/Project/Assets/ML-Agents/TestScenes/TestCompressedGrid/TestGridCompressed.unity/0 | {
"file_path": "ml-agents/Project/Assets/ML-Agents/TestScenes/TestCompressedGrid/TestGridCompressed.unity",
"repo_id": "ml-agents",
"token_count": 8708
} | 1,821 |
# ML-Agents Extensions
See the [package documentation](Documentation~/com.unity.ml-agents.extensions.md) for more information
| ml-agents/com.unity.ml-agents.extensions/README.md/0 | {
"file_path": "ml-agents/com.unity.ml-agents.extensions/README.md",
"repo_id": "ml-agents",
"token_count": 35
} | 1,822 |
fileFormatVersion: 2
guid: aa311fde3dac44f3b7998bb7fee77225
timeCreated: 1611356491 | ml-agents/com.unity.ml-agents.extensions/Runtime/Input/Adaptors/Vector2InputActionAdaptor.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents.extensions/Runtime/Input/Adaptors/Vector2InputActionAdaptor.cs.meta",
"repo_id": "ml-agents",
"token_count": 40
} | 1,823 |
#if UNITY_2020_1_OR_NEWER
using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents.Sensors;
namespace Unity.MLAgents.Extensions.Sensors
{
public class ArticulationBodyJointExtractor : IJointExtractor
{
ArticulationBody m_Body;
public ArticulationBodyJointExtractor(ArticulationBody body)
{
m_Body = body;
}
public int NumObservations(PhysicsSensorSettings settings)
{
return NumObservations(m_Body, settings);
}
public static int NumObservations(ArticulationBody body, PhysicsSensorSettings settings)
{
if (body == null || body.isRoot)
{
return 0;
}
var totalCount = 0;
if (settings.UseJointPositionsAndAngles)
{
switch (body.jointType)
{
case ArticulationJointType.RevoluteJoint:
case ArticulationJointType.SphericalJoint:
// Both RevoluteJoint and SphericalJoint have all angular components.
// We use sine and cosine of the angles for the observations.
totalCount += 2 * body.dofCount;
break;
case ArticulationJointType.FixedJoint:
// Since FixedJoint can't moved, there aren't any interesting observations for it.
break;
case ArticulationJointType.PrismaticJoint:
// One linear component
totalCount += body.dofCount;
break;
}
}
if (settings.UseJointForces)
{
totalCount += body.dofCount;
}
return totalCount;
}
public int Write(PhysicsSensorSettings settings, ObservationWriter writer, int offset)
{
if (m_Body == null || m_Body.isRoot)
{
return 0;
}
var currentOffset = offset;
// Write joint positions
if (settings.UseJointPositionsAndAngles)
{
switch (m_Body.jointType)
{
case ArticulationJointType.RevoluteJoint:
case ArticulationJointType.SphericalJoint:
// All joint positions are angular
for (var dofIndex = 0; dofIndex < m_Body.dofCount; dofIndex++)
{
var jointRotationRads = m_Body.jointPosition[dofIndex];
writer[currentOffset++] = Mathf.Sin(jointRotationRads);
writer[currentOffset++] = Mathf.Cos(jointRotationRads);
}
break;
case ArticulationJointType.FixedJoint:
// No observations
break;
case ArticulationJointType.PrismaticJoint:
writer[currentOffset++] = GetPrismaticValue();
break;
}
}
if (settings.UseJointForces)
{
for (var dofIndex = 0; dofIndex < m_Body.dofCount; dofIndex++)
{
// take tanh to keep in [-1, 1]
writer[currentOffset++] = (float)System.Math.Tanh(m_Body.jointForce[dofIndex]);
}
}
return currentOffset - offset;
}
float GetPrismaticValue()
{
// Prismatic joints should have at most one free axis.
bool limited = false;
var drive = m_Body.xDrive;
if (m_Body.linearLockX == ArticulationDofLock.LimitedMotion)
{
drive = m_Body.xDrive;
limited = true;
}
else if (m_Body.linearLockY == ArticulationDofLock.LimitedMotion)
{
drive = m_Body.yDrive;
limited = true;
}
else if (m_Body.linearLockZ == ArticulationDofLock.LimitedMotion)
{
drive = m_Body.zDrive;
limited = true;
}
var jointPos = m_Body.jointPosition[0];
if (limited)
{
// If locked, interpolate between the limits.
var upperLimit = drive.upperLimit;
var lowerLimit = drive.lowerLimit;
if (upperLimit <= lowerLimit)
{
// Invalid limits (probably equal), so don't try to lerp
return 0;
}
var invLerped = Mathf.InverseLerp(lowerLimit, upperLimit, jointPos);
// Convert [0, 1] -> [-1, 1]
var normalized = 2.0f * invLerped - 1.0f;
return normalized;
}
// take tanh() to keep in [-1, 1]
return (float)System.Math.Tanh(jointPos);
}
}
}
#endif
| ml-agents/com.unity.ml-agents.extensions/Runtime/Sensors/ArticulationBodyJointExtractor.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents.extensions/Runtime/Sensors/ArticulationBodyJointExtractor.cs",
"repo_id": "ml-agents",
"token_count": 2857
} | 1,824 |
using UnityEngine;
using Unity.MLAgents.Sensors;
namespace Unity.MLAgents.Extensions.Sensors
{
public class RigidBodyJointExtractor : IJointExtractor
{
Rigidbody m_Body;
Joint m_Joint;
public RigidBodyJointExtractor(Rigidbody body)
{
m_Body = body;
m_Joint = m_Body?.GetComponent<Joint>();
}
public int NumObservations(PhysicsSensorSettings settings)
{
return NumObservations(m_Body, m_Joint, settings);
}
public static int NumObservations(Rigidbody body, Joint joint, PhysicsSensorSettings settings)
{
if (body == null || joint == null)
{
return 0;
}
var numObservations = 0;
if (settings.UseJointForces)
{
// 3 force and 3 torque values
numObservations += 6;
}
return numObservations;
}
public int Write(PhysicsSensorSettings settings, ObservationWriter writer, int offset)
{
if (m_Body == null || m_Joint == null)
{
return 0;
}
var currentOffset = offset;
if (settings.UseJointForces)
{
// Take tanh of the forces and torques to ensure they're in [-1, 1]
writer[currentOffset++] = (float)System.Math.Tanh(m_Joint.currentForce.x);
writer[currentOffset++] = (float)System.Math.Tanh(m_Joint.currentForce.y);
writer[currentOffset++] = (float)System.Math.Tanh(m_Joint.currentForce.z);
writer[currentOffset++] = (float)System.Math.Tanh(m_Joint.currentTorque.x);
writer[currentOffset++] = (float)System.Math.Tanh(m_Joint.currentTorque.y);
writer[currentOffset++] = (float)System.Math.Tanh(m_Joint.currentTorque.z);
}
return currentOffset - offset;
}
}
}
| ml-agents/com.unity.ml-agents.extensions/Runtime/Sensors/RigidBodyJointExtractor.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents.extensions/Runtime/Sensors/RigidBodyJointExtractor.cs",
"repo_id": "ml-agents",
"token_count": 995
} | 1,825 |
fileFormatVersion: 2
guid: ae2012c098aa4b57ab09dbf72bcd4efe
timeCreated: 1613074622 | ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Input/Adaptors/DoubleInputActionAdaptorTests.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Input/Adaptors/DoubleInputActionAdaptorTests.cs.meta",
"repo_id": "ml-agents",
"token_count": 40
} | 1,826 |
fileFormatVersion: 2
guid: be1c02c37007345aa8ad2e44603852b2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/RuntimeExampleTest.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/RuntimeExampleTest.cs.meta",
"repo_id": "ml-agents",
"token_count": 95
} | 1,827 |
{
"name": "Unity.ML-Agents.Extensions.Tests",
"references": [
"Unity.ML-Agents.Extensions",
"Unity.ML-Agents"
],
"optionalUnityReferences": [
"TestAssemblies"
],
"includePlatforms": [],
"excludePlatforms": []
}
| ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Unity.ML-Agents.Extensions.Tests.asmdef/0 | {
"file_path": "ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Unity.ML-Agents.Extensions.Tests.asmdef",
"repo_id": "ml-agents",
"token_count": 125
} | 1,828 |
fileFormatVersion: 2
guid: c3b291e1cd0c64781861652b579d0ac1
timeCreated: 1503270350
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Editor/AgentEditor.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Editor/AgentEditor.cs.meta",
"repo_id": "ml-agents",
"token_count": 101
} | 1,829 |
{
"name": "Unity.ML-Agents.Editor",
"rootNamespace": "",
"references": [
"Unity.ML-Agents",
"Unity.ML-Agents.CommunicatorObjects",
"Unity.Sentis"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.modules.physics",
"expression": "1.0.0",
"define": "MLA_UNITY_PHYSICS_MODULE"
},
{
"name": "com.unity.modules.physics2d",
"expression": "1.0.0",
"define": "MLA_UNITY_PHYSICS2D_MODULE"
}
],
"noEngineReferences": false
} | ml-agents/com.unity.ml-agents/Editor/Unity.ML-Agents.Editor.asmdef/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Editor/Unity.ML-Agents.Editor.asmdef",
"repo_id": "ml-agents",
"token_count": 410
} | 1,830 |
fileFormatVersion: 2
guid: 7eeb863bd08ba4388829c23da03a714f
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
: Any
second:
enabled: 0
settings:
Exclude Android: 1
Exclude CloudRendering: 1
Exclude Editor: 0
Exclude Linux: 1
Exclude Linux64: 1
Exclude LinuxUniversal: 1
Exclude OSXIntel: 0
Exclude OSXIntel64: 0
Exclude OSXUniversal: 0
Exclude WebGL: 1
Exclude Win: 1
Exclude Win64: 1
Exclude iOS: 1
- first:
: OSXIntel
second:
enabled: 1
settings: {}
- first:
: OSXIntel64
second:
enabled: 1
settings: {}
- first:
Android: Android
second:
enabled: 0
settings:
CPU: ARMv7
- first:
Any:
second:
enabled: 0
settings: {}
- first:
CloudRendering: CloudRendering
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 1
settings:
CPU: x86_64
DefaultValueInitialized: true
OS: OSX
- first:
Facebook: Win
second:
enabled: 0
settings:
CPU: AnyCPU
- first:
Facebook: Win64
second:
enabled: 0
settings:
CPU: AnyCPU
- first:
Standalone: Linux
second:
enabled: 0
settings:
CPU: x86
- first:
Standalone: Linux64
second:
enabled: 0
settings:
CPU: AnyCPU
- first:
Standalone: LinuxUniversal
second:
enabled: 0
settings:
CPU: None
- first:
Standalone: OSXIntel
second:
enabled: 1
settings:
CPU: AnyCPU
- first:
Standalone: OSXIntel64
second:
enabled: 1
settings:
CPU: AnyCPU
- first:
Standalone: OSXUniversal
second:
enabled: 1
settings:
CPU: AnyCPU
- first:
Standalone: Win
second:
enabled: 0
settings:
CPU: AnyCPU
- first:
Standalone: Win64
second:
enabled: 0
settings:
CPU: AnyCPU
- first:
iPhone: iOS
second:
enabled: 0
settings:
AddToEmbeddedBinaries: false
CPU: AnyCPU
CompileFlags:
FrameworkDependencies:
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer/runtimes/osx/native/libgrpc_csharp_ext.x64.bundle.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer/runtimes/osx/native/libgrpc_csharp_ext.x64.bundle.meta",
"repo_id": "ml-agents",
"token_count": 1234
} | 1,831 |
fileFormatVersion: 2
guid: 26733e59183b6479e8f0e892a8bf09a4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Runtime/Actuators.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Actuators.meta",
"repo_id": "ml-agents",
"token_count": 71
} | 1,832 |
fileFormatVersion: 2
guid: e3d7ef9a9a5043549cc5c0bbee520810
timeCreated: 1613514041 | ml-agents/com.unity.ml-agents/Runtime/Actuators/IBuiltInActuator.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Actuators/IBuiltInActuator.cs.meta",
"repo_id": "ml-agents",
"token_count": 41
} | 1,833 |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
using UnityEngine;
#if MLA_UNITY_ANALYTICS_MODULE
#if ENABLE_CLOUD_SERVICES_ANALYTICS
using UnityEngine.Analytics;
#endif
#if UNITY_EDITOR
using UnityEditor.Analytics;
#endif
#endif
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Unity.MLAgents.Analytics
{
internal static class TrainingAnalytics
{
const string k_VendorKey = "unity.ml-agents";
const string k_TrainingEnvironmentInitializedEventName = "ml_agents_training_environment_initialized";
const string k_TrainingBehaviorInitializedEventName = "ml_agents_training_behavior_initialized";
const string k_RemotePolicyInitializedEventName = "ml_agents_remote_policy_initialized";
private static readonly string[] s_EventNames =
{
k_TrainingEnvironmentInitializedEventName,
k_TrainingBehaviorInitializedEventName,
k_RemotePolicyInitializedEventName
};
/// <summary>
/// Hourly limit for this event name
/// </summary>
const int k_MaxEventsPerHour = 1000;
/// <summary>
/// Maximum number of items in this event.
/// </summary>
const int k_MaxNumberOfElements = 1000;
private static bool s_SentEnvironmentInitialized;
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE && ENABLE_CLOUD_SERVICES_ANALYTICS
/// <summary>
/// Whether or not we've registered this particular event yet
/// </summary>
static bool s_EventsRegistered;
/// <summary>
/// Behaviors that we've already sent events for.
/// </summary>
private static HashSet<string> s_SentRemotePolicyInitialized;
private static HashSet<string> s_SentTrainingBehaviorInitialized;
#endif
private static Guid s_TrainingSessionGuid;
// These are set when the RpcCommunicator connects
private static string s_TrainerPackageVersion = "";
private static string s_TrainerCommunicationVersion = "";
internal static bool EnableAnalytics()
{
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE && ENABLE_CLOUD_SERVICES_ANALYTICS
if (s_EventsRegistered)
{
return true;
}
foreach (var eventName in s_EventNames)
{
AnalyticsResult result = EditorAnalytics.RegisterEventWithLimit(eventName, k_MaxEventsPerHour, k_MaxNumberOfElements, k_VendorKey);
if (result != AnalyticsResult.Ok)
{
return false;
}
}
s_EventsRegistered = true;
if (s_SentRemotePolicyInitialized == null)
{
s_SentRemotePolicyInitialized = new HashSet<string>();
s_SentTrainingBehaviorInitialized = new HashSet<string>();
s_TrainingSessionGuid = Guid.NewGuid();
}
return s_EventsRegistered;
#else
return false;
#endif // MLA_UNITY_ANALYTICS_MODULE
}
/// <summary>
/// Cache information about the trainer when it becomes available in the RpcCommunicator.
/// </summary>
/// <param name="communicationVersion"></param>
/// <param name="packageVersion"></param>
[Conditional("MLA_UNITY_ANALYTICS_MODULE")]
public static void SetTrainerInformation(string packageVersion, string communicationVersion)
{
s_TrainerPackageVersion = packageVersion;
s_TrainerCommunicationVersion = communicationVersion;
}
public static bool IsAnalyticsEnabled()
{
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE && ENABLE_CLOUD_SERVICES_ANALYTICS
return EditorAnalytics.enabled;
#else
return false;
#endif
}
[Conditional("MLA_UNITY_ANALYTICS_MODULE")]
public static void TrainingEnvironmentInitialized(TrainingEnvironmentInitializedEvent tbiEvent)
{
if (!IsAnalyticsEnabled())
return;
if (!EnableAnalytics())
return;
if (s_SentEnvironmentInitialized)
{
// We already sent an TrainingEnvironmentInitializedEvent. Exit so we don't resend.
return;
}
s_SentEnvironmentInitialized = true;
tbiEvent.TrainingSessionGuid = s_TrainingSessionGuid.ToString();
// Note - to debug, use JsonUtility.ToJson on the event.
// Debug.Log(
// $"Would send event {k_TrainingEnvironmentInitializedEventName} with body {JsonUtility.ToJson(tbiEvent, true)}"
// );
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE && ENABLE_CLOUD_SERVICES_ANALYTICS
if (AnalyticsUtils.s_SendEditorAnalytics)
{
EditorAnalytics.SendEventWithLimit(k_TrainingEnvironmentInitializedEventName, tbiEvent);
}
#endif
}
[Conditional("MLA_UNITY_ANALYTICS_MODULE")]
public static void RemotePolicyInitialized(
string fullyQualifiedBehaviorName,
IList<ISensor> sensors,
ActionSpec actionSpec,
IList<IActuator> actuators
)
{
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE && ENABLE_CLOUD_SERVICES_ANALYTICS
if (!IsAnalyticsEnabled())
return;
if (!EnableAnalytics())
return;
// Extract base behavior name (no team ID)
var behaviorName = ParseBehaviorName(fullyQualifiedBehaviorName);
var added = s_SentRemotePolicyInitialized.Add(behaviorName);
if (!added)
{
// We previously added this model. Exit so we don't resend.
return;
}
var data = GetEventForRemotePolicy(behaviorName, sensors, actionSpec, actuators);
// Note - to debug, use JsonUtility.ToJson on the event.
// Debug.Log(
// $"Would send event {k_RemotePolicyInitializedEventName} with body {JsonUtility.ToJson(data, true)}"
// );
if (AnalyticsUtils.s_SendEditorAnalytics)
{
EditorAnalytics.SendEventWithLimit(k_RemotePolicyInitializedEventName, data);
}
#endif
}
internal static string ParseBehaviorName(string fullyQualifiedBehaviorName)
{
var lastQuestionIndex = fullyQualifiedBehaviorName.LastIndexOf("?");
if (lastQuestionIndex < 0)
{
// Nothing to remove
return fullyQualifiedBehaviorName;
}
return fullyQualifiedBehaviorName.Substring(0, lastQuestionIndex);
}
internal static TrainingBehaviorInitializedEvent SanitizeTrainingBehaviorInitializedEvent(TrainingBehaviorInitializedEvent tbiEvent)
{
// Hash the behavior name if the message version is from an older version of ml-agents that doesn't do trainer-side hashing.
// We'll also, for extra safety, verify that the BehaviorName is the size of the expected SHA256 hash.
// Context: The config field was added at the same time as trainer side hashing, so messages including it should already be hashed.
if (tbiEvent.Config.Length == 0 || tbiEvent.BehaviorName.Length != 64)
{
tbiEvent.BehaviorName = AnalyticsUtils.Hash(k_VendorKey, tbiEvent.BehaviorName);
}
return tbiEvent;
}
[Conditional("MLA_UNITY_ANALYTICS_MODULE")]
public static void TrainingBehaviorInitialized(TrainingBehaviorInitializedEvent rawTbiEvent)
{
#if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE && ENABLE_CLOUD_SERVICES_ANALYTICS
if (!IsAnalyticsEnabled())
return;
if (!EnableAnalytics())
return;
var tbiEvent = SanitizeTrainingBehaviorInitializedEvent(rawTbiEvent);
var behaviorName = tbiEvent.BehaviorName;
var added = s_SentTrainingBehaviorInitialized.Add(behaviorName);
if (!added)
{
// We previously added this model. Exit so we don't resend.
return;
}
tbiEvent.TrainingSessionGuid = s_TrainingSessionGuid.ToString();
// Note - to debug, use JsonUtility.ToJson on the event.
// Debug.Log(
// $"Would send event {k_TrainingBehaviorInitializedEventName} with body {JsonUtility.ToJson(tbiEvent, true)}"
// );
if (AnalyticsUtils.s_SendEditorAnalytics)
{
EditorAnalytics.SendEventWithLimit(k_TrainingBehaviorInitializedEventName, tbiEvent);
}
#endif
}
internal static RemotePolicyInitializedEvent GetEventForRemotePolicy(
string behaviorName,
IList<ISensor> sensors,
ActionSpec actionSpec,
IList<IActuator> actuators
)
{
var remotePolicyEvent = new RemotePolicyInitializedEvent();
// Hash the behavior name so that there's no concern about PII or "secret" data being leaked.
remotePolicyEvent.BehaviorName = AnalyticsUtils.Hash(k_VendorKey, behaviorName);
remotePolicyEvent.TrainingSessionGuid = s_TrainingSessionGuid.ToString();
remotePolicyEvent.ActionSpec = EventActionSpec.FromActionSpec(actionSpec);
remotePolicyEvent.ObservationSpecs = new List<EventObservationSpec>(sensors.Count);
foreach (var sensor in sensors)
{
remotePolicyEvent.ObservationSpecs.Add(EventObservationSpec.FromSensor(sensor));
}
remotePolicyEvent.ActuatorInfos = new List<EventActuatorInfo>(actuators.Count);
foreach (var actuator in actuators)
{
remotePolicyEvent.ActuatorInfos.Add(EventActuatorInfo.FromActuator(actuator));
}
remotePolicyEvent.MLAgentsEnvsVersion = s_TrainerPackageVersion;
remotePolicyEvent.TrainerCommunicationVersion = s_TrainerCommunicationVersion;
return remotePolicyEvent;
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Analytics/TrainingAnalytics.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Analytics/TrainingAnalytics.cs",
"repo_id": "ml-agents",
"token_count": 4508
} | 1,834 |
using UnityEngine;
namespace Unity.MLAgents
{
public class UnityRLCapabilities
{
public bool BaseRLCapabilities;
public bool ConcatenatedPngObservations;
public bool CompressedChannelMapping;
public bool HybridActions;
public bool TrainingAnalytics;
public bool VariableLengthObservation;
public bool MultiAgentGroups;
/// <summary>
/// A class holding the capabilities flags for Reinforcement Learning across C# and the Trainer codebase. This
/// struct will be used to inform users if and when they are using C# / Trainer features that are mismatched.
/// </summary>
public UnityRLCapabilities(
bool baseRlCapabilities = true,
bool concatenatedPngObservations = true,
bool compressedChannelMapping = true,
bool hybridActions = true,
bool trainingAnalytics = true,
bool variableLengthObservation = true,
bool multiAgentGroups = true)
{
BaseRLCapabilities = baseRlCapabilities;
ConcatenatedPngObservations = concatenatedPngObservations;
CompressedChannelMapping = compressedChannelMapping;
HybridActions = hybridActions;
TrainingAnalytics = trainingAnalytics;
VariableLengthObservation = variableLengthObservation;
MultiAgentGroups = multiAgentGroups;
}
/// <summary>
/// Will print a warning to the console if Python does not support base capabilities and will
/// return <value>true</value> if the warning was printed.
/// </summary>
/// <returns></returns>
public bool WarnOnPythonMissingBaseRLCapabilities()
{
if (BaseRLCapabilities)
{
return false;
}
Debug.LogWarning("Unity has connected to a Training process that does not support" +
"Base Reinforcement Learning Capabilities. Please make sure you have the" +
" latest training codebase installed for this version of the ML-Agents package.");
return true;
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Communicator/UnityRLCapabilities.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Communicator/UnityRLCapabilities.cs",
"repo_id": "ml-agents",
"token_count": 876
} | 1,835 |
fileFormatVersion: 2
guid: 90ce0b26bef35484890eac0633b85eed
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Runtime/EnvironmentParameters.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/EnvironmentParameters.cs.meta",
"repo_id": "ml-agents",
"token_count": 93
} | 1,836 |
fileFormatVersion: 2
guid: 9949df411f7112bb290948f924e4c603
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/TrainingAnalytics.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/TrainingAnalytics.cs.meta",
"repo_id": "ml-agents",
"token_count": 93
} | 1,837 |
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Sentis;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Policies;
namespace Unity.MLAgents.Inference
{
/// <summary>
/// Prepares the Tensors for the Learning Brain and exposes a list of failed checks if Model
/// and BrainParameters are incompatible.
/// </summary>
internal class SentisModelParamLoader
{
internal enum ModelApiVersion
{
/// <summary>
/// ML-Agents model version for versions 1.x.y
/// The observations are split between vector and visual observations
/// There are legacy action outputs for discrete and continuous actions
/// LSTM inputs and outputs are handled by Sentis
/// </summary>
MLAgents1_0 = 2,
/// <summary>
/// All observations are treated the same and named obs_{i} with i being
/// the sensor index
/// Legacy "action" output is no longer present
/// LSTM inputs and outputs are treated like regular inputs and outputs
/// and no longer managed by Sentis
/// </summary>
MLAgents2_0 = 3,
MinSupportedVersion = MLAgents1_0,
MaxSupportedVersion = MLAgents2_0
}
internal class FailedCheck
{
public enum CheckTypeEnum
{
Info = 0,
Warning = 1,
Error = 2
}
public CheckTypeEnum CheckType;
public string Message;
public static FailedCheck Info(string message)
{
return new FailedCheck { CheckType = CheckTypeEnum.Info, Message = message };
}
public static FailedCheck Warning(string message)
{
return new FailedCheck { CheckType = CheckTypeEnum.Warning, Message = message };
}
public static FailedCheck Error(string message)
{
return new FailedCheck { CheckType = CheckTypeEnum.Error, Message = message };
}
}
/// <summary>
/// Checks that a model has the appropriate version.
/// </summary>
/// <param name="model">
/// The Sentis engine model for loading static parameters
/// </param>
/// <returns>A FailedCheck containing the error message if the version of the model does not mach, else null</returns>
public static FailedCheck CheckModelVersion(Model model)
{
var modelApiVersion = model.GetVersion();
if (modelApiVersion < (int)ModelApiVersion.MinSupportedVersion)
{
return FailedCheck.Error(
"Model was trained with a older version of the trainer than is supported. " +
"Either retrain with an newer trainer, or use an older version of com.unity.ml-agents.\n" +
$"Model version: {modelApiVersion} Minimum supported version: {(int)ModelApiVersion.MinSupportedVersion}"
);
}
if (modelApiVersion > (int)ModelApiVersion.MaxSupportedVersion)
{
return FailedCheck.Error(
"Model was trained with a newer version of the trainer than is supported. " +
"Either retrain with an older trainer, or update to a newer version of com.unity.ml-agents.\n" +
$"Model version: {modelApiVersion} Maximum supported version: {(int)ModelApiVersion.MaxSupportedVersion}"
);
}
var memorySize = (int)((TensorFloat)model.GetTensorByName(TensorNames.MemorySize))[0];
if (modelApiVersion == (int)ModelApiVersion.MLAgents1_0 && memorySize > 0)
{
// This block is to make sure that models that are trained with MLAgents version 1.x and have
// an LSTM (i.e. use the Sentis _c and _h inputs and outputs) will not work with MLAgents version
// 2.x. This is because Sentis version 2.x will eventually drop support for the _c and _h inputs
// and only ML-Agents 2.x models will be compatible.
return FailedCheck.Error(
"Models from com.unity.ml-agents 1.x that use recurrent neural networks are not supported in newer versions. " +
"Either retrain with an newer trainer, or use an older version of com.unity.ml-agents.\n"
);
}
return null;
}
/// <summary>
/// Factory for the ModelParamLoader : Creates a ModelParamLoader and runs the checks
/// on it.
/// </summary>
/// <param name="model">
/// The Sentis engine model for loading static parameters
/// </param>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="sensors">Attached sensor components</param>
/// <param name="actuatorComponents">Attached actuator components</param>
/// <param name="observableAttributeTotalSize">Sum of the sizes of all ObservableAttributes.</param>
/// <param name="behaviorType">BehaviorType or the Agent to check.</param>
/// <param name="deterministicInference"> Inference only: set to true if the action selection from model should be
/// deterministic. </param>
/// <returns>A IEnumerable of the checks that failed</returns>
public static IEnumerable<FailedCheck> CheckModel(
Model model,
BrainParameters brainParameters,
ISensor[] sensors,
ActuatorComponent[] actuatorComponents,
int observableAttributeTotalSize = 0,
BehaviorType behaviorType = BehaviorType.Default,
bool deterministicInference = false
)
{
List<FailedCheck> failedModelChecks = new List<FailedCheck>();
if (model == null)
{
var errorMsg = "There is no model for this Brain; cannot run inference. ";
if (behaviorType == BehaviorType.InferenceOnly)
{
errorMsg += "Either assign a model, or change to a different Behavior Type.";
}
else
{
errorMsg += "(But can still train)";
}
failedModelChecks.Add(FailedCheck.Info(errorMsg));
return failedModelChecks;
}
var hasExpectedTensors = model.CheckExpectedTensors(failedModelChecks, deterministicInference);
if (!hasExpectedTensors)
{
return failedModelChecks;
}
var modelApiVersion = model.GetVersion();
var versionCheck = CheckModelVersion(model);
if (versionCheck != null)
{
failedModelChecks.Add(versionCheck);
}
var memorySize = (int)((TensorFloat)model.GetTensorByName(TensorNames.MemorySize))[0];
if (memorySize == -1)
{
failedModelChecks.Add(FailedCheck.Warning($"Missing node in the model provided : {TensorNames.MemorySize}"
));
return failedModelChecks;
}
if (modelApiVersion == (int)ModelApiVersion.MLAgents1_0)
{
failedModelChecks.AddRange(
CheckInputTensorPresenceLegacy(model, brainParameters, memorySize, sensors)
);
failedModelChecks.AddRange(
CheckInputTensorShapeLegacy(model, brainParameters, sensors, observableAttributeTotalSize)
);
}
else if (modelApiVersion == (int)ModelApiVersion.MLAgents2_0)
{
failedModelChecks.AddRange(
CheckInputTensorPresence(model, brainParameters, memorySize, sensors, deterministicInference)
);
failedModelChecks.AddRange(
CheckInputTensorShape(model, brainParameters, sensors, observableAttributeTotalSize)
);
}
failedModelChecks.AddRange(
CheckOutputTensorShape(model, brainParameters, actuatorComponents)
);
failedModelChecks.AddRange(
CheckOutputTensorPresence(model, memorySize, deterministicInference)
);
return failedModelChecks;
}
/// <summary>
/// Generates failed checks that correspond to inputs expected by the model that are not
/// present in the BrainParameters. Tests the models created with the API of version 1.X
/// </summary>
/// <param name="model">
/// The Sentis engine model for loading static parameters
/// </param>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="memory">
/// The memory size that the model is expecting.
/// </param>
/// <param name="sensors">Array of attached sensor components</param>
/// <returns>
/// A IEnumerable of the checks that failed
/// </returns>
static IEnumerable<FailedCheck> CheckInputTensorPresenceLegacy(
Model model,
BrainParameters brainParameters,
int memory,
ISensor[] sensors
)
{
var failedModelChecks = new List<FailedCheck>();
var tensorsNames = model.GetInputNames();
// If there is no Vector Observation Input but the Brain Parameters expect one.
if ((brainParameters.VectorObservationSize != 0) &&
(!tensorsNames.Contains(TensorNames.VectorObservationPlaceholder)))
{
failedModelChecks.Add(
FailedCheck.Warning("The model does not contain a Vector Observation Placeholder Input. " +
"You must set the Vector Observation Space Size to 0.")
);
}
// If there are not enough Visual Observation Input compared to what the
// sensors expect.
var visObsIndex = 0;
for (var sensorIndex = 0; sensorIndex < sensors.Length; sensorIndex++)
{
var sensor = sensors[sensorIndex];
if (sensor.GetObservationSpec().Shape.Length == 3)
{
if (!tensorsNames.Contains(
TensorNames.GetVisualObservationName(visObsIndex)))
{
failedModelChecks.Add(
FailedCheck.Warning("The model does not contain a Visual Observation Placeholder Input " +
$"for sensor component {visObsIndex} ({sensor.GetType().Name}).")
);
}
visObsIndex++;
}
if (sensor.GetObservationSpec().Shape.Length == 2)
{
if (!tensorsNames.Contains(
TensorNames.GetObservationName(sensorIndex)))
{
failedModelChecks.Add(
FailedCheck.Warning("The model does not contain an Observation Placeholder Input " +
$"for sensor component {sensorIndex} ({sensor.GetType().Name}).")
);
}
}
}
var expectedVisualObs = model.GetNumVisualInputs();
// Check if there's not enough visual sensors (too many would be handled above)
if (expectedVisualObs > visObsIndex)
{
failedModelChecks.Add(
FailedCheck.Warning($"The model expects {expectedVisualObs} visual inputs," +
$" but only found {visObsIndex} visual sensors.")
);
}
// If the model has a non-negative memory size but requires a recurrent input
if (memory > 0)
{
if (!tensorsNames.Any(x => x.EndsWith("_h")) ||
!tensorsNames.Any(x => x.EndsWith("_c")))
{
failedModelChecks.Add(
FailedCheck.Warning("The model does not contain a Recurrent Input Node but has memory_size.")
);
}
}
// If the model uses discrete control but does not have an input for action masks
if (model.HasDiscreteOutputs())
{
if (!tensorsNames.Contains(TensorNames.ActionMaskPlaceholder))
{
failedModelChecks.Add(
FailedCheck.Warning("The model does not contain an Action Mask but is using Discrete Control.")
);
}
}
return failedModelChecks;
}
/// <summary>
/// Generates failed checks that correspond to inputs expected by the model that are not
/// present in the BrainParameters.
/// </summary>
/// <param name="model">
/// The Sentis engine model for loading static parameters
/// </param>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="memory">
/// The memory size that the model is expecting.
/// </param>
/// <param name="sensors">Array of attached sensor components</param>
/// <param name="deterministicInference"> Inference only: set to true if the action selection from model should be
/// Deterministic. </param>
/// <returns>
/// A IEnumerable of the checks that failed
/// </returns>
static IEnumerable<FailedCheck> CheckInputTensorPresence(
Model model,
BrainParameters brainParameters,
int memory,
ISensor[] sensors,
bool deterministicInference = false
)
{
var failedModelChecks = new List<FailedCheck>();
var tensorsNames = model.GetInputNames();
for (var sensorIndex = 0; sensorIndex < sensors.Length; sensorIndex++)
{
if (!tensorsNames.Contains(
TensorNames.GetObservationName(sensorIndex)))
{
var sensor = sensors[sensorIndex];
failedModelChecks.Add(
FailedCheck.Warning("The model does not contain an Observation Placeholder Input " +
$"for sensor component {sensorIndex} ({sensor.GetType().Name}).")
);
}
}
// If the model has a non-negative memory size but requires a recurrent input
if (memory > 0)
{
var modelVersion = model.GetVersion();
if (!tensorsNames.Any(x => x == TensorNames.RecurrentInPlaceholder))
{
failedModelChecks.Add(
FailedCheck.Warning("The model does not contain a Recurrent Input Node but has memory_size.")
);
}
}
// If the model uses discrete control but does not have an input for action masks
if (model.HasDiscreteOutputs(deterministicInference))
{
if (!tensorsNames.Contains(TensorNames.ActionMaskPlaceholder))
{
failedModelChecks.Add(
FailedCheck.Warning("The model does not contain an Action Mask but is using Discrete Control.")
);
}
}
return failedModelChecks;
}
/// <summary>
/// Generates failed checks that correspond to outputs expected by the model that are not
/// present in the BrainParameters.
/// </summary>
/// <param name="model">
/// The Sentis engine model for loading static parameters
/// </param>
/// <param name="memory">The memory size that the model is expecting/</param>
/// <param name="deterministicInference"> Inference only: set to true if the action selection from model should be
/// deterministic. </param>
/// <returns>
/// A IEnumerable of the checks that failed
/// </returns>
static IEnumerable<FailedCheck> CheckOutputTensorPresence(Model model, int memory, bool deterministicInference = false)
{
var failedModelChecks = new List<FailedCheck>();
// If there is no Recurrent Output but the model is Recurrent.
if (memory > 0)
{
var allOutputs = model.GetOutputNames(deterministicInference).ToList();
if (!allOutputs.Any(x => x == TensorNames.RecurrentOutput))
{
failedModelChecks.Add(
FailedCheck.Warning("The model does not contain a Recurrent Output Node but has memory_size.")
);
}
}
return failedModelChecks;
}
/// <summary>
/// Checks that the shape of the visual observation input placeholder is the same as the corresponding sensor.
/// </summary>
/// <param name="tensorProxy">The tensor that is expected by the model</param>
/// <param name="sensor">The sensor that produces the visual observation.</param>
/// <returns>
/// If the Check failed, returns a string containing information about why the
/// check failed. If the check passed, returns null.
/// </returns>
static FailedCheck CheckVisualObsShape(
TensorProxy tensorProxy, ISensor sensor)
{
var shape = sensor.GetObservationSpec().Shape;
var heightBp = shape[1];
var widthBp = shape[2];
var pixelBp = shape[0];
var heightT = tensorProxy.Height;
var widthT = tensorProxy.Width;
var pixelT = tensorProxy.Channels;
if ((widthBp != widthT) || (heightBp != heightT) || (pixelBp != pixelT))
{
return FailedCheck.Warning($"The visual Observation of the model does not match. " +
$"Received TensorProxy of shape [?x{widthBp}x{heightBp}x{pixelBp}] but " +
$"was expecting [?x{widthT}x{heightT}x{pixelT}] for the {sensor.GetName()} Sensor."
);
}
return null;
}
/// <summary>
/// Checks that the shape of the rank 2 observation input placeholder is the same as the corresponding sensor.
/// </summary>
/// <param name="tensorProxy">The tensor that is expected by the model</param>
/// <param name="sensor">The sensor that produces the visual observation.</param>
/// <returns>
/// If the Check failed, returns a string containing information about why the
/// check failed. If the check passed, returns null.
/// </returns>
static FailedCheck CheckRankTwoObsShape(
TensorProxy tensorProxy, ISensor sensor)
{
var shape = sensor.GetObservationSpec().Shape;
var dim1Bp = shape[0];
var dim2Bp = shape[1];
var dim1T = tensorProxy.Channels;
var dim2T = tensorProxy.Width;
var dim3T = tensorProxy.Height;
if ((dim1Bp != dim1T) || (dim2Bp != dim2T))
{
var proxyDimStr = $"[?x{dim1T}x{dim2T}]";
if (dim3T > 1)
{
proxyDimStr = $"[?x{dim3T}x{dim2T}x{dim1T}]";
}
return FailedCheck.Warning($"An Observation of the model does not match. " +
$"Received TensorProxy of shape [?x{dim1Bp}x{dim2Bp}] but " +
$"was expecting {proxyDimStr} for the {sensor.GetName()} Sensor."
);
}
return null;
}
/// <summary>
/// Checks that the shape of the rank 2 observation input placeholder is the same as the corresponding sensor.
/// </summary>
/// <param name="tensorProxy">The tensor that is expected by the model</param>
/// <param name="sensor">The sensor that produces the visual observation.</param>
/// <returns>
/// If the Check failed, returns a string containing information about why the
/// check failed. If the check passed, returns null.
/// </returns>
static FailedCheck CheckRankOneObsShape(
TensorProxy tensorProxy, ISensor sensor)
{
var shape = sensor.GetObservationSpec().Shape;
var dim1Bp = shape[0];
var dim1T = tensorProxy.Channels;
var dim2T = tensorProxy.Width;
var dim3T = tensorProxy.Height;
if ((dim1Bp != dim1T))
{
var proxyDimStr = $"[?x{dim1T}]";
if (dim2T > 1)
{
proxyDimStr = $"[?x{dim1T}x{dim2T}]";
}
if (dim3T > 1)
{
proxyDimStr = $"[?x{dim3T}x{dim2T}x{dim1T}]";
}
return FailedCheck.Warning($"An Observation of the model does not match. " +
$"Received TensorProxy of shape [?x{dim1Bp}] but " +
$"was expecting {proxyDimStr} for the {sensor.GetName()} Sensor."
);
}
return null;
}
/// <summary>
/// Generates failed checks that correspond to inputs shapes incompatibilities between
/// the model and the BrainParameters. Tests the models created with the API of version 1.X
/// </summary>
/// <param name="model">
/// The Sentis engine model for loading static parameters
/// </param>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="sensors">Attached sensors</param>
/// <param name="observableAttributeTotalSize">Sum of the sizes of all ObservableAttributes.</param>
/// <returns>A IEnumerable of the checks that failed</returns>
static IEnumerable<FailedCheck> CheckInputTensorShapeLegacy(
Model model, BrainParameters brainParameters, ISensor[] sensors,
int observableAttributeTotalSize)
{
var failedModelChecks = new List<FailedCheck>();
var tensorTester =
new Dictionary<string, Func<BrainParameters, TensorProxy, ISensor[], int, FailedCheck>>()
{
{TensorNames.VectorObservationPlaceholder, CheckVectorObsShapeLegacy},
{TensorNames.PreviousActionPlaceholder, CheckPreviousActionShape},
{TensorNames.RandomNormalEpsilonPlaceholder, ((bp, tensor, scs, i) => null)},
{TensorNames.ActionMaskPlaceholder, ((bp, tensor, scs, i) => null)},
{TensorNames.SequenceLengthPlaceholder, ((bp, tensor, scs, i) => null)},
{TensorNames.RecurrentInPlaceholder, ((bp, tensor, scs, i) => null)},
};
// foreach (var mem in model.memories)
// {
// tensorTester[mem.input] = ((bp, tensor, scs, i) => null);
// }
var visObsIndex = 0;
for (var sensorIndex = 0; sensorIndex < sensors.Length; sensorIndex++)
{
var sens = sensors[sensorIndex];
if (sens.GetObservationSpec().Shape.Length == 3)
{
tensorTester[TensorNames.GetVisualObservationName(visObsIndex)] =
(bp, tensor, scs, i) => CheckVisualObsShape(tensor, sens);
visObsIndex++;
}
if (sens.GetObservationSpec().Shape.Length == 2)
{
tensorTester[TensorNames.GetObservationName(sensorIndex)] =
(bp, tensor, scs, i) => CheckRankTwoObsShape(tensor, sens);
}
}
// If the model expects an input but it is not in this list
foreach (var tensor in model.GetInputTensors())
{
if (!tensorTester.ContainsKey(tensor.name))
{
if (!tensor.name.Contains("visual_observation"))
{
failedModelChecks.Add(
FailedCheck.Warning("Model contains an unexpected input named : " + tensor.name)
);
}
}
else
{
var tester = tensorTester[tensor.name];
var error = tester.Invoke(brainParameters, tensor, sensors, observableAttributeTotalSize);
if (error != null)
{
failedModelChecks.Add(error);
}
}
}
return failedModelChecks;
}
/// <summary>
/// Checks that the shape of the Vector Observation input placeholder is the same in the
/// model and in the Brain Parameters. Tests the models created with the API of version 1.X
/// </summary>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="tensorProxy">The tensor that is expected by the model</param>
/// <param name="sensors">Array of attached sensor components</param>
/// <param name="observableAttributeTotalSize">Sum of the sizes of all ObservableAttributes.</param>
/// <returns>
/// If the Check failed, returns a string containing information about why the
/// check failed. If the check passed, returns null.
/// </returns>
static FailedCheck CheckVectorObsShapeLegacy(
BrainParameters brainParameters, TensorProxy tensorProxy, ISensor[] sensors,
int observableAttributeTotalSize)
{
var vecObsSizeBp = brainParameters.VectorObservationSize;
var numStackedVector = brainParameters.NumStackedVectorObservations;
var totalVecObsSizeT = tensorProxy.shape[tensorProxy.shape.Length - 1];
var totalVectorSensorSize = 0;
foreach (var sens in sensors)
{
if ((sens.GetObservationSpec().Shape.Length == 1))
{
totalVectorSensorSize += sens.GetObservationSpec().Shape[0];
}
}
if (totalVectorSensorSize != totalVecObsSizeT)
{
var sensorSizes = "";
foreach (var sensorComp in sensors)
{
if (sensorComp.GetObservationSpec().Shape.Length == 1)
{
var vecSize = sensorComp.GetObservationSpec().Shape[0];
if (sensorSizes.Length == 0)
{
sensorSizes = $"[{vecSize}";
}
else
{
sensorSizes += $", {vecSize}";
}
}
}
sensorSizes += "]";
return FailedCheck.Warning(
$"Vector Observation Size of the model does not match. Was expecting {totalVecObsSizeT} " +
$"but received: \n" +
$"Vector observations: {vecObsSizeBp} x {numStackedVector}\n" +
$"Total [Observable] attributes: {observableAttributeTotalSize}\n" +
$"Sensor sizes: {sensorSizes}."
);
}
return null;
}
/// <summary>
/// Generates failed checks that correspond to inputs shapes incompatibilities between
/// the model and the BrainParameters.
/// </summary>
/// <param name="model">
/// The Sentis engine model for loading static parameters
/// </param>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="sensors">Attached sensors</param>
/// <param name="observableAttributeTotalSize">Sum of the sizes of all ObservableAttributes.</param>
/// <returns>A IEnumerable of the checks that failed</returns>
static IEnumerable<FailedCheck> CheckInputTensorShape(
Model model, BrainParameters brainParameters, ISensor[] sensors,
int observableAttributeTotalSize)
{
var failedModelChecks = new List<FailedCheck>();
var tensorTester =
new Dictionary<string, Func<BrainParameters, TensorProxy, ISensor[], int, FailedCheck>>()
{
{TensorNames.PreviousActionPlaceholder, CheckPreviousActionShape},
{TensorNames.RandomNormalEpsilonPlaceholder, ((bp, tensor, scs, i) => null)},
{TensorNames.ActionMaskPlaceholder, ((bp, tensor, scs, i) => null)},
{TensorNames.SequenceLengthPlaceholder, ((bp, tensor, scs, i) => null)},
{TensorNames.RecurrentInPlaceholder, ((bp, tensor, scs, i) => null)},
};
// foreach (var mem in model.memories)
// {
// tensorTester[mem.input] = ((bp, tensor, scs, i) => null);
// }
for (var sensorIndex = 0; sensorIndex < sensors.Length; sensorIndex++)
{
var sens = sensors[sensorIndex];
if (sens.GetObservationSpec().Rank == 3)
{
tensorTester[TensorNames.GetObservationName(sensorIndex)] =
(bp, tensor, scs, i) => CheckVisualObsShape(tensor, sens);
}
if (sens.GetObservationSpec().Rank == 2)
{
tensorTester[TensorNames.GetObservationName(sensorIndex)] =
(bp, tensor, scs, i) => CheckRankTwoObsShape(tensor, sens);
}
if (sens.GetObservationSpec().Rank == 1)
{
tensorTester[TensorNames.GetObservationName(sensorIndex)] =
(bp, tensor, scs, i) => CheckRankOneObsShape(tensor, sens);
}
}
// If the model expects an input but it is not in this list
foreach (var tensor in model.GetInputTensors())
{
if (!tensorTester.ContainsKey(tensor.name))
{
failedModelChecks.Add(FailedCheck.Warning("Model contains an unexpected input named : " + tensor.name
));
}
else
{
var tester = tensorTester[tensor.name];
var error = tester.Invoke(brainParameters, tensor, sensors, observableAttributeTotalSize);
if (error != null)
{
failedModelChecks.Add(error);
}
}
}
return failedModelChecks;
}
/// <summary>
/// Checks that the shape of the Previous Vector Action input placeholder is the same in the
/// model and in the Brain Parameters.
/// </summary>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="tensorProxy"> The tensor that is expected by the model</param>
/// <param name="sensors">Array of attached sensor components (unused).</param>
/// <param name="observableAttributeTotalSize">Sum of the sizes of all ObservableAttributes (unused).</param>
/// <returns>If the Check failed, returns a string containing information about why the
/// check failed. If the check passed, returns null.</returns>
static FailedCheck CheckPreviousActionShape(
BrainParameters brainParameters, TensorProxy tensorProxy,
ISensor[] sensors, int observableAttributeTotalSize)
{
var numberActionsBp = brainParameters.ActionSpec.NumDiscreteActions;
var numberActionsT = tensorProxy.shape[tensorProxy.shape.Length - 1];
if (numberActionsBp != numberActionsT)
{
return FailedCheck.Warning("Previous Action Size of the model does not match. " +
$"Received {numberActionsBp} but was expecting {numberActionsT}."
);
}
return null;
}
/// <summary>
/// Generates failed checks that correspond to output shapes incompatibilities between
/// the model and the BrainParameters.
/// </summary>
/// <param name="model">
/// The Sentis engine model for loading static parameters
/// </param>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="actuatorComponents">Array of attached actuator components.</param>
/// <returns>
/// A IEnumerable of error messages corresponding to the incompatible shapes between model
/// and BrainParameters.
/// </returns>
static IEnumerable<FailedCheck> CheckOutputTensorShape(
Model model,
BrainParameters brainParameters,
ActuatorComponent[] actuatorComponents)
{
var failedModelChecks = new List<FailedCheck>();
// If the model expects an output but it is not in this list
var modelContinuousActionSize = model.ContinuousOutputSize();
var continuousError = CheckContinuousActionOutputShape(brainParameters, actuatorComponents, modelContinuousActionSize);
if (continuousError != null)
{
failedModelChecks.Add(continuousError);
}
FailedCheck discreteError = null;
var modelApiVersion = model.GetVersion();
if (modelApiVersion == (int)ModelApiVersion.MLAgents1_0)
{
var modelSumDiscreteBranchSizes = model.DiscreteOutputSize();
discreteError = CheckDiscreteActionOutputShapeLegacy(brainParameters, actuatorComponents, modelSumDiscreteBranchSizes);
}
if (modelApiVersion == (int)ModelApiVersion.MLAgents2_0)
{
var modelDiscreteBranches = (TensorFloat)model.GetTensorByName(TensorNames.DiscreteActionOutputShape);
discreteError = CheckDiscreteActionOutputShape(brainParameters, actuatorComponents, modelDiscreteBranches);
}
if (discreteError != null)
{
failedModelChecks.Add(discreteError);
}
return failedModelChecks;
}
/// <summary>
/// Checks that the shape of the discrete action output is the same in the
/// model and in the Brain Parameters.
/// </summary>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="actuatorComponents">Array of attached actuator components.</param>
/// <param name="modelDiscreteBranches"> The Tensor of branch sizes.
/// </param>
/// <returns>
/// If the Check failed, returns a string containing information about why the
/// check failed. If the check passed, returns null.
/// </returns>
static FailedCheck CheckDiscreteActionOutputShape(
BrainParameters brainParameters, ActuatorComponent[] actuatorComponents, TensorFloat modelDiscreteBranches)
{
var discreteActionBranches = brainParameters.ActionSpec.BranchSizes.ToList();
foreach (var actuatorComponent in actuatorComponents)
{
var actionSpec = actuatorComponent.ActionSpec;
discreteActionBranches.AddRange(actionSpec.BranchSizes);
}
int modelDiscreteBranchesLength = modelDiscreteBranches?.shape.length ?? 0;
if (modelDiscreteBranchesLength != discreteActionBranches.Count)
{
return FailedCheck.Warning("Discrete Action Size of the model does not match. The BrainParameters expect " +
$"{discreteActionBranches.Count} branches but the model contains {modelDiscreteBranchesLength}."
);
}
for (int i = 0; i < modelDiscreteBranchesLength; i++)
{
if (modelDiscreteBranches != null && modelDiscreteBranches[i] != discreteActionBranches[i])
{
return FailedCheck.Warning($"The number of Discrete Actions of branch {i} does not match. " +
$"Was expecting {discreteActionBranches[i]} but the model contains {modelDiscreteBranches[i]} "
);
}
}
return null;
}
/// <summary>
/// Checks that the shape of the discrete action output is the same in the
/// model and in the Brain Parameters. Tests the models created with the API of version 1.X
/// </summary>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="actuatorComponents">Array of attached actuator components.</param>
/// <param name="modelSumDiscreteBranchSizes">
/// The size of the discrete action output that is expected by the model.
/// </param>
/// <returns>
/// If the Check failed, returns a string containing information about why the
/// check failed. If the check passed, returns null.
/// </returns>
static FailedCheck CheckDiscreteActionOutputShapeLegacy(
BrainParameters brainParameters, ActuatorComponent[] actuatorComponents, int modelSumDiscreteBranchSizes)
{
// TODO: check each branch size instead of sum of branch sizes
var sumOfDiscreteBranchSizes = brainParameters.ActionSpec.SumOfDiscreteBranchSizes;
foreach (var actuatorComponent in actuatorComponents)
{
var actionSpec = actuatorComponent.ActionSpec;
sumOfDiscreteBranchSizes += actionSpec.SumOfDiscreteBranchSizes;
}
if (modelSumDiscreteBranchSizes != sumOfDiscreteBranchSizes)
{
return FailedCheck.Warning("Discrete Action Size of the model does not match. The BrainParameters expect " +
$"{sumOfDiscreteBranchSizes} but the model contains {modelSumDiscreteBranchSizes}."
);
}
return null;
}
/// <summary>
/// Checks that the shape of the continuous action output is the same in the
/// model and in the Brain Parameters.
/// </summary>
/// <param name="brainParameters">
/// The BrainParameters that are used verify the compatibility with the InferenceEngine
/// </param>
/// <param name="actuatorComponents">Array of attached actuator components.</param>
/// <param name="modelContinuousActionSize">
/// The size of the continuous action output that is expected by the model.
/// </param>
/// <returns>If the Check failed, returns a string containing information about why the
/// check failed. If the check passed, returns null.</returns>
static FailedCheck CheckContinuousActionOutputShape(
BrainParameters brainParameters, ActuatorComponent[] actuatorComponents, int modelContinuousActionSize)
{
var numContinuousActions = brainParameters.ActionSpec.NumContinuousActions;
foreach (var actuatorComponent in actuatorComponents)
{
var actionSpec = actuatorComponent.ActionSpec;
numContinuousActions += actionSpec.NumContinuousActions;
}
if (modelContinuousActionSize != numContinuousActions)
{
return FailedCheck.Warning(
"Continuous Action Size of the model does not match. The BrainParameters and ActuatorComponents expect " +
$"{numContinuousActions} but the model contains {modelContinuousActionSize}."
);
}
return null;
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Inference/SentisModelParamLoader.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Inference/SentisModelParamLoader.cs",
"repo_id": "ml-agents",
"token_count": 18855
} | 1,838 |
fileFormatVersion: 2
guid: 5c9e297dad748408db9e5ce26b940fe3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Runtime/Inference/Utils/Multinomial.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Inference/Utils/Multinomial.cs.meta",
"repo_id": "ml-agents",
"token_count": 93
} | 1,839 |
fileFormatVersion: 2
guid: 530d2f105aa145bd8a00e021bdd925fd
timeCreated: 1600906676 | ml-agents/com.unity.ml-agents/Runtime/Integrations/Match3/Match3SensorComponent.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Integrations/Match3/Match3SensorComponent.cs.meta",
"repo_id": "ml-agents",
"token_count": 37
} | 1,840 |
using System;
using System.Collections.Generic;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
namespace Unity.MLAgents.Policies
{
/// <summary>
/// IPolicy is connected to a single Agent. Each time the agent needs
/// a decision, it will request a decision to the Policy. The decision
/// will not be taken immediately but will be taken before or when
/// DecideAction is called.
/// </summary>
internal interface IPolicy : IDisposable
{
/// <summary>
/// Signals the Brain that the Agent needs a Decision. The Policy
/// will make the decision at a later time to allow possible
/// batching of requests.
/// </summary>
/// <param name="info"></param>
/// <param name="sensors"></param>
void RequestDecision(AgentInfo info, List<ISensor> sensors);
/// <summary>
/// Signals the Policy that if the Decision has not been taken yet,
/// it must be taken now. The Brain is expected to update the actions
/// of the Agents at this point the latest.
/// </summary>
ref readonly ActionBuffers DecideAction();
}
}
| ml-agents/com.unity.ml-agents/Runtime/Policies/IPolicy.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Policies/IPolicy.cs",
"repo_id": "ml-agents",
"token_count": 405
} | 1,841 |
fileFormatVersion: 2
guid: 87820d9eb927c4fa483dff9289d983f1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Runtime/Sensors/IGridPerception.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/IGridPerception.cs.meta",
"repo_id": "ml-agents",
"token_count": 96
} | 1,842 |
fileFormatVersion: 2
guid: 45243967d8c0419b953c02bccb7c2768
timeCreated: 1573087062 | ml-agents/com.unity.ml-agents/Runtime/Sensors/RayPerceptionSensorComponentBase.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/RayPerceptionSensorComponentBase.cs.meta",
"repo_id": "ml-agents",
"token_count": 40
} | 1,843 |
namespace Unity.MLAgents.Sensors.Reflection
{
/// <summary>
/// Sensor that wraps a Vector2 field or property of an object, and returns
/// that as an observation.
/// </summary>
internal class Vector2ReflectionSensor : ReflectionSensorBase
{
public Vector2ReflectionSensor(ReflectionSensorInfo reflectionSensorInfo)
: base(reflectionSensorInfo, 2)
{ }
internal override void WriteReflectedField(ObservationWriter writer)
{
var vecVal = (UnityEngine.Vector2)GetReflectedValue();
writer[0] = vecVal.x;
writer[1] = vecVal.y;
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Sensors/Reflection/Vector2ReflectionSensor.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/Reflection/Vector2ReflectionSensor.cs",
"repo_id": "ml-agents",
"token_count": 257
} | 1,844 |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using UnityEngine;
namespace Unity.MLAgents.Sensors
{
/// <summary>
/// A sensor implementation for vector observations.
/// </summary>
public class VectorSensor : ISensor, IBuiltInSensor
{
// TODO use float[] instead
// TODO allow setting float[]
List<float> m_Observations;
ObservationSpec m_ObservationSpec;
string m_Name;
/// <summary>
/// Initializes the sensor.
/// </summary>
/// <param name="observationSize">Number of vector observations.</param>
/// <param name="name">Name of the sensor.</param>
/// <param name="observationType"></param>
public VectorSensor(int observationSize, string name = null, ObservationType observationType = ObservationType.Default)
{
if (string.IsNullOrEmpty(name))
{
name = $"VectorSensor_size{observationSize}";
if (observationType != ObservationType.Default)
{
name += $"_{observationType.ToString()}";
}
}
m_Observations = new List<float>(observationSize);
m_Name = name;
m_ObservationSpec = ObservationSpec.Vector(observationSize, observationType);
}
/// <inheritdoc/>
public int Write(ObservationWriter writer)
{
var expectedObservations = m_ObservationSpec.Shape[0];
if (m_Observations.Count > expectedObservations)
{
// Too many observations, truncate
Debug.LogWarningFormat(
"More observations ({0}) made than vector observation size ({1}). The observations will be truncated.",
m_Observations.Count, expectedObservations
);
m_Observations.RemoveRange(expectedObservations, m_Observations.Count - expectedObservations);
}
else if (m_Observations.Count < expectedObservations)
{
// Not enough observations; pad with zeros.
Debug.LogWarningFormat(
"Fewer observations ({0}) made than vector observation size ({1}). The observations will be padded.",
m_Observations.Count, expectedObservations
);
for (int i = m_Observations.Count; i < expectedObservations; i++)
{
m_Observations.Add(0);
}
}
writer.AddList(m_Observations);
return expectedObservations;
}
/// <summary>
/// Returns a read-only view of the observations that added.
/// </summary>
/// <returns>A read-only view of the observations list.</returns>
internal ReadOnlyCollection<float> GetObservations()
{
return m_Observations.AsReadOnly();
}
/// <inheritdoc/>
public void Update()
{
Clear();
}
/// <inheritdoc/>
public void Reset()
{
Clear();
}
/// <inheritdoc/>
public ObservationSpec GetObservationSpec()
{
return m_ObservationSpec;
}
/// <inheritdoc/>
public string GetName()
{
return m_Name;
}
/// <inheritdoc/>
public virtual byte[] GetCompressedObservation()
{
return null;
}
/// <inheritdoc/>
public CompressionSpec GetCompressionSpec()
{
return CompressionSpec.Default();
}
/// <inheritdoc/>
public BuiltInSensorType GetBuiltInSensorType()
{
return BuiltInSensorType.VectorSensor;
}
void Clear()
{
m_Observations.Clear();
}
void AddFloatObs(float obs)
{
Utilities.DebugCheckNanAndInfinity(obs, nameof(obs), nameof(AddFloatObs));
m_Observations.Add(obs);
}
// Compatibility methods with Agent observation. These should be removed eventually.
/// <summary>
/// Adds a float observation to the vector observations of the agent.
/// </summary>
/// <param name="observation">Observation.</param>
public void AddObservation(float observation)
{
AddFloatObs(observation);
}
/// <summary>
/// Adds an integer observation to the vector observations of the agent.
/// </summary>
/// <param name="observation">Observation.</param>
public void AddObservation(int observation)
{
AddFloatObs(observation);
}
/// <summary>
/// Adds an Vector3 observation to the vector observations of the agent.
/// </summary>
/// <param name="observation">Observation.</param>
public void AddObservation(Vector3 observation)
{
AddFloatObs(observation.x);
AddFloatObs(observation.y);
AddFloatObs(observation.z);
}
/// <summary>
/// Adds an Vector2 observation to the vector observations of the agent.
/// </summary>
/// <param name="observation">Observation.</param>
public void AddObservation(Vector2 observation)
{
AddFloatObs(observation.x);
AddFloatObs(observation.y);
}
/// <summary>
/// Adds a list or array of float observations to the vector observations of the agent.
/// </summary>
/// <param name="observation">Observation.</param>
public void AddObservation(IList<float> observation)
{
for (var i = 0; i < observation.Count; i++)
{
AddFloatObs(observation[i]);
}
}
/// <summary>
/// Adds a quaternion observation to the vector observations of the agent.
/// </summary>
/// <param name="observation">Observation.</param>
public void AddObservation(Quaternion observation)
{
AddFloatObs(observation.x);
AddFloatObs(observation.y);
AddFloatObs(observation.z);
AddFloatObs(observation.w);
}
/// <summary>
/// Adds a boolean observation to the vector observation of the agent.
/// </summary>
/// <param name="observation">Observation.</param>
public void AddObservation(bool observation)
{
AddFloatObs(observation ? 1f : 0f);
}
/// <summary>
/// Adds a one-hot encoding observation.
/// </summary>
/// <param name="observation">The index of this observation.</param>
/// <param name="range">The upper limit on the value observation can take (exclusive).</param>
public void AddOneHotObservation(int observation, int range)
{
for (var i = 0; i < range; i++)
{
AddFloatObs(i == observation ? 1.0f : 0.0f);
}
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Sensors/VectorSensor.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/VectorSensor.cs",
"repo_id": "ml-agents",
"token_count": 3277
} | 1,845 |
fileFormatVersion: 2
guid: 85e0054f8e64b47309646d35f8851f81
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Runtime/Unity.ML-Agents.asmdef.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Unity.ML-Agents.asmdef.meta",
"repo_id": "ml-agents",
"token_count": 65
} | 1,846 |
using System;
using NUnit.Framework;
using Unity.MLAgents.Actuators;
namespace Unity.MLAgents.Tests.Actuators
{
[TestFixture]
public class ActionSegmentTests
{
[Test]
public void TestConstruction()
{
var floatArray = new[] { 1f, 2f, 3f, 4f, 5f, 6f, 7f };
Assert.Throws<ArgumentOutOfRangeException>(
() => new ActionSegment<float>(floatArray, 100, 1));
var segment = new ActionSegment<float>(Array.Empty<float>(), 0, 0);
Assert.AreEqual(segment, ActionSegment<float>.Empty);
}
[Test]
public void TestIndexing()
{
var floatArray = new[] { 1f, 2f, 3f, 4f, 5f, 6f, 7f };
for (var i = 0; i < floatArray.Length; i++)
{
var start = 0 + i;
var length = floatArray.Length - i;
var actionSegment = new ActionSegment<float>(floatArray, start, length);
for (var j = 0; j < actionSegment.Length; j++)
{
Assert.AreEqual(actionSegment[j], floatArray[start + j]);
}
}
}
[Test]
public void TestEnumerator()
{
var floatArray = new[] { 1f, 2f, 3f, 4f, 5f, 6f, 7f };
for (var i = 0; i < floatArray.Length; i++)
{
var start = 0 + i;
var length = floatArray.Length - i;
var actionSegment = new ActionSegment<float>(floatArray, start, length);
var j = 0;
foreach (var item in actionSegment)
{
Assert.AreEqual(item, floatArray[start + j++]);
}
}
}
[Test]
public void TestNullConstructor()
{
var actionSegment = new ActionSegment<float>(null);
Assert.IsTrue(actionSegment.Length == 0);
Assert.IsTrue(actionSegment.Array == Array.Empty<float>());
}
}
}
| ml-agents/com.unity.ml-agents/Tests/Editor/Actuators/ActionSegmentTests.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Actuators/ActionSegmentTests.cs",
"repo_id": "ml-agents",
"token_count": 1071
} | 1,847 |
fileFormatVersion: 2
guid: 70b8f1544bc34b4e8f1bc1068c64f01c
timeCreated: 1610419546 | ml-agents/com.unity.ml-agents/Tests/Editor/Analytics/TrainingAnalyticsTest.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Analytics/TrainingAnalyticsTest.cs.meta",
"repo_id": "ml-agents",
"token_count": 42
} | 1,848 |
using System.Collections.Generic;
using Unity.Sentis;
using NUnit.Framework;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Inference;
namespace Unity.MLAgents.Tests
{
public class DiscreteActionOutputApplierTest
{
[Test]
public void TestDiscreteApply()
{
var actionSpec = ActionSpec.MakeDiscrete(3, 2);
var applier = new DiscreteActionOutputApplier(actionSpec, 2020, null);
var agentIds = new List<int> { 42, 1337 };
var actionBuffers = new Dictionary<int, ActionBuffers>();
actionBuffers[42] = new ActionBuffers(actionSpec);
actionBuffers[1337] = new ActionBuffers(actionSpec);
var actionTensor = new TensorProxy
{
data = new TensorInt(
new TensorShape(2, 2),
new[]
{
2, // Agent 0, branch 0
1, // Agent 0, branch 1
0, // Agent 1, branch 0
0 // Agent 1, branch 1
}),
shape = new long[] { 2, 2 },
valueType = TensorProxy.TensorType.Integer
};
applier.Apply(actionTensor, agentIds, actionBuffers);
Assert.AreEqual(2, actionBuffers[42].DiscreteActions[0]);
Assert.AreEqual(1, actionBuffers[42].DiscreteActions[1]);
Assert.AreEqual(0, actionBuffers[1337].DiscreteActions[0]);
Assert.AreEqual(0, actionBuffers[1337].DiscreteActions[1]);
}
}
public class LegacyDiscreteActionOutputApplierTest
{
[Test]
public void TestDiscreteApply()
{
var actionSpec = ActionSpec.MakeDiscrete(3, 2);
const float smallLogProb = -1000.0f;
const float largeLogProb = -1.0f;
var logProbs = new TensorProxy
{
data = new TensorFloat(
new TensorShape(2, 5),
new[]
{
smallLogProb, smallLogProb, largeLogProb, // Agent 0, branch 0
smallLogProb, largeLogProb, // Agent 0, branch 1
largeLogProb, smallLogProb, smallLogProb, // Agent 1, branch 0
largeLogProb, smallLogProb, // Agent 1, branch 1
}),
valueType = TensorProxy.TensorType.FloatingPoint
};
var applier = new LegacyDiscreteActionOutputApplier(actionSpec, 2020, null);
var agentIds = new List<int> { 42, 1337 };
var actionBuffers = new Dictionary<int, ActionBuffers>();
actionBuffers[42] = new ActionBuffers(actionSpec);
actionBuffers[1337] = new ActionBuffers(actionSpec);
applier.Apply(logProbs, agentIds, actionBuffers);
Assert.AreEqual(2, actionBuffers[42].DiscreteActions[0]);
Assert.AreEqual(1, actionBuffers[42].DiscreteActions[1]);
Assert.AreEqual(0, actionBuffers[1337].DiscreteActions[0]);
Assert.AreEqual(0, actionBuffers[1337].DiscreteActions[1]);
}
}
}
| ml-agents/com.unity.ml-agents/Tests/Editor/Inference/DiscreteActionOutputApplierTest.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Inference/DiscreteActionOutputApplierTest.cs",
"repo_id": "ml-agents",
"token_count": 1657
} | 1,849 |
using System;
using System.Collections.Generic;
using UnityEngine;
using NUnit.Framework;
using Unity.MLAgents.Integrations.Match3;
namespace Unity.MLAgents.Tests.Integrations.Match3
{
internal class StringBoard : AbstractBoard
{
internal int MaxRows;
internal int MaxColumns;
internal int NumCellTypes;
internal int NumSpecialTypes;
public int CurrentRows;
public int CurrentColumns;
public override BoardSize GetMaxBoardSize()
{
return new BoardSize
{
Rows = MaxRows,
Columns = MaxColumns,
NumCellTypes = NumCellTypes,
NumSpecialTypes = NumSpecialTypes
};
}
public override BoardSize GetCurrentBoardSize()
{
return new BoardSize
{
Rows = CurrentRows,
Columns = CurrentColumns,
NumCellTypes = NumCellTypes,
NumSpecialTypes = NumSpecialTypes
};
}
private string[] m_Board;
private string[] m_Special;
/// <summary>
/// Convert a string like "000\n010\n000" to a board representation
/// Row 0 is considered the bottom row
/// </summary>
/// <param name="newBoard"></param>
public void SetBoard(string newBoard)
{
m_Board = newBoard.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
MaxRows = m_Board.Length;
MaxColumns = m_Board[0].Length;
CurrentRows = MaxRows;
CurrentColumns = MaxColumns;
NumCellTypes = 0;
for (var r = 0; r < MaxRows; r++)
{
for (var c = 0; c < MaxColumns; c++)
{
NumCellTypes = Mathf.Max(NumCellTypes, 1 + GetCellType(r, c));
}
}
}
public void SetSpecial(string newSpecial)
{
m_Special = newSpecial.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
Debug.Assert(MaxRows == m_Special.Length);
Debug.Assert(MaxColumns == m_Special[0].Length);
NumSpecialTypes = 0;
for (var r = 0; r < MaxRows; r++)
{
for (var c = 0; c < MaxColumns; c++)
{
NumSpecialTypes = Mathf.Max(NumSpecialTypes, GetSpecialType(r, c));
}
}
}
public override bool MakeMove(Move m)
{
return true;
}
public override bool IsMoveValid(Move m)
{
return SimpleIsMoveValid(m);
}
public override int GetCellType(int row, int col)
{
if (row >= CurrentRows || col >= CurrentColumns)
{
throw new IndexOutOfRangeException("Tried to get celltype out of bounds");
}
var character = m_Board[m_Board.Length - 1 - row][col];
return (character - '0');
}
public override int GetSpecialType(int row, int col)
{
if (row >= CurrentRows || col >= CurrentColumns)
{
throw new IndexOutOfRangeException("Tried to get specialtype out of bounds");
}
var character = m_Special[m_Board.Length - 1 - row][col];
return (character - '0');
}
}
public class AbstractBoardTests
{
[Test]
public void TestBoardInit()
{
var boardString =
@"000
000
010";
var gameObj = new GameObject("board");
var board = gameObj.AddComponent<StringBoard>();
board.SetBoard(boardString);
var boardSize = board.GetMaxBoardSize();
Assert.AreEqual(3, boardSize.Rows);
Assert.AreEqual(3, boardSize.Columns);
Assert.AreEqual(2, boardSize.NumCellTypes);
for (var r = 0; r < 3; r++)
{
for (var c = 0; c < 3; c++)
{
var expected = (r == 0 && c == 1) ? 1 : 0;
Assert.AreEqual(expected, board.GetCellType(r, c));
}
}
}
internal static List<Move> GetValidMoves4x4(bool fullBoard, BoardSize boardSize)
{
var validMoves = new List<Move>
{
Move.FromPositionAndDirection(2, 1, Direction.Down, boardSize), // equivalent to (1, 1, Up)
Move.FromPositionAndDirection(1, 1, Direction.Down, boardSize),
Move.FromPositionAndDirection(1, 1, Direction.Left, boardSize),
Move.FromPositionAndDirection(1, 1, Direction.Right, boardSize),
Move.FromPositionAndDirection(0, 1, Direction.Left, boardSize),
};
if (fullBoard)
{
// This would move out of range on the small board
// Equivalent to (3, 1, Down)
validMoves.Add(Move.FromPositionAndDirection(2, 1, Direction.Up, boardSize));
// These moves require matching with a cell that's off the small board, so they're invalid
// (even though the move itself doesn't go out of range).
validMoves.Add(Move.FromPositionAndDirection(2, 1, Direction.Left, boardSize)); // Equivalent to (2, 0, Right)
validMoves.Add(Move.FromPositionAndDirection(2, 1, Direction.Right, boardSize));
}
return validMoves;
}
[TestCase(true, TestName = "Full Board")]
[TestCase(false, TestName = "Small Board")]
public void TestCheckValidMoves(bool fullBoard)
{
var gameObj = new GameObject("board");
var board = gameObj.AddComponent<StringBoard>();
var boardString =
@"0105
1024
0203
2022";
board.SetBoard(boardString);
var boardSize = board.GetMaxBoardSize();
if (!fullBoard)
{
board.CurrentRows -= 1;
}
var validMoves = GetValidMoves4x4(fullBoard, boardSize);
foreach (var m in validMoves)
{
Assert.IsTrue(board.IsMoveValid(m));
}
// Run through all moves and make sure those are the only valid ones
HashSet<int> validIndices = new HashSet<int>();
foreach (var m in validMoves)
{
validIndices.Add(m.MoveIndex);
}
// Make sure iterating over AllMoves is OK with the smaller board
foreach (var move in board.AllMoves())
{
var expected = validIndices.Contains(move.MoveIndex);
Assert.AreEqual(expected, board.IsMoveValid(move), $"({move.Row}, {move.Column}, {move.Direction})");
}
HashSet<int> validIndicesFromIterator = new HashSet<int>();
foreach (var move in board.ValidMoves())
{
validIndicesFromIterator.Add(move.MoveIndex);
}
Assert.IsTrue(validIndices.SetEquals(validIndicesFromIterator));
}
}
}
| ml-agents/com.unity.ml-agents/Tests/Editor/Integrations/Match3/AbstractBoardTests.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Integrations/Match3/AbstractBoardTests.cs",
"repo_id": "ml-agents",
"token_count": 3653
} | 1,850 |
fileFormatVersion: 2
guid: df271cac120e4d6893b14599fa8eb64d
timeCreated: 1617813392 | ml-agents/com.unity.ml-agents/Tests/Editor/Policies.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Policies.meta",
"repo_id": "ml-agents",
"token_count": 38
} | 1,851 |
fileFormatVersion: 2
guid: c2a71036ddec4ba4bf83c5e8ba1b8daa
timeCreated: 1610574895 | ml-agents/com.unity.ml-agents/Tests/Editor/TrainingAnalyticsSideChannelTests.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/TrainingAnalyticsSideChannelTests.cs.meta",
"repo_id": "ml-agents",
"token_count": 43
} | 1,852 |
behaviors:
Crawler:
trainer_type: ppo
hyperparameters:
batch_size: 2024
buffer_size: 20240
learning_rate: 0.0003
beta: 0.005
epsilon: 0.2
lambd: 0.95
num_epoch: 3
learning_rate_schedule: linear
network_settings:
normalize: true
hidden_units: 512
num_layers: 3
vis_encode_type: simple
reward_signals:
gail:
gamma: 0.99
strength: 1.0
network_settings:
normalize: true
hidden_units: 128
num_layers: 2
vis_encode_type: simple
learning_rate: 0.0003
use_actions: false
use_vail: false
demo_path: Project/Assets/ML-Agents/Examples/Crawler/Demos/ExpertCrawler.demo
keep_checkpoints: 5
max_steps: 10000000
time_horizon: 1000
summary_freq: 30000
behavioral_cloning:
demo_path: Project/Assets/ML-Agents/Examples/Crawler/Demos/ExpertCrawler.demo
steps: 50000
strength: 0.5
samples_per_update: 0
| ml-agents/config/imitation/Crawler.yaml/0 | {
"file_path": "ml-agents/config/imitation/Crawler.yaml",
"repo_id": "ml-agents",
"token_count": 500
} | 1,853 |
default_settings:
trainer_type: ppo
hyperparameters:
batch_size: 16
buffer_size: 120
learning_rate: 0.0003
beta: 0.005
epsilon: 0.2
lambd: 0.99
num_epoch: 3
learning_rate_schedule: constant
network_settings:
normalize: true
hidden_units: 256
num_layers: 4
vis_encode_type: match3
reward_signals:
extrinsic:
gamma: 0.99
strength: 1.0
keep_checkpoints: 5
max_steps: 5000000
time_horizon: 128
summary_freq: 10000
behaviors:
Match3SimpleHeuristic:
# Settings can be very simple since we don't care about actually training the model
trainer_type: ppo
hyperparameters:
batch_size: 16
buffer_size: 120
network_settings:
hidden_units: 4
num_layers: 1
max_steps: 5000000
summary_freq: 10000
Match3SmartHeuristic:
# Settings can be very simple since we don't care about actually training the model
trainer_type: ppo
hyperparameters:
batch_size: 16
buffer_size: 120
network_settings:
hidden_units: 4
num_layers: 1
max_steps: 5000000
summary_freq: 10000
| ml-agents/config/ppo/Match3.yaml/0 | {
"file_path": "ml-agents/config/ppo/Match3.yaml",
"repo_id": "ml-agents",
"token_count": 460
} | 1,854 |
behaviors:
GridWorld:
trainer_type: sac
hyperparameters:
learning_rate: 0.0003
learning_rate_schedule: constant
batch_size: 128
buffer_size: 50000
buffer_init_steps: 1000
tau: 0.005
steps_per_update: 10.0
save_replay_buffer: false
init_entcoef: 0.5
reward_signal_steps_per_update: 10.0
network_settings:
normalize: false
hidden_units: 128
num_layers: 1
vis_encode_type: simple
reward_signals:
extrinsic:
gamma: 0.9
strength: 1.0
keep_checkpoints: 5
max_steps: 500000
time_horizon: 5
summary_freq: 20000
| ml-agents/config/sac/GridWorld.yaml/0 | {
"file_path": "ml-agents/config/sac/GridWorld.yaml",
"repo_id": "ml-agents",
"token_count": 308
} | 1,855 |
# Frequently Asked Questions
## Installation problems
## Environment Permission Error
If you directly import your Unity environment without building it in the editor,
you might need to give it additional permissions to execute it.
If you receive such a permission error on macOS, run:
```sh
chmod -R 755 *.app
```
or on Linux:
```sh
chmod -R 755 *.x86_64
```
On Windows, you can find
[instructions](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc754344(v=ws.11)).
## Environment Connection Timeout
If you are able to launch the environment from `UnityEnvironment` but then
receive a timeout error like this:
```
UnityAgentsException: The Communicator was unable to connect. Please make sure the External process is ready to accept communication with Unity.
```
There may be a number of possible causes:
- _Cause_: There may be no agent in the scene
- _Cause_: On OSX, the firewall may be preventing communication with the
environment. _Solution_: Add the built environment binary to the list of
exceptions on the firewall by following
[instructions](https://support.apple.com/en-us/HT201642).
- _Cause_: An error happened in the Unity Environment preventing communication.
_Solution_: Look into the
[log files](https://docs.unity3d.com/Manual/LogFiles.html) generated by the
Unity Environment to figure what error happened.
- _Cause_: You have assigned `HTTP_PROXY` and `HTTPS_PROXY` values in your
environment variables. _Solution_: Remove these values and try again.
- _Cause_: You are running in a headless environment (e.g. remotely connected
to a server). _Solution_: Pass `--no-graphics` to `mlagents-learn`, or
`no_graphics=True` to `RemoteRegistryEntry.make()` or the `UnityEnvironment`
initializer. If you need graphics for visual observations, you will need to
set up `xvfb` (or equivalent).
## Communication port {} still in use
If you receive an exception
`"Couldn't launch new environment because communication port {} is still in use. "`,
you can change the worker number in the Python script when calling
```python
UnityEnvironment(file_name=filename, worker_id=X)
```
## Mean reward : nan
If you receive a message `Mean reward : nan` when attempting to train a model
using PPO, this is due to the episodes of the Learning Environment not
terminating. In order to address this, set `Max Steps` for the Agents within the
Scene Inspector to a value greater than 0. Alternatively, it is possible to
manually set `done` conditions for episodes from within scripts for custom
episode-terminating events.
## "File name" cannot be opened because the developer cannot be verified.
If you have downloaded the repository using the github website on macOS 10.15 (Catalina)
or later, you may see this error when attempting to play scenes in the Unity project.
Workarounds include installing the package using the Unity Package Manager (this is
the officially supported approach - see [here](Installation.md)), or following the
instructions [here](https://support.apple.com/en-us/HT202491) to verify the relevant
files on your machine on a file-by-file basis.
| ml-agents/docs/FAQ.md/0 | {
"file_path": "ml-agents/docs/FAQ.md",
"repo_id": "ml-agents",
"token_count": 838
} | 1,856 |
# ML-Agents Toolkit Overview
**Table of Contents**
- [Running Example: Training NPC Behaviors](#running-example-training-npc-behaviors)
- [Key Components](#key-components)
- [Training Modes](#training-modes)
- [Built-in Training and Inference](#built-in-training-and-inference)
- [Cross-Platform Inference](#cross-platform-inference)
- [Custom Training and Inference](#custom-training-and-inference)
- [Flexible Training Scenarios](#flexible-training-scenarios)
- [Training Methods: Environment-agnostic](#training-methods-environment-agnostic)
- [A Quick Note on Reward Signals](#a-quick-note-on-reward-signals)
- [Deep Reinforcement Learning](#deep-reinforcement-learning)
- [Curiosity for Sparse-reward Environments](#curiosity-for-sparse-reward-environments)
- [RND for Sparse-reward Environments](#rnd-for-sparse-reward-environments)
- [Imitation Learning](#imitation-learning)
- [GAIL (Generative Adversarial Imitation Learning)](#gail-generative-adversarial-imitation-learning)
- [Behavioral Cloning (BC)](#behavioral-cloning-bc)
- [Recording Demonstrations](#recording-demonstrations)
- [Summary](#summary)
- [Training Methods: Environment-specific](#training-methods-environment-specific)
- [Training in Competitive Multi-Agent Environments with Self-Play](#training-in-competitive-multi-agent-environments-with-self-play)
- [Training in Cooperative Multi-Agent Environments with MA-POCA](#training-in-cooperative-multi-agent-environments-with-ma-poca)
- [Solving Complex Tasks using Curriculum Learning](#solving-complex-tasks-using-curriculum-learning)
- [Training Robust Agents using Environment Parameter Randomization](#training-robust-agents-using-environment-parameter-randomization)
- [Model Types](#model-types)
- [Learning from Vector Observations](#learning-from-vector-observations)
- [Learning from Cameras using Convolutional Neural Networks](#learning-from-cameras-using-convolutional-neural-networks)
- [Learning from Variable Length Observations using Attention](#learning-from-variable-length-observations-using-attention)
- [Memory-enhanced Agents using Recurrent Neural Networks](#memory-enhanced-agents-using-recurrent-neural-networks)
- [Additional Features](#additional-features)
- [Summary and Next Steps](#summary-and-next-steps)
**The Unity Machine Learning Agents Toolkit** (ML-Agents Toolkit) is an
open-source project that enables games and simulations to serve as environments
for training intelligent agents. Agents can be trained using reinforcement
learning, imitation learning, neuroevolution, or other machine learning methods
through a simple-to-use Python API. We also provide implementations (based on
PyTorch) of state-of-the-art algorithms to enable game developers and
hobbyists to easily train intelligent agents for 2D, 3D and VR/AR games. These
trained agents can be used for multiple purposes, including controlling NPC
behavior (in a variety of settings such as multi-agent and adversarial),
automated testing of game builds and evaluating different game design decisions
pre-release. The ML-Agents Toolkit is mutually beneficial for both game
developers and AI researchers as it provides a central platform where advances
in AI can be evaluated on Unity’s rich environments and then made accessible to
the wider research and game developer communities.
Depending on your background (i.e. researcher, game developer, hobbyist), you
may have very different questions on your mind at the moment. To make your
transition to the ML-Agents Toolkit easier, we provide several background pages
that include overviews and helpful resources on the
[Unity Engine](Background-Unity.md),
[machine learning](Background-Machine-Learning.md) and
[PyTorch](Background-PyTorch.md). We **strongly** recommend browsing the
relevant background pages if you're not familiar with a Unity scene, basic
machine learning concepts or have not previously heard of PyTorch.
The remainder of this page contains a deep dive into ML-Agents, its key
components, different training modes and scenarios. By the end of it, you should
have a good sense of _what_ the ML-Agents Toolkit allows you to do. The
subsequent documentation pages provide examples of _how_ to use ML-Agents. To
get started, watch this
[demo video of ML-Agents in action](https://www.youtube.com/watch?v=fiQsmdwEGT8&feature=youtu.be).
## Running Example: Training NPC Behaviors
To help explain the material and terminology in this page, we'll use a
hypothetical, running example throughout. We will explore the problem of
training the behavior of a non-playable character (NPC) in a game. (An NPC is a
game character that is never controlled by a human player and its behavior is
pre-defined by the game developer.) More specifically, let's assume we're
building a multi-player, war-themed game in which players control the soldiers.
In this game, we have a single NPC who serves as a medic, finding and reviving
wounded players. Lastly, let us assume that there are two teams, each with five
players and one NPC medic.
The behavior of a medic is quite complex. It first needs to avoid getting
injured, which requires detecting when it is in danger and moving to a safe
location. Second, it needs to be aware of which of its team members are injured
and require assistance. In the case of multiple injuries, it needs to assess the
degree of injury and decide who to help first. Lastly, a good medic will always
place itself in a position where it can quickly help its team members. Factoring
in all of these traits means that at every instance, the medic needs to measure
several attributes of the environment (e.g. position of team members, position
of enemies, which of its team members are injured and to what degree) and then
decide on an action (e.g. hide from enemy fire, move to help one of its
members). Given the large number of settings of the environment and the large
number of actions that the medic can take, defining and implementing such
complex behaviors by hand is challenging and prone to errors.
With ML-Agents, it is possible to _train_ the behaviors of such NPCs (called
**Agents**) using a variety of methods. The basic idea is quite simple. We need
to define three entities at every moment of the game (called **environment**):
- **Observations** - what the medic perceives about the environment.
Observations can be numeric and/or visual. Numeric observations measure
attributes of the environment from the point of view of the agent. For our
medic this would be attributes of the battlefield that are visible to it. For
most interesting environments, an agent will require several continuous
numeric observations. Visual observations, on the other hand, are images
generated from the cameras attached to the agent and represent what the agent
is seeing at that point in time. It is common to confuse an agent's
observation with the environment (or game) **state**. The environment state
represents information about the entire scene containing all the game
characters. The agents observation, however, only contains information that
the agent is aware of and is typically a subset of the environment state. For
example, the medic observation cannot include information about an enemy in
hiding that the medic is unaware of.
- **Actions** - what actions the medic can take. Similar to observations,
actions can either be continuous or discrete depending on the complexity of
the environment and agent. In the case of the medic, if the environment is a
simple grid world where only their location matters, then a discrete action
taking on one of four values (north, south, east, west) suffices. However, if
the environment is more complex and the medic can move freely then using two
continuous actions (one for direction and another for speed) is more
appropriate.
- **Reward signals** - a scalar value indicating how well the medic is doing.
Note that the reward signal need not be provided at every moment, but only
when the medic performs an action that is good or bad. For example, it can
receive a large negative reward if it dies, a modest positive reward whenever
it revives a wounded team member, and a modest negative reward when a wounded
team member dies due to lack of assistance. Note that the reward signal is how
the objectives of the task are communicated to the agent, so they need to be
set up in a manner where maximizing reward generates the desired optimal
behavior.
After defining these three entities (the building blocks of a **reinforcement
learning task**), we can now _train_ the medic's behavior. This is achieved by
simulating the environment for many trials where the medic, over time, learns
what is the optimal action to take for every observation it measures by
maximizing its future reward. The key is that by learning the actions that
maximize its reward, the medic is learning the behaviors that make it a good
medic (i.e. one who saves the most number of lives). In **reinforcement
learning** terminology, the behavior that is learned is called a **policy**,
which is essentially a (optimal) mapping from observations to actions. Note that
the process of learning a policy through running simulations is called the
**training phase**, while playing the game with an NPC that is using its learned
policy is called the **inference phase**.
The ML-Agents Toolkit provides all the necessary tools for using Unity as the
simulation engine for learning the policies of different objects in a Unity
environment. In the next few sections, we discuss how the ML-Agents Toolkit
achieves this and what features it provides.
## Key Components
The ML-Agents Toolkit contains five high-level components:
- **Learning Environment** - which contains the Unity scene and all the game
characters. The Unity scene provides the environment in which agents observe,
act, and learn. How you set up the Unity scene to serve as a learning
environment really depends on your goal. You may be trying to solve a specific
reinforcement learning problem of limited scope, in which case you can use the
same scene for both training and for testing trained agents. Or, you may be
training agents to operate in a complex game or simulation. In this case, it
might be more efficient and practical to create a purpose-built training
scene. The ML-Agents Toolkit includes an ML-Agents Unity SDK
(`com.unity.ml-agents` package) that enables you to transform any Unity scene
into a learning environment by defining the agents and their behaviors.
- **Python Low-Level API** - which contains a low-level Python interface for
interacting and manipulating a learning environment. Note that, unlike the
Learning Environment, the Python API is not part of Unity, but lives outside
and communicates with Unity through the Communicator. This API is contained in
a dedicated `mlagents_envs` Python package and is used by the Python training
process to communicate with and control the Academy during training. However,
it can be used for other purposes as well. For example, you could use the API
to use Unity as the simulation engine for your own machine learning
algorithms. See [Python API](Python-LLAPI.md) for more information.
- **External Communicator** - which connects the Learning Environment with the
Python Low-Level API. It lives within the Learning Environment.
- **Python Trainers** which contains all the machine learning algorithms that
enable training agents. The algorithms are implemented in Python and are part
of their own `mlagents` Python package. The package exposes a single
command-line utility `mlagents-learn` that supports all the training methods
and options outlined in this document. The Python Trainers interface solely
with the Python Low-Level API.
- **Gym Wrapper** (not pictured). A common way in which machine learning
researchers interact with simulation environments is via a wrapper provided by
OpenAI called [gym](https://github.com/openai/gym). We provide a gym wrapper
in the `ml-agents-envs` package and [instructions](Python-Gym-API.md) for using
it with existing machine learning algorithms which utilize gym.
- **PettingZoo Wrapper** (not pictured) PettingZoo is python API for
interacting with multi-agent simulation environments that provides a
gym-like interface. We provide a PettingZoo wrapper for Unity ML-Agents
environments in the `ml-agents-envs` package and
[instructions](Python-PettingZoo-API.md) for using it with machine learning
algorithms.
<p align="center">
<img src="../images/learning_environment_basic.png"
alt="Simplified ML-Agents Scene Block Diagram"
width="600"
border="10" />
</p>
_Simplified block diagram of ML-Agents._
The Learning Environment contains two Unity Components that help organize the
Unity scene:
- **Agents** - which is attached to a Unity GameObject (any character within a
scene) and handles generating its observations, performing the actions it
receives and assigning a reward (positive / negative) when appropriate. Each
Agent is linked to a Behavior.
- **Behavior** - defines specific attributes of the agent such as the number of
actions that agent can take. Each Behavior is uniquely identified by a
`Behavior Name` field. A Behavior can be thought as a function that receives
observations and rewards from the Agent and returns actions. A Behavior can be
of one of three types: Learning, Heuristic or Inference. A Learning Behavior
is one that is not, yet, defined but about to be trained. A Heuristic Behavior
is one that is defined by a hard-coded set of rules implemented in code. An
Inference Behavior is one that includes a trained Neural Network file. In
essence, after a Learning Behavior is trained, it becomes an Inference
Behavior.
Every Learning Environment will always have one Agent for every character in the
scene. While each Agent must be linked to a Behavior, it is possible for Agents
that have similar observations and actions to have the same Behavior. In our
sample game, we have two teams each with their own medic. Thus we will have two
Agents in our Learning Environment, one for each medic, but both of these medics
can have the same Behavior. This does not mean that at each instance they will
have identical observation and action _values_.
<p align="center">
<img src="../images/learning_environment_example.png"
alt="Example ML-Agents Scene Block Diagram"
width="700"
border="10" />
</p>
_Example block diagram of ML-Agents Toolkit for our sample game._
Note that in a single environment, there can be multiple Agents and multiple
Behaviors at the same time. For example, if we expanded our game to include tank
driver NPCs, then the Agent attached to those characters cannot share its
Behavior with the Agent linked to the medics (medics and drivers have different
actions). The Learning Environment through the Academy (not represented in the
diagram) ensures that all the Agents are in sync in addition to controlling
environment-wide settings.
Lastly, it is possible to exchange data between Unity and Python outside of the
machine learning loop through _Side Channels_. One example of using _Side
Channels_ is to exchange data with Python about _Environment Parameters_. The
following diagram illustrates the above.
<p align="center">
<img src="../images/learning_environment_full.png"
alt="More Complete Example ML-Agents Scene Block Diagram"
border="10" />
</p>
## Training Modes
Given the flexibility of ML-Agents, there are a few ways in which training and
inference can proceed.
### Built-in Training and Inference
As mentioned previously, the ML-Agents Toolkit ships with several
implementations of state-of-the-art algorithms for training intelligent agents.
More specifically, during training, all the medics in the scene send their
observations to the Python API through the External Communicator. The Python API
processes these observations and sends back actions for each medic to take.
During training these actions are mostly exploratory to help the Python API
learn the best policy for each medic. Once training concludes, the learned
policy for each medic can be exported as a model file. Then during the inference
phase, the medics still continue to generate their observations, but instead of
being sent to the Python API, they will be fed into their (internal, embedded)
model to generate the _optimal_ action for each medic to take at every point in
time.
The [Getting Started Guide](Getting-Started.md) tutorial covers this training
mode with the **3D Balance Ball** sample environment.
#### Cross-Platform Inference
It is important to note that the ML-Agents Toolkit leverages the
[Sentis](Sentis.md) to run the models within a
Unity scene such that an agent can take the _optimal_ action at each step. Given
that Sentis support most platforms that Unity does, this
means that any model you train with the ML-Agents Toolkit can be embedded into
your Unity application that runs on any platform. See our
[dedicated blog post](https://blogs.unity3d.com/2019/03/01/unity-ml-agents-toolkit-v0-7-a-leap-towards-cross-platform-inference/)
for additional information.
### Custom Training and Inference
In the previous mode, the Agents were used for training to generate a PyTorch
model that the Agents can later use. However, any user of the ML-Agents Toolkit
can leverage their own algorithms for training. In this case, the behaviors of
all the Agents in the scene will be controlled within Python. You can even turn
your environment into a [gym.](Python-Gym-API.md)
We do not currently have a tutorial highlighting this mode, but you can learn
more about the Python API [here](Python-LLAPI.md).
## Flexible Training Scenarios
While the discussion so-far has mostly focused on training a single agent, with
ML-Agents, several training scenarios are possible. We are excited to see what
kinds of novel and fun environments the community creates. For those new to
training intelligent agents, below are a few examples that can serve as
inspiration:
- Single-Agent. A single agent, with its own reward signal. The traditional way
of training an agent. An example is any single-player game, such as Chicken.
- Simultaneous Single-Agent. Multiple independent agents with independent reward
signals with same `Behavior Parameters`. A parallelized version of the
traditional training scenario, which can speed-up and stabilize the training
process. Helpful when you have multiple versions of the same character in an
environment who should learn similar behaviors. An example might be training a
dozen robot-arms to each open a door simultaneously.
- Adversarial Self-Play. Two interacting agents with inverse reward signals. In
two-player games, adversarial self-play can allow an agent to become
increasingly more skilled, while always having the perfectly matched opponent:
itself. This was the strategy employed when training AlphaGo, and more
recently used by OpenAI to train a human-beating 1-vs-1 Dota 2 agent.
- Cooperative Multi-Agent. Multiple interacting agents with a shared reward
signal with same or different `Behavior Parameters`. In this scenario, all
agents must work together to accomplish a task that cannot be done alone.
Examples include environments where each agent only has access to partial
information, which needs to be shared in order to accomplish the task or
collaboratively solve a puzzle.
- Competitive Multi-Agent. Multiple interacting agents with inverse reward
signals with same or different `Behavior Parameters`. In this scenario, agents
must compete with one another to either win a competition, or obtain some
limited set of resources. All team sports fall into this scenario.
- Ecosystem. Multiple interacting agents with independent reward signals with
same or different `Behavior Parameters`. This scenario can be thought of as
creating a small world in which animals with different goals all interact,
such as a savanna in which there might be zebras, elephants and giraffes, or
an autonomous driving simulation within an urban environment.
## Training Methods: Environment-agnostic
The remaining sections overview the various state-of-the-art machine learning
algorithms that are part of the ML-Agents Toolkit. If you aren't studying
machine and reinforcement learning as a subject and just want to train agents to
accomplish tasks, you can treat these algorithms as _black boxes_. There are a
few training-related parameters to adjust inside Unity as well as on the Python
training side, but you do not need in-depth knowledge of the algorithms
themselves to successfully create and train agents. Step-by-step procedures for
running the training process are provided in the
[Training ML-Agents](Training-ML-Agents.md) page.
This section specifically focuses on the training methods that are available
regardless of the specifics of your learning environment.
#### A Quick Note on Reward Signals
In this section we introduce the concepts of _intrinsic_ and _extrinsic_
rewards, which helps explain some of the training methods.
In reinforcement learning, the end goal for the Agent is to discover a behavior
(a Policy) that maximizes a reward. You will need to provide the agent one or
more reward signals to use during training. Typically, a reward is defined by
your environment, and corresponds to reaching some goal. These are what we refer
to as _extrinsic_ rewards, as they are defined external of the learning
algorithm.
Rewards, however, can be defined outside of the environment as well, to
encourage the agent to behave in certain ways, or to aid the learning of the
true extrinsic reward. We refer to these rewards as _intrinsic_ reward signals.
The total reward that the agent will learn to maximize can be a mix of extrinsic
and intrinsic reward signals.
The ML-Agents Toolkit allows reward signals to be defined in a modular way, and
we provide four reward signals that can the mixed and matched to help shape
your agent's behavior:
- `extrinsic`: represents the rewards defined in your environment, and is
enabled by default
- `gail`: represents an intrinsic reward signal that is defined by GAIL (see
below)
- `curiosity`: represents an intrinsic reward signal that encourages exploration
in sparse-reward environments that is defined by the Curiosity module (see
below).
- `rnd`: represents an intrinsic reward signal that encourages exploration
in sparse-reward environments that is defined by the Curiosity module (see
below).
### Deep Reinforcement Learning
ML-Agents provide an implementation of two reinforcement learning algorithms:
- [Proximal Policy Optimization (PPO)](https://openai.com/research/openai-baselines-ppo)
- [Soft Actor-Critic (SAC)](https://bair.berkeley.edu/blog/2018/12/14/sac/)
The default algorithm is PPO. This is a method that has been shown to be more
general purpose and stable than many other RL algorithms.
In contrast with PPO, SAC is _off-policy_, which means it can learn from
experiences collected at any time during the past. As experiences are collected,
they are placed in an experience replay buffer and randomly drawn during
training. This makes SAC significantly more sample-efficient, often requiring
5-10 times less samples to learn the same task as PPO. However, SAC tends to
require more model updates. SAC is a good choice for heavier or slower
environments (about 0.1 seconds per step or more). SAC is also a "maximum
entropy" algorithm, and enables exploration in an intrinsic way. Read more about
maximum entropy RL
[here](https://bair.berkeley.edu/blog/2017/10/06/soft-q-learning/).
#### Curiosity for Sparse-reward Environments
In environments where the agent receives rare or infrequent rewards (i.e.
sparse-reward), an agent may never receive a reward signal on which to bootstrap
its training process. This is a scenario where the use of an intrinsic reward
signals can be valuable. Curiosity is one such signal which can help the agent
explore when extrinsic rewards are sparse.
The `curiosity` Reward Signal enables the Intrinsic Curiosity Module. This is an
implementation of the approach described in
[Curiosity-driven Exploration by Self-supervised Prediction](https://pathak22.github.io/noreward-rl/)
by Pathak, et al. It trains two networks:
- an inverse model, which takes the current and next observation of the agent,
encodes them, and uses the encoding to predict the action that was taken
between the observations
- a forward model, which takes the encoded current observation and action, and
predicts the next encoded observation.
The loss of the forward model (the difference between the predicted and actual
encoded observations) is used as the intrinsic reward, so the more surprised the
model is, the larger the reward will be.
For more information, see our dedicated
[blog post on the Curiosity module](https://blogs.unity3d.com/2018/06/26/solving-sparse-reward-tasks-with-curiosity/).
#### RND for Sparse-reward Environments
Similarly to Curiosity, Random Network Distillation (RND) is useful in sparse or rare
reward environments as it helps the Agent explore. The RND Module is implemented following
the paper [Exploration by Random Network Distillation](https://arxiv.org/abs/1810.12894).
RND uses two networks:
- The first is a network with fixed random weights that takes observations as inputs and
generates an encoding
- The second is a network with similar architecture that is trained to predict the
outputs of the first network and uses the observations the Agent collects as training data.
The loss (the squared difference between the predicted and actual encoded observations)
of the trained model is used as intrinsic reward. The more an Agent visits a state, the
more accurate the predictions and the lower the rewards which encourages the Agent to
explore new states with higher prediction errors.
### Imitation Learning
It is often more intuitive to simply demonstrate the behavior we want an agent
to perform, rather than attempting to have it learn via trial-and-error methods.
For example, instead of indirectly training a medic with the help of a reward
function, we can give the medic real world examples of observations from the
game and actions from a game controller to guide the medic's behavior. Imitation
Learning uses pairs of observations and actions from a demonstration to learn a
policy. See this [video demo](https://youtu.be/kpb8ZkMBFYs) of imitation
learning .
Imitation learning can either be used alone or in conjunction with reinforcement
learning. If used alone it can provide a mechanism for learning a specific type
of behavior (i.e. a specific style of solving the task). If used in conjunction
with reinforcement learning it can dramatically reduce the time the agent takes
to solve the environment. This can be especially pronounced in sparse-reward
environments. For instance, on the
[Pyramids environment](Learning-Environment-Examples.md#pyramids), using 6
episodes of demonstrations can reduce training steps by more than 4 times. See
Behavioral Cloning + GAIL + Curiosity + RL below.
<p align="center">
<img src="../images/mlagents-ImitationAndRL.png"
alt="Using Demonstrations with Reinforcement Learning"
width="700" border="0" />
</p>
The ML-Agents Toolkit provides a way to learn directly from demonstrations, as
well as use them to help speed up reward-based training (RL). We include two
algorithms called Behavioral Cloning (BC) and Generative Adversarial Imitation
Learning (GAIL). In most scenarios, you can combine these two features:
- If you want to help your agents learn (especially with environments that have
sparse rewards) using pre-recorded demonstrations, you can generally enable
both GAIL and Behavioral Cloning at low strengths in addition to having an
extrinsic reward. An example of this is provided for the PushBlock example
environment in `config/imitation/PushBlock.yaml`.
- If you want to train purely from demonstrations with GAIL and BC _without_ an
extrinsic reward signal, please see the CrawlerStatic example environment under
in `config/imitation/CrawlerStatic.yaml`.
***Note:*** GAIL introduces a [_survivor bias_](https://arxiv.org/pdf/1809.02925.pdf)
to the learning process. That is, by giving positive rewards based on similarity
to the expert, the agent is incentivized to remain alive for as long as possible.
This can directly conflict with goal-oriented tasks like our PushBlock or Pyramids
example environments where an agent must reach a goal state thus ending the
episode as quickly as possible. In these cases, we strongly recommend that you
use a low strength GAIL reward signal and a sparse extrinsic signal when
the agent achieves the task. This way, the GAIL reward signal will guide the
agent until it discovers the extrinsic signal and will not overpower it. If the
agent appears to be ignoring the extrinsic reward signal, you should reduce
the strength of GAIL.
#### GAIL (Generative Adversarial Imitation Learning)
GAIL, or
[Generative Adversarial Imitation Learning](https://arxiv.org/abs/1606.03476),
uses an adversarial approach to reward your Agent for behaving similar to a set
of demonstrations. GAIL can be used with or without environment rewards, and
works well when there are a limited number of demonstrations. In this framework,
a second neural network, the discriminator, is taught to distinguish whether an
observation/action is from a demonstration or produced by the agent. This
discriminator can then examine a new observation/action and provide it a reward
based on how close it believes this new observation/action is to the provided
demonstrations.
At each training step, the agent tries to learn how to maximize this reward.
Then, the discriminator is trained to better distinguish between demonstrations
and agent state/actions. In this way, while the agent gets better and better at
mimicking the demonstrations, the discriminator keeps getting stricter and
stricter and the agent must try harder to "fool" it.
This approach learns a _policy_ that produces states and actions similar to the
demonstrations, requiring fewer demonstrations than direct cloning of the
actions. In addition to learning purely from demonstrations, the GAIL reward
signal can be mixed with an extrinsic reward signal to guide the learning
process.
#### Behavioral Cloning (BC)
BC trains the Agent's policy to exactly mimic the actions shown in a set of
demonstrations. The BC feature can be enabled on the PPO or SAC trainers. As BC
cannot generalize past the examples shown in the demonstrations, BC tends to
work best when there exists demonstrations for nearly all of the states that the
agent can experience, or in conjunction with GAIL and/or an extrinsic reward.
#### Recording Demonstrations
Demonstrations of agent behavior can be recorded from the Unity Editor or build,
and saved as assets. These demonstrations contain information on the
observations, actions, and rewards for a given agent during the recording
session. They can be managed in the Editor, as well as used for training with BC
and GAIL. See the
[Designing Agents](Learning-Environment-Design-Agents.md#recording-demonstrations)
page for more information on how to record demonstrations for your agent.
### Summary
To summarize, we provide 3 training methods: BC, GAIL and RL (PPO or SAC) that
can be used independently or together:
- BC can be used on its own or as a pre-training step before GAIL and/or RL
- GAIL can be used with or without extrinsic rewards
- RL can be used on its own (either PPO or SAC) or in conjunction with BC and/or
GAIL.
Leveraging either BC or GAIL requires recording demonstrations to be provided as
input to the training algorithms.
## Training Methods: Environment-specific
In addition to the three environment-agnostic training methods introduced in the
previous section, the ML-Agents Toolkit provides additional methods that can aid
in training behaviors for specific types of environments.
### Training in Competitive Multi-Agent Environments with Self-Play
ML-Agents provides the functionality to train both symmetric and asymmetric
adversarial games with
[Self-Play](https://openai.com/research/competitive-self-play). A symmetric game is
one in which opposing agents are equal in form, function and objective. Examples
of symmetric games are our Tennis and Soccer example environments. In
reinforcement learning, this means both agents have the same observation and
actions and learn from the same reward function and so _they can share the
same policy_. In asymmetric games, this is not the case. An example of an
asymmetric games are Hide and Seek. Agents in these types of games do not always
have the same observation or actions and so sharing policy networks is not
necessarily ideal.
With self-play, an agent learns in adversarial games by competing against fixed,
past versions of its opponent (which could be itself as in symmetric games) to
provide a more stable, stationary learning environment. This is compared to
competing against the current, best opponent in every episode, which is
constantly changing (because it's learning).
Self-play can be used with our implementations of both Proximal Policy
Optimization (PPO) and Soft Actor-Critic (SAC). However, from the perspective of
an individual agent, these scenarios appear to have non-stationary dynamics
because the opponent is often changing. This can cause significant issues in the
experience replay mechanism used by SAC. Thus, we recommend that users use PPO.
For further reading on this issue in particular, see the paper
[Stabilising Experience Replay for Deep Multi-Agent Reinforcement Learning](https://arxiv.org/pdf/1702.08887.pdf).
See our
[Designing Agents](Learning-Environment-Design-Agents.md#defining-teams-for-multi-agent-scenarios)
page for more information on setting up teams in your Unity scene. Also, read
our
[blog post on self-play](https://blogs.unity3d.com/2020/02/28/training-intelligent-adversaries-using-self-play-with-ml-agents/)
for additional information. Additionally, check [ELO Rating System](ELO-Rating-System.md) the method we use to calculate
the relative skill level between two players.
### Training In Cooperative Multi-Agent Environments with MA-POCA

ML-Agents provides the functionality for training cooperative behaviors - i.e.,
groups of agents working towards a common goal, where the success of the individual
is linked to the success of the whole group. In such a scenario, agents typically receive
rewards as a group. For instance, if a team of agents wins a game against an opposing
team, everyone is rewarded - even agents who did not directly contribute to the win. This
makes learning what to do as an individual difficult - you may get a win
for doing nothing, and a loss for doing your best.
In ML-Agents, we provide MA-POCA (MultiAgent POsthumous Credit Assignment), which
is a novel multi-agent trainer that trains a _centralized critic_, a neural network
that acts as a "coach" for a whole group of agents. You can then give rewards to the team
as a whole, and the agents will learn how best to contribute to achieving that reward.
Agents can _also_ be given rewards individually, and the team will work together to help the
individual achieve those goals. During an episode, agents can be added or removed from the group,
such as when agents spawn or die in a game. If agents are removed mid-episode (e.g., if teammates die
or are removed from the game), they will still learn whether their actions contributed
to the team winning later, enabling agents to take group-beneficial actions even if
they result in the individual being removed from the game (i.e., self-sacrifice).
MA-POCA can also be combined with self-play to train teams of agents to play against each other.
To learn more about enabling cooperative behaviors for agents in an ML-Agents environment,
check out [this page](Learning-Environment-Design-Agents.md#groups-for-cooperative-scenarios).
To learn more about MA-POCA, please see our paper
[On the Use and Misuse of Absorbing States in Multi-Agent Reinforcement Learning](https://arxiv.org/pdf/2111.05992.pdf).
For further reading, MA-POCA builds on previous work in multi-agent cooperative learning
([Lowe et al.](https://arxiv.org/abs/1706.02275), [Foerster et al.](https://arxiv.org/pdf/1705.08926.pdf),
among others) to enable the above use-cases.
### Solving Complex Tasks using Curriculum Learning
Curriculum learning is a way of training a machine learning model where more
difficult aspects of a problem are gradually introduced in such a way that the
model is always optimally challenged. This idea has been around for a long time,
and it is how we humans typically learn. If you imagine any childhood primary
school education, there is an ordering of classes and topics. Arithmetic is
taught before algebra, for example. Likewise, algebra is taught before calculus.
The skills and knowledge learned in the earlier subjects provide a scaffolding
for later lessons. The same principle can be applied to machine learning, where
training on easier tasks can provide a scaffolding for harder tasks in the
future.
Imagine training the medic to scale a wall to arrive at a wounded team
member. The starting point when training a medic to accomplish this task will be
a random policy. That starting policy will have the medic running in circles,
and will likely never, or very rarely scale the wall properly to revive their
team member (and achieve the reward). If we start with a simpler task, such as
moving toward an unobstructed team member, then the medic can easily learn to
accomplish the task. From there, we can slowly add to the difficulty of the task
by increasing the size of the wall until the medic can complete the initially
near-impossible task of scaling the wall. We have included an environment to
demonstrate this with ML-Agents, called
[Wall Jump](Learning-Environment-Examples.md#wall-jump).

_Demonstration of a hypothetical curriculum training scenario in which a
progressively taller wall obstructs the path to the goal._
_[**Note**: The example provided above is for instructional purposes, and was
based on an early version of the
[Wall Jump example environment](Learning-Environment-Examples.md). As such, it
is not possible to directly replicate the results here using that environment.]_
The ML-Agents Toolkit supports modifying custom environment parameters during
the training process to aid in learning. This allows elements of the environment
related to difficulty or complexity to be dynamically adjusted based on training
progress. The [Training ML-Agents](Training-ML-Agents.md#curriculum-learning)
page has more information on defining training curriculums.
### Training Robust Agents using Environment Parameter Randomization
An agent trained on a specific environment, may be unable to generalize to any
tweaks or variations in the environment (in machine learning this is referred to
as overfitting). This becomes problematic in cases where environments are
instantiated with varying objects or properties. One mechanism to alleviate this
and train more robust agents that can generalize to unseen variations of the
environment is to expose them to these variations during training. Similar to
Curriculum Learning, where environments become more difficult as the agent
learns, the ML-Agents Toolkit provides a way to randomly sample parameters of
the environment during training. We refer to this approach as **Environment
Parameter Randomization**. For those familiar with Reinforcement Learning
research, this approach is based on the concept of
[Domain Randomization](https://arxiv.org/abs/1703.06907). By using
[parameter randomization during training](Training-ML-Agents.md#environment-parameter-randomization),
the agent can be better suited to adapt (with higher performance) to future
unseen variations of the environment.
| Ball scale of 0.5 | Ball scale of 4 |
| :--------------------------: | :------------------------: |
|  |  |
_Example of variations of the 3D Ball environment. The environment parameters
are `gravity`, `ball_mass` and `ball_scale`._
## Model Types
Regardless of the training method deployed, there are a few model types that
users can train using the ML-Agents Toolkit. This is due to the flexibility in
defining agent observations, which include vector, ray cast and visual
observations. You can learn more about how to instrument an agent's observation
in the [Designing Agents](Learning-Environment-Design-Agents.md) guide.
### Learning from Vector Observations
Whether an agent's observations are ray cast or vector, the ML-Agents Toolkit
provides a fully connected neural network model to learn from those
observations. At training time you can configure different aspects of this model
such as the number of hidden units and number of layers.
### Learning from Cameras using Convolutional Neural Networks
Unlike other platforms, where the agent’s observation might be limited to a
single vector or image, the ML-Agents Toolkit allows multiple cameras to be used
for observations per agent. This enables agents to learn to integrate
information from multiple visual streams. This can be helpful in several
scenarios such as training a self-driving car which requires multiple cameras
with different viewpoints, or a navigational agent which might need to integrate
aerial and first-person visuals. You can learn more about adding visual
observations to an agent
[here](Learning-Environment-Design-Agents.md#multiple-visual-observations).
When visual observations are utilized, the ML-Agents Toolkit leverages
convolutional neural networks (CNN) to learn from the input images. We offer
three network architectures:
- a simple encoder which consists of two convolutional layers
- the implementation proposed by
[Mnih et al.](https://www.nature.com/articles/nature14236), consisting of
three convolutional layers,
- the [IMPALA Resnet](https://arxiv.org/abs/1802.01561) consisting of three
stacked layers, each with two residual blocks, making a much larger network
than the other two.
The choice of the architecture depends on the visual complexity of the scene and
the available computational resources.
### Learning from Variable Length Observations using Attention
Using the ML-Agents Toolkit, it is possible to have agents learn from a
varying number of inputs. To do so, each agent can keep track of a buffer
of vector observations. At each step, the agent will go through all the
elements in the buffer and extract information but the elements
in the buffer can change at every step.
This can be useful in scenarios in which the agents must keep track of
a varying number of elements throughout the episode. For example in a game
where an agent must learn to avoid projectiles, but the projectiles can vary in
numbers.

You can learn more about variable length observations
[here](Learning-Environment-Design-Agents.md#variable-length-observations).
When variable length observations are utilized, the ML-Agents Toolkit
leverages attention networks to learn from a varying number of entities.
Agents using attention will ignore entities that are deemed not relevant
and pay special attention to entities relevant to the current situation
based on context.
### Memory-enhanced Agents using Recurrent Neural Networks
Have you ever entered a room to get something and immediately forgot what you
were looking for? Don't let that happen to your agents.

In some scenarios, agents must learn to remember the past in order to take the
best decision. When an agent only has partial observability of the environment,
keeping track of past observations can help the agent learn. Deciding what the
agents should remember in order to solve a task is not easy to do by hand, but
our training algorithms can learn to keep track of what is important to remember
with [LSTM](https://en.wikipedia.org/wiki/Long_short-term_memory).
## Additional Features
Beyond the flexible training scenarios available, the ML-Agents Toolkit includes
additional features which improve the flexibility and interpretability of the
training process.
- **Concurrent Unity Instances** - We enable developers to run concurrent,
parallel instances of the Unity executable during training. For certain
scenarios, this should speed up training. Check out our dedicated page on
[creating a Unity executable](Learning-Environment-Executable.md) and the
[Training ML-Agents](Training-ML-Agents.md#training-using-concurrent-unity-instances)
page for instructions on how to set the number of concurrent instances.
- **Recording Statistics from Unity** - We enable developers to
[record statistics](Learning-Environment-Design.md#recording-statistics) from
within their Unity environments. These statistics are aggregated and generated
during the training process.
- **Custom Side Channels** - We enable developers to
[create custom side channels](Custom-SideChannels.md) to manage data transfer
between Unity and Python that is unique to their training workflow and/or
environment.
- **Custom Samplers** - We enable developers to
[create custom sampling methods](Training-ML-Agents.md#defining-a-new-sampler-type)
for Environment Parameter Randomization. This enables users to customize this
training method for their particular environment.
## Summary and Next Steps
To briefly summarize: The ML-Agents Toolkit enables games and simulations built
in Unity to serve as the platform for training intelligent agents. It is
designed to enable a large variety of training modes and scenarios and comes
packed with several features to enable researchers and developers to leverage
(and enhance) machine learning within Unity.
In terms of next steps:
- For a walkthrough of running ML-Agents with a simple scene, check out the
[Getting Started](Getting-Started.md) guide.
- For a "Hello World" introduction to creating your own Learning Environment,
check out the
[Making a New Learning Environment](Learning-Environment-Create-New.md) page.
- For an overview on the more complex example environments that are provided in
this toolkit, check out the
[Example Environments](Learning-Environment-Examples.md) page.
- For more information on the various training options available, check out the
[Training ML-Agents](Training-ML-Agents.md) page.
| ml-agents/docs/ML-Agents-Overview.md/0 | {
"file_path": "ml-agents/docs/ML-Agents-Overview.md",
"repo_id": "ml-agents",
"token_count": 11221
} | 1,857 |
# Sentis
The ML-Agents Toolkit allows you to use pre-trained neural network models inside
your Unity games. This support is possible thanks to the
[Sentis](https://docs.unity3d.com/Packages/com.unity.sentis@latest/index.html)
(codenamed Sentis). Sentis uses
[compute shaders](https://docs.unity3d.com/Manual/class-ComputeShader.html) to
run the neural network within Unity.
## Supported devices
See the Sentis documentation for a list of the
[supported platforms](https://docs.unity3d.com/Manual/PlatformSpecific.html).
Scripting Backends : Sentis is generally faster with
**IL2CPP** than with **Mono** for Standalone builds. In the Editor, It is not
possible to use Sentis with GPU device selected when Editor
Graphics Emulation is set to **OpenGL(ES) 3.0 or 2.0 emulation**. Also there
might be non-fatal build time errors when target platform includes Graphics API
that does not support **Unity Compute Shaders**.
## Using Sentis
When using a model, drag the model file into the **Model** field in the
Inspector of the Agent. Select the **Inference Device** : CPU or GPU you want to
use for Inference.
**Note:** For most of the models generated with the ML-Agents Toolkit, CPU will
be faster than GPU. You should use the GPU only if you use the ResNet visual
encoder or have a large number of agents with visual observations.
# Unsupported use cases
## Externally trained models
The ML-Agents Toolkit only supports the models created with our trainers. Model
loading expects certain conventions for constants and tensor names. While it is
possible to construct a model that follows these conventions, we don't provide
any additional help for this. More details can be found in
[TensorNames.cs](https://github.com/Unity-Technologies/ml-agents/blob/release_21_docs/com.unity.ml-agents/Runtime/Inference/TensorNames.cs)
and
[SentisModelParamLoader.cs](https://github.com/Unity-Technologies/ml-agents/blob/release_21_docs/com.unity.ml-agents/Runtime/Inference/SentisModelParamLoader.cs).
If you wish to run inference on an externally trained model, you should use
Sentis directly, instead of trying to run it through ML-Agents.
## Model inference outside of Unity
We do not provide support for inference anywhere outside of Unity. The `.onnx` files produced by training use the open format ONNX; if you wish to convert a `.onnx` file to another
format or run inference with them, refer to their documentation.
| ml-agents/docs/Sentis.md/0 | {
"file_path": "ml-agents/docs/Sentis.md",
"repo_id": "ml-agents",
"token_count": 655
} | 1,858 |
/* The standard CSS for doxygen 1.8.14 */
body, table, div, p, dl {
font: 400 14px/22px Roboto,sans-serif;
}
p.reference, p.definition {
font: 400 14px/22px Roboto,sans-serif;
}
/* @group Heading Levels */
h1.groupheader {
font-size: 150%;
}
.title {
font: 400 14px/28px Roboto,sans-serif;
font-size: 150%;
font-weight: bold;
margin: 10px 2px;
}
h2.groupheader {
border-bottom: 1px solid #879ECB;
color: #354C7B;
font-size: 150%;
font-weight: normal;
margin-top: 1.75em;
padding-top: 8px;
padding-bottom: 4px;
width: 100%;
}
h3.groupheader {
font-size: 100%;
}
h1, h2, h3, h4, h5, h6 {
-webkit-transition: text-shadow 0.5s linear;
-moz-transition: text-shadow 0.5s linear;
-ms-transition: text-shadow 0.5s linear;
-o-transition: text-shadow 0.5s linear;
transition: text-shadow 0.5s linear;
margin-right: 15px;
}
h1.glow, h2.glow, h3.glow, h4.glow, h5.glow, h6.glow {
text-shadow: 0 0 15px cyan;
}
dt {
font-weight: bold;
}
div.multicol {
-moz-column-gap: 1em;
-webkit-column-gap: 1em;
-moz-column-count: 3;
-webkit-column-count: 3;
}
p.startli, p.startdd {
margin-top: 2px;
}
p.starttd {
margin-top: 0px;
}
p.endli {
margin-bottom: 0px;
}
p.enddd {
margin-bottom: 4px;
}
p.endtd {
margin-bottom: 2px;
}
/* @end */
caption {
font-weight: bold;
}
span.legend {
font-size: 70%;
text-align: center;
}
h3.version {
font-size: 90%;
text-align: center;
}
div.qindex, div.navtab{
background-color: #EBEFF6;
border: 1px solid #A3B4D7;
text-align: center;
}
div.qindex, div.navpath {
width: 100%;
line-height: 140%;
}
div.navtab {
margin-right: 15px;
}
/* @group Link Styling */
a {
color: #3D578C;
font-weight: normal;
text-decoration: none;
}
.contents a:visited {
color: #4665A2;
}
a:hover {
text-decoration: underline;
}
a.qindex {
font-weight: bold;
}
a.qindexHL {
font-weight: bold;
background-color: #9CAFD4;
color: #ffffff;
border: 1px double #869DCA;
}
.contents a.qindexHL:visited {
color: #ffffff;
}
a.el {
font-weight: bold;
}
a.elRef {
}
a.code, a.code:visited, a.line, a.line:visited {
color: #4665A2;
}
a.codeRef, a.codeRef:visited, a.lineRef, a.lineRef:visited {
color: #4665A2;
}
/* @end */
dl.el {
margin-left: -1cm;
}
pre.fragment {
border: 1px solid #C4CFE5;
background-color: #FBFCFD;
padding: 4px 6px;
margin: 4px 8px 4px 2px;
overflow: auto;
word-wrap: break-word;
font-size: 9pt;
line-height: 125%;
font-family: monospace, fixed;
font-size: 105%;
}
div.fragment {
padding: 0px;
margin: 4px 8px 4px 2px;
background-color: #FBFCFD;
border: 1px solid #C4CFE5;
}
div.line {
font-family: monospace, fixed;
font-size: 13px;
min-height: 13px;
line-height: 1.0;
text-wrap: unrestricted;
white-space: -moz-pre-wrap; /* Moz */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: pre-wrap; /* CSS3 */
word-wrap: break-word; /* IE 5.5+ */
text-indent: -53px;
padding-left: 53px;
padding-bottom: 0px;
margin: 0px;
-webkit-transition-property: background-color, box-shadow;
-webkit-transition-duration: 0.5s;
-moz-transition-property: background-color, box-shadow;
-moz-transition-duration: 0.5s;
-ms-transition-property: background-color, box-shadow;
-ms-transition-duration: 0.5s;
-o-transition-property: background-color, box-shadow;
-o-transition-duration: 0.5s;
transition-property: background-color, box-shadow;
transition-duration: 0.5s;
}
div.line:after {
content:"\000A";
white-space: pre;
}
div.line.glow {
background-color: cyan;
box-shadow: 0 0 10px cyan;
}
span.lineno {
padding-right: 4px;
text-align: right;
border-right: 2px solid #0F0;
background-color: #E8E8E8;
white-space: pre;
}
span.lineno a {
background-color: #D8D8D8;
}
span.lineno a:hover {
background-color: #C8C8C8;
}
.lineno {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
div.ah, span.ah {
background-color: black;
font-weight: bold;
color: #ffffff;
margin-bottom: 3px;
margin-top: 3px;
padding: 0.2em;
border: solid thin #333;
border-radius: 0.5em;
-webkit-border-radius: .5em;
-moz-border-radius: .5em;
box-shadow: 2px 2px 3px #999;
-webkit-box-shadow: 2px 2px 3px #999;
-moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px;
background-image: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#000),color-stop(0.3, #444));
background-image: -moz-linear-gradient(center top, #eee 0%, #444 40%, #000 110%);
}
div.classindex ul {
list-style: none;
padding-left: 0;
}
div.classindex span.ai {
display: inline-block;
}
div.groupHeader {
margin-left: 16px;
margin-top: 12px;
font-weight: bold;
}
div.groupText {
margin-left: 16px;
font-style: italic;
}
body {
background-color: white;
color: black;
margin: 0;
}
div.contents {
margin-top: 10px;
margin-left: 12px;
margin-right: 8px;
}
td.indexkey {
background-color: #EBEFF6;
font-weight: bold;
border: 1px solid #e6e6e6;
margin: 2px 0px 2px 0;
padding: 2px 10px;
white-space: nowrap;
vertical-align: top;
}
td.indexvalue {
background-color: #EBEFF6;
border: 1px solid #e6e6e6;
padding: 2px 10px;
margin: 2px 0px;
}
tr.memlist {
background-color: #EEF1F7;
}
p.formulaDsp {
text-align: center;
}
img.formulaDsp {
}
img.formulaInl {
vertical-align: middle;
}
div.center {
text-align: center;
margin-top: 0px;
margin-bottom: 0px;
padding: 0px;
}
div.center img {
border: 0px;
}
address.footer {
text-align: right;
padding-right: 12px;
}
img.footer {
border: 0px;
vertical-align: middle;
}
/* @group Code Colorization */
span.keyword {
color: #008000
}
span.keywordtype {
color: #604020
}
span.keywordflow {
color: #e08000
}
span.comment {
color: #800000
}
span.preprocessor {
color: #806020
}
span.stringliteral {
color: #002080
}
span.charliteral {
color: #008080
}
span.vhdldigit {
color: #ff00ff
}
span.vhdlchar {
color: #000000
}
span.vhdlkeyword {
color: #700070
}
span.vhdllogic {
color: #ff0000
}
blockquote {
background-color: #F7F8FB;
border-left: 2px solid #e6e6e6;
margin: 0 24px 0 4px;
padding: 0 12px 0 16px;
}
/* @end */
/*
.search {
color: #003399;
font-weight: bold;
}
form.search {
margin-bottom: 0px;
margin-top: 0px;
}
input.search {
font-size: 75%;
color: #000080;
font-weight: normal;
background-color: #e8eef2;
}
*/
td.tiny {
font-size: 75%;
}
.dirtab {
padding: 4px;
border-collapse: collapse;
border: 1px solid #e6e6e6;
}
th.dirtab {
background: #EBEFF6;
font-weight: bold;
}
hr {
height: 0px;
border: none;
border-top: 1px solid #e6e6e6;
}
hr.footer {
height: 1px;
}
/* @group Member Descriptions */
table.memberdecls {
border-spacing: 0px;
padding: 0px;
}
.memberdecls td, .fieldtable tr {
-webkit-transition-property: background-color, box-shadow;
-webkit-transition-duration: 0.5s;
-moz-transition-property: background-color, box-shadow;
-moz-transition-duration: 0.5s;
-ms-transition-property: background-color, box-shadow;
-ms-transition-duration: 0.5s;
-o-transition-property: background-color, box-shadow;
-o-transition-duration: 0.5s;
transition-property: background-color, box-shadow;
transition-duration: 0.5s;
}
.memberdecls td.glow, .fieldtable tr.glow {
background-color: cyan;
box-shadow: 0 0 15px cyan;
}
.mdescLeft, .mdescRight,
.memItemLeft, .memItemRight,
.memTemplItemLeft, .memTemplItemRight, .memTemplParams {
background-color: #F9FAFC;
border: none;
margin: 4px;
padding: 1px 0 0 8px;
}
.mdescLeft, .mdescRight {
padding: 0px 8px 4px 8px;
color: #555;
}
.memSeparator {
border-bottom: 1px solid #e6e6e6;
line-height: 1px;
margin: 0px;
padding: 0px;
}
.memItemLeft, .memTemplItemLeft {
white-space: nowrap;
}
.memItemRight {
width: 100%;
}
.memTemplParams {
color: #4665A2;
white-space: nowrap;
font-size: 80%;
}
/* @end */
/* @group Member Details */
/* Styles for detailed member documentation */
.memtitle {
display: none;
padding: 8px 0px 8px 8px;
border-top: 1px solid #e6e6e6;
border-left: 1px solid #e6e6e6;
border-right: 1px solid #e6e6e6;
/* border-top-right-radius: 4px;
border-top-left-radius: 4px; */
margin-bottom: -1px;
/* background-image: url('nav_f.png'); */
background-repeat: repeat-x;
background-color: #E2E8F2;
line-height: 1.25;
font-weight: 300;
/* float:left; */
/* added */
width: 100%;
}
.permalink
{
font-size: 65%;
display: inline-block;
vertical-align: middle;
}
.memtemplate {
font-size: 80%;
color: #4665A2;
font-weight: normal;
margin-left: 9px;
}
.memnav {
background-color: #EBEFF6;
border: 1px solid #e6e6e6;
text-align: center;
margin: 2px;
margin-right: 15px;
padding: 2px;
}
.mempage {
width: 100%;
}
.memitem {
padding: 0;
margin-bottom: 10px;
margin-right: 5px;
-webkit-transition: box-shadow 0.5s linear;
-moz-transition: box-shadow 0.5s linear;
-ms-transition: box-shadow 0.5s linear;
-o-transition: box-shadow 0.5s linear;
transition: box-shadow 0.5s linear;
display: table !important;
width: 100%;
}
.memitem.glow {
box-shadow: 0 0 15px cyan;
}
.memname {
font-weight: 400;
margin-left: 6px;
}
.memname td {
font-weight: 900;
vertical-align: bottom;
}
.memproto, dl.reflist dt {
border-top: 1px solid #e6e6e6;
border-left: 1px solid #e6e6e6;
border-right: 1px solid #e6e6e6;
border-bottom: 1px dotted #e6e6e6;
padding: 6px 0px 6px 0px;
color: #253555;
font-weight: bold;
//text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9);
background-color: #f8f8f8;
/* opera specific markup */
//box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15);
//border-top-right-radius: 4px;
/* firefox specific markup */
//-moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px;
//-moz-border-radius-topright: 4px;
/* webkit specific markup */
//-webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15);
//-webkit-border-top-right-radius: 4px;
}
.overload {
font-family: "courier new",courier,monospace;
font-size: 65%;
}
.memdoc, dl.reflist dd {
border-bottom: 1px solid #e6e6e6;
border-left: 1px solid #e6e6e6;
border-right: 1px solid #e6e6e6;
padding: 6px 10px 2px 10px;
border-top-width: 0;
//background-image:url('nav_g.png');
//background-repeat:repeat-x;
background-color: #FFFFFF;
/* opera specific markup */
//border-bottom-left-radius: 4px;
//border-bottom-right-radius: 4px;
//box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15);
/* firefox specific markup */
//-moz-border-radius-bottomleft: 4px;
//-moz-border-radius-bottomright: 4px;
// -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px;
/* webkit specific markup */
//-webkit-border-bottom-left-radius: 4px;
//-webkit-border-bottom-right-radius: 4px;
// -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15);
}
dl.reflist dt {
padding: 5px;
}
dl.reflist dd {
margin: 0px 0px 10px 0px;
padding: 5px;
}
.paramkey {
text-align: right;
}
.paramtype {
white-space: nowrap;
}
.paramname {
color: #602020;
white-space: nowrap;
}
.paramname em {
font-style: normal;
}
.paramname code {
line-height: 14px;
}
.params, .retval, .exception, .tparams {
margin-left: 0px;
padding-left: 0px;
}
.params .paramname, .retval .paramname {
font-weight: bold;
vertical-align: top;
}
.params .paramtype {
font-style: italic;
vertical-align: top;
}
.params .paramdir {
font-family: "courier new",courier,monospace;
vertical-align: top;
}
table.mlabels {
border-spacing: 0px;
}
td.mlabels-left {
width: 100%;
padding: 0px;
}
td.mlabels-right {
vertical-align: bottom;
padding: 0px;
white-space: nowrap;
}
span.mlabels {
margin-left: 8px;
}
span.mlabel {
background-color: #728DC1;
border-top:1px solid #e6e6e6;
border-left:1px solid #e6e6e6;
border-right:1px solid #e6e6e6;
border-bottom:1px solid #e6e6e6;
text-shadow: none;
color: white;
margin-right: 4px;
padding: 2px 3px;
border-radius: 3px;
font-size: 7pt;
white-space: nowrap;
vertical-align: middle;
}
/* @end */
/* these are for tree view inside a (index) page */
div.directory {
margin: 10px 0px;
border-top: 1px solid #e6e6e6;
border-bottom: 1px solid #e6e6e6;
width: 100%;
}
.directory table {
border-collapse:collapse;
}
.directory td {
margin: 0px;
padding: 0px;
vertical-align: top;
}
.directory td.entry {
white-space: nowrap;
padding-right: 6px;
padding-top: 3px;
}
.directory td.entry a {
outline:none;
}
.directory td.entry a img {
border: none;
}
.directory td.desc {
width: 100%;
padding-left: 6px;
padding-right: 6px;
padding-top: 3px;
border-left: 1px solid rgba(0,0,0,0.05);
}
.directory tr.even {
padding-left: 6px;
background-color: #F7F8FB;
}
.directory img {
vertical-align: -30%;
}
.directory .levels {
white-space: nowrap;
width: 100%;
text-align: right;
font-size: 9pt;
}
.directory .levels span {
cursor: pointer;
padding-left: 2px;
padding-right: 2px;
color: #3D578C;
}
.arrow {
color: #9CAFD4;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
font-size: 80%;
display: inline-block;
width: 16px;
height: 22px;
}
.icon {
font-family: Arial, Helvetica;
font-weight: bold;
font-size: 12px;
height: 14px;
width: 16px;
display: inline-block;
background-color: #728DC1;
color: white;
text-align: center;
border-radius: 4px;
margin-left: 2px;
margin-right: 2px;
}
.icona {
width: 24px;
height: 22px;
display: inline-block;
}
.iconfopen {
width: 24px;
height: 18px;
margin-bottom: 4px;
background-image:url('folderopen.png');
background-position: 0px -4px;
background-repeat: repeat-y;
vertical-align:top;
display: inline-block;
}
.iconfclosed {
width: 24px;
height: 18px;
margin-bottom: 4px;
background-image:url('folderclosed.png');
background-position: 0px -4px;
background-repeat: repeat-y;
vertical-align:top;
display: inline-block;
}
.icondoc {
width: 24px;
height: 18px;
margin-bottom: 4px;
background-image:url('doc.png');
background-position: 0px -4px;
background-repeat: repeat-y;
vertical-align:top;
display: inline-block;
}
table.directory {
font: 400 14px Roboto,sans-serif;
}
/* @end */
div.dynheader {
margin-top: 8px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
address {
font-style: normal;
color: #2A3D61;
}
table.doxtable caption {
caption-side: top;
}
table.doxtable {
border-collapse:collapse;
margin-top: 4px;
margin-bottom: 4px;
}
table.doxtable td, table.doxtable th {
border: 1px solid #2D4068;
padding: 3px 7px 2px;
}
table.doxtable th {
background-color: #374F7F;
color: #FFFFFF;
font-size: 110%;
padding-bottom: 4px;
padding-top: 5px;
}
table.fieldtable {
/*width: 100%;*/
margin-bottom: 10px;
border: 1px solid #e6e6e6;
border-spacing: 0px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
-moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px;
-webkit-box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15);
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15);
}
.fieldtable td, .fieldtable th {
padding: 3px 7px 2px;
}
.fieldtable td.fieldtype, .fieldtable td.fieldname {
white-space: nowrap;
border-right: 1px solid #e6e6e6;
border-bottom: 1px solid #e6e6e6;
vertical-align: top;
}
.fieldtable td.fieldname {
padding-top: 3px;
}
.fieldtable td.fielddoc {
border-bottom: 1px solid #e6e6e6;
/*width: 100%;*/
}
.fieldtable td.fielddoc p:first-child {
margin-top: 0px;
}
.fieldtable td.fielddoc p:last-child {
margin-bottom: 2px;
}
.fieldtable tr:last-child td {
border-bottom: none;
}
.fieldtable th {
background-image:url('nav_f.png');
background-repeat:repeat-x;
background-color: #E2E8F2;
font-size: 90%;
color: #253555;
padding-bottom: 4px;
padding-top: 5px;
text-align:left;
font-weight: 400;
-moz-border-radius-topleft: 4px;
-moz-border-radius-topright: 4px;
-webkit-border-top-left-radius: 4px;
-webkit-border-top-right-radius: 4px;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom: 1px solid #e6e6e6;
}
.tabsearch {
top: 0px;
left: 10px;
height: 36px;
background-image: url('tab_b.png');
z-index: 101;
overflow: hidden;
font-size: 13px;
}
.navpath ul
{
font-size: 11px;
background-image:url('tab_b.png');
background-repeat:repeat-x;
background-position: 0 -5px;
height:30px;
line-height:30px;
color:#8AA0CC;
border:solid 1px #e6e6e6;
overflow:hidden;
margin:0px;
padding:0px;
}
.navpath li
{
list-style-type:none;
float:left;
padding-left:10px;
padding-right:15px;
background-image:url('bc_s.png');
background-repeat:no-repeat;
background-position:right;
color:#364D7C;
}
.navpath li.navelem a
{
height:32px;
display:block;
text-decoration: none;
outline: none;
color: #283A5D;
font-family: 'Lucida Grande',Geneva,Helvetica,Arial,sans-serif;
text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9);
text-decoration: none;
}
.navpath li.navelem a:hover
{
color:#6884BD;
}
.navpath li.footer
{
list-style-type:none;
float:right;
padding-left:10px;
padding-right:15px;
background-image:none;
background-repeat:no-repeat;
background-position:right;
color:#364D7C;
font-size: 8pt;
}
div.summary
{
float: right;
font-size: 8pt;
padding-right: 5px;
width: 50%;
text-align: right;
}
div.summary a
{
white-space: nowrap;
}
table.classindex
{
margin: 10px;
white-space: nowrap;
margin-left: 3%;
margin-right: 3%;
width: 94%;
border: 0;
border-spacing: 0;
padding: 0;
}
div.ingroups
{
font-size: 8pt;
width: 50%;
text-align: left;
}
div.ingroups a
{
white-space: nowrap;
}
div.header
{
background-image:url('nav_h.png');
background-repeat:repeat-x;
background-color: #F9FAFC;
margin: 0px;
border-bottom: 1px solid #e6e6e6;
}
div.headertitle
{
padding: 5px 5px 5px 10px;
}
dl
{
padding: 0 0 0 10px;
}
/* dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug */
dl.section
{
margin-left: 0px;
padding-left: 0px;
}
dl.note
{
margin-left:-7px;
padding-left: 3px;
border-left:4px solid;
border-color: #e6e6e6;
}
dl.warning, dl.attention
{
margin-left:-7px;
padding-left: 3px;
border-left:4px solid;
border-color: #FF0000;
}
dl.pre, dl.post, dl.invariant
{
margin-left:-7px;
padding-left: 3px;
border-left:4px solid;
border-color: #00D000;
}
dl.deprecated
{
margin-left:-7px;
padding-left: 3px;
border-left:4px solid;
border-color: #505050;
}
dl.todo
{
margin-left:-7px;
padding-left: 3px;
border-left:4px solid;
border-color: #00C0E0;
}
dl.test
{
margin-left:-7px;
padding-left: 3px;
border-left:4px solid;
border-color: #3030E0;
}
dl.bug
{
margin-left:-7px;
padding-left: 3px;
border-left:4px solid;
border-color: #C08050;
}
dl.section dd {
margin-bottom: 6px;
}
#projectlogo
{
text-align: center;
vertical-align: bottom;
border-collapse: separate;
}
#projectlogo img
{
border: 0px none;
}
#projectalign
{
vertical-align: middle;
}
#projectname
{
font: 300% Tahoma, Arial,sans-serif;
margin: 0px;
padding: 2px 0px;
}
#projectbrief
{
font: 120% Tahoma, Arial,sans-serif;
margin: 0px;
padding: 0px;
}
#projectnumber
{
font: 50% Tahoma, Arial,sans-serif;
margin: 0px;
padding: 0px;
}
#titlearea
{
padding: 0px;
margin: 0px;
width: 100%;
border-bottom: 1px solid #5373B4;
}
.image
{
text-align: center;
}
.dotgraph
{
text-align: center;
}
.mscgraph
{
text-align: center;
}
.plantumlgraph
{
text-align: center;
}
.diagraph
{
text-align: center;
}
.caption
{
font-weight: bold;
}
div.zoom
{
border: 1px solid #90A5CE;
}
dl.citelist {
margin-bottom:50px;
}
dl.citelist dt {
color:#334975;
float:left;
font-weight:bold;
margin-right:10px;
padding:5px;
}
dl.citelist dd {
margin:2px 0;
padding:5px 0;
}
div.toc {
padding: 14px 25px;
background-color: #F4F6FA;
border: 1px solid #D8DFEE;
border-radius: 7px 7px 7px 7px;
float: right;
height: auto;
margin: 0 8px 10px 10px;
width: 200px;
}
div.toc li {
background: url("bdwn.png") no-repeat scroll 0 5px transparent;
font: 10px/1.2 Verdana,DejaVu Sans,Geneva,sans-serif;
margin-top: 5px;
padding-left: 10px;
padding-top: 2px;
}
div.toc h3 {
font: bold 12px/1.2 Arial,FreeSans,sans-serif;
color: #4665A2;
border-bottom: 0 none;
margin: 0;
}
div.toc ul {
list-style: none outside none;
border: medium none;
padding: 0px;
}
div.toc li.level1 {
margin-left: 0px;
}
div.toc li.level2 {
margin-left: 15px;
}
div.toc li.level3 {
margin-left: 30px;
}
div.toc li.level4 {
margin-left: 45px;
}
.inherit_header {
font-weight: bold;
color: gray;
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.inherit_header td {
padding: 6px 0px 2px 5px;
}
.inherit {
display: none;
}
tr.heading h2 {
margin-top: 12px;
margin-bottom: 4px;
}
/* tooltip related style info */
.ttc {
position: absolute;
display: none;
}
#powerTip {
cursor: default;
white-space: nowrap;
background-color: white;
border: 1px solid gray;
border-radius: 4px 4px 4px 4px;
box-shadow: 1px 1px 7px gray;
display: none;
font-size: smaller;
max-width: 80%;
opacity: 0.9;
padding: 1ex 1em 1em;
position: absolute;
z-index: 2147483647;
}
#powerTip div.ttdoc {
color: grey;
font-style: italic;
}
#powerTip div.ttname a {
font-weight: bold;
}
#powerTip div.ttname {
font-weight: bold;
}
#powerTip div.ttdeci {
color: #006318;
}
#powerTip div {
margin: 0px;
padding: 0px;
font: 12px/16px Roboto,sans-serif;
}
#powerTip:before, #powerTip:after {
content: "";
position: absolute;
margin: 0px;
}
#powerTip.n:after, #powerTip.n:before,
#powerTip.s:after, #powerTip.s:before,
#powerTip.w:after, #powerTip.w:before,
#powerTip.e:after, #powerTip.e:before,
#powerTip.ne:after, #powerTip.ne:before,
#powerTip.se:after, #powerTip.se:before,
#powerTip.nw:after, #powerTip.nw:before,
#powerTip.sw:after, #powerTip.sw:before {
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
}
#powerTip.n:after, #powerTip.s:after,
#powerTip.w:after, #powerTip.e:after,
#powerTip.nw:after, #powerTip.ne:after,
#powerTip.sw:after, #powerTip.se:after {
border-color: rgba(255, 255, 255, 0);
}
#powerTip.n:before, #powerTip.s:before,
#powerTip.w:before, #powerTip.e:before,
#powerTip.nw:before, #powerTip.ne:before,
#powerTip.sw:before, #powerTip.se:before {
border-color: rgba(128, 128, 128, 0);
}
#powerTip.n:after, #powerTip.n:before,
#powerTip.ne:after, #powerTip.ne:before,
#powerTip.nw:after, #powerTip.nw:before {
top: 100%;
}
#powerTip.n:after, #powerTip.ne:after, #powerTip.nw:after {
border-top-color: #ffffff;
border-width: 10px;
margin: 0px -10px;
}
#powerTip.n:before {
border-top-color: #808080;
border-width: 11px;
margin: 0px -11px;
}
#powerTip.n:after, #powerTip.n:before {
left: 50%;
}
#powerTip.nw:after, #powerTip.nw:before {
right: 14px;
}
#powerTip.ne:after, #powerTip.ne:before {
left: 14px;
}
#powerTip.s:after, #powerTip.s:before,
#powerTip.se:after, #powerTip.se:before,
#powerTip.sw:after, #powerTip.sw:before {
bottom: 100%;
}
#powerTip.s:after, #powerTip.se:after, #powerTip.sw:after {
border-bottom-color: #ffffff;
border-width: 10px;
margin: 0px -10px;
}
#powerTip.s:before, #powerTip.se:before, #powerTip.sw:before {
border-bottom-color: #808080;
border-width: 11px;
margin: 0px -11px;
}
#powerTip.s:after, #powerTip.s:before {
left: 50%;
}
#powerTip.sw:after, #powerTip.sw:before {
right: 14px;
}
#powerTip.se:after, #powerTip.se:before {
left: 14px;
}
#powerTip.e:after, #powerTip.e:before {
left: 100%;
}
#powerTip.e:after {
border-left-color: #ffffff;
border-width: 10px;
top: 50%;
margin-top: -10px;
}
#powerTip.e:before {
border-left-color: #808080;
border-width: 11px;
top: 50%;
margin-top: -11px;
}
#powerTip.w:after, #powerTip.w:before {
right: 100%;
}
#powerTip.w:after {
border-right-color: #ffffff;
border-width: 10px;
top: 50%;
margin-top: -10px;
}
#powerTip.w:before {
border-right-color: #808080;
border-width: 11px;
top: 50%;
margin-top: -11px;
}
@media print
{
#top { display: none; }
#side-nav { display: none; }
#nav-path { display: none; }
body { overflow:visible; }
h1, h2, h3, h4, h5, h6 { page-break-after: avoid; }
.summary { display: none; }
.memitem { page-break-inside: avoid; }
#doc-content
{
margin-left:0 !important;
height:auto !important;
width:auto !important;
overflow:inherit;
display:inline;
}
}
/* @group Markdown */
/*
table.markdownTable {
border-collapse:collapse;
margin-top: 4px;
margin-bottom: 4px;
}
table.markdownTable td, table.markdownTable th {
border: 1px solid #2D4068;
padding: 3px 7px 2px;
}
table.markdownTableHead tr {
}
table.markdownTableBodyLeft td, table.markdownTable th {
border: 1px solid #2D4068;
padding: 3px 7px 2px;
}
th.markdownTableHeadLeft th.markdownTableHeadRight th.markdownTableHeadCenter th.markdownTableHeadNone {
background-color: #374F7F;
color: #FFFFFF;
font-size: 110%;
padding-bottom: 4px;
padding-top: 5px;
}
th.markdownTableHeadLeft {
text-align: left
}
th.markdownTableHeadRight {
text-align: right
}
th.markdownTableHeadCenter {
text-align: center
}
*/
table.markdownTable {
border-collapse:collapse;
margin-top: 4px;
margin-bottom: 4px;
}
table.markdownTable td, table.markdownTable th {
border: 1px solid #2D4068;
padding: 3px 7px 2px;
}
table.markdownTable tr {
}
th.markdownTableHeadLeft, th.markdownTableHeadRight, th.markdownTableHeadCenter, th.markdownTableHeadNone {
background-color: #374F7F;
color: #FFFFFF;
font-size: 110%;
padding-bottom: 4px;
padding-top: 5px;
}
th.markdownTableHeadLeft, td.markdownTableBodyLeft {
text-align: left
}
th.markdownTableHeadRight, td.markdownTableBodyRight {
text-align: right
}
th.markdownTableHeadCenter, td.markdownTableBodyCenter {
text-align: center
}
/* @end */
| ml-agents/docs/doxygen/doxygenbase.css/0 | {
"file_path": "ml-agents/docs/doxygen/doxygenbase.css",
"repo_id": "ml-agents",
"token_count": 13348
} | 1,859 |
# ML-Agents 용 도커 사용법
도커를 사용해 추론과 학습을 하고자하는 Windows와 Mac 사용자를 위한 솔루션을 제공합니다.
이것은 Python과 TensorFlow 설치를 피하고자 하는 분에게 매력적인 옵션이 될 것입니다. 현재 설정은 TensorFlow와 Unity가 _CPU를 통해서만_
계산하도록 합니다. 따라서 도커 시뮬레이션은 GPU를 사용하지 않고 시각적 렌더링을 위해 [`Xvfb`](https://en.wikipedia.org/wiki/Xvfb)를 사용합니다.
`Xvfb`는 `ML-Agents`(또는 다른 응용 프로그램)가 가상으로 렌더링을 할 수 있게하는 유틸리티 입니다. 즉, `ML-Agents`를 실행하는 기계가 GPU를 가지고 있거나
디스플레이를 가지고 있다고 가정하지 않습니다. 이것은 카메라 기반의 시각적 관찰 요소가 포함된 환경은 더욱 느려질 수도 있음을 의미합니다.
## 요구사항
- 유니티 _Linux Build Support_ 컴포넌트
- [도커](https://www.docker.com)
## 설치
- 유니티 인스톨러를 [다운로드](https://unity3d.com/kr/get-unity/download)하고 _Linux Build Support_ 컴포넌트를 추가하십시오.
- 도커가 설치되어 있지 않다면 [다운로드](https://www.docker.com/community-edition#/download)하고 설치 하십시오.
- 호스트 머신과 분리된 환경에서 도커를 실행하기 때문에, 호스트 머신안에 마운트된 디렉토리는 트레이너 환경 설정 파일,
유니티 실행 파일, 커리큘럼 파일과 TensorFlow 그래프와 같은 데이터를 공유하기위해 사용됩니다.
이를 위해, 편의상 비어있는 `unity-volume` 디렉토리를 저장소의 루트에 만들었으나, 다른 디렉토리의 사용은 자유롭게 할 수 있습니다.
이 가이드의 나머지 부분에서는 `unity-volume` 디렉토리가 사용된다고 가정하고 진행됩니다.
## 사용법
ML-Agents 용 도커 사용에는 세 단계가 포함됩니다.: 특정 플래그를 사용하여 유니티 환경 빌드, 도커 컨테이너 빌드
마지막으로, 컨테이너 실행. 만약 ML-Agents 용 유니티 환경 빌드에 익숙하지 않다면, [3D 밸런스 볼 예제와 함께 시작하기](Getting-Started-with-Balance-Ball.md) 가이드를 먼저 읽으십시오.
### 환경 빌드 (옵션)
_학습을 위해 에디터 사용을 원한다면 이 단계를 건너뛸 수 있습니다._
도커는 일반적으로 호스트 머신과 (리눅스) 커널을 공유하는 컨테이너를 실행하기 때문에,
유니티 환경은 리눅스 플랫폼이 구축되어야 합니다. 유니티 환경을 빌드할 때, 빌드 세팅 창(Build Settings window)에서
다음 옵션을 선택해 주십시오:
- 타겟 플랫폼을 `리눅스`로 설정 (Set the _Target Platform_ to `Linux`)
- _아키텍처_를 `x86_64'로 설정 (Set the _Architecture_ to `x86_64`)
- 환경에서 시각적인 관찰을 필요로 하지않는다면, `headless` 옵션을 선택할 수 있습니다 (아래 사진 참조).
`빌드` (Build)를 클릭하고, 환경 이름을 선택하고 (예시: `3DBall`) 출력 디레토리를 `unity-volume`으로 설정하십시오.
빌드 후에, 파일 `<환경 이름>.x86_64` 와 하위디렉토리 `<환경 이름>_Data/` 가 `unity-volume` 에 생성 되어있는지 확인하십시오.

### 도커 컨테이너 빌드
첫 번째, 도커 머신이 시스템에서 작동하는지 확인하십시오. 저장소의 최상단에서 다음 명령어를 호출하여
도커 컨테이너를 빌드하십시오:
```sh
docker build -t <image-name> .
```
`<image-name>`을 도커 이미지 이름으로 바꾸십시오, 예시: `balance.ball.v0.1`.
### 도커 컨테이너 실행
저장소의 최상단에서 다음 명령어를 호출하여 도커 컨테이너를 실행하십시오:
```sh
docker run --name <container-name> \
--mount type=bind,source="$(pwd)"/unity-volume,target=/unity-volume \
-p 5005:5005 \
<image-name>:latest \
--docker-target-name=unity-volume \
<trainer-config-file> \
--env=<environment-name> \
--train \
--run-id=<run-id>
```
인수(argument) 값 정보:
- `<container-name>` 은 컨테이너를 구분하기위해 사용됩니다 (컨테이너를 인터럽트하거나 종료시킬 때).
이것은 선택사항이며 설정하지 않았을 경우 도커는 랜덤한 이름을 생성합니다. _도커 이미지를 실행할 때마다
고유한 이름을 가져야함에 유의하십시오._
- `<image-name>` 컨테이너를 빌드할 때 사용할 image name을 참조합니다.
- `<environment-name>` __(옵션)__: 리눅스 실행파일과 함께 학습을 할 경우, 인수 값이 실행파일의 이름이 된다.
에디터에서 학습을 할 경우, `<environment-name>` 인수를 전달하지 말고 유니티에서 _"Start training by pressing
the Play button in the Unity Editor"_ 메세지가 화면에 표시될 때 :arrow_forward: 버튼을 누르십시오.
- `source`: 유니티 실행파일을 저장할 호스트 운영체제의 경로를 참조합니다.
- `target`: 도커가`source` 경로에 이 이름을 가진 디스크로 마운트하도록 합니다.
- `docker-target-name`: ML-Agents 파이썬 패키지에게 유니티 실행파일을 읽고 그래프를 저장할 수 있는 디스크의 이름을 알려준다.
**그러므로 `target`과 동일한 값을 가져야 합니다.**
- `trainer-config-file`, `train`, `run-id`: ML-Agents 인자들은 `mlagents-learn`로 전달됩니다. 트레이너 설정 파일의 이름 `trainer-config-file`,
알고리즘을 학습하는 `train`, 그리고 각 실험에 고유한 식별자를 태깅하는데 사용되는 `run-id`.
컨테이너가 파일에 접근할 수 있도록 trainer-config 파일을 `unity-volume` 안에 둘 것을 권장합니다.
`3DBall` 환경 실행파일을 학습하기 위해 다음 명령어가 사용됩니다:
```sh
docker run --name 3DBallContainer.first.trial \
--mount type=bind,source="$(pwd)"/unity-volume,target=/unity-volume \
-p 5005:5005 \
balance.ball.v0.1:latest 3DBall \
--docker-target-name=unity-volume \
trainer_config.yaml \
--env=3DBall
--train \
--run-id=3dball_first_trial
```
도커 마운트에 대한 세부 사항은 도커의 [이 문서](https://docs.docker.com/storage/bind-mounts/)를 참고해 주십시오.
**참고** 도커를 사용해 시각적인 관찰을 포함한 환경을 학습할 경우, 콘테이너를 위해 할당한 도커의 디폴트 메모리를 늘려야할 것입니다.
예를 들어, [여기](https://docs.docker.com/docker-for-mac/#advanced) Mac 사용자를 위한 도커 지시사항을 봐주십시오.
### 컨테이너 중지 및 상태 저장
학습 진행 상황에 만족했을 경우, 상태를 저장하는 동안 `Ctrl+C` or `⌘+C` (Mac) 키를 사용하거나 다음 명령어를 통해 도커 컨테이너를 중지할 수 있습니다:
```sh
docker kill --signal=SIGINT <container-name>
```
`<container-name>` 은 `docker run` 명령어에 지정된 컨테이너 이름입니다. 지정하지 않으면 무작위로 생성되며`docker container ls`를 통해 확인할 수 있습니다.
## 한글 번역
해당 문서의 한글 번역은 [장현준 (Hyeonjun Jang)]([https://github.com/janghyeonjun](https://github.com/janghyeonjun))에 의해 진행되었습니다. 내용상 오류나 오탈자가 있는 경우 totok682@naver.com 으로 연락주시면 감사드리겠습니다.
| ml-agents/localized_docs/KR/docs/Using-Docker.md/0 | {
"file_path": "ml-agents/localized_docs/KR/docs/Using-Docker.md",
"repo_id": "ml-agents",
"token_count": 5712
} | 1,860 |
# @generated by generate_proto_mypy_stubs.py. Do not edit!
import sys
from google.protobuf.descriptor import (
Descriptor as google___protobuf___descriptor___Descriptor,
)
from google.protobuf.message import (
Message as google___protobuf___message___Message,
)
from typing import (
Optional as typing___Optional,
Text as typing___Text,
)
from typing_extensions import (
Literal as typing_extensions___Literal,
)
builtin___bool = bool
builtin___bytes = bytes
builtin___float = float
builtin___int = int
class DemonstrationMetaProto(google___protobuf___message___Message):
DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
api_version = ... # type: builtin___int
demonstration_name = ... # type: typing___Text
number_steps = ... # type: builtin___int
number_episodes = ... # type: builtin___int
mean_reward = ... # type: builtin___float
def __init__(self,
*,
api_version : typing___Optional[builtin___int] = None,
demonstration_name : typing___Optional[typing___Text] = None,
number_steps : typing___Optional[builtin___int] = None,
number_episodes : typing___Optional[builtin___int] = None,
mean_reward : typing___Optional[builtin___float] = None,
) -> None: ...
@classmethod
def FromString(cls, s: builtin___bytes) -> DemonstrationMetaProto: ...
def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ...
def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ...
if sys.version_info >= (3,):
def ClearField(self, field_name: typing_extensions___Literal[u"api_version",u"demonstration_name",u"mean_reward",u"number_episodes",u"number_steps"]) -> None: ...
else:
def ClearField(self, field_name: typing_extensions___Literal[u"api_version",b"api_version",u"demonstration_name",b"demonstration_name",u"mean_reward",b"mean_reward",u"number_episodes",b"number_episodes",u"number_steps",b"number_steps"]) -> None: ...
| ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/demonstration_meta_pb2.pyi/0 | {
"file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/demonstration_meta_pb2.pyi",
"repo_id": "ml-agents",
"token_count": 729
} | 1,861 |
# @generated by generate_proto_mypy_stubs.py. Do not edit!
import sys
from google.protobuf.descriptor import (
Descriptor as google___protobuf___descriptor___Descriptor,
)
from google.protobuf.message import (
Message as google___protobuf___message___Message,
)
from mlagents_envs.communicator_objects.unity_rl_initialization_output_pb2 import (
UnityRLInitializationOutputProto as mlagents_envs___communicator_objects___unity_rl_initialization_output_pb2___UnityRLInitializationOutputProto,
)
from mlagents_envs.communicator_objects.unity_rl_output_pb2 import (
UnityRLOutputProto as mlagents_envs___communicator_objects___unity_rl_output_pb2___UnityRLOutputProto,
)
from typing import (
Optional as typing___Optional,
)
from typing_extensions import (
Literal as typing_extensions___Literal,
)
builtin___bool = bool
builtin___bytes = bytes
builtin___float = float
builtin___int = int
class UnityOutputProto(google___protobuf___message___Message):
DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
@property
def rl_output(self) -> mlagents_envs___communicator_objects___unity_rl_output_pb2___UnityRLOutputProto: ...
@property
def rl_initialization_output(self) -> mlagents_envs___communicator_objects___unity_rl_initialization_output_pb2___UnityRLInitializationOutputProto: ...
def __init__(self,
*,
rl_output : typing___Optional[mlagents_envs___communicator_objects___unity_rl_output_pb2___UnityRLOutputProto] = None,
rl_initialization_output : typing___Optional[mlagents_envs___communicator_objects___unity_rl_initialization_output_pb2___UnityRLInitializationOutputProto] = None,
) -> None: ...
@classmethod
def FromString(cls, s: builtin___bytes) -> UnityOutputProto: ...
def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ...
def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ...
if sys.version_info >= (3,):
def HasField(self, field_name: typing_extensions___Literal[u"rl_initialization_output",u"rl_output"]) -> builtin___bool: ...
def ClearField(self, field_name: typing_extensions___Literal[u"rl_initialization_output",u"rl_output"]) -> None: ...
else:
def HasField(self, field_name: typing_extensions___Literal[u"rl_initialization_output",b"rl_initialization_output",u"rl_output",b"rl_output"]) -> builtin___bool: ...
def ClearField(self, field_name: typing_extensions___Literal[u"rl_initialization_output",b"rl_initialization_output",u"rl_output",b"rl_output"]) -> None: ...
| ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_output_pb2.pyi/0 | {
"file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_output_pb2.pyi",
"repo_id": "ml-agents",
"token_count": 909
} | 1,862 |
from typing import Optional, Union, List
from mlagents_envs import logging_util
from mlagents_envs.exception import UnityWorkerInUseException
from mlagents_envs.registry import default_registry
from mlagents_envs.side_channel.engine_configuration_channel import (
EngineConfigurationChannel,
)
from mlagents_envs.side_channel.environment_parameters_channel import (
EnvironmentParametersChannel,
)
from mlagents_envs.side_channel.stats_side_channel import StatsSideChannel
from mlagents_envs.envs.unity_aec_env import UnityAECEnv
logger = logging_util.get_logger(__name__)
class PettingZooEnvFactory:
def __init__(self, env_id: str) -> None:
self.env_id = env_id
def env(
self, seed: Optional[int] = None, **kwargs: Union[List, int, bool, None]
) -> UnityAECEnv:
"""
Creates the environment with env_id from unity's default_registry and wraps it in a UnityToPettingZooWrapper
:param seed: The seed for the action spaces of the agents.
:param kwargs: Any argument accepted by `UnityEnvironment`class except file_name
"""
# If not side_channels specified, add the followings
if "side_channels" not in kwargs:
kwargs["side_channels"] = [
EngineConfigurationChannel(),
EnvironmentParametersChannel(),
StatsSideChannel(),
]
_env = None
# If no base port argument is provided, try ports starting at 6000 until one is free
if "base_port" not in kwargs:
port = 6000
while _env is None:
try:
kwargs["base_port"] = port
_env = default_registry[self.env_id].make(**kwargs)
except UnityWorkerInUseException:
port += 1
pass
else:
_env = default_registry[self.env_id].make(**kwargs)
return UnityAECEnv(_env, seed)
| ml-agents/ml-agents-envs/mlagents_envs/envs/pettingzoo_env_factory.py/0 | {
"file_path": "ml-agents/ml-agents-envs/mlagents_envs/envs/pettingzoo_env_factory.py",
"repo_id": "ml-agents",
"token_count": 824
} | 1,863 |
import sys
import uuid
import mlagents_envs
from mlagents_envs.exception import UnityCommunicationException
from mlagents_envs.side_channel import SideChannel, IncomingMessage, OutgoingMessage
from mlagents_envs.communicator_objects.training_analytics_pb2 import (
TrainingEnvironmentInitialized,
)
from google.protobuf.any_pb2 import Any
class DefaultTrainingAnalyticsSideChannel(SideChannel):
"""
Side channel that sends information about the training to the Unity environment so it can be logged.
"""
CHANNEL_ID = uuid.UUID("b664a4a9-d86f-5a5f-95cb-e8353a7e8356")
def __init__(self) -> None:
# >>> uuid.uuid5(uuid.NAMESPACE_URL, "com.unity.ml-agents/TrainingAnalyticsSideChannel")
# UUID('b664a4a9-d86f-5a5f-95cb-e8353a7e8356')
# We purposefully use the SAME side channel as the TrainingAnalyticsSideChannel
super().__init__(DefaultTrainingAnalyticsSideChannel.CHANNEL_ID)
def on_message_received(self, msg: IncomingMessage) -> None:
raise UnityCommunicationException(
"The DefaultTrainingAnalyticsSideChannel received a message from Unity, "
+ "this should not have happened."
)
def environment_initialized(self) -> None:
# Tuple of (major, minor, patch)
vi = sys.version_info
msg = TrainingEnvironmentInitialized(
python_version=f"{vi[0]}.{vi[1]}.{vi[2]}",
mlagents_version="Custom",
mlagents_envs_version=mlagents_envs.__version__,
torch_version="Unknown",
torch_device_type="Unknown",
)
any_message = Any()
any_message.Pack(msg)
env_init_msg = OutgoingMessage()
env_init_msg.set_raw_bytes(any_message.SerializeToString()) # type: ignore
super().queue_message_to_send(env_init_msg)
| ml-agents/ml-agents-envs/mlagents_envs/side_channel/default_training_analytics_side_channel.py/0 | {
"file_path": "ml-agents/ml-agents-envs/mlagents_envs/side_channel/default_training_analytics_side_channel.py",
"repo_id": "ml-agents",
"token_count": 728
} | 1,864 |
import os
from unittest import mock
import pytest
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.base_env import DecisionSteps, TerminalSteps, ActionTuple
from mlagents_envs.exception import UnityEnvironmentException, UnityActionException
from mlagents_envs.mock_communicator import MockCommunicator
@mock.patch("mlagents_envs.environment.UnityEnvironment._get_communicator")
def test_handles_bad_filename(get_communicator):
with pytest.raises(UnityEnvironmentException):
UnityEnvironment(" ")
@mock.patch("mlagents_envs.env_utils.launch_executable")
@mock.patch("mlagents_envs.environment.UnityEnvironment._get_communicator")
def test_initialization(mock_communicator, mock_launcher):
mock_communicator.return_value = MockCommunicator(
discrete_action=False, visual_inputs=0
)
env = UnityEnvironment(" ")
assert list(env.behavior_specs.keys()) == ["RealFakeBrain"]
env.close()
@pytest.mark.parametrize(
"base_port,file_name,expected",
[
# Non-None base port value will always be used
(6001, "foo.exe", 6001),
# No port specified and environment specified, so use BASE_ENVIRONMENT_PORT
(None, "foo.exe", UnityEnvironment.BASE_ENVIRONMENT_PORT),
# No port specified and no environment, so use DEFAULT_EDITOR_PORT
(None, None, UnityEnvironment.DEFAULT_EDITOR_PORT),
],
)
@mock.patch("mlagents_envs.env_utils.launch_executable")
@mock.patch("mlagents_envs.environment.UnityEnvironment._get_communicator")
def test_port_defaults(
mock_communicator, mock_launcher, base_port, file_name, expected
):
mock_communicator.return_value = MockCommunicator(
discrete_action=False, visual_inputs=0
)
env = UnityEnvironment(file_name=file_name, worker_id=0, base_port=base_port)
assert expected == env._port
env.close()
@mock.patch("mlagents_envs.env_utils.launch_executable")
@mock.patch("mlagents_envs.environment.UnityEnvironment._get_communicator")
def test_log_file_path_is_set(mock_communicator, mock_launcher):
mock_communicator.return_value = MockCommunicator()
env = UnityEnvironment(
file_name="myfile",
worker_id=0,
log_folder=os.path.join(".", "some-log-folder-path"),
)
args = env._executable_args()
log_file_index = args.index("-logFile")
assert args[log_file_index + 1] == os.path.join(
".", "some-log-folder-path", "Player-0.log"
)
env.close()
@mock.patch("mlagents_envs.env_utils.launch_executable")
@mock.patch("mlagents_envs.environment.UnityEnvironment._get_communicator")
def test_reset(mock_communicator, mock_launcher):
mock_communicator.return_value = MockCommunicator(
discrete_action=False, visual_inputs=0
)
env = UnityEnvironment(" ")
spec = env.behavior_specs["RealFakeBrain"]
env.reset()
decision_steps, terminal_steps = env.get_steps("RealFakeBrain")
env.close()
assert isinstance(decision_steps, DecisionSteps)
assert isinstance(terminal_steps, TerminalSteps)
assert len(spec.observation_specs) == len(decision_steps.obs)
assert len(spec.observation_specs) == len(terminal_steps.obs)
n_agents = len(decision_steps)
for sen_spec, obs in zip(spec.observation_specs, decision_steps.obs):
assert (n_agents,) + sen_spec.shape == obs.shape
n_agents = len(terminal_steps)
for sen_spec, obs in zip(spec.observation_specs, terminal_steps.obs):
assert (n_agents,) + sen_spec.shape == obs.shape
@mock.patch("mlagents_envs.env_utils.launch_executable")
@mock.patch("mlagents_envs.environment.UnityEnvironment._get_communicator")
def test_step(mock_communicator, mock_launcher):
mock_communicator.return_value = MockCommunicator(
discrete_action=False, visual_inputs=0
)
env = UnityEnvironment(" ")
spec = env.behavior_specs["RealFakeBrain"]
env.step()
decision_steps, terminal_steps = env.get_steps("RealFakeBrain")
n_agents = len(decision_steps)
env.set_actions("RealFakeBrain", spec.action_spec.empty_action(n_agents))
env.step()
with pytest.raises(UnityActionException):
env.set_actions("RealFakeBrain", spec.action_spec.empty_action(n_agents - 1))
decision_steps, terminal_steps = env.get_steps("RealFakeBrain")
n_agents = len(decision_steps)
_empty_act = spec.action_spec.empty_action(n_agents)
next_action = ActionTuple(_empty_act.continuous - 1, _empty_act.discrete - 1)
env.set_actions("RealFakeBrain", next_action)
env.step()
env.close()
assert isinstance(decision_steps, DecisionSteps)
assert isinstance(terminal_steps, TerminalSteps)
assert len(spec.observation_specs) == len(decision_steps.obs)
assert len(spec.observation_specs) == len(terminal_steps.obs)
for spec, obs in zip(spec.observation_specs, decision_steps.obs):
assert (n_agents,) + spec.shape == obs.shape
assert 0 in decision_steps
assert 2 in terminal_steps
@mock.patch("mlagents_envs.env_utils.launch_executable")
@mock.patch("mlagents_envs.environment.UnityEnvironment._get_communicator")
def test_close(mock_communicator, mock_launcher):
comm = MockCommunicator(discrete_action=False, visual_inputs=0)
mock_communicator.return_value = comm
env = UnityEnvironment(" ")
assert env._loaded
env.close()
assert not env._loaded
assert comm.has_been_closed
def test_check_communication_compatibility():
unity_ver = "1.0.0"
python_ver = "1.0.0"
unity_package_version = "0.15.0"
assert UnityEnvironment._check_communication_compatibility(
unity_ver, python_ver, unity_package_version
)
unity_ver = "1.1.0"
assert UnityEnvironment._check_communication_compatibility(
unity_ver, python_ver, unity_package_version
)
unity_ver = "2.0.0"
assert not UnityEnvironment._check_communication_compatibility(
unity_ver, python_ver, unity_package_version
)
unity_ver = "0.16.0"
python_ver = "0.16.0"
assert UnityEnvironment._check_communication_compatibility(
unity_ver, python_ver, unity_package_version
)
unity_ver = "0.17.0"
assert not UnityEnvironment._check_communication_compatibility(
unity_ver, python_ver, unity_package_version
)
unity_ver = "1.16.0"
assert not UnityEnvironment._check_communication_compatibility(
unity_ver, python_ver, unity_package_version
)
def test_returncode_to_signal_name():
assert UnityEnvironment._returncode_to_signal_name(-2) == "SIGINT"
assert UnityEnvironment._returncode_to_signal_name(42) is None
assert UnityEnvironment._returncode_to_signal_name("SIGINT") is None
if __name__ == "__main__":
pytest.main()
| ml-agents/ml-agents-envs/tests/test_envs.py/0 | {
"file_path": "ml-agents/ml-agents-envs/tests/test_envs.py",
"repo_id": "ml-agents",
"token_count": 2494
} | 1,865 |
from typing import Optional
import os
def get_num_threads_to_use() -> Optional[int]:
"""
Gets the number of threads to use. For most problems, 4 is all you
need, but for smaller machines, we'd like to scale to less than that.
By default, PyTorch uses 1/2 of the available cores.
"""
num_cpus = _get_num_available_cpus()
return max(min(num_cpus // 2, 4), 1) if num_cpus is not None else None
def _get_num_available_cpus() -> Optional[int]:
"""
Returns number of CPUs using cgroups if possible. This accounts
for Docker containers that are limited in cores.
"""
period = _read_in_integer_file("/sys/fs/cgroup/cpu/cpu.cfs_period_us")
quota = _read_in_integer_file("/sys/fs/cgroup/cpu/cpu.cfs_quota_us")
share = _read_in_integer_file("/sys/fs/cgroup/cpu/cpu.shares")
is_kubernetes = os.getenv("KUBERNETES_SERVICE_HOST") is not None
if period > 0 and quota > 0:
return int(quota // period)
elif period > 0 and share > 0 and is_kubernetes:
# In kubernetes, each requested CPU is 1024 CPU shares
# https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#how-pods-with-resource-limits-are-run
return int(share // 1024)
else:
return os.cpu_count()
def _read_in_integer_file(filename: str) -> int:
try:
with open(filename) as f:
return int(f.read().rstrip())
except FileNotFoundError:
return -1
| ml-agents/ml-agents/mlagents/torch_utils/cpu_utils.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/torch_utils/cpu_utils.py",
"repo_id": "ml-agents",
"token_count": 574
} | 1,866 |
# # Unity ML-Agents Toolkit
# ## ML-Agent Learning (Ghost Trainer)
from collections import defaultdict
from typing import Deque, Dict, DefaultDict, List
import numpy as np
from mlagents_envs.logging_util import get_logger
from mlagents_envs.base_env import BehaviorSpec
from mlagents.trainers.policy import Policy
from mlagents.trainers.trainer import Trainer
from mlagents.trainers.optimizer.torch_optimizer import TorchOptimizer
from mlagents.trainers.trajectory import Trajectory
from mlagents.trainers.agent_processor import AgentManagerQueue
from mlagents.trainers.stats import StatsPropertyType
from mlagents.trainers.behavior_id_utils import (
BehaviorIdentifiers,
create_name_behavior_id,
)
from mlagents.trainers.training_status import GlobalTrainingStatus, StatusType
logger = get_logger(__name__)
class GhostTrainer(Trainer):
"""
The GhostTrainer trains agents in adversarial games (there are teams in opposition) using a self-play mechanism.
In adversarial settings with self-play, at any time, there is only a single learning team. The other team(s) is
"ghosted" which means that its agents are executing fixed policies and not learning. The GhostTrainer wraps
a standard RL trainer which trains the learning team and ensures that only the trajectories collected
by the learning team are used for training. The GhostTrainer also maintains past policy snapshots to be used
as the fixed policies when the team is not learning. The GhostTrainer is 1:1 with brain_names as the other
trainers, and is responsible for one or more teams. Note, a GhostTrainer can have only one team in
asymmetric games where there is only one team with a particular behavior i.e. Hide and Seek.
The GhostController manages high level coordination between multiple ghost trainers. The learning team id
is cycled throughout a training run.
"""
def __init__(
self,
trainer,
brain_name,
controller,
reward_buff_cap,
trainer_settings,
training,
artifact_path,
):
"""
Creates a GhostTrainer.
:param trainer: The trainer of the policy/policies being trained with self_play
:param brain_name: The name of the brain associated with trainer config
:param controller: GhostController that coordinates all ghost trainers and calculates ELO
:param reward_buff_cap: Max reward history to track in the reward buffer
:param trainer_settings: The parameters for the trainer.
:param training: Whether the trainer is set for training.
:param artifact_path: Path to store artifacts from this trainer.
"""
super().__init__(
brain_name, trainer_settings, training, artifact_path, reward_buff_cap
)
self.trainer = trainer
self.controller = controller
self._internal_trajectory_queues: Dict[str, AgentManagerQueue[Trajectory]] = {}
self._internal_policy_queues: Dict[str, AgentManagerQueue[Policy]] = {}
self._team_to_name_to_policy_queue: DefaultDict[
int, Dict[str, AgentManagerQueue[Policy]]
] = defaultdict(dict)
self._name_to_parsed_behavior_id: Dict[str, BehaviorIdentifiers] = {}
# assign ghost's stats collection to wrapped trainer's
self._stats_reporter = self.trainer.stats_reporter
# Set the logging to print ELO in the console
self._stats_reporter.add_property(StatsPropertyType.SELF_PLAY, True)
self_play_parameters = trainer_settings.self_play
self.window = self_play_parameters.window
self.play_against_latest_model_ratio = (
self_play_parameters.play_against_latest_model_ratio
)
if (
self.play_against_latest_model_ratio > 1.0
or self.play_against_latest_model_ratio < 0.0
):
logger.warning(
"The play_against_latest_model_ratio is not between 0 and 1."
)
self.steps_between_save = self_play_parameters.save_steps
self.steps_between_swap = self_play_parameters.swap_steps
self.steps_to_train_team = self_play_parameters.team_change
if self.steps_to_train_team > self.get_max_steps:
logger.warning(
"The max steps of the GhostTrainer for behavior name {} is less than team change. This team will not face \
opposition that has been trained if the opposition is managed by a different GhostTrainer as in an \
asymmetric game.".format(
self.brain_name
)
)
# Counts the number of steps of the ghost policies. Snapshot swapping
# depends on this counter whereas snapshot saving and team switching depends
# on the wrapped. This ensures that all teams train for the same number of trainer
# steps.
self.ghost_step: int = 0
# A list of dicts from brain name to a single snapshot for this trainer's policies
self.policy_snapshots: List[Dict[str, List[float]]] = []
# A dict from brain name to the current snapshot of this trainer's policies
self.current_policy_snapshot: Dict[str, List[float]] = {}
self.snapshot_counter: int = 0
# wrapped_training_team and learning team need to be separate
# in the situation where new agents are created destroyed
# after learning team switches. These agents need to be added
# to trainers properly.
self._learning_team: int = None
self.wrapped_trainer_team: int = None
self.last_save: int = 0
self.last_swap: int = 0
self.last_team_change: int = 0
self.initial_elo = GlobalTrainingStatus.get_parameter_state(
self.brain_name, StatusType.ELO
)
if self.initial_elo is None:
self.initial_elo = self_play_parameters.initial_elo
self.policy_elos: List[float] = [self.initial_elo] * (
self.window + 1
) # for learning policy
self.current_opponent: int = 0
@property
def get_step(self) -> int:
"""
Returns the number of steps the wrapped trainer has performed
:return: the step count of the wrapped trainer
"""
return self.trainer.get_step
@property
def reward_buffer(self) -> Deque[float]:
"""
Returns the reward buffer. The reward buffer contains the cumulative
rewards of the most recent episodes completed by agents using this
trainer.
:return: the reward buffer.
"""
return self.trainer.reward_buffer
@property
def current_elo(self) -> float:
"""
Gets ELO of current policy which is always last in the list
:return: ELO of current policy
"""
return self.policy_elos[-1]
def change_current_elo(self, change: float) -> None:
"""
Changes elo of current policy which is always last in the list
:param change: Amount to change current elo by
"""
self.policy_elos[-1] += change
def get_opponent_elo(self) -> float:
"""
Get elo of current opponent policy
:return: ELO of current opponent policy
"""
return self.policy_elos[self.current_opponent]
def change_opponent_elo(self, change: float) -> None:
"""
Changes elo of current opponent policy
:param change: Amount to change current opponent elo by
"""
self.policy_elos[self.current_opponent] -= change
def _process_trajectory(self, trajectory: Trajectory) -> None:
"""
Determines the final result of an episode and asks the GhostController
to calculate the ELO change. The GhostController changes the ELO
of the opponent policy since this may be in a different GhostTrainer
i.e. in asymmetric games. We assume the last reward determines the winner.
:param trajectory: Trajectory.
"""
if (
trajectory.done_reached
and trajectory.all_group_dones_reached
and not trajectory.interrupted
):
# Assumption is that final reward is >0/0/<0 for win/draw/loss
final_reward = (
trajectory.steps[-1].reward + trajectory.steps[-1].group_reward
)
result = 0.5
if final_reward > 0:
result = 1.0
elif final_reward < 0:
result = 0.0
change = self.controller.compute_elo_rating_changes(
self.current_elo, result
)
self.change_current_elo(change)
self._stats_reporter.add_stat("Self-play/ELO", self.current_elo)
def advance(self) -> None:
"""
Steps the trainer, passing trajectories to wrapped trainer and calling trainer advance
"""
for trajectory_queue in self.trajectory_queues:
parsed_behavior_id = self._name_to_parsed_behavior_id[
trajectory_queue.behavior_id
]
if parsed_behavior_id.team_id == self._learning_team:
# With a future multiagent trainer, this will be indexed by 'role'
internal_trajectory_queue = self._internal_trajectory_queues[
parsed_behavior_id.brain_name
]
try:
# We grab at most the maximum length of the queue.
# This ensures that even if the queue is being filled faster than it is
# being emptied, the trajectories in the queue are on-policy.
for _ in range(trajectory_queue.qsize()):
t = trajectory_queue.get_nowait()
# adds to wrapped trainers queue
internal_trajectory_queue.put(t)
self._process_trajectory(t)
except AgentManagerQueue.Empty:
pass
else:
# Dump trajectories from non-learning policy
try:
for _ in range(trajectory_queue.qsize()):
t = trajectory_queue.get_nowait()
# count ghost steps
self.ghost_step += len(t.steps)
except AgentManagerQueue.Empty:
pass
self._next_summary_step = self.trainer._next_summary_step
self.trainer.advance()
if self.get_step - self.last_team_change > self.steps_to_train_team:
self.controller.change_training_team(self.get_step)
self.last_team_change = self.get_step
next_learning_team = self.controller.get_learning_team
# Case 1: No team change. The if statement just continues to push the policy
# into the correct queue (or not if not learning team).
for brain_name in self._internal_policy_queues:
internal_policy_queue = self._internal_policy_queues[brain_name]
try:
policy = internal_policy_queue.get_nowait()
self.current_policy_snapshot[brain_name] = policy.get_weights()
except AgentManagerQueue.Empty:
continue
if (
self._learning_team == next_learning_team
and next_learning_team in self._team_to_name_to_policy_queue
):
name_to_policy_queue = self._team_to_name_to_policy_queue[
next_learning_team
]
if brain_name in name_to_policy_queue:
behavior_id = create_name_behavior_id(
brain_name, next_learning_team
)
policy = self.get_policy(behavior_id)
policy.load_weights(self.current_policy_snapshot[brain_name])
name_to_policy_queue[brain_name].put(policy)
# CASE 2: Current learning team is managed by this GhostTrainer.
# If the learning team changes, the following loop over queues will push the
# new policy into the policy queue for the new learning agent if
# that policy is managed by this GhostTrainer. Otherwise, it will save the current snapshot.
# CASE 3: Current learning team is managed by a different GhostTrainer.
# If the learning team changes to a team managed by this GhostTrainer, this loop
# will push the current_snapshot into the correct queue. Otherwise,
# it will continue skipping and swap_snapshot will continue to handle
# pushing fixed snapshots
if (
self._learning_team != next_learning_team
and next_learning_team in self._team_to_name_to_policy_queue
):
name_to_policy_queue = self._team_to_name_to_policy_queue[
next_learning_team
]
for brain_name in name_to_policy_queue:
behavior_id = create_name_behavior_id(brain_name, next_learning_team)
policy = self.get_policy(behavior_id)
policy.load_weights(self.current_policy_snapshot[brain_name])
name_to_policy_queue[brain_name].put(policy)
# Note save and swap should be on different step counters.
# We don't want to save unless the policy is learning.
if self.get_step - self.last_save > self.steps_between_save:
self._save_snapshot()
self.last_save = self.get_step
if (
self._learning_team != next_learning_team
or self.ghost_step - self.last_swap > self.steps_between_swap
):
self._learning_team = next_learning_team
self._swap_snapshots()
self.last_swap = self.ghost_step
def end_episode(self):
"""
Forwarding call to wrapped trainers end_episode
"""
self.trainer.end_episode()
def save_model(self) -> None:
"""
Forwarding call to wrapped trainers save_model.
"""
GlobalTrainingStatus.set_parameter_state(
self.brain_name, StatusType.ELO, self.current_elo
)
self.trainer.save_model()
def create_policy(
self,
parsed_behavior_id: BehaviorIdentifiers,
behavior_spec: BehaviorSpec,
) -> Policy:
"""
Creates policy with the wrapped trainer's create_policy function
The first policy encountered sets the wrapped
trainer team. This is to ensure that all agents from the same multi-agent
team are grouped. All policies associated with this team are added to the
wrapped trainer to be trained.
"""
policy = self.trainer.create_policy(parsed_behavior_id, behavior_spec)
team_id = parsed_behavior_id.team_id
self.controller.subscribe_team_id(team_id, self)
# First policy or a new agent on the same team encountered
if self.wrapped_trainer_team is None or team_id == self.wrapped_trainer_team:
internal_trainer_policy = self.trainer.create_policy(
parsed_behavior_id, behavior_spec
)
self.trainer.add_policy(parsed_behavior_id, internal_trainer_policy)
self.current_policy_snapshot[
parsed_behavior_id.brain_name
] = internal_trainer_policy.get_weights()
policy.load_weights(internal_trainer_policy.get_weights())
self._save_snapshot() # Need to save after trainer initializes policy
self._learning_team = self.controller.get_learning_team
self.wrapped_trainer_team = team_id
else:
# Load the weights of the ghost policy from the wrapped one
policy.load_weights(
self.trainer.get_policy(parsed_behavior_id).get_weights()
)
return policy
def create_optimizer(self) -> TorchOptimizer:
pass
def add_policy(
self, parsed_behavior_id: BehaviorIdentifiers, policy: Policy
) -> None:
"""
Adds policy to GhostTrainer.
:param parsed_behavior_id: Behavior ID that the policy should belong to.
:param policy: Policy to associate with name_behavior_id.
"""
name_behavior_id = parsed_behavior_id.behavior_id
self._name_to_parsed_behavior_id[name_behavior_id] = parsed_behavior_id
self.policies[name_behavior_id] = policy
def _save_snapshot(self) -> None:
"""
Saves a snapshot of the current weights of the policy and maintains the policy_snapshots
according to the window size
"""
for brain_name in self.current_policy_snapshot:
current_snapshot_for_brain_name = self.current_policy_snapshot[brain_name]
try:
self.policy_snapshots[self.snapshot_counter][
brain_name
] = current_snapshot_for_brain_name
except IndexError:
self.policy_snapshots.append(
{brain_name: current_snapshot_for_brain_name}
)
self.policy_elos[self.snapshot_counter] = self.current_elo
self.snapshot_counter = (self.snapshot_counter + 1) % self.window
def _swap_snapshots(self) -> None:
"""
Swaps the appropriate weight to the policy and pushes it to respective policy queues
"""
for team_id in self._team_to_name_to_policy_queue:
if team_id == self._learning_team:
continue
elif np.random.uniform() < (1 - self.play_against_latest_model_ratio):
x = np.random.randint(len(self.policy_snapshots))
snapshot = self.policy_snapshots[x]
else:
snapshot = self.current_policy_snapshot
x = "current"
self.current_opponent = -1 if x == "current" else x
name_to_policy_queue = self._team_to_name_to_policy_queue[team_id]
for brain_name in self._team_to_name_to_policy_queue[team_id]:
behavior_id = create_name_behavior_id(brain_name, team_id)
policy = self.get_policy(behavior_id)
policy.load_weights(snapshot[brain_name])
name_to_policy_queue[brain_name].put(policy)
logger.debug(
"Step {}: Swapping snapshot {} to id {} with team {} learning".format(
self.ghost_step, x, behavior_id, self._learning_team
)
)
def publish_policy_queue(self, policy_queue: AgentManagerQueue[Policy]) -> None:
"""
Adds a policy queue for every member of the team to the list of queues to publish to when this Trainer
makes a policy update. Creates an internal policy queue for the wrapped
trainer to push to. The GhostTrainer pushes all policies to the env.
:param queue: Policy queue to publish to.
"""
super().publish_policy_queue(policy_queue)
parsed_behavior_id = self._name_to_parsed_behavior_id[policy_queue.behavior_id]
self._team_to_name_to_policy_queue[parsed_behavior_id.team_id][
parsed_behavior_id.brain_name
] = policy_queue
if parsed_behavior_id.team_id == self.wrapped_trainer_team:
# With a future multiagent trainer, this will be indexed by 'role'
internal_policy_queue: AgentManagerQueue[Policy] = AgentManagerQueue(
parsed_behavior_id.brain_name
)
self._internal_policy_queues[
parsed_behavior_id.brain_name
] = internal_policy_queue
self.trainer.publish_policy_queue(internal_policy_queue)
def subscribe_trajectory_queue(
self, trajectory_queue: AgentManagerQueue[Trajectory]
) -> None:
"""
Adds a trajectory queue for every member of the team to the list of queues for the trainer
to ingest Trajectories from. Creates an internal trajectory queue to push trajectories from
the learning team. The wrapped trainer subscribes to this queue.
:param queue: Trajectory queue to publish to.
"""
super().subscribe_trajectory_queue(trajectory_queue)
parsed_behavior_id = self._name_to_parsed_behavior_id[
trajectory_queue.behavior_id
]
if parsed_behavior_id.team_id == self.wrapped_trainer_team:
# With a future multiagent trainer, this will be indexed by 'role'
internal_trajectory_queue: AgentManagerQueue[
Trajectory
] = AgentManagerQueue(parsed_behavior_id.brain_name)
self._internal_trajectory_queues[
parsed_behavior_id.brain_name
] = internal_trajectory_queue
self.trainer.subscribe_trajectory_queue(internal_trajectory_queue)
| ml-agents/ml-agents/mlagents/trainers/ghost/trainer.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/ghost/trainer.py",
"repo_id": "ml-agents",
"token_count": 8827
} | 1,867 |
from typing import Dict, cast
import attr
from mlagents.torch_utils import torch, default_device
from mlagents.trainers.buffer import AgentBuffer, BufferKey, RewardSignalUtil
from mlagents_envs.timers import timed
from mlagents.trainers.policy.torch_policy import TorchPolicy
from mlagents.trainers.optimizer.torch_optimizer import TorchOptimizer
from mlagents.trainers.settings import (
TrainerSettings,
OnPolicyHyperparamSettings,
ScheduleType,
)
from mlagents.trainers.torch_entities.networks import ValueNetwork
from mlagents.trainers.torch_entities.agent_action import AgentAction
from mlagents.trainers.torch_entities.action_log_probs import ActionLogProbs
from mlagents.trainers.torch_entities.utils import ModelUtils
from mlagents.trainers.trajectory import ObsUtil
@attr.s(auto_attribs=True)
class PPOSettings(OnPolicyHyperparamSettings):
beta: float = 5.0e-3
epsilon: float = 0.2
lambd: float = 0.95
num_epoch: int = 3
shared_critic: bool = False
learning_rate_schedule: ScheduleType = ScheduleType.LINEAR
beta_schedule: ScheduleType = ScheduleType.LINEAR
epsilon_schedule: ScheduleType = ScheduleType.LINEAR
class TorchPPOOptimizer(TorchOptimizer):
def __init__(self, policy: TorchPolicy, trainer_settings: TrainerSettings):
"""
Takes a Policy and a Dict of trainer parameters and creates an Optimizer around the policy.
The PPO optimizer has a value estimator and a loss function.
:param policy: A TorchPolicy object that will be updated by this PPO Optimizer.
:param trainer_params: Trainer parameters dictionary that specifies the
properties of the trainer.
"""
# Create the graph here to give more granular control of the TF graph to the Optimizer.
super().__init__(policy, trainer_settings)
reward_signal_configs = trainer_settings.reward_signals
reward_signal_names = [key.value for key, _ in reward_signal_configs.items()]
self.hyperparameters: PPOSettings = cast(
PPOSettings, trainer_settings.hyperparameters
)
params = list(self.policy.actor.parameters())
if self.hyperparameters.shared_critic:
self._critic = policy.actor
else:
self._critic = ValueNetwork(
reward_signal_names,
policy.behavior_spec.observation_specs,
network_settings=trainer_settings.network_settings,
)
self._critic.to(default_device())
params += list(self._critic.parameters())
self.decay_learning_rate = ModelUtils.DecayedValue(
self.hyperparameters.learning_rate_schedule,
self.hyperparameters.learning_rate,
1e-10,
self.trainer_settings.max_steps,
)
self.decay_epsilon = ModelUtils.DecayedValue(
self.hyperparameters.epsilon_schedule,
self.hyperparameters.epsilon,
0.1,
self.trainer_settings.max_steps,
)
self.decay_beta = ModelUtils.DecayedValue(
self.hyperparameters.beta_schedule,
self.hyperparameters.beta,
1e-5,
self.trainer_settings.max_steps,
)
self.optimizer = torch.optim.Adam(
params, lr=self.trainer_settings.hyperparameters.learning_rate
)
self.stats_name_to_update_name = {
"Losses/Value Loss": "value_loss",
"Losses/Policy Loss": "policy_loss",
}
self.stream_names = list(self.reward_signals.keys())
@property
def critic(self):
return self._critic
@timed
def update(self, batch: AgentBuffer, num_sequences: int) -> Dict[str, float]:
"""
Performs update on model.
:param batch: Batch of experiences.
:param num_sequences: Number of sequences to process.
:return: Results of update.
"""
# Get decayed parameters
decay_lr = self.decay_learning_rate.get_value(self.policy.get_current_step())
decay_eps = self.decay_epsilon.get_value(self.policy.get_current_step())
decay_bet = self.decay_beta.get_value(self.policy.get_current_step())
returns = {}
old_values = {}
for name in self.reward_signals:
old_values[name] = ModelUtils.list_to_tensor(
batch[RewardSignalUtil.value_estimates_key(name)]
)
returns[name] = ModelUtils.list_to_tensor(
batch[RewardSignalUtil.returns_key(name)]
)
n_obs = len(self.policy.behavior_spec.observation_specs)
current_obs = ObsUtil.from_buffer(batch, n_obs)
# Convert to tensors
current_obs = [ModelUtils.list_to_tensor(obs) for obs in current_obs]
act_masks = ModelUtils.list_to_tensor(batch[BufferKey.ACTION_MASK])
actions = AgentAction.from_buffer(batch)
memories = [
ModelUtils.list_to_tensor(batch[BufferKey.MEMORY][i])
for i in range(0, len(batch[BufferKey.MEMORY]), self.policy.sequence_length)
]
if len(memories) > 0:
memories = torch.stack(memories).unsqueeze(0)
# Get value memories
value_memories = [
ModelUtils.list_to_tensor(batch[BufferKey.CRITIC_MEMORY][i])
for i in range(
0, len(batch[BufferKey.CRITIC_MEMORY]), self.policy.sequence_length
)
]
if len(value_memories) > 0:
value_memories = torch.stack(value_memories).unsqueeze(0)
run_out = self.policy.actor.get_stats(
current_obs,
actions,
masks=act_masks,
memories=memories,
sequence_length=self.policy.sequence_length,
)
log_probs = run_out["log_probs"]
entropy = run_out["entropy"]
values, _ = self.critic.critic_pass(
current_obs,
memories=value_memories,
sequence_length=self.policy.sequence_length,
)
old_log_probs = ActionLogProbs.from_buffer(batch).flatten()
log_probs = log_probs.flatten()
loss_masks = ModelUtils.list_to_tensor(batch[BufferKey.MASKS], dtype=torch.bool)
value_loss = ModelUtils.trust_region_value_loss(
values, old_values, returns, decay_eps, loss_masks
)
policy_loss = ModelUtils.trust_region_policy_loss(
ModelUtils.list_to_tensor(batch[BufferKey.ADVANTAGES]),
log_probs,
old_log_probs,
loss_masks,
decay_eps,
)
loss = (
policy_loss
+ 0.5 * value_loss
- decay_bet * ModelUtils.masked_mean(entropy, loss_masks)
)
# Set optimizer learning rate
ModelUtils.update_learning_rate(self.optimizer, decay_lr)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
update_stats = {
# NOTE: abs() is not technically correct, but matches the behavior in TensorFlow.
# TODO: After PyTorch is default, change to something more correct.
"Losses/Policy Loss": torch.abs(policy_loss).item(),
"Losses/Value Loss": value_loss.item(),
"Policy/Learning Rate": decay_lr,
"Policy/Epsilon": decay_eps,
"Policy/Beta": decay_bet,
}
return update_stats
# TODO move module update into TorchOptimizer for reward_provider
def get_modules(self):
modules = {
"Optimizer:value_optimizer": self.optimizer,
"Optimizer:critic": self._critic,
}
for reward_provider in self.reward_signals.values():
modules.update(reward_provider.get_modules())
return modules
| ml-agents/ml-agents/mlagents/trainers/ppo/optimizer_torch.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/ppo/optimizer_torch.py",
"repo_id": "ml-agents",
"token_count": 3493
} | 1,868 |
from unittest.mock import MagicMock, patch
import pytest
from mlagents.torch_utils import torch
from mlagents.trainers.trainer_controller import TrainerController
from mlagents.trainers.environment_parameter_manager import EnvironmentParameterManager
from mlagents.trainers.ghost.controller import GhostController
@pytest.fixture
def basic_trainer_controller():
trainer_factory_mock = MagicMock()
trainer_factory_mock.ghost_controller = GhostController()
return TrainerController(
trainer_factory=trainer_factory_mock,
output_path="test_model_path",
run_id="test_run_id",
param_manager=EnvironmentParameterManager(),
train=True,
training_seed=99,
)
@patch("numpy.random.seed")
@patch.object(torch, "manual_seed")
def test_initialization_seed(numpy_random_seed, torch_set_seed):
seed = 27
trainer_factory_mock = MagicMock()
trainer_factory_mock.ghost_controller = GhostController()
TrainerController(
trainer_factory=trainer_factory_mock,
output_path="",
run_id="1",
param_manager=None,
train=True,
training_seed=seed,
)
numpy_random_seed.assert_called_with(seed)
torch_set_seed.assert_called_with(seed)
@pytest.fixture
def trainer_controller_with_start_learning_mocks(basic_trainer_controller):
trainer_mock = MagicMock()
trainer_mock.get_step = 0
trainer_mock.get_max_steps = 5
trainer_mock.should_still_train = True
trainer_mock.parameters = {"some": "parameter"}
trainer_mock.write_tensorboard_text = MagicMock()
tc = basic_trainer_controller
tc.trainers = {"testbrain": trainer_mock}
tc.advance = MagicMock()
tc.trainers["testbrain"].get_step = 0
def take_step_sideeffect(env):
tc.trainers["testbrain"].get_step += 1
if (
not tc.trainers["testbrain"].get_step
<= tc.trainers["testbrain"].get_max_steps
):
tc.trainers["testbrain"].should_still_train = False
if tc.trainers["testbrain"].get_step > 10:
raise KeyboardInterrupt
return 1
tc.advance.side_effect = take_step_sideeffect
tc._save_models = MagicMock()
return tc, trainer_mock
def test_start_learning_trains_forever_if_no_train_model(
trainer_controller_with_start_learning_mocks,
):
tc, trainer_mock = trainer_controller_with_start_learning_mocks
tc.train_model = False
env_mock = MagicMock()
env_mock.close = MagicMock()
env_mock.reset = MagicMock()
env_mock.training_behaviors = MagicMock()
tc.start_learning(env_mock)
env_mock.reset.assert_called_once()
assert tc.advance.call_count == 11
tc._save_models.assert_not_called()
def test_start_learning_trains_until_max_steps_then_saves(
trainer_controller_with_start_learning_mocks,
):
tc, trainer_mock = trainer_controller_with_start_learning_mocks
brain_info_mock = MagicMock()
env_mock = MagicMock()
env_mock.close = MagicMock()
env_mock.reset = MagicMock(return_value=brain_info_mock)
env_mock.training_behaviors = MagicMock()
tc.start_learning(env_mock)
env_mock.reset.assert_called_once()
assert tc.advance.call_count == trainer_mock.get_max_steps + 1
tc._save_models.assert_called_once()
@pytest.fixture
def trainer_controller_with_take_step_mocks(basic_trainer_controller):
trainer_mock = MagicMock()
trainer_mock.get_step = 0
trainer_mock.get_max_steps = 5
trainer_mock.parameters = {"some": "parameter"}
trainer_mock.write_tensorboard_text = MagicMock()
tc = basic_trainer_controller
tc.trainers = {"testbrain": trainer_mock}
tc.managers = {"testbrain": MagicMock()}
return tc, trainer_mock
def test_advance_adds_experiences_to_trainer_and_trains(
trainer_controller_with_take_step_mocks,
):
tc, trainer_mock = trainer_controller_with_take_step_mocks
brain_name = "testbrain"
env_mock = MagicMock()
tc.brain_name_to_identifier[brain_name].add(brain_name)
tc.advance(env_mock)
env_mock.reset.assert_not_called()
env_mock.get_steps.assert_called_once()
env_mock.process_steps.assert_called_once()
# May have been called many times due to thread
# assert trainer_mock.advance.call_count > 0
| ml-agents/ml-agents/mlagents/trainers/tests/test_trainer_controller.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/tests/test_trainer_controller.py",
"repo_id": "ml-agents",
"token_count": 1708
} | 1,869 |
import pytest
from mlagents.torch_utils import torch
from mlagents.trainers.torch_entities.decoders import ValueHeads
def test_valueheads():
stream_names = [f"reward_signal_{num}" for num in range(5)]
input_size = 5
batch_size = 4
# Test default 1 value per head
value_heads = ValueHeads(stream_names, input_size)
input_data = torch.ones((batch_size, input_size))
value_out = value_heads(input_data) # Note: mean value will be removed shortly
for stream_name in stream_names:
assert value_out[stream_name].shape == (batch_size,)
# Test that inputting the wrong size input will throw an error
with pytest.raises(Exception):
value_out = value_heads(torch.ones((batch_size, input_size + 2)))
# Test multiple values per head (e.g. discrete Q function)
output_size = 4
value_heads = ValueHeads(stream_names, input_size, output_size)
input_data = torch.ones((batch_size, input_size))
value_out = value_heads(input_data)
for stream_name in stream_names:
assert value_out[stream_name].shape == (batch_size, output_size)
| ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_decoders.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_decoders.py",
"repo_id": "ml-agents",
"token_count": 393
} | 1,870 |
import pytest
import attr
from mlagents.trainers.tests.simple_test_envs import (
SimpleEnvironment,
MultiAgentEnvironment,
MemoryEnvironment,
RecordEnvironment,
)
from mlagents.trainers.demo_loader import write_demo
from mlagents.trainers.settings import (
NetworkSettings,
SelfPlaySettings,
BehavioralCloningSettings,
GAILSettings,
RewardSignalType,
EncoderType,
ConditioningType,
)
from mlagents_envs.communicator_objects.demonstration_meta_pb2 import (
DemonstrationMetaProto,
)
from mlagents_envs.communicator_objects.brain_parameters_pb2 import (
BrainParametersProto,
ActionSpecProto,
)
from mlagents.trainers.tests.dummy_config import (
ppo_dummy_config,
sac_dummy_config,
poca_dummy_config,
)
from mlagents.trainers.tests.check_env_trains import (
check_environment_trains,
default_reward_processor,
)
BRAIN_NAME = "1D"
PPO_TORCH_CONFIG = ppo_dummy_config()
SAC_TORCH_CONFIG = sac_dummy_config()
POCA_TORCH_CONFIG = poca_dummy_config()
# tests in this file won't be tested on GPU machine
pytestmark = pytest.mark.slow
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_simple_poca(action_sizes):
env = MultiAgentEnvironment([BRAIN_NAME], action_sizes=action_sizes, num_agents=2)
config = attr.evolve(POCA_TORCH_CONFIG)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("num_visual", [1, 2])
def test_visual_poca(num_visual):
env = MultiAgentEnvironment(
[BRAIN_NAME], action_sizes=(0, 1), num_agents=2, num_visual=num_visual
)
new_hyperparams = attr.evolve(
POCA_TORCH_CONFIG.hyperparameters, learning_rate=3.0e-4
)
config = attr.evolve(POCA_TORCH_CONFIG, hyperparameters=new_hyperparams)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("conditioning_type", [ConditioningType.HYPER])
@pytest.mark.parametrize("num_var_len", [1, 2])
@pytest.mark.parametrize("num_vector", [0, 1])
@pytest.mark.parametrize("num_vis", [0, 1])
def test_var_len_obs_and_goal_poca(num_vis, num_vector, num_var_len, conditioning_type):
env = MultiAgentEnvironment(
[BRAIN_NAME],
action_sizes=(0, 1),
num_visual=num_vis,
num_vector=num_vector,
num_var_len=num_var_len,
step_size=0.2,
num_agents=2,
goal_indices=[0],
)
new_network = attr.evolve(
POCA_TORCH_CONFIG.network_settings, goal_conditioning_type=conditioning_type
)
new_hyperparams = attr.evolve(
POCA_TORCH_CONFIG.hyperparameters, learning_rate=3.0e-4
)
config = attr.evolve(
POCA_TORCH_CONFIG,
hyperparameters=new_hyperparams,
network_settings=new_network,
max_steps=5000,
)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
@pytest.mark.parametrize("is_multiagent", [True, False])
def test_recurrent_poca(action_sizes, is_multiagent):
if is_multiagent:
# This is not a recurrent environment, just check if LSTM doesn't crash
env = MultiAgentEnvironment(
[BRAIN_NAME], action_sizes=action_sizes, num_agents=2
)
else:
# Actually test LSTM here
env = MemoryEnvironment([BRAIN_NAME], action_sizes=action_sizes)
new_network_settings = attr.evolve(
POCA_TORCH_CONFIG.network_settings,
memory=NetworkSettings.MemorySettings(memory_size=16),
)
new_hyperparams = attr.evolve(
POCA_TORCH_CONFIG.hyperparameters,
learning_rate=1.0e-3,
batch_size=64,
buffer_size=128,
)
config = attr.evolve(
POCA_TORCH_CONFIG,
hyperparameters=new_hyperparams,
network_settings=new_network_settings,
max_steps=500 if is_multiagent else 6000,
)
check_environment_trains(
env, {BRAIN_NAME: config}, success_threshold=None if is_multiagent else 0.9
)
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_simple_ppo(action_sizes):
env = SimpleEnvironment([BRAIN_NAME], action_sizes=action_sizes)
config = attr.evolve(PPO_TORCH_CONFIG)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("action_sizes", [(0, 2), (2, 0)])
def test_2d_ppo(action_sizes):
env = SimpleEnvironment([BRAIN_NAME], action_sizes=action_sizes, step_size=0.8)
new_hyperparams = attr.evolve(
PPO_TORCH_CONFIG.hyperparameters, batch_size=64, buffer_size=640
)
config = attr.evolve(
PPO_TORCH_CONFIG, hyperparameters=new_hyperparams, max_steps=10000
)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
@pytest.mark.parametrize("num_visual", [1, 2])
@pytest.mark.parametrize("shared_critic", [True, False])
def test_visual_ppo(shared_critic, num_visual, action_sizes):
env = SimpleEnvironment(
[BRAIN_NAME],
action_sizes=action_sizes,
num_visual=num_visual,
num_vector=0,
step_size=0.2,
)
new_hyperparams = attr.evolve(
PPO_TORCH_CONFIG.hyperparameters,
learning_rate=3.0e-4,
shared_critic=shared_critic,
)
config = attr.evolve(PPO_TORCH_CONFIG, hyperparameters=new_hyperparams)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("conditioning_type", [ConditioningType.HYPER])
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
@pytest.mark.parametrize("num_var_len", [1, 2])
@pytest.mark.parametrize("num_vector", [0, 1])
@pytest.mark.parametrize("num_vis", [0, 1])
def test_var_len_obs_and_goal_ppo(
num_vis, num_vector, num_var_len, action_sizes, conditioning_type
):
env = SimpleEnvironment(
[BRAIN_NAME],
action_sizes=action_sizes,
num_visual=num_vis,
num_vector=num_vector,
num_var_len=num_var_len,
step_size=0.2,
goal_indices=[0],
)
new_network = attr.evolve(
POCA_TORCH_CONFIG.network_settings, goal_conditioning_type=conditioning_type
)
new_hyperparams = attr.evolve(
PPO_TORCH_CONFIG.hyperparameters, learning_rate=3.0e-4
)
config = attr.evolve(
PPO_TORCH_CONFIG, hyperparameters=new_hyperparams, network_settings=new_network
)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("num_visual", [1, 2])
@pytest.mark.parametrize("vis_encode_type", ["resnet", "nature_cnn", "match3"])
def test_visual_advanced_ppo(vis_encode_type, num_visual):
env = SimpleEnvironment(
[BRAIN_NAME],
action_sizes=(0, 1),
num_visual=num_visual,
num_vector=0,
step_size=0.5,
vis_obs_size=(5, 5, 5) if vis_encode_type == "match3" else (3, 36, 36),
)
new_networksettings = attr.evolve(
SAC_TORCH_CONFIG.network_settings, vis_encode_type=EncoderType(vis_encode_type)
)
new_hyperparams = attr.evolve(
PPO_TORCH_CONFIG.hyperparameters, learning_rate=3.0e-4
)
config = attr.evolve(
PPO_TORCH_CONFIG,
hyperparameters=new_hyperparams,
network_settings=new_networksettings,
max_steps=900,
summary_freq=100,
)
# The number of steps is pretty small for these encoders
check_environment_trains(env, {BRAIN_NAME: config}, success_threshold=0.5)
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_recurrent_ppo(action_sizes):
env = MemoryEnvironment([BRAIN_NAME], action_sizes=action_sizes)
new_network_settings = attr.evolve(
PPO_TORCH_CONFIG.network_settings,
memory=NetworkSettings.MemorySettings(memory_size=16),
)
new_hyperparams = attr.evolve(
PPO_TORCH_CONFIG.hyperparameters,
learning_rate=1.0e-3,
batch_size=64,
buffer_size=128,
)
config = attr.evolve(
PPO_TORCH_CONFIG,
hyperparameters=new_hyperparams,
network_settings=new_network_settings,
max_steps=6000,
)
check_environment_trains(env, {BRAIN_NAME: config}, success_threshold=0.9)
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_simple_sac(action_sizes):
env = SimpleEnvironment([BRAIN_NAME], action_sizes=action_sizes)
config = attr.evolve(SAC_TORCH_CONFIG)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("action_sizes", [(0, 2), (2, 0)])
def test_2d_sac(action_sizes):
env = SimpleEnvironment([BRAIN_NAME], action_sizes=action_sizes, step_size=0.8)
new_hyperparams = attr.evolve(
SAC_TORCH_CONFIG.hyperparameters, buffer_init_steps=2000
)
config = attr.evolve(
SAC_TORCH_CONFIG, hyperparameters=new_hyperparams, max_steps=3000
)
check_environment_trains(env, {BRAIN_NAME: config}, success_threshold=0.8)
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
@pytest.mark.parametrize("num_visual", [1, 2])
def test_visual_sac(num_visual, action_sizes):
env = SimpleEnvironment(
[BRAIN_NAME],
action_sizes=action_sizes,
num_visual=num_visual,
num_vector=0,
step_size=0.2,
)
new_hyperparams = attr.evolve(
SAC_TORCH_CONFIG.hyperparameters, batch_size=16, learning_rate=3e-4
)
config = attr.evolve(SAC_TORCH_CONFIG, hyperparameters=new_hyperparams)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
@pytest.mark.parametrize("num_var_len", [1, 2])
def test_var_len_obs_sac(num_var_len, action_sizes):
env = SimpleEnvironment(
[BRAIN_NAME],
action_sizes=action_sizes,
num_visual=0,
num_var_len=num_var_len,
num_vector=0,
step_size=0.2,
)
new_hyperparams = attr.evolve(
SAC_TORCH_CONFIG.hyperparameters, batch_size=16, learning_rate=3e-4
)
config = attr.evolve(SAC_TORCH_CONFIG, hyperparameters=new_hyperparams)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("num_visual", [1, 2])
@pytest.mark.parametrize("vis_encode_type", ["resnet", "nature_cnn", "match3"])
def test_visual_advanced_sac(vis_encode_type, num_visual):
env = SimpleEnvironment(
[BRAIN_NAME],
action_sizes=(0, 1),
num_visual=num_visual,
num_vector=0,
step_size=0.5,
vis_obs_size=(5, 5, 5) if vis_encode_type == "match3" else (3, 36, 36),
)
new_networksettings = attr.evolve(
SAC_TORCH_CONFIG.network_settings, vis_encode_type=EncoderType(vis_encode_type)
)
new_hyperparams = attr.evolve(
SAC_TORCH_CONFIG.hyperparameters,
batch_size=16,
learning_rate=3e-4,
buffer_init_steps=0,
)
config = attr.evolve(
SAC_TORCH_CONFIG,
hyperparameters=new_hyperparams,
network_settings=new_networksettings,
max_steps=100,
)
# The number of steps is pretty small for these encoders
check_environment_trains(env, {BRAIN_NAME: config}, success_threshold=0.5)
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_recurrent_sac(action_sizes):
step_size = 0.2 if action_sizes == (0, 1) else 0.5
env = MemoryEnvironment(
[BRAIN_NAME], action_sizes=action_sizes, step_size=step_size
)
new_networksettings = attr.evolve(
SAC_TORCH_CONFIG.network_settings,
memory=NetworkSettings.MemorySettings(memory_size=16, sequence_length=16),
)
new_hyperparams = attr.evolve(
SAC_TORCH_CONFIG.hyperparameters,
batch_size=256,
learning_rate=3e-4,
buffer_init_steps=1000,
steps_per_update=2,
)
config = attr.evolve(
SAC_TORCH_CONFIG,
hyperparameters=new_hyperparams,
network_settings=new_networksettings,
max_steps=4000,
)
check_environment_trains(env, {BRAIN_NAME: config}, training_seed=1337)
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_simple_ghost(action_sizes):
env = SimpleEnvironment(
[BRAIN_NAME + "?team=0", BRAIN_NAME + "?team=1"], action_sizes=action_sizes
)
self_play_settings = SelfPlaySettings(
play_against_latest_model_ratio=1.0, save_steps=2000, swap_steps=2000
)
config = attr.evolve(PPO_TORCH_CONFIG, self_play=self_play_settings, max_steps=2500)
check_environment_trains(env, {BRAIN_NAME: config})
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_simple_ghost_fails(action_sizes):
env = SimpleEnvironment(
[BRAIN_NAME + "?team=0", BRAIN_NAME + "?team=1"], action_sizes=action_sizes
)
# This config should fail because the ghosted policy is never swapped with a competent policy.
# Swap occurs after max step is reached.
self_play_settings = SelfPlaySettings(
play_against_latest_model_ratio=1.0, save_steps=2000, swap_steps=4000
)
config = attr.evolve(PPO_TORCH_CONFIG, self_play=self_play_settings, max_steps=2500)
check_environment_trains(env, {BRAIN_NAME: config}, success_threshold=None)
processed_rewards = [
default_reward_processor(rewards) for rewards in env.final_rewards.values()
]
success_threshold = 0.9
assert any(reward > success_threshold for reward in processed_rewards) and any(
reward < success_threshold for reward in processed_rewards
)
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_simple_asymm_ghost(action_sizes):
# Make opponent for asymmetric case
brain_name_opp = BRAIN_NAME + "Opp"
env = SimpleEnvironment(
[BRAIN_NAME + "?team=0", brain_name_opp + "?team=1"], action_sizes=action_sizes
)
self_play_settings = SelfPlaySettings(
play_against_latest_model_ratio=1.0,
save_steps=10000,
swap_steps=10000,
team_change=400,
)
config = attr.evolve(PPO_TORCH_CONFIG, self_play=self_play_settings, max_steps=4000)
check_environment_trains(env, {BRAIN_NAME: config, brain_name_opp: config})
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_simple_asymm_ghost_fails(action_sizes):
# Make opponent for asymmetric case
brain_name_opp = BRAIN_NAME + "Opp"
env = SimpleEnvironment(
[BRAIN_NAME + "?team=0", brain_name_opp + "?team=1"], action_sizes=action_sizes
)
# This config should fail because the team that us not learning when both have reached
# max step should be executing the initial, untrained poliy.
self_play_settings = SelfPlaySettings(
play_against_latest_model_ratio=0.0,
save_steps=5000,
swap_steps=5000,
team_change=2000,
)
config = attr.evolve(PPO_TORCH_CONFIG, self_play=self_play_settings, max_steps=3000)
check_environment_trains(
env, {BRAIN_NAME: config, brain_name_opp: config}, success_threshold=None
)
processed_rewards = [
default_reward_processor(rewards) for rewards in env.final_rewards.values()
]
success_threshold = 0.9
assert any(reward > success_threshold for reward in processed_rewards) and any(
reward < success_threshold for reward in processed_rewards
)
@pytest.fixture(scope="session")
def simple_record(tmpdir_factory):
def record_demo(action_sizes, num_visual=0, num_vector=1):
env = RecordEnvironment(
[BRAIN_NAME],
action_sizes=action_sizes,
num_visual=num_visual,
num_vector=num_vector,
n_demos=100,
)
# If we want to use true demos, we can solve the env in the usual way
# Otherwise, we can just call solve to execute the optimal policy
env.solve()
agent_info_protos = env.demonstration_protos[BRAIN_NAME]
meta_data_proto = DemonstrationMetaProto()
continuous_action_size, discrete_action_size = action_sizes
action_spec_proto = ActionSpecProto(
num_continuous_actions=continuous_action_size,
num_discrete_actions=discrete_action_size,
discrete_branch_sizes=[2] if discrete_action_size > 0 else None,
)
brain_param_proto = BrainParametersProto(
brain_name=BRAIN_NAME, is_training=True, action_spec=action_spec_proto
)
action_type = "Discrete" if action_sizes else "Continuous"
demo_path_name = "1DTest" + action_type + ".demo"
demo_path = str(tmpdir_factory.mktemp("tmp_demo").join(demo_path_name))
write_demo(demo_path, meta_data_proto, brain_param_proto, agent_info_protos)
return demo_path
return record_demo
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
@pytest.mark.parametrize("trainer_config", [PPO_TORCH_CONFIG, SAC_TORCH_CONFIG])
def test_gail(simple_record, action_sizes, trainer_config):
demo_path = simple_record(action_sizes)
env = SimpleEnvironment([BRAIN_NAME], action_sizes=action_sizes, step_size=0.2)
bc_settings = BehavioralCloningSettings(demo_path=demo_path, steps=1000)
reward_signals = {
RewardSignalType.GAIL: GAILSettings(encoding_size=32, demo_path=demo_path)
}
config = attr.evolve(
trainer_config,
reward_signals=reward_signals,
behavioral_cloning=bc_settings,
max_steps=500,
)
check_environment_trains(env, {BRAIN_NAME: config}, success_threshold=0.9)
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_gail_visual_ppo(simple_record, action_sizes):
demo_path = simple_record(action_sizes, num_visual=1, num_vector=0)
env = SimpleEnvironment(
[BRAIN_NAME],
num_visual=1,
num_vector=0,
action_sizes=action_sizes,
step_size=0.3,
)
bc_settings = BehavioralCloningSettings(demo_path=demo_path, steps=1500)
reward_signals = {
RewardSignalType.GAIL: GAILSettings(
gamma=0.8, encoding_size=32, demo_path=demo_path
)
}
hyperparams = attr.evolve(PPO_TORCH_CONFIG.hyperparameters, learning_rate=1e-3)
config = attr.evolve(
PPO_TORCH_CONFIG,
reward_signals=reward_signals,
hyperparameters=hyperparams,
behavioral_cloning=bc_settings,
max_steps=1000,
)
check_environment_trains(env, {BRAIN_NAME: config}, success_threshold=0.9)
@pytest.mark.parametrize("action_sizes", [(0, 1), (1, 0)])
def test_gail_visual_sac(simple_record, action_sizes):
demo_path = simple_record(action_sizes, num_visual=1, num_vector=0)
env = SimpleEnvironment(
[BRAIN_NAME],
num_visual=1,
num_vector=0,
action_sizes=action_sizes,
step_size=0.2,
)
bc_settings = BehavioralCloningSettings(demo_path=demo_path, steps=1000)
reward_signals = {
RewardSignalType.GAIL: GAILSettings(encoding_size=32, demo_path=demo_path)
}
hyperparams = attr.evolve(
SAC_TORCH_CONFIG.hyperparameters, learning_rate=3e-4, batch_size=16
)
config = attr.evolve(
SAC_TORCH_CONFIG,
reward_signals=reward_signals,
hyperparameters=hyperparams,
behavioral_cloning=bc_settings,
max_steps=500,
)
check_environment_trains(env, {BRAIN_NAME: config}, success_threshold=0.9)
| ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_simple_rl.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_simple_rl.py",
"repo_id": "ml-agents",
"token_count": 8497
} | 1,871 |
from typing import Optional, Dict, List
import numpy as np
from mlagents.torch_utils import torch, default_device
from mlagents.trainers.buffer import AgentBuffer, BufferKey
from mlagents.trainers.torch_entities.components.reward_providers.base_reward_provider import (
BaseRewardProvider,
)
from mlagents.trainers.settings import GAILSettings
from mlagents_envs.base_env import BehaviorSpec
from mlagents_envs import logging_util
from mlagents.trainers.torch_entities.utils import ModelUtils
from mlagents.trainers.torch_entities.agent_action import AgentAction
from mlagents.trainers.torch_entities.action_flattener import ActionFlattener
from mlagents.trainers.torch_entities.networks import NetworkBody
from mlagents.trainers.torch_entities.layers import linear_layer, Initialization
from mlagents.trainers.demo_loader import demo_to_buffer
from mlagents.trainers.trajectory import ObsUtil
logger = logging_util.get_logger(__name__)
class GAILRewardProvider(BaseRewardProvider):
def __init__(self, specs: BehaviorSpec, settings: GAILSettings) -> None:
super().__init__(specs, settings)
self._ignore_done = False
self._discriminator_network = DiscriminatorNetwork(specs, settings)
self._discriminator_network.to(default_device())
_, self._demo_buffer = demo_to_buffer(
settings.demo_path, 1, specs
) # This is supposed to be the sequence length but we do not have access here
params = list(self._discriminator_network.parameters())
self.optimizer = torch.optim.Adam(params, lr=settings.learning_rate)
def evaluate(self, mini_batch: AgentBuffer) -> np.ndarray:
with torch.no_grad():
estimates, _ = self._discriminator_network.compute_estimate(
mini_batch, use_vail_noise=False
)
return ModelUtils.to_numpy(
-torch.log(
1.0
- estimates.squeeze(dim=1)
* (1.0 - self._discriminator_network.EPSILON)
)
)
def update(self, mini_batch: AgentBuffer) -> Dict[str, np.ndarray]:
expert_batch = self._demo_buffer.sample_mini_batch(
mini_batch.num_experiences, 1
)
self._discriminator_network.encoder.update_normalization(expert_batch)
loss, stats_dict = self._discriminator_network.compute_loss(
mini_batch, expert_batch
)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
return stats_dict
def get_modules(self):
return {f"Module:{self.name}": self._discriminator_network}
class DiscriminatorNetwork(torch.nn.Module):
gradient_penalty_weight = 10.0
z_size = 128
alpha = 0.0005
mutual_information = 0.5
EPSILON = 1e-7
initial_beta = 0.0
def __init__(self, specs: BehaviorSpec, settings: GAILSettings) -> None:
super().__init__()
self._use_vail = settings.use_vail
self._settings = settings
encoder_settings = settings.network_settings
if encoder_settings.memory is not None:
encoder_settings.memory = None
logger.warning(
"memory was specified in network_settings but is not supported by GAIL. It is being ignored."
)
self._action_flattener = ActionFlattener(specs.action_spec)
unencoded_size = (
self._action_flattener.flattened_size + 1 if settings.use_actions else 0
) # +1 is for dones
self.encoder = NetworkBody(
specs.observation_specs, encoder_settings, unencoded_size
)
estimator_input_size = encoder_settings.hidden_units
if settings.use_vail:
estimator_input_size = self.z_size
self._z_sigma = torch.nn.Parameter(
torch.ones((self.z_size), dtype=torch.float), requires_grad=True
)
self._z_mu_layer = linear_layer(
encoder_settings.hidden_units,
self.z_size,
kernel_init=Initialization.KaimingHeNormal,
kernel_gain=0.1,
)
self._beta = torch.nn.Parameter(
torch.tensor(self.initial_beta, dtype=torch.float), requires_grad=False
)
self._estimator = torch.nn.Sequential(
linear_layer(estimator_input_size, 1, kernel_gain=0.2), torch.nn.Sigmoid()
)
def get_action_input(self, mini_batch: AgentBuffer) -> torch.Tensor:
"""
Creates the action Tensor. In continuous case, corresponds to the action. In
the discrete case, corresponds to the concatenation of one hot action Tensors.
"""
return self._action_flattener.forward(AgentAction.from_buffer(mini_batch))
def get_state_inputs(self, mini_batch: AgentBuffer) -> List[torch.Tensor]:
"""
Creates the observation input.
"""
n_obs = len(self.encoder.processors)
np_obs = ObsUtil.from_buffer(mini_batch, n_obs)
# Convert to tensors
tensor_obs = [ModelUtils.list_to_tensor(obs) for obs in np_obs]
return tensor_obs
def compute_estimate(
self, mini_batch: AgentBuffer, use_vail_noise: bool = False
) -> torch.Tensor:
"""
Given a mini_batch, computes the estimate (How much the discriminator believes
the data was sampled from the demonstration data).
:param mini_batch: The AgentBuffer of data
:param use_vail_noise: Only when using VAIL : If true, will sample the code, if
false, will return the mean of the code.
"""
inputs = self.get_state_inputs(mini_batch)
if self._settings.use_actions:
actions = self.get_action_input(mini_batch)
dones = torch.as_tensor(
mini_batch[BufferKey.DONE], dtype=torch.float
).unsqueeze(1)
action_inputs = torch.cat([actions, dones], dim=1)
hidden, _ = self.encoder(inputs, action_inputs)
else:
hidden, _ = self.encoder(inputs)
z_mu: Optional[torch.Tensor] = None
if self._settings.use_vail:
z_mu = self._z_mu_layer(hidden)
hidden = z_mu + torch.randn_like(z_mu) * self._z_sigma * use_vail_noise
estimate = self._estimator(hidden)
return estimate, z_mu
def compute_loss(
self, policy_batch: AgentBuffer, expert_batch: AgentBuffer
) -> torch.Tensor:
"""
Given a policy mini_batch and an expert mini_batch, computes the loss of the discriminator.
"""
total_loss = torch.zeros(1)
stats_dict: Dict[str, np.ndarray] = {}
policy_estimate, policy_mu = self.compute_estimate(
policy_batch, use_vail_noise=True
)
expert_estimate, expert_mu = self.compute_estimate(
expert_batch, use_vail_noise=True
)
stats_dict["Policy/GAIL Policy Estimate"] = policy_estimate.mean().item()
stats_dict["Policy/GAIL Expert Estimate"] = expert_estimate.mean().item()
discriminator_loss = -(
torch.log(expert_estimate + self.EPSILON)
+ torch.log(1.0 - policy_estimate + self.EPSILON)
).mean()
stats_dict["Losses/GAIL Loss"] = discriminator_loss.item()
total_loss += discriminator_loss
if self._settings.use_vail:
# KL divergence loss (encourage latent representation to be normal)
kl_loss = torch.mean(
-torch.sum(
1
+ (self._z_sigma**2).log()
- 0.5 * expert_mu**2
- 0.5 * policy_mu**2
- (self._z_sigma**2),
dim=1,
)
)
vail_loss = self._beta * (kl_loss - self.mutual_information)
with torch.no_grad():
self._beta.data = torch.max(
self._beta + self.alpha * (kl_loss - self.mutual_information),
torch.tensor(0.0),
)
total_loss += vail_loss
stats_dict["Policy/GAIL Beta"] = self._beta.item()
stats_dict["Losses/GAIL KL Loss"] = kl_loss.item()
if self.gradient_penalty_weight > 0.0:
gradient_magnitude_loss = (
self.gradient_penalty_weight
* self.compute_gradient_magnitude(policy_batch, expert_batch)
)
stats_dict["Policy/GAIL Grad Mag Loss"] = gradient_magnitude_loss.item()
total_loss += gradient_magnitude_loss
return total_loss, stats_dict
def compute_gradient_magnitude(
self, policy_batch: AgentBuffer, expert_batch: AgentBuffer
) -> torch.Tensor:
"""
Gradient penalty from https://arxiv.org/pdf/1704.00028. Adds stability esp.
for off-policy. Compute gradients w.r.t randomly interpolated input.
"""
policy_inputs = self.get_state_inputs(policy_batch)
expert_inputs = self.get_state_inputs(expert_batch)
interp_inputs = []
for policy_input, expert_input in zip(policy_inputs, expert_inputs):
obs_epsilon = torch.rand(policy_input.shape)
interp_input = obs_epsilon * policy_input + (1 - obs_epsilon) * expert_input
interp_input.requires_grad = True # For gradient calculation
interp_inputs.append(interp_input)
if self._settings.use_actions:
policy_action = self.get_action_input(policy_batch)
expert_action = self.get_action_input(expert_batch)
action_epsilon = torch.rand(policy_action.shape)
policy_dones = torch.as_tensor(
policy_batch[BufferKey.DONE], dtype=torch.float
).unsqueeze(1)
expert_dones = torch.as_tensor(
expert_batch[BufferKey.DONE], dtype=torch.float
).unsqueeze(1)
dones_epsilon = torch.rand(policy_dones.shape)
action_inputs = torch.cat(
[
action_epsilon * policy_action
+ (1 - action_epsilon) * expert_action,
dones_epsilon * policy_dones + (1 - dones_epsilon) * expert_dones,
],
dim=1,
)
action_inputs.requires_grad = True
hidden, _ = self.encoder(interp_inputs, action_inputs)
encoder_input = tuple(interp_inputs + [action_inputs])
else:
hidden, _ = self.encoder(interp_inputs)
encoder_input = tuple(interp_inputs)
if self._settings.use_vail:
use_vail_noise = True
z_mu = self._z_mu_layer(hidden)
hidden = z_mu + torch.randn_like(z_mu) * self._z_sigma * use_vail_noise
estimate = self._estimator(hidden).squeeze(1).sum()
gradient = torch.autograd.grad(estimate, encoder_input, create_graph=True)[0]
# Norm's gradient could be NaN at 0. Use our own safe_norm
safe_norm = (torch.sum(gradient**2, dim=1) + self.EPSILON).sqrt()
gradient_mag = torch.mean((safe_norm - 1) ** 2)
return gradient_mag
| ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/gail_reward_provider.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/gail_reward_provider.py",
"repo_id": "ml-agents",
"token_count": 5175
} | 1,872 |
import os
from typing import Dict
from mlagents_envs.logging_util import get_logger
from mlagents.trainers.environment_parameter_manager import EnvironmentParameterManager
from mlagents.trainers.exception import TrainerConfigError
from mlagents.trainers.trainer import Trainer
from mlagents.trainers.ghost.trainer import GhostTrainer
from mlagents.trainers.ghost.controller import GhostController
from mlagents.trainers.settings import TrainerSettings
from mlagents.plugins import all_trainer_types
logger = get_logger(__name__)
class TrainerFactory:
def __init__(
self,
trainer_config: Dict[str, TrainerSettings],
output_path: str,
train_model: bool,
load_model: bool,
seed: int,
param_manager: EnvironmentParameterManager,
init_path: str = None,
multi_gpu: bool = False,
):
"""
The TrainerFactory generates the Trainers based on the configuration passed as
input.
:param trainer_config: A dictionary from behavior name to TrainerSettings
:param output_path: The path to the directory where the artifacts generated by
the trainer will be saved.
:param train_model: If True, the Trainers will train the model and if False,
only perform inference.
:param load_model: If True, the Trainer will load neural networks weights from
the previous run.
:param seed: The seed of the Trainers. Dictates how the neural networks will be
initialized.
:param param_manager: The EnvironmentParameterManager that will dictate when/if
the EnvironmentParameters must change.
:param init_path: Path from which to load model.
:param multi_gpu: If True, multi-gpu will be used. (currently not available)
"""
self.trainer_config = trainer_config
self.output_path = output_path
self.init_path = init_path
self.train_model = train_model
self.load_model = load_model
self.seed = seed
self.param_manager = param_manager
self.multi_gpu = multi_gpu
self.ghost_controller = GhostController()
def generate(self, behavior_name: str) -> Trainer:
trainer_settings = self.trainer_config[behavior_name]
return TrainerFactory._initialize_trainer(
trainer_settings,
behavior_name,
self.output_path,
self.train_model,
self.load_model,
self.ghost_controller,
self.seed,
self.param_manager,
self.multi_gpu,
)
@staticmethod
def _initialize_trainer(
trainer_settings: TrainerSettings,
brain_name: str,
output_path: str,
train_model: bool,
load_model: bool,
ghost_controller: GhostController,
seed: int,
param_manager: EnvironmentParameterManager,
multi_gpu: bool = False,
) -> Trainer:
"""
Initializes a trainer given a provided trainer configuration and brain parameters, as well as
some general training session options.
:param trainer_settings: Original trainer configuration loaded from YAML
:param brain_name: Name of the brain to be associated with trainer
:param output_path: Path to save the model and summary statistics
:param keep_checkpoints: How many model checkpoints to keep
:param train_model: Whether to train the model (vs. run inference)
:param load_model: Whether to load the model or randomly initialize
:param ghost_controller: The object that coordinates ghost trainers
:param seed: The random seed to use
:param param_manager: EnvironmentParameterManager, used to determine a reward buffer length for PPOTrainer
:return:
"""
trainer_artifact_path = os.path.join(output_path, brain_name)
min_lesson_length = param_manager.get_minimum_reward_buffer_size(brain_name)
trainer: Trainer = None # type: ignore # will be set to one of these, or raise
try:
trainer_type = all_trainer_types[trainer_settings.trainer_type]
trainer = trainer_type(
brain_name,
min_lesson_length,
trainer_settings,
train_model,
load_model,
seed,
trainer_artifact_path,
)
except KeyError:
raise TrainerConfigError(
f"The trainer config contains an unknown trainer type "
f"{trainer_settings.trainer_type} for brain {brain_name}"
)
if trainer_settings.self_play is not None:
trainer = GhostTrainer(
trainer,
brain_name,
ghost_controller,
min_lesson_length,
trainer_settings,
train_model,
trainer_artifact_path,
)
return trainer
| ml-agents/ml-agents/mlagents/trainers/trainer/trainer_factory.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/trainer/trainer_factory.py",
"repo_id": "ml-agents",
"token_count": 2025
} | 1,873 |
import argparse
import numpy as np
from mlagents_envs.environment import UnityEnvironment
EPSILON = 0.001
def test_run_environment(env_name):
"""
Run the low-level API test of compressed sensors using the specified environment
:param env_name: Name of the Unity environment binary to launch
"""
env = UnityEnvironment(
file_name=env_name, no_graphics=True, additional_args=["-logFile", "-"]
)
try:
# Reset the environment
env.reset()
env.step()
# Set the default brain to work with
group_name = list(env.behavior_specs.keys())[0]
# Get the state of the agents
decision_steps, _ = env.get_steps(group_name)
# One observation comes from compressed sensor while the other comes
# from an uncompressed sensor
obs_1 = decision_steps.obs[0][0, :, :, :]
obs_2 = decision_steps.obs[0][1, :, :, :]
diff = np.abs(obs_1 - obs_2)
# make sure both are identical
assert np.max(diff) < EPSILON
# make sure an actual observation was collected
assert np.max(obs_1) > EPSILON
print("Observations were identical")
finally:
env.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--env", default="artifacts/testPlayer")
args = parser.parse_args()
test_run_environment(args.env)
| ml-agents/ml-agents/tests/yamato/scripts/run_compressed_sensor.py/0 | {
"file_path": "ml-agents/ml-agents/tests/yamato/scripts/run_compressed_sensor.py",
"repo_id": "ml-agents",
"token_count": 549
} | 1,874 |
syntax = "proto3";
option csharp_namespace = "Unity.MLAgents.CommunicatorObjects";
package communicator_objects;
message CustomResetParametersProto {
}
| ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/custom_reset_parameters.proto/0 | {
"file_path": "ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/custom_reset_parameters.proto",
"repo_id": "ml-agents",
"token_count": 49
} | 1,875 |
[coverage:run]
omit = */tests/*
[coverage:report]
# Run "pytest --cov=ml-agents --cov=ml-agents-envs --cov=gym-unity" to see the current coverage percentage.
# Run the above plus "--cov-report html" to get a nice visualization of what is/isn't covered in html format.
fail_under = 60
[flake8]
# black will apply a line length of 88 to code but not docstrings/comments
# This seems like a decent compromise between readability and redoing all the docstrings.
max-line-length=120
ignore =
# Black tends to introduce things flake8 doesn't like, such as "line break before binary operator"
# or whitespace before ':'. Rather than fight with black, just ignore these for now.
W503, E203,
# flake-tidy-import adds this warning, which we don't really care about for now
I200,
banned-modules = tensorflow = use mlagents.tf_utils instead (it handles tf2 compat).
logging = use mlagents_envs.logging_util instead
torch = use mlagents.torch_utils instead (handles GPU detection).
| ml-agents/setup.cfg/0 | {
"file_path": "ml-agents/setup.cfg",
"repo_id": "ml-agents",
"token_count": 336
} | 1,876 |
using System;
using System.IO;
using System.Security.Cryptography;
namespace XLua
{
public class FilesSignature
{
static void usage()
{
Console.WriteLine("FilesSignature from_path to_path");
}
static void doSignature(string from, string to, SHA1 sha, RSACryptoServiceProvider rsa)
{
if (!Directory.Exists(to))
{
Directory.CreateDirectory(to);
}
foreach (var filename in Directory.GetFiles(from, "*.lua"))
{
byte[] filecontent = File.ReadAllBytes(filename);
byte[] sig = rsa.SignData(filecontent, sha);
string sigFilePath = Path.Combine(to, Path.GetFileName(filename));
using (FileStream fs = new FileStream(sigFilePath, FileMode.Create))
{
fs.Write(sig, 0, sig.Length);
fs.Write(filecontent, 0, filecontent.Length);
fs.Flush();
}
}
foreach (var dir in Directory.GetDirectories(from))
{
string newDir = Path.Combine(to, new DirectoryInfo(dir).Name);
doSignature(dir, newDir, sha, rsa);
}
}
public static void Main(string[] args)
{
if (!File.Exists("key_rsa"))
{
Console.WriteLine("No key_rsa file found!");
return;
}
if (args.Length != 2)
{
usage();
return;
}
SHA1 sha = new SHA1CryptoServiceProvider();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(File.ReadAllText("key_rsa"));
doSignature(args[0], args[1], sha, rsa);
}
}
}
| xLua/General/Src/FilesSignature.cs/0 | {
"file_path": "xLua/General/Src/FilesSignature.cs",
"repo_id": "xLua",
"token_count": 990
} | 1,877 |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{DF2795A4-CBF4-EFAF-F40D-DE57E039253E}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>XLuaTest</RootNamespace>
<AssemblyName>XLuaTest</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Bin\</OutputPath>
<BaseIntermediateOutputPath>obj\Any CPU\Debug\XLuaTest\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath>
<DefineConstants>_DEBUG;DEBUG;TRACE;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Bin\</OutputPath>
<BaseIntermediateOutputPath>obj\Any CPU\Release\XLuaTest\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath>
<DefineConstants></DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Src\XLuaTest.cs">
<Link>Src\XLuaTest.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="XLua.Mini.csproj">
<Project>{9A2C7D34-0697-31AB-4FD5-E250BB7E0F00}</Project>
<Name>XLua.Mini</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | xLua/General/vs2013/XLuaTest.csproj/0 | {
"file_path": "xLua/General/vs2013/XLuaTest.csproj",
"repo_id": "xLua",
"token_count": 993
} | 1,878 |
strValue = "D.lua" | xLua/Test/UnitTest/StreamingAssets/D.lua/0 | {
"file_path": "xLua/Test/UnitTest/StreamingAssets/D.lua",
"repo_id": "xLua",
"token_count": 8
} | 1,879 |
fileFormatVersion: 2
guid: 3def27a586fdac545a71c421a4593354
timeCreated: 1483528414
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Test/UnitTest/StreamingAssets/luaCallCsReflect.lua.meta/0 | {
"file_path": "xLua/Test/UnitTest/StreamingAssets/luaCallCsReflect.lua.meta",
"repo_id": "xLua",
"token_count": 67
} | 1,880 |
fileFormatVersion: 2
guid: d3e28212fb5931d44bc37dcd4fd0127f
folderAsset: yes
timeCreated: 1483527547
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Test/UnitTest/xLuaTest/CSharpCallLua.meta/0 | {
"file_path": "xLua/Test/UnitTest/xLuaTest/CSharpCallLua.meta",
"repo_id": "xLua",
"token_count": 75
} | 1,881 |
#if !XLUA_GENERAL
using UnityEngine;
#endif
using System.Collections;
using System.Collections.Generic;
using XLua;
using System;
using System.IO;
public class LuaEnvSingletonForTest {
static private LuaEnv instance = null;
static public LuaEnv Instance
{
get
{
if(instance == null)
{
instance = new LuaEnv();
#if XLUA_GENERAL
instance.DoString("package.path = package.path..';../Test/UnitTest/xLuaTest/CSharpCallLua/Resources/?.lua.txt;../Test/UnitTest/StreamingAssets/?.lua'");
#endif
}
return instance;
}
}
}
public static class GenClass
{
[CSharpCallLua]
public static List<Type> mymodule_lua_call_cs_list = new List<Type>()
{
typeof(System.Action),
};
}
public struct Pedding
{
public byte c;
}
[GCOptimize]
[LuaCallCSharp]
public struct TestStruct
{
public TestStruct(int p1, int p2)
{
a = p1;
b = p2;
c = p2;
e.c = (byte)p1;
}
public int a;
public int b;
public decimal c;
public Pedding e;
}
[LuaCallCSharp]
public class TCForTestCSCallLua{
public static LuaEnv luaEnv = LuaEnvSingletonForTest.Instance;
string msg = "";
public void LOG(string text)
{
msg += text;
}
string script = @"
bValue1 = false
bValue2 = true
strValueEmpty = ''
strValueLong = string.rep('a', 2^10)
strValueShort = 'boo123'
strValueExp = '.* ? [ ] ^ $~`!@#$%^&()_-+=[];\',““〈〉〖【℃ $ ¤№ ☆ ★■ⅷ②㈣'
strValue5 = '\r\na'
strValue6 = [[
<html>
<head>
<title>test</title>
</head>
<body>
this is just a test lua multi lines string
</body>
</html>]]
strValueChin = '中文字符串'
strValueComp = '繁體國陸'
strValueHoX = '吙煋呅僦媞這樣孒'
sbyteValueMax = 127
sbyteValueMin = -128
byteValueMax = 255
byteValueMin = 0
shortValueMax = 32767
shortValueMin= -32768
ushortValueMax = 65535
ushortValueMid = 32768
intValueMax = 2147483647
intValueMin = -2147483648
uintValueMax = 4294967295
uintValueMid = 2147483648
longValue = 42949672960
longValue2 = -42949672960
ulongValueMax = 42949672961111
ulongValueMin = 0
doubleValue = 3.14159265
doubleValue2 = -3.14159265
floatValue = 3.14159265
floatValue2 = -3.14
charValue = 97
charValue2 = 65
decValue = 12.3111111111
decValue2 = -12.3111111111
intValue3 = 0
intZero = 0
tableValue1 = {
key1 = 100000, key2 = 10, key3 = true,
'red', 'yellow', 'green',
sub = function(self, a, b)
print('tableValue1.sub called')
return a - b
end,
tableValueInclude = {
1,2,3,4,5,6,7,8,9,0
},
tableVarInclude = {ikey1 = 10, ikey2 = 12}
}
tableValue2 = {
kv1 = true, kv2 = 'monday', kv3 = 1
}
tableValue3 = {
'apple', 'banana', 'orange', 'kiwi', 'grape', 'lemon', 'strawberry', 'pear'
}
tableValue4 = {
k1= 1, k2= 10, k3 = 100, k4 = 1000, k5 = 10000
}
tableValue5 = {
[100] = 100, [101] = 1000, [102] = 10000
}
tableValue6 = {1,2,3}
tableValue7 = {
key1 = 'abc', key2 = 10}
function func_self_increase()
print('func_self_inscrease called')
intValue3 = intValue3 + 1;
end
function func_add_table(a)
local sum = 0
for i, v in ipairs(a) do
sum = sum + v
end
return sum
end
function func_add_2(a)
local sum = 0
for i, v in pairs(a) do
sum = sum + v
end
return sum
end
function func_return_multivalues()
local update = false
local strShort = 'false'
print('intValue3=', intValue3)
if intValue3 > 0
then
print('in if, intValue3=', intValue3)
update = true
strShort = 'true'
end
return update, strShort, {k1 = 11, k2 = 12}
end
function func_return_multivalues2()
local update = false
local strShort = 'false'
print('intValue3=', intValue3)
if intValue3 > 0
then
print('in if, intValue3=', intValue3)
update = true
strShort = 'true'
end
return update, strShort, {k1 = 11, k2 = 12}
end
function func_return_func()
print('func_return_func called')
return func_self_increase
end
function func_closure()
local i = 0
return function()
i = i + 1
return i
end
end
function func_multi_params(a, b, c)
if a == true
then
b = b + 1
c = string.lower(c)
end
return a, b, c
end
function func_multi_params2(a, b)
local sum = 0
if a == true
then
sum = b + 1
end
return func_self_increase, a, sum
end
function func_multi_params3(b, a)
local sum = 0
if a == true
then
sum = b + 1
end
return sum, a
end
function func_multi_params4(b, a)
local sum = 0
if a == true
then
sum = b + 1
end
return sum, a
end
function func_varparams(...)
local arg={...}
local sum = 0
print(select('#', ...))
for key, value in ipairs(arg)
do
sum = sum + value
--print(value)
--sum = sum + 1
end
return sum
end
function func_readfile(file_name)
local hFile = io.open(file_name, r)
if hFile
then
local strContent = hFile:read('*all')
print(strContent)
return strContent
else
print('file is not exist')
end
return nil
end
function func_return_object(type)
if type == 0 then
local ret = io.open(CS.LuaTestCommon.xxxtdrfilepath, r)
print('open A.lua.txt ret is ', ret)
return ret
end
if type == 1 then
return CS.LongStatic.LONG_MAX
end
if type == 2 then
return CS.LongStatic.ULONG_MAX
end
return 0
end
";
public struct TestResult
{
public bool result;
public string msg;
public override string ToString()
{
return "Result: " + result.ToString () + ", Msg:" + msg;
}
}
public TCForTestCSCallLua()
{
}
public void setResult(bool result, string msg, out TestResult resultStruct)
{
resultStruct.result = result;
resultStruct.msg = msg;
}
public void updateResult(bool result, string msg, ref TestResult resultStruct)
{
if (resultStruct.result == true) {
resultStruct.msg = msg;
} else {
resultStruct.msg = resultStruct.msg + "\r\n" + msg;
}
resultStruct.result = result;
}
public byte[] AddLoader1(ref string filename)
{
if (filename == "InMemory")
{
string script = "return {ccc = 9999}";
return System.Text.Encoding.UTF8.GetBytes(script);
}
return null;
}
public byte[] AddLoader2(ref string filename)
{
if (filename == "InFile") {
string script = "filestring = 'addloader2'";
return System.Text.Encoding.UTF8.GetBytes (script);
} else if (filename == "other") {
string script = "error('filename is error')";
return System.Text.Encoding.UTF8.GetBytes (script);
} else if (filename == "error_lua") {
string script = "maths:abs(-10)";
return System.Text.Encoding.UTF8.GetBytes (script);
}
return null;
}
public string listToString(List<int> a)
{
string result = "";
foreach (int i in a) {
result += i.ToString() + ",";
}
return result.TrimEnd(',');
}
public string listToStr(List<string> a)
{
string result = "";
foreach (string i in a) {
result += i + ",";
}
return result.TrimEnd(',');
}
public TestResult testDoString2LoadLua_Step_1()
{
/*
*/
string caseName = "testDoString2LoadLua_Step_1: ";
LOG ("*************" + caseName);
TestResult result;
try
{
string luaScript = @"
--call standard lib
require 'math'
a = math.abs(-10)
print('abs: ', a)
";
luaEnv.DoString (luaScript);
setResult (true, "pass", out result);
}
catch(Exception e)
{
setResult(false, e.Message , out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testDoString2LoadLua_Step_2()
{
/*
*
*/
string caseName = "testDoString2LoadLua_Step_2: ";
LOG ("*************" + caseName);
TestResult result;
try
{
string luaScript = @"
checkFlag = false;
a = 100
b = 1000
if a < b then
error('error raise')
end
";
luaEnv.DoString (luaScript);
setResult(false, "syntax error should be found, but there is no exception.", out result);
}
catch(Exception e)
{
setResult (true, "pass" , out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testDoString2LoadLua_Step_3()
{
/*
*
*/
string caseName = "testDoString2LoadLua_Step_3: ";
LOG ("*************" + caseName);
TestResult result;
try
{
string luaScript = @"
--call standard lib
a = maths.abs(-10)
print('abs: ', a)
";
luaEnv.DoString (luaScript);
setResult(false, "exception should be raised, but there is no exception.", out result);
}
catch(Exception e)
{
setResult (true, "pass" , out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testRequire2LoadLua_Step_1_3()
{
/*
*/
string caseName = "testRequire2LoadLua_Step_1_3: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.DoString("require 'A'");
luaEnv.DoString("require 'testlua.B';require 'D'");
luaEnv.DoString("require 'empty'");
// luaEnv.DoString ("require 'testlua.main'");
setResult (true, "pass", out result);
}
catch(Exception e)
{
setResult(false, e.Message , out result);
}
string dValue = luaEnv.Global.Get<string> ("strValue");
LOG ("_G.strValue = " + dValue);
if (dValue != "D.lua.txt") {
setResult (false, result.msg + ", require should require d from Resources, but strValue=" + dValue, out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testRequire2LoadLua_Step_4()
{
/*
*/
string caseName = "testRequire2LoadLua_Step_4: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.DoString ("require 'testlua.main'");
setResult (true, "pass", out result);
}
catch(Exception e)
{
setResult(false, e.Message , out result);
}
string dValue = luaEnv.Global.Get<string> ("strValue");
LOG ("_G.strValue = " + dValue);
if (dValue != "D.lua.txt") {
setResult (false, result.msg + ", require should require d from Resources, but strValue=" + dValue, out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testRequire2LoadLua_Step_5()
{
/*
*/
string caseName = "testRequire2LoadLua_Step_5: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.DoString ("require 'E'");
setResult(false, "E.lua in Resources path, but be loaded, no exception be raised.", out result);
}
catch(Exception e)
{
setResult (true, "pass" , out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testRequire2LoadLua_Step_6()
{
/*
*/
string caseName = "testRequire2LoadLua_Step_6: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.DoString ("require 'F'");
setResult(false, "F.lua deesn't exist, but no exception be raised.", out result);
}
catch(Exception e)
{
setResult (true, "pass" , out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testRequire2LoadLua_Step_7()
{
/*
*/
string caseName = "testRequire2LoadLua_Step_7: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.DoString ("require 'error'");
setResult(false, "there is syntax errors in error.lua, but no exception be raised.", out result);
}
catch(Exception e)
{
setResult (true, "pass" , out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testAddLoader2LoadLua_Step_1_2()
{
/*
*/
string caseName = "testAddLoader2LoadLua_Step_1_2: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.AddLoader(AddLoader1);
luaEnv.DoString("inmemory = require('InMemory').ccc");
luaEnv.AddLoader(AddLoader2);
luaEnv.DoString("require('InFile')");
luaEnv.AddLoader(AddLoader2);
luaEnv.DoString("require('InFile')");
setResult (true, "pass", out result);
}
catch(Exception e)
{
setResult(false, e.Message , out result);
}
LuaTestCommon.Log ("InMemory.ccc=" + luaEnv.Global.Get<int> ("inmemory"));
LuaTestCommon.Log("InFile.filestring=" + luaEnv.Global.Get<string>("filestring"));
LOG (caseName + result.ToString());
return result;
}
public TestResult testAddLoader2LoadLua_Step_3()
{
/*
*/
string caseName = "testAddLoader2LoadLua_Step_3: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.AddLoader(AddLoader2);
luaEnv.DoString(" require('other')");
setResult(false, "AddLoader2 should raise exception, but it doesn't.", out result);
}
catch(Exception e)
{
setResult (true, "pass" , out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testAddLoader2LoadLua_Step_6()
{
/*
*/
string caseName = "testAddLoader2LoadLua_Step_6: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.AddLoader(AddLoader2);
luaEnv.DoString(" require('error_lua')");
setResult(false, "AddLoader2 should raise exception, but it doesn't.", out result);
}
catch(Exception e)
{
setResult (true, "pass", out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testAddLoader2LoadLua_Step_7()
{
/*
*/
string caseName = "testAddLoader2LoadLua_Step_7: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.AddLoader(AddLoader2);
luaEnv.DoString(@"package.loaded['InFil'] = nil");
luaEnv.DoString("require('InFile')");
setResult (true, "pass", out result);
}
catch(Exception e)
{
setResult(false, e.Message , out result);
}
string filestring = luaEnv.Global.Get<string> ("filestring");
if (filestring != "addloader2")
{
setResult(false, "shoulde load loader defined, but loadfile in Resources.", out result);
}
LuaTestCommon.Log ("InFile.filestring=" + filestring);
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeBool_Step_1()
{
/*
*/
string caseName = "testGetBasicDataTypeBool_step_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
bool falseVar = luaEnv.Global.Get<bool> ("bValue1");
bool trueVar = luaEnv.Global.Get<bool> ("bValue2");
LOG ("bValue1=" + falseVar + "; bValue2=" + trueVar);
if (falseVar == false && trueVar == true) {
setResult (true, "pass", out result);
} else {
setResult (false, "fail", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeString_Step_2()
{
/*
*/
string caseName = "testGetBasicDataTypeString_step_2: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
string emptyStr = luaEnv.Global.Get<string> ("strValueEmpty");
string longStr = luaEnv.Global.Get<string> ("strValueLong");
string shortStr = luaEnv.Global.Get<string> ("strValueShort");
string expStr = luaEnv.Global.Get<string> ("strValueExp");
string zhuanyiStr = luaEnv.Global.Get<string> ("strValue5");
string linesStr = luaEnv.Global.Get<string> ("strValue6");
string chinStr = luaEnv.Global.Get<string> ("strValueChin");
string compStr = luaEnv.Global.Get<string> ("strValueComp");
string huoxingStr = luaEnv.Global.Get<string> ("strValueHoX");
LOG ("strValueEmpty=" + emptyStr + "; strValueLong length=" + longStr.Length);
LOG ("strValueShort=" + shortStr + "; trValueExp=" + expStr);
LOG ("strValue5=" + zhuanyiStr + "; strValue6=" + linesStr);
LOG ("strValueChin=" + chinStr + "; strValueComp=" + compStr);
LOG ("strValueHoX=" + huoxingStr);
if (emptyStr == "") {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).empty string isn't empty, is " + emptyStr, out result);
}
if (longStr.Length != 1024) {
updateResult(false, "(2). long string's length should be 1024, but is " + longStr.Length, ref result);
}
if (shortStr != "boo123") {
updateResult(false, "(3). short string should be bool123 but is " + shortStr, ref result);
}
if (expStr != ".* ? [ ] ^ $~`!@#$%^&()_-+=[];\',““〈〉〖【℃ $ ¤№ ☆ ★■ⅷ②㈣") {
updateResult(false, "(4). complex string is wrong, which is " + expStr, ref result);
}
if (zhuanyiStr != "\r\na") {
updateResult(false, "(5).zhuanyi string is wrong, which is " + zhuanyiStr, ref result);
}
if (linesStr.Split('\n').Length !=8) {
updateResult(false, "(6).multi lines string should have 8 liens, but it is " + linesStr.Split('\n').Length, ref result);
}
if (chinStr != "中文字符串") {
updateResult(false, "(7).chinese string is wrong, which is " + chinStr, ref result);
}
if (compStr != "繁體國陸") {
updateResult(false, "(8).fanti string is wrong, which is " + compStr, ref result);
}
if (huoxingStr != "吙煋呅僦媞這樣孒") {
updateResult(false, "(9).huoxing string is wrong, which is " + huoxingStr, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToSByte()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToSByte: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> sbyte
sbyte sbyteValueMax = luaEnv.Global.Get<sbyte> ("sbyteValueMax");
sbyte sbyteValueMin = luaEnv.Global.Get<sbyte> ("sbyteValueMin");
sbyte sbyteOverMax = luaEnv.Global.Get<sbyte> ("intValueMax");
sbyte sbyteOverMin = luaEnv.Global.Get<sbyte> ("intValueMin");
LOG ("sbyteValueMax=" + sbyteValueMax + "; sbyteValueMin=" + sbyteValueMin);
LOG ("sbyteOverMax=" + sbyteOverMax + "; sbyteOverMin=" + sbyteOverMin);
if (sbyteValueMax == System.SByte.MaxValue) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).sbyteValueMax, is " + sbyteValueMax, out result);
}
if (sbyteValueMin != System.SByte.MinValue) {
updateResult(false, "(2).sbyteValueMin, is " + sbyteValueMin, ref result);
}
if (sbyteOverMax != -1) {
updateResult(false, "(3).sbyteOverMax, is " + sbyteOverMax, ref result);
}
if (sbyteOverMin != 0) {
updateResult(false, "(4).sbyteOverMin, is " + sbyteOverMin, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToByte()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToByte: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> byte
byte byteValueMax = luaEnv.Global.Get<byte> ("byteValueMax");
byte byteValueMin = luaEnv.Global.Get<byte> ("byteValueMin");
byte byteOverMax = luaEnv.Global.Get<byte> ("intValueMax");
byte byteOverMin = luaEnv.Global.Get<byte> ("intValueMin");
LOG ("byteValueMax=" + byteValueMax + "; byteValueMin=" + byteValueMin);
LOG ("byteOverMax=" + byteOverMax + "; byteOverMin=" + byteOverMin);
if (byteValueMax == System.Byte.MaxValue) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).byteValueMax, is " + byteValueMax, out result);
}
if (byteValueMin != System.Byte.MinValue) {
updateResult(false, "(2).byteValueMin, is " + byteValueMin, ref result);
}
if (byteOverMax != 255) {
updateResult(false, "(3).byteOverMax, is " + byteOverMax, ref result);
}
if (byteOverMin != 0) {
updateResult(false, "(4).sbyteOverMin, is " + byteOverMin, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToShort()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToShort: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> short
short shortValueMax = luaEnv.Global.Get<short> ("shortValueMax");
short shortValueMin = luaEnv.Global.Get<short> ("shortValueMin");
LOG ("shortValueMax=" + shortValueMax + "; shortValueMin=" + shortValueMin);
if (shortValueMax == System.Int16.MaxValue) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).shortValueMax, is " + shortValueMax, out result);
}
if (shortValueMin != System.Int16.MinValue) {
updateResult(false, "(2).shortValueMin, is " + shortValueMin, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToUShort()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToUShort: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> ushort
ushort ushortValueMax = luaEnv.Global.Get<ushort> ("ushortValueMax");
ushort ushortValueMid = luaEnv.Global.Get<ushort> ("ushortValueMid");
LOG ("ushortValueMax=" + ushortValueMax + "; shortValueMin=" + ushortValueMid);
if (ushortValueMax == System.UInt16.MaxValue) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).ushortValueMax, is " + ushortValueMax, out result);
}
if (ushortValueMid != 32768) {
updateResult(false, "(2).ushortValueMid, is " + ushortValueMid, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToInt()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToInt: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> int
int intValueMax = luaEnv.Global.Get<int> ("intValueMax");
int intValueMin = luaEnv.Global.Get<int> ("intValueMin");
int intZero = luaEnv.Global.Get<int> ("intZero");
LOG ("intValueMax=" + intValueMax + "; intValueMin=" + intValueMin);
if (intValueMax == System.Int32.MaxValue) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).intValueMax, is " + intValueMax, out result);
}
if (intValueMin != System.Int32.MinValue) {
updateResult(false, "(2).intValueMin, is " + intValueMin, ref result);
}
if (intZero != 0) {
updateResult(false, "(3).intZero, is " + intZero, ref result);
}
try {
int intValueOverMax = luaEnv.Global.Get<int> ("longValue");
int intValueOverMin = luaEnv.Global.Get<int> ("uintValueMax");
LOG ("intValueOverMax=" + intValueOverMax + "; intValueOverMin=" + intValueOverMin);
} catch(Exception e) {
updateResult(false, "it shouldn't raise exception, but e.msg:" + e.Message, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToUInt()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToUInt: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> uint
uint uintValueMax = luaEnv.Global.Get<uint> ("uintValueMax");
uint uintValueMid = luaEnv.Global.Get<uint> ("uintValueMid");
LOG ("uintValueMax=" + uintValueMax + "; uintValueMid=" + uintValueMid);
if (uintValueMax == System.UInt32.MaxValue) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).uintValueMax, is " + uintValueMax, out result);
}
if (uintValueMid != 2147483648) {
updateResult(false, "(2).uintValueMid, is " + uintValueMid, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToLong()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToLong: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> long
long longValue = luaEnv.Global.Get<long> ("longValue");
long longValue2 = luaEnv.Global.Get<long> ("longValue2");
LOG ("longValue=" + longValue + "; longValue2=" + longValue2);
LuaTestCommon.Log("longValue=" + longValue + "; longValue2=" + longValue2);
if (longValue == 42949672960) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).longValue, is " + longValue, out result);
}
if (longValue2 != -42949672960) {
updateResult(false, "(2).longValue2, is " + longValue2, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToULong()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToULong: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> ulong
ulong ulongValueMax = luaEnv.Global.Get<ulong> ("ulongValueMax");
ulong ulongValueMin = luaEnv.Global.Get<ulong> ("ulongValueMin");
LOG ("ulongValueMax=" + ulongValueMax + "; ulongValueMin=" + ulongValueMin);
if (ulongValueMax == 42949672961111) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).ulongValueMax, is " + ulongValueMax, out result);
}
if (ulongValueMin != 0) {
updateResult(false, "(2).ulongValueMin, is " + ulongValueMin, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToDouble()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToDouble: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> double
double doubleValue = luaEnv.Global.Get<double> ("doubleValue");
double doubleValue2 = luaEnv.Global.Get<double> ("doubleValue2");
LOG ("doubleValue=" + doubleValue + "; doubleValue2=" + doubleValue2);
if (doubleValue == 3.14159265) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).doubleValue, is " + doubleValue, out result);
}
if (doubleValue2 != -3.14159265) {
updateResult(false, "(2).doubleValue2, is " + doubleValue2, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToChar()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToChar: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> char
char charValue = luaEnv.Global.Get<char> ("charValue");
char charValue2 = luaEnv.Global.Get<char> ("charValue2");
LOG ("charValue=" + charValue + "; charValue2=" + charValue2);
if (charValue == 'a') {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).charValue, is " + charValue, out result);
}
if (charValue2 != 'A') {
updateResult(false, "(2).charValue2, is " + charValue2, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToFloat()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToFloat: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> float
float floatValue = luaEnv.Global.Get<float> ("floatValue");
float floatValue2 = luaEnv.Global.Get<float> ("floatValue2");
LOG ("floatValue=" + floatValue.ToString("F8") + "; charValue2=" + floatValue2);
if (System.Math.Abs(floatValue - 3.141593) < 0.000001) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).floatValue, is " + floatValue, out result);
}
if (System.Math.Abs(floatValue + 3.14) < 0.000001) {
updateResult(false, "(2).floatValue2, is " + floatValue2, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataTypeNumberToDecimal()
{
/*
*/
string caseName = "testGetBasicDataTypeNumberToDecimal: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
// number -> decimal
decimal decValue = luaEnv.Global.Get<decimal> ("decValue");
decimal decValue2 = luaEnv.Global.Get<decimal> ("decValue2");
decimal expectValue = 12.3111111111m;
decimal expectValue2 = -12.3111111111m;
LOG ("decValue=" + decValue + "; decValue2=" + decValue2);
if (decValue == expectValue) {
setResult (true, "pass", out result);
} else {
setResult (false, "(1).decValue, is " + decValue, out result);
}
if (decValue2 != expectValue2) {
updateResult(false, "(2).decValue2, is " + decValue2, ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataType_Step_4()
{
/*
*/
string caseName = "testGetBasicDataType_Step_4: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.DoString(script);
int noExistInt = luaEnv.Global.Get<int> ("noExistValue");
string noExistString = luaEnv.Global.Get<string> ("noExistString");
LOG ("noExistInt=" + noExistInt + "; noExistString=" + noExistString);
//setResult (false, "no exist value should raise exception", out result);
//setResult(false, "there is no var defined, should raise exception, but it doesn't.", out result);
setResult (false, "v2.1.3 change,noExistValue, only value type and nil value will raise exception", out result);
}
catch(Exception e)
{
LOG(e.Message);
setResult (true, "pass", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetBasicDataType_Step_5()
{
/*
*/
string caseName = "testGetBasicDataType_Step_5: ";
LOG ("*************" + caseName);
TestResult result;
try
{
luaEnv.DoString(script);
luaEnv.DoString("str2int='123'");
int string2Int = luaEnv.Global.Get<int> ("str2int");
/*string number2str = luaEnv.Global.Get<string>("byteValueMax");
LOG ("string2Int=" + string2Int + ", number2str=" + number2str);
int bool2int = luaEnv.Global.Get<int> ("bValue2");
string bool2str = luaEnv.Global.Get<string> ("bValue1");
LOG ("bool2int=" + bool2int + ", bool2str=" + bool2str);*/
//setResult (false, "type is not same, should raise exception", out result);
// setResult(false, "there is no var defined, should raise exception, but it doesn't.", out result);
setResult (true, "pass", out result);
}
catch(Exception e)
{
LOG(e.Message);
setResult (false, "v2.1.3 change, type is not same, only value type and nil value will raise exception", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToClass_Step_1()
{
/*
*/
string caseName = "testGetTableToClass_Step_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1ClassEqual tb1Class = luaEnv.Global.Get<tableValue1ClassEqual> ("tableValue1");
List<int> tableValueIncludeList = new List<int>(){1,2,3,4,5,6,7,8,9,0};
LOG ("tableValue1.key1 = " + tb1Class.key1 + "; tableValue1.key2= " + tb1Class.key2);
LOG ("tableValue1.key3 = " + tb1Class.key3 + "; tableValue1.tableValueInclude= " +
listToString(tb1Class.tableValueInclude));
if (tb1Class.key1 == 100000){
setResult (true, "pass", out result);
} else {
setResult (false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb1Class.key1 + "", out result);
}
if (tb1Class.key2 != 10) {
updateResult(false, "(2).tableValue1.key2 should be 10, but in fact is " + tb1Class.key2 , ref result);
}
if (tb1Class.key3 != true) {
updateResult(false, "(3).tableValue1.key3 should be true, but in fact is " + tb1Class.key3 , ref result);
}
if (tb1Class.tableValueInclude.Count != tableValueIncludeList.Count ||
tb1Class.tableValueInclude[0] != tableValueIncludeList[0]) {
updateResult(false, "(4).tableValue1.tableValueInclude should be {1,2,3,4,5,6,7,8,9,0}," +
"but in fact is " + listToString(tb1Class.tableValueInclude), ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToClass_Step_2()
{
/*
*/
string caseName = "testGetTableToClass_Step_2: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1ClassLess tb1Class = luaEnv.Global.Get<tableValue1ClassLess> ("tableValue1");
LOG ("tableValue1.key1 = " + tb1Class.key1 + "; tableValue1.key2= " + tb1Class.key2);
if (tb1Class.key1 == 100000){
setResult (true, "pass", out result);
} else {
setResult (false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb1Class.key1 + "", out result);
}
if (tb1Class.key2 != 10) {
updateResult(false, "(2).tableValue1.key2 should be 10, but in fact is " + tb1Class.key2 , ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToClass_Step_3()
{
/*
*/
string caseName = "testGetTableToClass_Step_3: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1ClassMore tb1Class = luaEnv.Global.Get<tableValue1ClassMore> ("tableValue1");
LOG ("tableValue1.key1 = " + tb1Class.key1 + "; tableValue1.key2 = " + tb1Class.key2);
LOG ("tableValue1.key3 = " + tb1Class.key3 + "; tableValue1ClassMore.key4 = " + tb1Class.key4);
if (tb1Class.key1 == 100000){
setResult (true, "pass", out result);
} else {
setResult (false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb1Class.key1 + "", out result);
}
if (tb1Class.key2 != 10) {
updateResult(false, "(2).tableValue1.key2 should be 10, but in fact is " + tb1Class.key2 , ref result);
}
if (tb1Class.key3 != true) {
updateResult(false, "(3).tableValue1.key3 should be true, but in fact is " + tb1Class.key3 , ref result);
}
if (tb1Class.key4 != 0) {
updateResult(false, "(4).key4 should be 0 default, but in fact is " + tb1Class.key4 , ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToClass_Step_4()
{
/*
*/
string caseName = "testGetTableToClass_Step_4: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1ClassMore tb1Class = luaEnv.Global.Get<tableValue1ClassMore> ("tableValue1");
LOG ("tableValue1.key1 = " + tb1Class.key1 + "; tableValue1.key2 = " + tb1Class.key2);
LOG ("tableValue1.key3 = " + tb1Class.key3 + "; tableValue1ClassMore.key4 = " + tb1Class.key4);
if (tb1Class.key1 == 100000){
setResult (true, "pass", out result);
} else {
setResult (false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb1Class.key1 + "", out result);
}
tb1Class.key1 = 100;
tableValue1ClassMore tb1Class2 = luaEnv.Global.Get<tableValue1ClassMore> ("tableValue1");
LOG ("tableValue1.key1 = " + tb1Class2.key1);
if (tb1Class2.key1 != 100000){
updateResult(false, "(2).tableValue1.key1 should be 100000, but int fact is" + tb1Class2.key1 , ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToClass_Step_5()
{
/*
*/
string caseName = "testGetTableToClass_Step_5: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1ClassPrivate tb1Class = luaEnv.Global.Get<tableValue1ClassPrivate> ("tableValue1");
LOG ("tableValue1.key1 = " + tb1Class.key1 + "; tableValue1.key2 = " + tb1Class.Get());
LOG ("tableValue1.key3 = " + tb1Class.key3);
if (tb1Class.key1 == 100000){
setResult (true, "pass", out result);
} else {
setResult (false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb1Class.key1 + "", out result);
}
if (tb1Class.Get () != 0){
updateResult(false, "(2).private key2 should be 0, but int fact is " + tb1Class.Get () , ref result);
}
if (tb1Class.key3 != true) {
updateResult(false, "(3).tableValue1.key3 should be true, but in fact is " + tb1Class.key3 , ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToClass_Step_1_1()
{
/*
*/
string caseName = "testGetTableToClass_Step_1_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
try{
tableValue1ClassParamConstucter tb1Class = luaEnv.Global.Get<tableValue1ClassParamConstucter> ("tableValue1");
// LOG ("tableValue1.key1 = " + tb1Class.key1 + "; tableValue1.key2 = " + tb1Class.key2);
// LOG ("tableValue1.key3 = " + tb1Class.key3);
setResult (true, "pass", out result);
} catch(Exception e){
setResult (false, "v2.1.3change, only value type and nil value will raise exception ,class has no non-param constructor will not", out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToClass_Step_1_3()
{
/*
*/
string caseName = "testGetTableToClass_Step_1_3: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1ClassTwoConstructer tb1Class = luaEnv.Global.Get<tableValue1ClassTwoConstructer> ("tableValue1");
LOG ("tableValue1.key1 = " + tb1Class.key1 + "; tableValue1.key2 = " + tb1Class.key2);
LOG ("tableValue1.key3 = " + tb1Class.key3 );
if (tb1Class.key1 == 100000){
setResult (true, "pass", out result);
} else {
setResult (false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb1Class.key1 + "", out result);
}
if (tb1Class.key2 != 10) {
updateResult(false, "(2).tableValue1.key2 should be 10, but in fact is " + tb1Class.key2 , ref result);
}
if (tb1Class.key3 != true) {
updateResult(false, "(3).tableValue1.key3 should be true, but in fact is " + tb1Class.key3 , ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToClass_Step_1_4()
{
/*
*/
string caseName = "testGetTableToClass_Step_1_4: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
try{
tableValue1ClassException tb1Class = luaEnv.Global.Get<tableValue1ClassException> ("tableValue1");
setResult (false, "class constructor should raise exception, but it doesnpt", out result);
} catch(Exception e){
setResult (true, "pass", out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToInterface_Step_6()
{
string caseName = "testGetTableToInterface_Step_6: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1InfEqual tb1Inf = luaEnv.Global.Get<tableValue1InfEqual> ("tableValue1");
LOG ("tableValue1.key1 = " + tb1Inf.key1 + "; tableValue1.key2 = " + tb1Inf.key2);
LOG ("tableValue1.key3 = " + tb1Inf.key3 );
LOG ("tableValue1.tableVarInclude.ikey1 = " + tb1Inf.tableVarInclude.ikey1 +
"; tableValue1.tableVarInclude.ikey2 = " + tb1Inf.tableVarInclude.ikey2);
if (tb1Inf.key1 == 100000){
setResult (true, "pass", out result);
} else {
setResult (false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb1Inf.key1 + "", out result);
}
if (tb1Inf.key2 != 10) {
updateResult(false, "(2).tableValue1.key2 should be 10, but in fact is " + tb1Inf.key2 , ref result);
}
if (tb1Inf.key3 != true) {
updateResult(false, "(3).tableValue1.key3 should be true, but in fact is " + tb1Inf.key3 , ref result);
}
if (tb1Inf.tableVarInclude.ikey1 != 10) {
updateResult(false, "(4).tableValue1.tableVarInclude.ikey1 should be 10, but in fact is " + tb1Inf.tableVarInclude.ikey1 , ref result);
}
if (tb1Inf.tableVarInclude.ikey2 != 12) {
updateResult(false, "(5).tableValue1.tableVarInclude.ikey2 should be 12, but in fact is " + tb1Inf.tableVarInclude.ikey2, ref result);
}
int subResult = tb1Inf.sub (1000, 100);
if (subResult != 900 ) {
updateResult(false, "(6).sub result is error, 1000 - 100 = " + subResult , ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToInterface_Step_7()
{
/*
*/
string caseName = "testGetTableToInterface_Step_7: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1InfLess tb1Inf = luaEnv.Global.Get<tableValue1InfLess> ("tableValue1");
LOG ("tableValue1.key1 = " + tb1Inf.key1 + "; tableValue1.key2 = " + tb1Inf.key2);
if (tb1Inf.key1 == 100000){
setResult (true, "pass", out result);
} else {
setResult (false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb1Inf.key1 + "", out result);
}
if (tb1Inf.key2 != 10) {
updateResult(false, "(2).tableValue1.key2 should be 10, but in fact is " + tb1Inf.key2 , ref result);
}
int subResult = tb1Inf.sub (1000, 100);
if (subResult != 900 ) {
updateResult(false, "(3).sub result is error, 1000 - 100 = " + subResult , ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToInterface_Step_8()
{
/*
*/
string caseName = "testGetTableToInterface_Step_8: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1InfMore tb1Inf = luaEnv.Global.Get<tableValue1InfMore> ("tableValue1");
LOG ("tableValue1InfMore.key4 = " + tb1Inf.key4);
if (tb1Inf.key4 == null){
setResult (true, "pass", out result);
} else {
setResult (false, "(1).key4 should be '' default, but int fact is : " + tb1Inf.key4 + "", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToInterface_Step_9()
{
/*
*/
string caseName = "testGetTableToInterface_Step_9: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue2Inf tb1Inf = luaEnv.Global.Get<tableValue2Inf> ("tableValue2");
LOG ("tableValue2.kv1 = " + tb1Inf.kv1 + "; tableValue2.kv2 = " + tb1Inf.kv2);
LOG ("tableValue2.kv3 = " + tb1Inf.kv3 );
tb1Inf.kv1 = false;
tb1Inf.kv2 = "test";
tb1Inf.kv3 = 3;
tableValue2Inf tb1Inf2 = luaEnv.Global.Get<tableValue2Inf> ("tableValue2");
LOG ("tableValue2.kv1 = " + tb1Inf2.kv1 + "; tableValue2.kv2 = " + tb1Inf2.kv2);
LOG ("tableValue2.kv3 = " + tb1Inf2.kv3 );
if (tb1Inf2.kv1 == false && tb1Inf2.kv2 == "test" && tb1Inf2.kv3 == 3){
setResult (true, "pass", out result);
} else {
setResult (false, "by ref, kv1, kv2, kv3 = " + tb1Inf2.kv1 +
", " + tb1Inf2.kv2 + ", " + tb1Inf2.kv3, out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToInterface_Step_6_1()
{
/*
*/
string caseName = "testGetTableToInterface_Step_6_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
try{
tableValue1InfTypeDiff tb1Inf = luaEnv.Global.Get<tableValue1InfTypeDiff> ("tableValue1");
LOG ("tableValue1.key1 = " + tb1Inf.key1 + "; tableValue1.key2 = " + tb1Inf.key2);
tableValue1InfLess tb2Inf = luaEnv.Global.Get<tableValue1InfLess> ("tableValue7");
LOG ("tableValue1.key1 = " + tb2Inf.key1 + "; tableValue2.key2 = " + tb2Inf.key2);
setResult (true, "pass", out result);
} catch(Exception e){
setResult (false, "class constructor should raise exception, but it doesnpt", out result);
LOG (e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToDic_Step_10()
{
/*
*/
string caseName = "testGetTableToDic_Step_10: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
Dictionary<string, int> dict = luaEnv.Global.Get<Dictionary<string, int>> ("tableValue4");
LOG ("tableValue4.k1 = " + dict["k1"] + "; tableValue4.k2 = " + dict["k2"]);
LOG ("tableValue4.k3 = " + dict["k3"] + "; tableValue4.k4 = " + dict["k4"]);
LOG ("tableValue4.k5 = " + dict["k5"]);
if (dict["k1"] == 1 && dict["k2"] == 10 && dict["k3"] == 100 && dict["k4"] == 1000
&& dict["k5"] == 10000){
setResult (true, "pass", out result);
} else {
setResult (false, "tableValue4 should be k1= 1, k2= 10, k3 = 100, k4 = 1000, k5 = 10000", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToDic_Step_11_1()
{
/*
*/
string caseName = "testGetTableToDic_Step_11_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
Dictionary<int, string> dict = luaEnv.Global.Get<Dictionary<int, string>> ("tableValue4");
LOG ("dict.Count = " + dict.Count);
if (dict.Count == 0){
setResult (true, "pass", out result);
} else {
setResult (false, "dict should be {}", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToDic_Step_11_2()
{
/*
*/
string caseName = "testGetTableToDic_Step_11_2: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
Dictionary<string, int> dict = luaEnv.Global.Get<Dictionary<string, int>> ("tableValue1");
LOG ("tableValue1.key1 = " + dict["key1"] + ", tableValue1.key2 = " + dict["key2"]);
LOG ("dict.Count = " + dict.Count);
if (dict.Count == 2 && dict["key1"] == 100000 && dict["key2"] == 10){
setResult (true, "pass", out result);
} else {
setResult (false, "dict should have key1 = 100000, key2 = 10", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToDic_Step_11_3()
{
/*
*/
string caseName = "testGetTableToDic_Step_11_3: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
Dictionary<int, int> dict = luaEnv.Global.Get<Dictionary<int, int>> ("tableValue3");
LOG ("dict.Count = " + dict.Count);
if (dict.Count == 0){
setResult (true, "pass", out result);
} else {
setResult (false, "dict should {}", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToList_Step_12()
{
/*
*/
string caseName = "testGetTableToList_Step_12: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
List<string> listVar = luaEnv.Global.Get<List<string>> ("tableValue3");
LOG ("listVar = " + listToStr(listVar));
if (listVar.Count == 8){
setResult (true, "pass", out result);
} else {
setResult (false, "listVar should be {'apple', 'banana', 'orange', 'kiwi', " +
"'grape', 'lemon', 'strawberry', 'pear'}", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToList_Step_13_1_int()
{
/*
*/
string caseName = "testGetTableToList_Step_13_1_int: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
List<int> listVar = luaEnv.Global.Get<List<int>> ("tableValue3");
LOG ("listVar = " + listToString(listVar));
if (listVar.Count == 0){
setResult (true, "pass", out result);
} else {
setResult (false, "listVar should be {}", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToList_Step_13_1_string()
{
/*
*/
string caseName = "testGetTableToList_Step_13_1_string: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
List<string> listVar = luaEnv.Global.Get<List<string>> ("tableValue6");
LOG ("listVar.count = " + listVar.Count);
if (listVar.Count == 0){
setResult (true, "pass", out result);
} else {
setResult (false, "listVar should be {}", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToList_Step_13_2()
{
/*
*/
string caseName = "testGetTableToList_Step_13_2: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
List<string> listVar = luaEnv.Global.Get<List<string>> ("tableValue1");
LOG ("listVar.count = " + listVar.Count + ", listVar = " + listToStr(listVar));
if (listVar.Count == 3){
setResult (true, "pass", out result);
} else {
setResult (false, "listVar should be {'red', 'yellow', 'green''}", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetTableToLuaTable_Step_14()
{
/*
*/
string caseName = "testGetTableToLuaTable_Step_14: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
LuaTable table = luaEnv.Global.Get<LuaTable> ("tableValue1");
LOG ("tableValue1.key1 = " + table.Get<int>("key1"));
LOG ("tableValue1.key2 = " + table.Get<int>("key2"));
LOG ("tableValue1.key3 = " + table.Get<bool>("key3"));
LOG ("tableValue1.1 = " + table[1]);
LOG ("tableValue1.2 = " + table[2]);
LOG ("tableValue1.3 = " + table[3]);
LOG ("tableValue1.sub = " + Convert.ToInt32(table.Get<LuaFunction>("sub").Call (table, 100, 10)[0]));
LOG ("tableValue1.tableValueInclude.count = " + table.Get<List<int>>("tableValueInclude").Count);
LOG ("tableValue1.tableVarInclude.count = " + table.Get<Dictionary<string, int>>("tableVarInclude").Count);
if (table.Get<int>("key1") == 100000){
setResult (true, "pass", out result);
} else {
setResult (false, "tablevalue1 is error", out result);
}
table ["key1"] = 100;
LuaTable table2 = luaEnv.Global.Get<LuaTable> ("tableValue1");
LOG ("tableValue1.key1 = " + table2.Get<int>("key1"));
if (Convert.ToInt32(table2["key1"]) != 100) {
updateResult(false, "modify no change.", ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_1()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncSelfINcreaseDelegate delegate1 = luaEnv.Global.Get<FuncSelfINcreaseDelegate> ("func_self_increase");
delegate1 ();
int intValue3 = luaEnv.Global.Get<int> ("intValue3");
LOG ("intValues = " + intValue3);
if (intValue3 == 1){
setResult (true, "pass", out result);
} else {
setResult (false, "intValue3 + 1 = 1, but is " + intValue3, out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_2_1()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_2_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncReturnMultivaluesDelegate2 delegate1 = luaEnv.Global.Get<FuncReturnMultivaluesDelegate2> ("func_return_multivalues");
string str;
tableValue4Class table;
bool update;
delegate1(out update, out str, out table);
LOG ("str = " + str + ", update = " + update + ", {k1 = " +
table.k1 + ", k2 = " + table.k2 + "}");
if (update == false && str == "false" && table.k1 == 11 && table.k2 == 12){
setResult (true, "pass", out result);
} else {
setResult (false, "function return error, should be false, 'false', {k1=11, k2=12}", out result);
}
FuncSelfINcreaseDelegate delegate2 = luaEnv.Global.Get<FuncSelfINcreaseDelegate> ("func_self_increase");
delegate2 ();
// int intValue3 = luaEnv.Global.Get<int> ("intValue3");
// intValue3 = 3;
delegate1(out update, out str, out table);
LOG ("get again, str = " + str + ", update = " + update + ", {k1 = " +
table.k1 + ", k2 = " + table.k2 + "}");
if (update != true || str != "true" || table.k1 != 11 || table.k2 != 12){
updateResult (false, "function return error, should be true, 'true', {k1=11, k2=12}", ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_2_2()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_2_2: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncReturnMultivaluesDelegate1 delegate1 = luaEnv.Global.Get<FuncReturnMultivaluesDelegate1> ("func_return_multivalues");
string str;
tableValue4Class table;
bool update = delegate1(out str, out table);
if (update == false && str == "false" && table.k1 == 11 && table.k2 == 12){
setResult (true, "pass", out result);
} else {
setResult (false, "function return error, should be false, 'false', {k1=11, k2=12}", out result);
}
FuncSelfINcreaseDelegate delegate2 = luaEnv.Global.Get<FuncSelfINcreaseDelegate> ("func_self_increase");
delegate2 ();
update = delegate1(out str, out table);
LOG ("get again, str = " + str + ", update = " + update + ", {k1 = " +
table.k1 + ", k2 = " + table.k2 + "}");
if (update != true || str != "true" || table.k1 != 11 || table.k2 != 12){
updateResult (false, "function return error, should be true, 'true', {k1=11, k2=12}", ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_2_3()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_2_3: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncReturnMultivaluesDelegate3 delegate1 = luaEnv.Global.Get<FuncReturnMultivaluesDelegate3> ("func_return_multivalues");
int a;
string str;
tableValue4Class table;
bool update;
delegate1(out update, out str, out table, out a);
LOG ("str = " + str + ", update = " + update + ", {k1 = " +
table.k1 + ", k2 = " + table.k2 + "}");
if (update == false && str == "false" && table.k1 == 11 && table.k2 == 12 && a == 0){
setResult (true, "pass", out result);
} else {
setResult (false, "function return error, should be false, 'false', {k1=11, k2=12}", out result);
}
FuncReturnMultivaluesDelegate31 delegate2 = luaEnv.Global.Get<FuncReturnMultivaluesDelegate31> ("func_return_multivalues2");
tableValue4Class noreturn;
delegate2(out update, out str, out table, out noreturn);
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_2_4()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_2_4: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncReturnMultivaluesDelegate4 delegate1 = luaEnv.Global.Get<FuncReturnMultivaluesDelegate4> ("func_return_multivalues");
string str;
bool update = delegate1(out str);
LOG ("str = " + str + ", update = " + update);
if (update == false && str == "false"){
setResult (true, "pass", out result);
} else {
setResult (false, "function return error, should be false, 'false'", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_3()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_3: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
GetFuncIncreaseDelegate delegate1 = luaEnv.Global.Get<GetFuncIncreaseDelegate> ("func_return_func");
Action e = delegate1();
e ();
int intValue3 = luaEnv.Global.Get<int>("intValue3");
if ( intValue3 == 1){
setResult (true, "pass", out result);
} else {
setResult (false, "intValue3 should be 1, but is" + intValue3, out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_5()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_5: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncMultiParamsDelegate delegate1 = luaEnv.Global.Get<FuncMultiParamsDelegate> ("func_multi_params");
bool a = true;
int b = 2;
string c = "ABC";
int d;
delegate1(ref a, ref b, ref c, out d);
LOG ("a = " + a + ", b = " + b + ", c = " + c);
if (a == true && b == 3 && c == "abc"){
setResult (true, "pass", out result);
} else {
setResult (false, "function return error, should be true, 3, 'abc'", out result);
}
a = false;
b = 2;
c = "ABC";
delegate1(ref a, ref b, ref c, out d);
if (a != false || b != 2 || c != "ABC") {
updateResult (false, "function return error, should be false, 2, 'ABC'", ref result);
}
LOG (caseName + result.ToString());
return result;
}
FuncMultiParams3Delegate2 delegate1;
public TestResult testGetFuncToDelegate_Step_5_1()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_5_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
delegate1 = luaEnv.Global.Get<FuncMultiParams3Delegate2> ("func_multi_params3");
bool a = true;
int b = 5;
int sum;
delegate1(b, out sum, ref a);
LOG ("sum = " + sum + ", a = " + a);
if (a == true && sum == 6 ){
setResult (true, "pass", out result);
} else {
setResult (false, "should be sum = 6, a = true", out result);
}
try {
FuncMultiParams3Delegate delegate2 = luaEnv.Global.Get<FuncMultiParams3Delegate> ("func_multi_params3");
}
catch (Exception e){
updateResult(false, "FuncMultiParams3Delegate to same function raise exception.", ref result);
LOG(e.Message);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_5_1_0()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_5_1_0: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncMultiParams3Delegate2 delegate1 = luaEnv.Global.Get<FuncMultiParams3Delegate2> ("func_multi_params3");
bool a = true;
int b = 5;
int sum;
delegate1(b, out sum, ref a);
LOG ("sum = " + sum + ", a = " + a);
if (a == true && sum == 6 ){
setResult (true, "pass", out result);
} else {
setResult (false, "should be sum = 6, a = true", out result);
}
FuncMultiParams3Delegate delegate2 = luaEnv.Global.Get<FuncMultiParams3Delegate> ("func_multi_params4");
a = false;
delegate2(out sum, b, ref a);
LOG ("FuncMultiParams3Delegate, sum = " + sum + ", a = " + a);
if (a != false || sum != 0) {
updateResult (false, "FuncMultiParams3Delegate, should be sum = 0, a = false", ref result);
}
LOG (caseName + result.ToString());
return result;
}
/*
public TestResult testGetFuncToDelegate_Step_5_2()
{
string caseName = "testGetFuncToDelegate_Step_5_2: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncMultiParams2Delegate delegate1 = luaEnv.Global.Get<FuncMultiParams2Delegate> ("func_multi_params2");
bool a = true;
int b = 5;
int sum;
Action d;
d = delegate1(ref a, b, out sum);
LOG ("sum = " + sum + ", a = " + a);
d();
int intValue3 = luaEnv.Global.Get<int> ("intValue3");
if (a == true && sum == 6 && intValue3 == 1){
setResult (true, "pass", out result);
} else {
setResult (false, "should be sum = 6, a = true, intValue3 = 1", out result);
}
LOG (caseName + result.ToString());
return result;
}
*/
public TestResult testGetFuncToDelegate_Step_6()
{
/*
*/
string caseName = "testGetFuncToDelegate_Step_6: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FucnVarParamsDelegate delegate1 = luaEnv.Global.Get<FucnVarParamsDelegate> ("func_varparams");
int sum = delegate1(6, 4);
LOG ("sum = " + sum );
if ( sum == 10){
setResult (true, "pass", out result);
} else {
setResult (false, "should be sum = 10", out result);
}
sum = delegate1(10, 5);
LOG ("sum = " + sum );
if (sum != 15) {
updateResult (false, "more input params, should be sum = 15", ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToLuaFunc_Step_8()
{
/*
*/
string caseName = "testGetFuncToLuaFunc_Step_8: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
LuaFunction func1 = luaEnv.Global.Get<LuaFunction> ("func_self_increase");
func1.Call ();
int intValue3 = luaEnv.Global.Get<int> ("intValue3");
LOG ("intValues = " + intValue3);
if (intValue3 == 1){
setResult (true, "pass", out result);
} else {
setResult (false, "intValue3 + 1 = 1, but is " + intValue3, out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToLuaFunc_Step_9_1()
{
/*
*/
string caseName = "testGetFuncToLuaFunc_Step_9_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
LuaFunction func1 = luaEnv.Global.Get<LuaFunction> ("func_return_multivalues");
object[] returns = func1.Call();
string str = (string)returns[1];
LuaTable table = (LuaTable)returns[2];
bool update = (bool)returns[0];
LOG ("str = " + str + ", update = " + update + ", {k1 = " +
table["k1"] + ", k2 = " + table["k2"] + "}");
if (update == false && str == "false" && Convert.ToInt32(table["k1"]) == 11 && Convert.ToInt32(table["k2"]) == 12){
setResult (true, "pass", out result);
} else {
setResult (false, "function return error, should be false, 'false', {k1=11, k2=12}", out result);
}
FuncSelfINcreaseDelegate delegate2 = luaEnv.Global.Get<FuncSelfINcreaseDelegate> ("func_self_increase");
delegate2 ();
// int intValue3 = luaEnv.Global.Get<int> ("intValue3");
// intValue3 = 3;
returns = func1.Call();
str = (string)returns[1];
table = (LuaTable)returns[2];
update = (bool)returns[0];
LOG ("get again, str = " + str + ", update = " + update + ", {k1 = " +
table["k1"] + ", k2 = " + table["k2"] + "}");
if (update != true || str != "true" || Convert.ToInt32(table["k1"]) != 11 || Convert.ToInt32(table["k2"]) != 12){
updateResult (false, "function return error, should be true, 'true', {k1=11, k2=12}", ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToLuaFunc_Step_10()
{
/*
*/
string caseName = "testGetFuncToLuaFunc_Step_10: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
LuaFunction func1 = luaEnv.Global.Get<LuaFunction> ("func_return_func");
LuaFunction e = (LuaFunction)func1.Call ()[0];
e.Call ();
int intValue3 = luaEnv.Global.Get<int>("intValue3");
if ( intValue3 == 1){
setResult (true, "pass", out result);
} else {
setResult (false, "intValue3 should be 1, but is" + intValue3, out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToLuaFunc_Step_12()
{
/*
*/
string caseName = "testGetFuncToLuaFunc_Step_12: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
LuaFunction func1 = luaEnv.Global.Get<LuaFunction> ("func_multi_params");
bool a = true;
int b = 2;
string c = "ABC";
int d;
object[] returns = func1.Call(a, b, c);
a = (bool)returns [0];
b = Convert.ToInt32(returns [1]);
c = (string)returns [2];
LOG ("a = " + a + ", b = " + b + ", c = " + c);
if (a == true && b == 3 && c == "abc"){
setResult (true, "pass", out result);
} else {
setResult (false, "function return error, should be true, 3, 'abc'", out result);
}
a = false;
b = 2;
c = "ABC";
returns = func1.Call(a, b, c);
a = (bool)returns [0];
b = Convert.ToInt32(returns [1]);
c = (string)returns [2];
if (a != false || b != 2 || c != "ABC") {
updateResult (false, "function return error, should be false, 2, 'ABC'", ref result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToLuaFunc_Step_13()
{
/*
*/
string caseName = "testGetFuncToLuaFunc_Step_13: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
LuaFunction func1 = luaEnv.Global.Get<LuaFunction> ("func_varparams");
object[] returns = func1.Call(6, 4);
int sum = Convert.ToInt32(returns [0]);
LOG ("sum = " + sum );
if ( sum == 10){
setResult (true, "pass", out result);
} else {
setResult (false, "should be sum = 10", out result);
}
returns = func1.Call(10, 1, 4);
sum = Convert.ToInt32(returns [0]);
LOG ("sum = " + sum );
LOG ("sum = " + sum );
if (sum != 15) {
updateResult (false, "more input params, should be sum = 15", ref result);
}
LOG (caseName + result.ToString());
return result;
}
// 补充用例C#以返回值为object的delegate调用Lua函数,
// (1)而在lua函数侧返回的是long,ulong,都能正确返回。
// (2)在lua函数返回别的地方创建的userdata,比如io.open返回的文件句柄,在c#那接收到的是null
public TestResult testGetFuncToDelegate_Step_7_1()
{
string caseName = "testGetFuncToDelegate_Step_7_1: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncReturnObjectDelegate delegate1 = luaEnv.Global.Get<FuncReturnObjectDelegate> ("func_return_object");
System.Object ret = delegate1(0);
LuaTestCommon.Log ("ret= " + ret );
if ( ret == null){
setResult (true, "pass", out result);
} else {
setResult (false, "should be ret = null", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_7_2()
{
string caseName = "testGetFuncToDelegate_Step_7_2: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncReturnObjectDelegate delegate1 = luaEnv.Global.Get<FuncReturnObjectDelegate> ("func_return_object");
System.Object ret = delegate1(1);
LuaTestCommon.Log ("ret= " + ret );
if ( Convert.ToInt64(ret)== System.Int64.MaxValue){
setResult (true, "pass", out result);
} else {
setResult (false, "should be ret = System.Int64.MaxValue", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testGetFuncToDelegate_Step_7_3()
{
string caseName = "testGetFuncToDelegate_Step_7_3: ";
LOG ("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncReturnObjectDelegate delegate1 = luaEnv.Global.Get<FuncReturnObjectDelegate> ("func_return_object");
System.Object ret = delegate1(2);
LuaTestCommon.Log ("ret= " + ret );
//if ( Convert.ToUInt64(ret) == System.UInt64.MaxValue){
if ( Convert.ToInt64(ret) == -1){
setResult (true, "pass", out result);
} else {
setResult (false, "should be ret = System.UInt64.MaxValue", out result);
}
LOG (caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_int_1()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_int_1: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
int ret = luaEnv.Global.Get<int>("intValueMax");
LuaTestCommon.Log("ret= " + ret);
if (ret == System.Int32.MaxValue)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "(1).intValueMax, is " + ret, out result);
}
luaEnv.Global.Set("intValueMax", 12345);
ret = luaEnv.Global.Get<int>("intValueMax");
LuaTestCommon.Log("ret= " + ret);
if (ret == 12345)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2).after set intValueMax=12345, get is " + ret, ref result);
}
ret = 0;
luaEnv.Global.Get("intValueMax", out ret);
LuaTestCommon.Log("out ret= " + ret);
if (ret == 12345)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(3).after set intValueMax=12345, get is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_int_2()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_int_2: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
int ret;
luaEnv.Global.Set(123, 12345);
ret = luaEnv.Global.Get<int>(123);
LuaTestCommon.Log("ret= " + ret);
if (ret == 12345)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "(1).after set 123=12345, get is " + ret, out result);
}
ret = 0;
luaEnv.Global.Get(123, out ret);
LuaTestCommon.Log("out ret= " + ret);
if (ret == 12345)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2).after set intValueMax=12345, get is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_string_1()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_string_1: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
string ret;
luaEnv.Global.Set("strValueChin", "中文字符串mix12345587");
luaEnv.Global.Get("strValueChin", out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == "中文字符串mix12345587")
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_sbyte()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_sbyte: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
sbyte ret;
luaEnv.Global.Set((sbyte)12, (sbyte)23);
luaEnv.Global.Get((sbyte)12, out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == (sbyte)23)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
luaEnv.Global.Get("sbyteValueMin", out ret);
if (ret == -128)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get sbyteValueMin is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_byte()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_byte: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
byte ret;
luaEnv.Global.Set((byte)255, (byte)23);
luaEnv.Global.Get((byte)255, out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == (byte)23)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
luaEnv.Global.Get("byteValueMax", out ret);
if (ret == (byte)255)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get byteValueMax is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_short()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_short: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
short ret;
luaEnv.Global.Set((short)256, (short)512);
luaEnv.Global.Get((short)256, out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == 512)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
luaEnv.Global.Get("shortValueMax", out ret);
if (ret == 32767)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get shortValueMax is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_ushort()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_ushort: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
ushort ret;
luaEnv.Global.Set((ushort)1024, (ushort)32768);
luaEnv.Global.Get((ushort)1024, out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == 32768)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
luaEnv.Global.Get("ushortValueMax", out ret);
if (ret == 65535)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get ushortValueMax is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_long()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_long: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
long ret;
luaEnv.Global.Set("test", (long)3276800000);
luaEnv.Global.Get("test", out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == 3276800000)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
luaEnv.Global.Get("longValue2", out ret);
if (ret == -42949672960)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get longValue2 is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_ulong()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_ulong: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
ulong ret;
luaEnv.Global.Set("test", (ulong)42949672960);
luaEnv.Global.Get("test", out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == 42949672960)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
luaEnv.Global.Get("ulongValueMax", out ret);
if (ret == 42949672961111)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get ulongValueMax is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_double()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_double: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
double ret;
luaEnv.Global.Set((double)0.0000001, (double)1.000124587);
luaEnv.Global.Get((double)0.0000001, out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == 1.000124587)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
luaEnv.Global.Get("doubleValue2", out ret);
if (ret == -3.14159265)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get doubleValue2 is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_float()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_float: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
float ret;
luaEnv.Global.Set((float)3.14, (float)3.15);
luaEnv.Global.Get((float)3.14, out ret);
LuaTestCommon.Log("ret= " + ret);
if (System.Math.Abs(ret - 3.15) < 0.000001)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
ret = 0;
luaEnv.Global.Get("floatValue2", out ret);
if (System.Math.Abs(ret + 3.14) < 0.000001)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get floatValue2 is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_char()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_char: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
char ret;
luaEnv.Global.Set('a', 'b');
luaEnv.Global.Get('a', out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == 'b')
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
luaEnv.Global.Get("charValue", out ret);
if (ret == 'a')
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get charValue is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_BasicType_decimal()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_decimal: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
decimal key = -32132143143100109.00010001010M;
decimal value = 0.0000001M;
decimal ret;
luaEnv.Global.Set(123.01, value);
luaEnv.Global.Get(123.01, out ret);
LuaTestCommon.Log("ret= " + ret);
if (ret == value)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + ret, out result);
}
luaEnv.Global.Get("decValue2", out ret);
if (ret == -12.3111111111M)
{
updateResult(true, "pass", ref result);
}
else
{
updateResult(false, "(2) get decValue2 is " + ret, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_struct()
{
string caseName = "testLuaTableGetSetKeyValue_BasicType_struct: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
TestStruct mystruct = new TestStruct(5, 6); // custom complex value type
TestStruct mystruct2;
luaEnv.Global.Set(123, mystruct);
luaEnv.Global.Get(123, out mystruct2);
LuaTestCommon.Log("ret= " + mystruct2);
if (mystruct.a == mystruct2.a)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "ret is " + mystruct2.a, out result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_class()
{
string caseName = "testLuaTableGetSetKeyValue_class: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1ClassPrivate tb1Class = luaEnv.Global.Get<tableValue1ClassPrivate>("tableValue1");
tableValue1ClassPrivate tb2Class;
luaEnv.Global.Set(tb1Class.key1, tb1Class);
luaEnv.Global.Get(tb1Class.key1, out tb2Class);
LOG("tableValue1.key1 = " + tb2Class.key1 + "; tableValue1.key2 = " + tb2Class.Get());
LOG("tableValue1.key3 = " + tb2Class.key3);
if (tb2Class.key1 == 100000)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb2Class.key1 + "", out result);
}
if (tb2Class.Get() != 0)
{
updateResult(false, "(2).private key2 should be 0, but int fact is " + tb2Class.Get(), ref result);
}
if (tb2Class.key3 != true)
{
updateResult(false, "(3).tableValue1.key3 should be true, but in fact is " + tb2Class.key3, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_interface()
{
string caseName = "testLuaTableGetSetKeyValue_interface: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
tableValue1InfEqual tb1Inf = luaEnv.Global.Get<tableValue1InfEqual>("tableValue1");
tb1Inf.key3 = false;
tableValue1InfEqual tb2Inf;
LOG("tableValue1.key1 = " + tb1Inf.key1 + "; tableValue1.key2 = " + tb1Inf.key2);
LOG("tableValue1.key3 = " + tb1Inf.key3);
LOG("tableValue1.tableVarInclude.ikey1 = " + tb1Inf.tableVarInclude.ikey1 +
"; tableValue1.tableVarInclude.ikey2 = " + tb1Inf.tableVarInclude.ikey2);
luaEnv.Global.Set("tableValue1", tb1Inf);
luaEnv.Global.Get("tableValue1", out tb2Inf);
if (tb2Inf.key1 == 100000)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "(1).tableValue1.key1 should be 100000, but int fact is : " + tb2Inf.key1 + "", out result);
}
if (tb2Inf.key2 != 10)
{
updateResult(false, "(2).tableValue1.key2 should be 10, but in fact is " + tb2Inf.key2, ref result);
}
if (tb2Inf.key3 != false)
{
updateResult(false, "(3).tableValue1.key3 should be true, but in fact is " + tb2Inf.key3, ref result);
}
if (tb2Inf.tableVarInclude.ikey1 != 10)
{
updateResult(false, "(4).tableValue1.tableVarInclude.ikey1 should be 10, but in fact is " + tb2Inf.tableVarInclude.ikey1, ref result);
}
if (tb2Inf.tableVarInclude.ikey2 != 12)
{
updateResult(false, "(5).tableValue1.tableVarInclude.ikey2 should be 12, but in fact is " + tb2Inf.tableVarInclude.ikey2, ref result);
}
int subResult = tb2Inf.sub(1000, 100);
if (subResult != 900)
{
updateResult(false, "(6).sub result is error, 1000 - 100 = " + subResult, ref result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_dict()
{
string caseName = "testLuaTableGetSetKeyValue_dict: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
Dictionary<string, int> dict = luaEnv.Global.Get<Dictionary<string, int>>("tableValue1");
Dictionary<string, int> dict2;
LOG("tableValue1.key1 = " + dict["key1"] + ", tableValue1.key2 = " + dict["key2"]);
LOG("dict.Count = " + dict.Count);
luaEnv.Global.Set("tableValue1", dict);
luaEnv.Global.Get("tableValue1", out dict2);
LOG("tableValue1.key1 = " + dict2["key1"] + ", tableValue1.key2 = " + dict2["key2"]);
LOG("dict.Count = " + dict2.Count);
if (dict2.Count == 2 && dict2["key1"] == 100000 && dict2["key2"] == 10)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "dict should have key1 = 100000, key2 = 10", out result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_list()
{
string caseName = "testLuaTableGetSetKeyValue_list: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
List<string> listVar = luaEnv.Global.Get<List<string>>("tableValue3");
List<string> listVar2;
LOG("listVar = " + listToStr(listVar));
listVar[0] = "test";
luaEnv.Global.Set("tableValue3", listVar);
luaEnv.Global.Get("tableValue3", out listVar2);
if (listVar2.Count == 8)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "listVar2 should be {'test', 'banana', 'orange', 'kiwi', " +
"'grape', 'lemon', 'strawberry', 'pear'}", out result);
}
LOG(caseName + result.ToString());
return result;
}
public TestResult testLuaTableGetSetKeyValue_delegate()
{
string caseName = "testLuaTableGetSetKeyValue_delegate: ";
LOG("*************" + caseName);
TestResult result;
luaEnv.DoString(script);
FuncSelfINcreaseDelegate delegate1 = luaEnv.Global.Get<FuncSelfINcreaseDelegate>("func_self_increase");
FuncSelfINcreaseDelegate delegate2;
luaEnv.Global.Set("test_delegate", delegate1);
luaEnv.Global.Get("test_delegate", out delegate2);
delegate2();
int intValue3 = luaEnv.Global.Get<int>("intValue3");
LOG("intValues = " + intValue3);
if (intValue3 == 1)
{
setResult(true, "pass", out result);
}
else
{
setResult(false, "intValue3 + 1 = 1, but is " + intValue3, out result);
}
LOG(caseName + result.ToString());
return result;
}
}
| xLua/Test/UnitTest/xLuaTest/CSharpCallLua/TCForTestCSCallLua.cs/0 | {
"file_path": "xLua/Test/UnitTest/xLuaTest/CSharpCallLua/TCForTestCSCallLua.cs",
"repo_id": "xLua",
"token_count": 37173
} | 1,882 |
<!-- $Id: lua.man,v 1.11 2006/01/06 16:03:34 lhf Exp $ -->
<HTML>
<HEAD>
<TITLE>LUA man page</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<H2>NAME</H2>
lua - Lua interpreter
<H2>SYNOPSIS</H2>
<B>lua</B>
[
<I>options</I>
]
[
<I>script</I>
[
<I>args</I>
]
]
<H2>DESCRIPTION</H2>
<B>lua</B>
is the stand-alone Lua interpreter.
It loads and executes Lua programs,
either in textual source form or
in precompiled binary form.
(Precompiled binaries are output by
<B>luac</B>,
the Lua compiler.)
<B>lua</B>
can be used as a batch interpreter and also interactively.
<P>
The given
<I>options</I>
(see below)
are executed and then
the Lua program in file
<I>script</I>
is loaded and executed.
The given
<I>args</I>
are available to
<I>script</I>
as strings in a global table named
<B>arg</B>.
If these arguments contain spaces or other characters special to the shell,
then they should be quoted
(but note that the quotes will be removed by the shell).
The arguments in
<B>arg</B>
start at 0,
which contains the string
'<I>script</I>'.
The index of the last argument is stored in
<B>arg.n</B>.
The arguments given in the command line before
<I>script</I>,
including the name of the interpreter,
are available in negative indices in
<B>arg</B>.
<P>
At the very start,
before even handling the command line,
<B>lua</B>
executes the contents of the environment variable
<B>LUA_INIT</B>,
if it is defined.
If the value of
<B>LUA_INIT</B>
is of the form
'@<I>filename</I>',
then
<I>filename</I>
is executed.
Otherwise, the string is assumed to be a Lua statement and is executed.
<P>
Options start with
<B>'-'</B>
and are described below.
You can use
<B>'--'</B>
to signal the end of options.
<P>
If no arguments are given,
then
<B>"-v -i"</B>
is assumed when the standard input is a terminal;
otherwise,
<B>"-"</B>
is assumed.
<P>
In interactive mode,
<B>lua</B>
prompts the user,
reads lines from the standard input,
and executes them as they are read.
If a line does not contain a complete statement,
then a secondary prompt is displayed and
lines are read until a complete statement is formed or
a syntax error is found.
So, one way to interrupt the reading of an incomplete statement is
to force a syntax error:
adding a
<B>';'</B>
in the middle of a statement is a sure way of forcing a syntax error
(except inside multiline strings and comments; these must be closed explicitly).
If a line starts with
<B>'='</B>,
then
<B>lua</B>
displays the values of all the expressions in the remainder of the
line. The expressions must be separated by commas.
The primary prompt is the value of the global variable
<B>_PROMPT</B>,
if this value is a string;
otherwise, the default prompt is used.
Similarly, the secondary prompt is the value of the global variable
<B>_PROMPT2</B>.
So,
to change the prompts,
set the corresponding variable to a string of your choice.
You can do that after calling the interpreter
or on the command line
(but in this case you have to be careful with quotes
if the prompt string contains a space; otherwise you may confuse the shell.)
The default prompts are "> " and ">> ".
<H2>OPTIONS</H2>
<P>
<B>-</B>
load and execute the standard input as a file,
that is,
not interactively,
even when the standard input is a terminal.
<P>
<B>-e </B><I>stat</I>
execute statement
<I>stat</I>.
You need to quote
<I>stat </I>
if it contains spaces, quotes,
or other characters special to the shell.
<P>
<B>-i</B>
enter interactive mode after
<I>script</I>
is executed.
<P>
<B>-l </B><I>name</I>
call
<B>require</B>('<I>name</I>')
before executing
<I>script</I>.
Typically used to load libraries.
<P>
<B>-v</B>
show version information.
<H2>SEE ALSO</H2>
<B>luac</B>(1)
<BR>
<A HREF="http://www.lua.org/">http://www.lua.org/</A>
<H2>DIAGNOSTICS</H2>
Error messages should be self explanatory.
<H2>AUTHORS</H2>
R. Ierusalimschy,
L. H. de Figueiredo,
and
W. Celes
<!-- EOF -->
</BODY>
</HTML>
| xLua/build/lua-5.1.5/doc/lua.html/0 | {
"file_path": "xLua/build/lua-5.1.5/doc/lua.html",
"repo_id": "xLua",
"token_count": 1372
} | 1,883 |
# makefile for building Lua
# see ../INSTALL for installation instructions
# see ../Makefile and luaconf.h for further customization
# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
# Your platform. See PLATS for possible values.
PLAT= none
CC= gcc
CFLAGS= -O2 -Wall $(MYCFLAGS)
AR= ar rcu
RANLIB= ranlib
RM= rm -f
LIBS= -lm $(MYLIBS)
MYCFLAGS=
MYLDFLAGS=
MYLIBS=
# == END OF USER SETTINGS. NO NEED TO CHANGE ANYTHING BELOW THIS LINE =========
PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris
LUA_A= liblua.a
CORE_O= lapi.o lcode.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o \
lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o \
lundump.o lvm.o lzio.o
LIB_O= lauxlib.o lbaselib.o ldblib.o liolib.o lmathlib.o loslib.o ltablib.o \
lstrlib.o loadlib.o linit.o
LUA_T= lua
LUA_O= lua.o
LUAC_T= luac
LUAC_O= luac.o print.o
ALL_O= $(CORE_O) $(LIB_O) $(LUA_O) $(LUAC_O)
ALL_T= $(LUA_A) $(LUA_T) $(LUAC_T)
ALL_A= $(LUA_A)
default: $(PLAT)
all: $(ALL_T)
o: $(ALL_O)
a: $(ALL_A)
$(LUA_A): $(CORE_O) $(LIB_O)
$(AR) $@ $(CORE_O) $(LIB_O) # DLL needs all object files
$(RANLIB) $@
$(LUA_T): $(LUA_O) $(LUA_A)
$(CC) -o $@ $(MYLDFLAGS) $(LUA_O) $(LUA_A) $(LIBS)
$(LUAC_T): $(LUAC_O) $(LUA_A)
$(CC) -o $@ $(MYLDFLAGS) $(LUAC_O) $(LUA_A) $(LIBS)
clean:
$(RM) $(ALL_T) $(ALL_O)
depend:
@$(CC) $(CFLAGS) -MM l*.c print.c
echo:
@echo "PLAT = $(PLAT)"
@echo "CC = $(CC)"
@echo "CFLAGS = $(CFLAGS)"
@echo "AR = $(AR)"
@echo "RANLIB = $(RANLIB)"
@echo "RM = $(RM)"
@echo "MYCFLAGS = $(MYCFLAGS)"
@echo "MYLDFLAGS = $(MYLDFLAGS)"
@echo "MYLIBS = $(MYLIBS)"
# convenience targets for popular platforms
none:
@echo "Please choose a platform:"
@echo " $(PLATS)"
aix:
$(MAKE) all CC="xlc" CFLAGS="-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-ldl" MYLDFLAGS="-brtl -bexpall"
ansi:
$(MAKE) all MYCFLAGS=-DLUA_ANSI
bsd:
$(MAKE) all MYCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-Wl,-E"
freebsd:
$(MAKE) all MYCFLAGS="-DLUA_USE_LINUX" MYLIBS="-Wl,-E -lreadline"
generic:
$(MAKE) all MYCFLAGS=
linux:
$(MAKE) all MYCFLAGS=-DLUA_USE_LINUX MYLIBS="-Wl,-E -ldl -lreadline -lhistory -lncurses"
macosx:
$(MAKE) all MYCFLAGS=-DLUA_USE_LINUX MYLIBS="-lreadline"
# use this on Mac OS X 10.3-
# $(MAKE) all MYCFLAGS=-DLUA_USE_MACOSX
mingw:
$(MAKE) "LUA_A=lua51.dll" "LUA_T=lua.exe" \
"AR=$(CC) -shared -o" "RANLIB=strip --strip-unneeded" \
"MYCFLAGS=-DLUA_BUILD_AS_DLL" "MYLIBS=" "MYLDFLAGS=-s" lua.exe
$(MAKE) "LUAC_T=luac.exe" luac.exe
posix:
$(MAKE) all MYCFLAGS=-DLUA_USE_POSIX
solaris:
$(MAKE) all MYCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-ldl"
# list targets that do not create files (but not all makes understand .PHONY)
.PHONY: all $(PLATS) default o a clean depend echo none
# DO NOT DELETE
lapi.o: lapi.c lua.h luaconf.h lapi.h lobject.h llimits.h ldebug.h \
lstate.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h \
lundump.h lvm.h
lauxlib.o: lauxlib.c lua.h luaconf.h lauxlib.h
lbaselib.o: lbaselib.c lua.h luaconf.h lauxlib.h lualib.h
lcode.o: lcode.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \
lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lgc.h \
ltable.h
ldblib.o: ldblib.c lua.h luaconf.h lauxlib.h lualib.h
ldebug.o: ldebug.c lua.h luaconf.h lapi.h lobject.h llimits.h lcode.h \
llex.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h \
lfunc.h lstring.h lgc.h ltable.h lvm.h
ldo.o: ldo.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lparser.h lstring.h \
ltable.h lundump.h lvm.h
ldump.o: ldump.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h \
lzio.h lmem.h lundump.h
lfunc.o: lfunc.c lua.h luaconf.h lfunc.h lobject.h llimits.h lgc.h lmem.h \
lstate.h ltm.h lzio.h
lgc.o: lgc.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h
linit.o: linit.c lua.h luaconf.h lualib.h lauxlib.h
liolib.o: liolib.c lua.h luaconf.h lauxlib.h lualib.h
llex.o: llex.c lua.h luaconf.h ldo.h lobject.h llimits.h lstate.h ltm.h \
lzio.h lmem.h llex.h lparser.h lstring.h lgc.h ltable.h
lmathlib.o: lmathlib.c lua.h luaconf.h lauxlib.h lualib.h
lmem.o: lmem.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
ltm.h lzio.h lmem.h ldo.h
loadlib.o: loadlib.c lua.h luaconf.h lauxlib.h lualib.h
lobject.o: lobject.c lua.h luaconf.h ldo.h lobject.h llimits.h lstate.h \
ltm.h lzio.h lmem.h lstring.h lgc.h lvm.h
lopcodes.o: lopcodes.c lopcodes.h llimits.h lua.h luaconf.h
loslib.o: loslib.c lua.h luaconf.h lauxlib.h lualib.h
lparser.o: lparser.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \
lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h \
lfunc.h lstring.h lgc.h ltable.h
lstate.o: lstate.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h llex.h lstring.h ltable.h
lstring.o: lstring.c lua.h luaconf.h lmem.h llimits.h lobject.h lstate.h \
ltm.h lzio.h lstring.h lgc.h
lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h
ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
ltm.h lzio.h lmem.h ldo.h lgc.h ltable.h
ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h
ltm.o: ltm.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h lzio.h \
lmem.h lstring.h lgc.h ltable.h
lua.o: lua.c lua.h luaconf.h lauxlib.h lualib.h
luac.o: luac.c lua.h luaconf.h lauxlib.h ldo.h lobject.h llimits.h \
lstate.h ltm.h lzio.h lmem.h lfunc.h lopcodes.h lstring.h lgc.h \
lundump.h
lundump.o: lundump.c lua.h luaconf.h ldebug.h lstate.h lobject.h \
llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h lundump.h
lvm.o: lvm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h lvm.h
lzio.o: lzio.c lua.h luaconf.h llimits.h lmem.h lstate.h lobject.h ltm.h \
lzio.h
print.o: print.c ldebug.h lstate.h lua.h luaconf.h lobject.h llimits.h \
ltm.h lzio.h lmem.h lopcodes.h lundump.h
# (end of Makefile)
| xLua/build/lua-5.1.5/src/Makefile/0 | {
"file_path": "xLua/build/lua-5.1.5/src/Makefile",
"repo_id": "xLua",
"token_count": 3243
} | 1,884 |
/*
** $Id: lgc.c,v 2.38.1.2 2011/03/18 18:05:38 roberto Exp $
** Garbage Collector
** See Copyright Notice in lua.h
*/
#include <string.h>
#define lgc_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#define GCSTEPSIZE 1024u
#define GCSWEEPMAX 40
#define GCSWEEPCOST 10
#define GCFINALIZECOST 100
#define maskmarks cast_byte(~(bitmask(BLACKBIT)|WHITEBITS))
#define makewhite(g,x) \
((x)->gch.marked = cast_byte(((x)->gch.marked & maskmarks) | luaC_white(g)))
#define white2gray(x) reset2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT)
#define black2gray(x) resetbit((x)->gch.marked, BLACKBIT)
#define stringmark(s) reset2bits((s)->tsv.marked, WHITE0BIT, WHITE1BIT)
#define isfinalized(u) testbit((u)->marked, FINALIZEDBIT)
#define markfinalized(u) l_setbit((u)->marked, FINALIZEDBIT)
#define KEYWEAK bitmask(KEYWEAKBIT)
#define VALUEWEAK bitmask(VALUEWEAKBIT)
#define markvalue(g,o) { checkconsistency(o); \
if (iscollectable(o) && iswhite(gcvalue(o))) reallymarkobject(g,gcvalue(o)); }
#define markobject(g,t) { if (iswhite(obj2gco(t))) \
reallymarkobject(g, obj2gco(t)); }
#define setthreshold(g) (g->GCthreshold = (g->estimate/100) * g->gcpause)
static void removeentry (Node *n) {
lua_assert(ttisnil(gval(n)));
if (iscollectable(gkey(n)))
setttype(gkey(n), LUA_TDEADKEY); /* dead key; remove it */
}
static void reallymarkobject (global_State *g, GCObject *o) {
lua_assert(iswhite(o) && !isdead(g, o));
white2gray(o);
switch (o->gch.tt) {
case LUA_TSTRING: {
return;
}
case LUA_TUSERDATA: {
Table *mt = gco2u(o)->metatable;
gray2black(o); /* udata are never gray */
if (mt) markobject(g, mt);
markobject(g, gco2u(o)->env);
return;
}
case LUA_TUPVAL: {
UpVal *uv = gco2uv(o);
markvalue(g, uv->v);
if (uv->v == &uv->u.value) /* closed? */
gray2black(o); /* open upvalues are never black */
return;
}
case LUA_TFUNCTION: {
gco2cl(o)->c.gclist = g->gray;
g->gray = o;
break;
}
case LUA_TTABLE: {
gco2h(o)->gclist = g->gray;
g->gray = o;
break;
}
case LUA_TTHREAD: {
gco2th(o)->gclist = g->gray;
g->gray = o;
break;
}
case LUA_TPROTO: {
gco2p(o)->gclist = g->gray;
g->gray = o;
break;
}
default: lua_assert(0);
}
}
static void marktmu (global_State *g) {
GCObject *u = g->tmudata;
if (u) {
do {
u = u->gch.next;
makewhite(g, u); /* may be marked, if left from previous GC */
reallymarkobject(g, u);
} while (u != g->tmudata);
}
}
/* move `dead' udata that need finalization to list `tmudata' */
size_t luaC_separateudata (lua_State *L, int all) {
global_State *g = G(L);
size_t deadmem = 0;
GCObject **p = &g->mainthread->next;
GCObject *curr;
while ((curr = *p) != NULL) {
if (!(iswhite(curr) || all) || isfinalized(gco2u(curr)))
p = &curr->gch.next; /* don't bother with them */
else if (fasttm(L, gco2u(curr)->metatable, TM_GC) == NULL) {
markfinalized(gco2u(curr)); /* don't need finalization */
p = &curr->gch.next;
}
else { /* must call its gc method */
deadmem += sizeudata(gco2u(curr));
markfinalized(gco2u(curr));
*p = curr->gch.next;
/* link `curr' at the end of `tmudata' list */
if (g->tmudata == NULL) /* list is empty? */
g->tmudata = curr->gch.next = curr; /* creates a circular list */
else {
curr->gch.next = g->tmudata->gch.next;
g->tmudata->gch.next = curr;
g->tmudata = curr;
}
}
}
return deadmem;
}
static int traversetable (global_State *g, Table *h) {
int i;
int weakkey = 0;
int weakvalue = 0;
const TValue *mode;
if (h->metatable)
markobject(g, h->metatable);
mode = gfasttm(g, h->metatable, TM_MODE);
if (mode && ttisstring(mode)) { /* is there a weak mode? */
weakkey = (strchr(svalue(mode), 'k') != NULL);
weakvalue = (strchr(svalue(mode), 'v') != NULL);
if (weakkey || weakvalue) { /* is really weak? */
h->marked &= ~(KEYWEAK | VALUEWEAK); /* clear bits */
h->marked |= cast_byte((weakkey << KEYWEAKBIT) |
(weakvalue << VALUEWEAKBIT));
h->gclist = g->weak; /* must be cleared after GC, ... */
g->weak = obj2gco(h); /* ... so put in the appropriate list */
}
}
if (weakkey && weakvalue) return 1;
if (!weakvalue) {
i = h->sizearray;
while (i--)
markvalue(g, &h->array[i]);
}
i = sizenode(h);
while (i--) {
Node *n = gnode(h, i);
lua_assert(ttype(gkey(n)) != LUA_TDEADKEY || ttisnil(gval(n)));
if (ttisnil(gval(n)))
removeentry(n); /* remove empty entries */
else {
lua_assert(!ttisnil(gkey(n)));
if (!weakkey) markvalue(g, gkey(n));
if (!weakvalue) markvalue(g, gval(n));
}
}
return weakkey || weakvalue;
}
/*
** All marks are conditional because a GC may happen while the
** prototype is still being created
*/
static void traverseproto (global_State *g, Proto *f) {
int i;
if (f->source) stringmark(f->source);
for (i=0; i<f->sizek; i++) /* mark literals */
markvalue(g, &f->k[i]);
for (i=0; i<f->sizeupvalues; i++) { /* mark upvalue names */
if (f->upvalues[i])
stringmark(f->upvalues[i]);
}
for (i=0; i<f->sizep; i++) { /* mark nested protos */
if (f->p[i])
markobject(g, f->p[i]);
}
for (i=0; i<f->sizelocvars; i++) { /* mark local-variable names */
if (f->locvars[i].varname)
stringmark(f->locvars[i].varname);
}
}
static void traverseclosure (global_State *g, Closure *cl) {
markobject(g, cl->c.env);
if (cl->c.isC) {
int i;
for (i=0; i<cl->c.nupvalues; i++) /* mark its upvalues */
markvalue(g, &cl->c.upvalue[i]);
}
else {
int i;
lua_assert(cl->l.nupvalues == cl->l.p->nups);
markobject(g, cl->l.p);
for (i=0; i<cl->l.nupvalues; i++) /* mark its upvalues */
markobject(g, cl->l.upvals[i]);
}
}
static void checkstacksizes (lua_State *L, StkId max) {
int ci_used = cast_int(L->ci - L->base_ci); /* number of `ci' in use */
int s_used = cast_int(max - L->stack); /* part of stack in use */
if (L->size_ci > LUAI_MAXCALLS) /* handling overflow? */
return; /* do not touch the stacks */
if (4*ci_used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci)
luaD_reallocCI(L, L->size_ci/2); /* still big enough... */
condhardstacktests(luaD_reallocCI(L, ci_used + 1));
if (4*s_used < L->stacksize &&
2*(BASIC_STACK_SIZE+EXTRA_STACK) < L->stacksize)
luaD_reallocstack(L, L->stacksize/2); /* still big enough... */
condhardstacktests(luaD_reallocstack(L, s_used));
}
static void traversestack (global_State *g, lua_State *l) {
StkId o, lim;
CallInfo *ci;
markvalue(g, gt(l));
lim = l->top;
for (ci = l->base_ci; ci <= l->ci; ci++) {
lua_assert(ci->top <= l->stack_last);
if (lim < ci->top) lim = ci->top;
}
for (o = l->stack; o < l->top; o++)
markvalue(g, o);
for (; o <= lim; o++)
setnilvalue(o);
checkstacksizes(l, lim);
}
/*
** traverse one gray object, turning it to black.
** Returns `quantity' traversed.
*/
static l_mem propagatemark (global_State *g) {
GCObject *o = g->gray;
lua_assert(isgray(o));
gray2black(o);
switch (o->gch.tt) {
case LUA_TTABLE: {
Table *h = gco2h(o);
g->gray = h->gclist;
if (traversetable(g, h)) /* table is weak? */
black2gray(o); /* keep it gray */
return sizeof(Table) + sizeof(TValue) * h->sizearray +
sizeof(Node) * sizenode(h);
}
case LUA_TFUNCTION: {
Closure *cl = gco2cl(o);
g->gray = cl->c.gclist;
traverseclosure(g, cl);
return (cl->c.isC) ? sizeCclosure(cl->c.nupvalues) :
sizeLclosure(cl->l.nupvalues);
}
case LUA_TTHREAD: {
lua_State *th = gco2th(o);
g->gray = th->gclist;
th->gclist = g->grayagain;
g->grayagain = o;
black2gray(o);
traversestack(g, th);
return sizeof(lua_State) + sizeof(TValue) * th->stacksize +
sizeof(CallInfo) * th->size_ci;
}
case LUA_TPROTO: {
Proto *p = gco2p(o);
g->gray = p->gclist;
traverseproto(g, p);
return sizeof(Proto) + sizeof(Instruction) * p->sizecode +
sizeof(Proto *) * p->sizep +
sizeof(TValue) * p->sizek +
sizeof(int) * p->sizelineinfo +
sizeof(LocVar) * p->sizelocvars +
sizeof(TString *) * p->sizeupvalues;
}
default: lua_assert(0); return 0;
}
}
static size_t propagateall (global_State *g) {
size_t m = 0;
while (g->gray) m += propagatemark(g);
return m;
}
/*
** The next function tells whether a key or value can be cleared from
** a weak table. Non-collectable objects are never removed from weak
** tables. Strings behave as `values', so are never removed too. for
** other objects: if really collected, cannot keep them; for userdata
** being finalized, keep them in keys, but not in values
*/
static int iscleared (const TValue *o, int iskey) {
if (!iscollectable(o)) return 0;
if (ttisstring(o)) {
stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */
return 0;
}
return iswhite(gcvalue(o)) ||
(ttisuserdata(o) && (!iskey && isfinalized(uvalue(o))));
}
/*
** clear collected entries from weaktables
*/
static void cleartable (GCObject *l) {
while (l) {
Table *h = gco2h(l);
int i = h->sizearray;
lua_assert(testbit(h->marked, VALUEWEAKBIT) ||
testbit(h->marked, KEYWEAKBIT));
if (testbit(h->marked, VALUEWEAKBIT)) {
while (i--) {
TValue *o = &h->array[i];
if (iscleared(o, 0)) /* value was collected? */
setnilvalue(o); /* remove value */
}
}
i = sizenode(h);
while (i--) {
Node *n = gnode(h, i);
if (!ttisnil(gval(n)) && /* non-empty entry? */
(iscleared(key2tval(n), 1) || iscleared(gval(n), 0))) {
setnilvalue(gval(n)); /* remove value ... */
removeentry(n); /* remove entry from table */
}
}
l = h->gclist;
}
}
static void freeobj (lua_State *L, GCObject *o) {
switch (o->gch.tt) {
case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
case LUA_TFUNCTION: luaF_freeclosure(L, gco2cl(o)); break;
case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break;
case LUA_TTABLE: luaH_free(L, gco2h(o)); break;
case LUA_TTHREAD: {
lua_assert(gco2th(o) != L && gco2th(o) != G(L)->mainthread);
luaE_freethread(L, gco2th(o));
break;
}
case LUA_TSTRING: {
G(L)->strt.nuse--;
luaM_freemem(L, o, sizestring(gco2ts(o)));
break;
}
case LUA_TUSERDATA: {
luaM_freemem(L, o, sizeudata(gco2u(o)));
break;
}
default: lua_assert(0);
}
}
#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
GCObject *curr;
global_State *g = G(L);
int deadmask = otherwhite(g);
while ((curr = *p) != NULL && count-- > 0) {
if (curr->gch.tt == LUA_TTHREAD) /* sweep open upvalues of each thread */
sweepwholelist(L, &gco2th(curr)->openupval);
if ((curr->gch.marked ^ WHITEBITS) & deadmask) { /* not dead? */
lua_assert(!isdead(g, curr) || testbit(curr->gch.marked, FIXEDBIT));
makewhite(g, curr); /* make it white (for next cycle) */
p = &curr->gch.next;
}
else { /* must erase `curr' */
lua_assert(isdead(g, curr) || deadmask == bitmask(SFIXEDBIT));
*p = curr->gch.next;
if (curr == g->rootgc) /* is the first element of the list? */
g->rootgc = curr->gch.next; /* adjust first */
freeobj(L, curr);
}
}
return p;
}
static void checkSizes (lua_State *L) {
global_State *g = G(L);
/* check size of string hash */
if (g->strt.nuse < cast(lu_int32, g->strt.size/4) &&
g->strt.size > MINSTRTABSIZE*2)
luaS_resize(L, g->strt.size/2); /* table is too big */
/* check size of buffer */
if (luaZ_sizebuffer(&g->buff) > LUA_MINBUFFER*2) { /* buffer too big? */
size_t newsize = luaZ_sizebuffer(&g->buff) / 2;
luaZ_resizebuffer(L, &g->buff, newsize);
}
}
static void GCTM (lua_State *L) {
global_State *g = G(L);
GCObject *o = g->tmudata->gch.next; /* get first element */
Udata *udata = rawgco2u(o);
const TValue *tm;
/* remove udata from `tmudata' */
if (o == g->tmudata) /* last element? */
g->tmudata = NULL;
else
g->tmudata->gch.next = udata->uv.next;
udata->uv.next = g->mainthread->next; /* return it to `root' list */
g->mainthread->next = o;
makewhite(g, o);
tm = fasttm(L, udata->uv.metatable, TM_GC);
if (tm != NULL) {
lu_byte oldah = L->allowhook;
lu_mem oldt = g->GCthreshold;
L->allowhook = 0; /* stop debug hooks during GC tag method */
g->GCthreshold = 2*g->totalbytes; /* avoid GC steps */
setobj2s(L, L->top, tm);
setuvalue(L, L->top+1, udata);
L->top += 2;
luaD_call(L, L->top - 2, 0);
L->allowhook = oldah; /* restore hooks */
g->GCthreshold = oldt; /* restore threshold */
}
}
/*
** Call all GC tag methods
*/
void luaC_callGCTM (lua_State *L) {
while (G(L)->tmudata)
GCTM(L);
}
void luaC_freeall (lua_State *L) {
global_State *g = G(L);
int i;
g->currentwhite = WHITEBITS | bitmask(SFIXEDBIT); /* mask to collect all elements */
sweepwholelist(L, &g->rootgc);
for (i = 0; i < g->strt.size; i++) /* free all string lists */
sweepwholelist(L, &g->strt.hash[i]);
}
static void markmt (global_State *g) {
int i;
for (i=0; i<NUM_TAGS; i++)
if (g->mt[i]) markobject(g, g->mt[i]);
}
/* mark root set */
static void markroot (lua_State *L) {
global_State *g = G(L);
g->gray = NULL;
g->grayagain = NULL;
g->weak = NULL;
markobject(g, g->mainthread);
/* make global table be traversed before main stack */
markvalue(g, gt(g->mainthread));
markvalue(g, registry(L));
markmt(g);
g->gcstate = GCSpropagate;
}
static void remarkupvals (global_State *g) {
UpVal *uv;
for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) {
lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
if (isgray(obj2gco(uv)))
markvalue(g, uv->v);
}
}
static void atomic (lua_State *L) {
global_State *g = G(L);
size_t udsize; /* total size of userdata to be finalized */
/* remark occasional upvalues of (maybe) dead threads */
remarkupvals(g);
/* traverse objects cautch by write barrier and by 'remarkupvals' */
propagateall(g);
/* remark weak tables */
g->gray = g->weak;
g->weak = NULL;
lua_assert(!iswhite(obj2gco(g->mainthread)));
markobject(g, L); /* mark running thread */
markmt(g); /* mark basic metatables (again) */
propagateall(g);
/* remark gray again */
g->gray = g->grayagain;
g->grayagain = NULL;
propagateall(g);
udsize = luaC_separateudata(L, 0); /* separate userdata to be finalized */
marktmu(g); /* mark `preserved' userdata */
udsize += propagateall(g); /* remark, to propagate `preserveness' */
cleartable(g->weak); /* remove collected objects from weak tables */
/* flip current white */
g->currentwhite = cast_byte(otherwhite(g));
g->sweepstrgc = 0;
g->sweepgc = &g->rootgc;
g->gcstate = GCSsweepstring;
g->estimate = g->totalbytes - udsize; /* first estimate */
}
static l_mem singlestep (lua_State *L) {
global_State *g = G(L);
/*lua_checkmemory(L);*/
switch (g->gcstate) {
case GCSpause: {
markroot(L); /* start a new collection */
return 0;
}
case GCSpropagate: {
if (g->gray)
return propagatemark(g);
else { /* no more `gray' objects */
atomic(L); /* finish mark phase */
return 0;
}
}
case GCSsweepstring: {
lu_mem old = g->totalbytes;
sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]);
if (g->sweepstrgc >= g->strt.size) /* nothing more to sweep? */
g->gcstate = GCSsweep; /* end sweep-string phase */
lua_assert(old >= g->totalbytes);
g->estimate -= old - g->totalbytes;
return GCSWEEPCOST;
}
case GCSsweep: {
lu_mem old = g->totalbytes;
g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
if (*g->sweepgc == NULL) { /* nothing more to sweep? */
checkSizes(L);
g->gcstate = GCSfinalize; /* end sweep phase */
}
lua_assert(old >= g->totalbytes);
g->estimate -= old - g->totalbytes;
return GCSWEEPMAX*GCSWEEPCOST;
}
case GCSfinalize: {
if (g->tmudata) {
GCTM(L);
if (g->estimate > GCFINALIZECOST)
g->estimate -= GCFINALIZECOST;
return GCFINALIZECOST;
}
else {
g->gcstate = GCSpause; /* end collection */
g->gcdept = 0;
return 0;
}
}
default: lua_assert(0); return 0;
}
}
void luaC_step (lua_State *L) {
global_State *g = G(L);
l_mem lim = (GCSTEPSIZE/100) * g->gcstepmul;
if (lim == 0)
lim = (MAX_LUMEM-1)/2; /* no limit */
g->gcdept += g->totalbytes - g->GCthreshold;
do {
lim -= singlestep(L);
if (g->gcstate == GCSpause)
break;
} while (lim > 0);
if (g->gcstate != GCSpause) {
if (g->gcdept < GCSTEPSIZE)
g->GCthreshold = g->totalbytes + GCSTEPSIZE; /* - lim/g->gcstepmul;*/
else {
g->gcdept -= GCSTEPSIZE;
g->GCthreshold = g->totalbytes;
}
}
else {
setthreshold(g);
}
}
void luaC_fullgc (lua_State *L) {
global_State *g = G(L);
if (g->gcstate <= GCSpropagate) {
/* reset sweep marks to sweep all elements (returning them to white) */
g->sweepstrgc = 0;
g->sweepgc = &g->rootgc;
/* reset other collector lists */
g->gray = NULL;
g->grayagain = NULL;
g->weak = NULL;
g->gcstate = GCSsweepstring;
}
lua_assert(g->gcstate != GCSpause && g->gcstate != GCSpropagate);
/* finish any pending sweep phase */
while (g->gcstate != GCSfinalize) {
lua_assert(g->gcstate == GCSsweepstring || g->gcstate == GCSsweep);
singlestep(L);
}
markroot(L);
while (g->gcstate != GCSpause) {
singlestep(L);
}
setthreshold(g);
}
void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v) {
global_State *g = G(L);
lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
lua_assert(ttype(&o->gch) != LUA_TTABLE);
/* must keep invariant? */
if (g->gcstate == GCSpropagate)
reallymarkobject(g, v); /* restore invariant */
else /* don't mind */
makewhite(g, o); /* mark as white just to avoid other barriers */
}
void luaC_barrierback (lua_State *L, Table *t) {
global_State *g = G(L);
GCObject *o = obj2gco(t);
lua_assert(isblack(o) && !isdead(g, o));
lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
black2gray(o); /* make table gray (again) */
t->gclist = g->grayagain;
g->grayagain = o;
}
void luaC_link (lua_State *L, GCObject *o, lu_byte tt) {
global_State *g = G(L);
o->gch.next = g->rootgc;
g->rootgc = o;
o->gch.marked = luaC_white(g);
o->gch.tt = tt;
}
void luaC_linkupval (lua_State *L, UpVal *uv) {
global_State *g = G(L);
GCObject *o = obj2gco(uv);
o->gch.next = g->rootgc; /* link upvalue into `rootgc' list */
g->rootgc = o;
if (isgray(o)) {
if (g->gcstate == GCSpropagate) {
gray2black(o); /* closed upvalues need barrier */
luaC_barrier(L, uv, uv->v);
}
else { /* sweep phase: sweep it (turning it into white) */
makewhite(g, o);
lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
}
}
}
| xLua/build/lua-5.1.5/src/lgc.c/0 | {
"file_path": "xLua/build/lua-5.1.5/src/lgc.c",
"repo_id": "xLua",
"token_count": 9245
} | 1,885 |
/*
** $Id: lparser.c,v 2.42.1.4 2011/10/21 19:31:42 roberto Exp $
** Lua Parser
** See Copyright Notice in lua.h
*/
#include <string.h>
#define lparser_c
#define LUA_CORE
#include "lua.h"
#include "lcode.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "llex.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
#define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]])
#define luaY_checklimit(fs,v,l,m) if ((v)>(l)) errorlimit(fs,l,m)
/*
** nodes for block list (list of active blocks)
*/
typedef struct BlockCnt {
struct BlockCnt *previous; /* chain */
int breaklist; /* list of jumps out of this loop */
lu_byte nactvar; /* # active locals outside the breakable structure */
lu_byte upval; /* true if some variable in the block is an upvalue */
lu_byte isbreakable; /* true if `block' is a loop */
} BlockCnt;
/*
** prototypes for recursive non-terminal functions
*/
static void chunk (LexState *ls);
static void expr (LexState *ls, expdesc *v);
static void anchor_token (LexState *ls) {
if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
TString *ts = ls->t.seminfo.ts;
luaX_newstring(ls, getstr(ts), ts->tsv.len);
}
}
static void error_expected (LexState *ls, int token) {
luaX_syntaxerror(ls,
luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token)));
}
static void errorlimit (FuncState *fs, int limit, const char *what) {
const char *msg = (fs->f->linedefined == 0) ?
luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) :
luaO_pushfstring(fs->L, "function at line %d has more than %d %s",
fs->f->linedefined, limit, what);
luaX_lexerror(fs->ls, msg, 0);
}
static int testnext (LexState *ls, int c) {
if (ls->t.token == c) {
luaX_next(ls);
return 1;
}
else return 0;
}
static void check (LexState *ls, int c) {
if (ls->t.token != c)
error_expected(ls, c);
}
static void checknext (LexState *ls, int c) {
check(ls, c);
luaX_next(ls);
}
#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
static void check_match (LexState *ls, int what, int who, int where) {
if (!testnext(ls, what)) {
if (where == ls->linenumber)
error_expected(ls, what);
else {
luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
LUA_QS " expected (to close " LUA_QS " at line %d)",
luaX_token2str(ls, what), luaX_token2str(ls, who), where));
}
}
}
static TString *str_checkname (LexState *ls) {
TString *ts;
check(ls, TK_NAME);
ts = ls->t.seminfo.ts;
luaX_next(ls);
return ts;
}
static void init_exp (expdesc *e, expkind k, int i) {
e->f = e->t = NO_JUMP;
e->k = k;
e->u.s.info = i;
}
static void codestring (LexState *ls, expdesc *e, TString *s) {
init_exp(e, VK, luaK_stringK(ls->fs, s));
}
static void checkname(LexState *ls, expdesc *e) {
codestring(ls, e, str_checkname(ls));
}
static int registerlocalvar (LexState *ls, TString *varname) {
FuncState *fs = ls->fs;
Proto *f = fs->f;
int oldsize = f->sizelocvars;
luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
LocVar, SHRT_MAX, "too many local variables");
while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
f->locvars[fs->nlocvars].varname = varname;
luaC_objbarrier(ls->L, f, varname);
return fs->nlocvars++;
}
#define new_localvarliteral(ls,v,n) \
new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n)
static void new_localvar (LexState *ls, TString *name, int n) {
FuncState *fs = ls->fs;
luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables");
fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name));
}
static void adjustlocalvars (LexState *ls, int nvars) {
FuncState *fs = ls->fs;
fs->nactvar = cast_byte(fs->nactvar + nvars);
for (; nvars; nvars--) {
getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc;
}
}
static void removevars (LexState *ls, int tolevel) {
FuncState *fs = ls->fs;
while (fs->nactvar > tolevel)
getlocvar(fs, --fs->nactvar).endpc = fs->pc;
}
static int indexupvalue (FuncState *fs, TString *name, expdesc *v) {
int i;
Proto *f = fs->f;
int oldsize = f->sizeupvalues;
for (i=0; i<f->nups; i++) {
if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) {
lua_assert(f->upvalues[i] == name);
return i;
}
}
/* new one */
luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues");
luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues,
TString *, MAX_INT, "");
while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL;
f->upvalues[f->nups] = name;
luaC_objbarrier(fs->L, f, name);
lua_assert(v->k == VLOCAL || v->k == VUPVAL);
fs->upvalues[f->nups].k = cast_byte(v->k);
fs->upvalues[f->nups].info = cast_byte(v->u.s.info);
return f->nups++;
}
static int searchvar (FuncState *fs, TString *n) {
int i;
for (i=fs->nactvar-1; i >= 0; i--) {
if (n == getlocvar(fs, i).varname)
return i;
}
return -1; /* not found */
}
static void markupval (FuncState *fs, int level) {
BlockCnt *bl = fs->bl;
while (bl && bl->nactvar > level) bl = bl->previous;
if (bl) bl->upval = 1;
}
static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
if (fs == NULL) { /* no more levels? */
init_exp(var, VGLOBAL, NO_REG); /* default is global variable */
return VGLOBAL;
}
else {
int v = searchvar(fs, n); /* look up at current level */
if (v >= 0) {
init_exp(var, VLOCAL, v);
if (!base)
markupval(fs, v); /* local will be used as an upval */
return VLOCAL;
}
else { /* not found at current level; try upper one */
if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL)
return VGLOBAL;
var->u.s.info = indexupvalue(fs, n, var); /* else was LOCAL or UPVAL */
var->k = VUPVAL; /* upvalue in this level */
return VUPVAL;
}
}
}
static void singlevar (LexState *ls, expdesc *var) {
TString *varname = str_checkname(ls);
FuncState *fs = ls->fs;
if (singlevaraux(fs, varname, var, 1) == VGLOBAL)
var->u.s.info = luaK_stringK(fs, varname); /* info points to global name */
}
static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
FuncState *fs = ls->fs;
int extra = nvars - nexps;
if (hasmultret(e->k)) {
extra++; /* includes call itself */
if (extra < 0) extra = 0;
luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
if (extra > 1) luaK_reserveregs(fs, extra-1);
}
else {
if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */
if (extra > 0) {
int reg = fs->freereg;
luaK_reserveregs(fs, extra);
luaK_nil(fs, reg, extra);
}
}
}
static void enterlevel (LexState *ls) {
if (++ls->L->nCcalls > LUAI_MAXCCALLS)
luaX_lexerror(ls, "chunk has too many syntax levels", 0);
}
#define leavelevel(ls) ((ls)->L->nCcalls--)
static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {
bl->breaklist = NO_JUMP;
bl->isbreakable = isbreakable;
bl->nactvar = fs->nactvar;
bl->upval = 0;
bl->previous = fs->bl;
fs->bl = bl;
lua_assert(fs->freereg == fs->nactvar);
}
static void leaveblock (FuncState *fs) {
BlockCnt *bl = fs->bl;
fs->bl = bl->previous;
removevars(fs->ls, bl->nactvar);
if (bl->upval)
luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
/* a block either controls scope or breaks (never both) */
lua_assert(!bl->isbreakable || !bl->upval);
lua_assert(bl->nactvar == fs->nactvar);
fs->freereg = fs->nactvar; /* free registers */
luaK_patchtohere(fs, bl->breaklist);
}
static void pushclosure (LexState *ls, FuncState *func, expdesc *v) {
FuncState *fs = ls->fs;
Proto *f = fs->f;
int oldsize = f->sizep;
int i;
luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
MAXARG_Bx, "constant table overflow");
while (oldsize < f->sizep) f->p[oldsize++] = NULL;
f->p[fs->np++] = func->f;
luaC_objbarrier(ls->L, f, func->f);
init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
for (i=0; i<func->f->nups; i++) {
OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0);
}
}
static void open_func (LexState *ls, FuncState *fs) {
lua_State *L = ls->L;
Proto *f = luaF_newproto(L);
fs->f = f;
fs->prev = ls->fs; /* linked list of funcstates */
fs->ls = ls;
fs->L = L;
ls->fs = fs;
fs->pc = 0;
fs->lasttarget = -1;
fs->jpc = NO_JUMP;
fs->freereg = 0;
fs->nk = 0;
fs->np = 0;
fs->nlocvars = 0;
fs->nactvar = 0;
fs->bl = NULL;
f->source = ls->source;
f->maxstacksize = 2; /* registers 0/1 are always valid */
fs->h = luaH_new(L, 0, 0);
/* anchor table of constants and prototype (to avoid being collected) */
sethvalue2s(L, L->top, fs->h);
incr_top(L);
setptvalue2s(L, L->top, f);
incr_top(L);
}
static void close_func (LexState *ls) {
lua_State *L = ls->L;
FuncState *fs = ls->fs;
Proto *f = fs->f;
removevars(ls, 0);
luaK_ret(fs, 0, 0); /* final return */
luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
f->sizecode = fs->pc;
luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
f->sizelineinfo = fs->pc;
luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
f->sizek = fs->nk;
luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
f->sizep = fs->np;
luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
f->sizelocvars = fs->nlocvars;
luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *);
f->sizeupvalues = f->nups;
lua_assert(luaG_checkcode(f));
lua_assert(fs->bl == NULL);
ls->fs = fs->prev;
/* last token read was anchored in defunct function; must reanchor it */
if (fs) anchor_token(ls);
L->top -= 2; /* remove table and prototype from the stack */
}
Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
struct LexState lexstate;
struct FuncState funcstate;
lexstate.buff = buff;
luaX_setinput(L, &lexstate, z, luaS_new(L, name));
open_func(&lexstate, &funcstate);
funcstate.f->is_vararg = VARARG_ISVARARG; /* main func. is always vararg */
luaX_next(&lexstate); /* read first token */
chunk(&lexstate);
check(&lexstate, TK_EOS);
close_func(&lexstate);
lua_assert(funcstate.prev == NULL);
lua_assert(funcstate.f->nups == 0);
lua_assert(lexstate.fs == NULL);
return funcstate.f;
}
/*============================================================*/
/* GRAMMAR RULES */
/*============================================================*/
static void field (LexState *ls, expdesc *v) {
/* field -> ['.' | ':'] NAME */
FuncState *fs = ls->fs;
expdesc key;
luaK_exp2anyreg(fs, v);
luaX_next(ls); /* skip the dot or colon */
checkname(ls, &key);
luaK_indexed(fs, v, &key);
}
static void yindex (LexState *ls, expdesc *v) {
/* index -> '[' expr ']' */
luaX_next(ls); /* skip the '[' */
expr(ls, v);
luaK_exp2val(ls->fs, v);
checknext(ls, ']');
}
/*
** {======================================================================
** Rules for Constructors
** =======================================================================
*/
struct ConsControl {
expdesc v; /* last list item read */
expdesc *t; /* table descriptor */
int nh; /* total number of `record' elements */
int na; /* total number of array elements */
int tostore; /* number of array elements pending to be stored */
};
static void recfield (LexState *ls, struct ConsControl *cc) {
/* recfield -> (NAME | `['exp1`]') = exp1 */
FuncState *fs = ls->fs;
int reg = ls->fs->freereg;
expdesc key, val;
int rkkey;
if (ls->t.token == TK_NAME) {
luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
checkname(ls, &key);
}
else /* ls->t.token == '[' */
yindex(ls, &key);
cc->nh++;
checknext(ls, '=');
rkkey = luaK_exp2RK(fs, &key);
expr(ls, &val);
luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val));
fs->freereg = reg; /* free registers */
}
static void closelistfield (FuncState *fs, struct ConsControl *cc) {
if (cc->v.k == VVOID) return; /* there is no list item */
luaK_exp2nextreg(fs, &cc->v);
cc->v.k = VVOID;
if (cc->tostore == LFIELDS_PER_FLUSH) {
luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); /* flush */
cc->tostore = 0; /* no more items pending */
}
}
static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
if (cc->tostore == 0) return;
if (hasmultret(cc->v.k)) {
luaK_setmultret(fs, &cc->v);
luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET);
cc->na--; /* do not count last expression (unknown number of elements) */
}
else {
if (cc->v.k != VVOID)
luaK_exp2nextreg(fs, &cc->v);
luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);
}
}
static void listfield (LexState *ls, struct ConsControl *cc) {
expr(ls, &cc->v);
luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
cc->na++;
cc->tostore++;
}
static void constructor (LexState *ls, expdesc *t) {
/* constructor -> ?? */
FuncState *fs = ls->fs;
int line = ls->linenumber;
int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
struct ConsControl cc;
cc.na = cc.nh = cc.tostore = 0;
cc.t = t;
init_exp(t, VRELOCABLE, pc);
init_exp(&cc.v, VVOID, 0); /* no value (yet) */
luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */
checknext(ls, '{');
do {
lua_assert(cc.v.k == VVOID || cc.tostore > 0);
if (ls->t.token == '}') break;
closelistfield(fs, &cc);
switch(ls->t.token) {
case TK_NAME: { /* may be listfields or recfields */
luaX_lookahead(ls);
if (ls->lookahead.token != '=') /* expression? */
listfield(ls, &cc);
else
recfield(ls, &cc);
break;
}
case '[': { /* constructor_item -> recfield */
recfield(ls, &cc);
break;
}
default: { /* constructor_part -> listfield */
listfield(ls, &cc);
break;
}
}
} while (testnext(ls, ',') || testnext(ls, ';'));
check_match(ls, '}', '{', line);
lastlistfield(fs, &cc);
SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
}
/* }====================================================================== */
static void parlist (LexState *ls) {
/* parlist -> [ param { `,' param } ] */
FuncState *fs = ls->fs;
Proto *f = fs->f;
int nparams = 0;
f->is_vararg = 0;
if (ls->t.token != ')') { /* is `parlist' not empty? */
do {
switch (ls->t.token) {
case TK_NAME: { /* param -> NAME */
new_localvar(ls, str_checkname(ls), nparams++);
break;
}
case TK_DOTS: { /* param -> `...' */
luaX_next(ls);
#if defined(LUA_COMPAT_VARARG)
/* use `arg' as default name */
new_localvarliteral(ls, "arg", nparams++);
f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG;
#endif
f->is_vararg |= VARARG_ISVARARG;
break;
}
default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
}
} while (!f->is_vararg && testnext(ls, ','));
}
adjustlocalvars(ls, nparams);
f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG));
luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
}
static void body (LexState *ls, expdesc *e, int needself, int line) {
/* body -> `(' parlist `)' chunk END */
FuncState new_fs;
open_func(ls, &new_fs);
new_fs.f->linedefined = line;
checknext(ls, '(');
if (needself) {
new_localvarliteral(ls, "self", 0);
adjustlocalvars(ls, 1);
}
parlist(ls);
checknext(ls, ')');
chunk(ls);
new_fs.f->lastlinedefined = ls->linenumber;
check_match(ls, TK_END, TK_FUNCTION, line);
close_func(ls);
pushclosure(ls, &new_fs, e);
}
static int explist1 (LexState *ls, expdesc *v) {
/* explist1 -> expr { `,' expr } */
int n = 1; /* at least one expression */
expr(ls, v);
while (testnext(ls, ',')) {
luaK_exp2nextreg(ls->fs, v);
expr(ls, v);
n++;
}
return n;
}
static void funcargs (LexState *ls, expdesc *f) {
FuncState *fs = ls->fs;
expdesc args;
int base, nparams;
int line = ls->linenumber;
switch (ls->t.token) {
case '(': { /* funcargs -> `(' [ explist1 ] `)' */
if (line != ls->lastline)
luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
luaX_next(ls);
if (ls->t.token == ')') /* arg list is empty? */
args.k = VVOID;
else {
explist1(ls, &args);
luaK_setmultret(fs, &args);
}
check_match(ls, ')', '(', line);
break;
}
case '{': { /* funcargs -> constructor */
constructor(ls, &args);
break;
}
case TK_STRING: { /* funcargs -> STRING */
codestring(ls, &args, ls->t.seminfo.ts);
luaX_next(ls); /* must use `seminfo' before `next' */
break;
}
default: {
luaX_syntaxerror(ls, "function arguments expected");
return;
}
}
lua_assert(f->k == VNONRELOC);
base = f->u.s.info; /* base register for call */
if (hasmultret(args.k))
nparams = LUA_MULTRET; /* open call */
else {
if (args.k != VVOID)
luaK_exp2nextreg(fs, &args); /* close last argument */
nparams = fs->freereg - (base+1);
}
init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
luaK_fixline(fs, line);
fs->freereg = base+1; /* call remove function and arguments and leaves
(unless changed) one result */
}
/*
** {======================================================================
** Expression parsing
** =======================================================================
*/
static void prefixexp (LexState *ls, expdesc *v) {
/* prefixexp -> NAME | '(' expr ')' */
switch (ls->t.token) {
case '(': {
int line = ls->linenumber;
luaX_next(ls);
expr(ls, v);
check_match(ls, ')', '(', line);
luaK_dischargevars(ls->fs, v);
return;
}
case TK_NAME: {
singlevar(ls, v);
return;
}
default: {
luaX_syntaxerror(ls, "unexpected symbol");
return;
}
}
}
static void primaryexp (LexState *ls, expdesc *v) {
/* primaryexp ->
prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
FuncState *fs = ls->fs;
prefixexp(ls, v);
for (;;) {
switch (ls->t.token) {
case '.': { /* field */
field(ls, v);
break;
}
case '[': { /* `[' exp1 `]' */
expdesc key;
luaK_exp2anyreg(fs, v);
yindex(ls, &key);
luaK_indexed(fs, v, &key);
break;
}
case ':': { /* `:' NAME funcargs */
expdesc key;
luaX_next(ls);
checkname(ls, &key);
luaK_self(fs, v, &key);
funcargs(ls, v);
break;
}
case '(': case TK_STRING: case '{': { /* funcargs */
luaK_exp2nextreg(fs, v);
funcargs(ls, v);
break;
}
default: return;
}
}
}
static void simpleexp (LexState *ls, expdesc *v) {
/* simpleexp -> NUMBER | STRING | NIL | true | false | ... |
constructor | FUNCTION body | primaryexp */
switch (ls->t.token) {
case TK_NUMBER: {
init_exp(v, VKNUM, 0);
v->u.nval = ls->t.seminfo.r;
break;
}
case TK_STRING: {
codestring(ls, v, ls->t.seminfo.ts);
break;
}
case TK_NIL: {
init_exp(v, VNIL, 0);
break;
}
case TK_TRUE: {
init_exp(v, VTRUE, 0);
break;
}
case TK_FALSE: {
init_exp(v, VFALSE, 0);
break;
}
case TK_DOTS: { /* vararg */
FuncState *fs = ls->fs;
check_condition(ls, fs->f->is_vararg,
"cannot use " LUA_QL("...") " outside a vararg function");
fs->f->is_vararg &= ~VARARG_NEEDSARG; /* don't need 'arg' */
init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
break;
}
case '{': { /* constructor */
constructor(ls, v);
return;
}
case TK_FUNCTION: {
luaX_next(ls);
body(ls, v, 0, ls->linenumber);
return;
}
default: {
primaryexp(ls, v);
return;
}
}
luaX_next(ls);
}
static UnOpr getunopr (int op) {
switch (op) {
case TK_NOT: return OPR_NOT;
case '-': return OPR_MINUS;
case '#': return OPR_LEN;
default: return OPR_NOUNOPR;
}
}
static BinOpr getbinopr (int op) {
switch (op) {
case '+': return OPR_ADD;
case '-': return OPR_SUB;
case '*': return OPR_MUL;
case '/': return OPR_DIV;
case '%': return OPR_MOD;
case '^': return OPR_POW;
case TK_CONCAT: return OPR_CONCAT;
case TK_NE: return OPR_NE;
case TK_EQ: return OPR_EQ;
case '<': return OPR_LT;
case TK_LE: return OPR_LE;
case '>': return OPR_GT;
case TK_GE: return OPR_GE;
case TK_AND: return OPR_AND;
case TK_OR: return OPR_OR;
default: return OPR_NOBINOPR;
}
}
static const struct {
lu_byte left; /* left priority for each binary operator */
lu_byte right; /* right priority */
} priority[] = { /* ORDER OPR */
{6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */
{10, 9}, {5, 4}, /* power and concat (right associative) */
{3, 3}, {3, 3}, /* equality and inequality */
{3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */
{2, 2}, {1, 1} /* logical (and/or) */
};
#define UNARY_PRIORITY 8 /* priority for unary operators */
/*
** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
** where `binop' is any binary operator with a priority higher than `limit'
*/
static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
BinOpr op;
UnOpr uop;
enterlevel(ls);
uop = getunopr(ls->t.token);
if (uop != OPR_NOUNOPR) {
luaX_next(ls);
subexpr(ls, v, UNARY_PRIORITY);
luaK_prefix(ls->fs, uop, v);
}
else simpleexp(ls, v);
/* expand while operators have priorities higher than `limit' */
op = getbinopr(ls->t.token);
while (op != OPR_NOBINOPR && priority[op].left > limit) {
expdesc v2;
BinOpr nextop;
luaX_next(ls);
luaK_infix(ls->fs, op, v);
/* read sub-expression with higher priority */
nextop = subexpr(ls, &v2, priority[op].right);
luaK_posfix(ls->fs, op, v, &v2);
op = nextop;
}
leavelevel(ls);
return op; /* return first untreated operator */
}
static void expr (LexState *ls, expdesc *v) {
subexpr(ls, v, 0);
}
/* }==================================================================== */
/*
** {======================================================================
** Rules for Statements
** =======================================================================
*/
static int block_follow (int token) {
switch (token) {
case TK_ELSE: case TK_ELSEIF: case TK_END:
case TK_UNTIL: case TK_EOS:
return 1;
default: return 0;
}
}
static void block (LexState *ls) {
/* block -> chunk */
FuncState *fs = ls->fs;
BlockCnt bl;
enterblock(fs, &bl, 0);
chunk(ls);
lua_assert(bl.breaklist == NO_JUMP);
leaveblock(fs);
}
/*
** structure to chain all variables in the left-hand side of an
** assignment
*/
struct LHS_assign {
struct LHS_assign *prev;
expdesc v; /* variable (global, local, upvalue, or indexed) */
};
/*
** check whether, in an assignment to a local variable, the local variable
** is needed in a previous assignment (to a table). If so, save original
** local value in a safe place and use this safe copy in the previous
** assignment.
*/
static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
FuncState *fs = ls->fs;
int extra = fs->freereg; /* eventual position to save local variable */
int conflict = 0;
for (; lh; lh = lh->prev) {
if (lh->v.k == VINDEXED) {
if (lh->v.u.s.info == v->u.s.info) { /* conflict? */
conflict = 1;
lh->v.u.s.info = extra; /* previous assignment will use safe copy */
}
if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */
conflict = 1;
lh->v.u.s.aux = extra; /* previous assignment will use safe copy */
}
}
}
if (conflict) {
luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */
luaK_reserveregs(fs, 1);
}
}
static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
expdesc e;
check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
"syntax error");
if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
struct LHS_assign nv;
nv.prev = lh;
primaryexp(ls, &nv.v);
if (nv.v.k == VLOCAL)
check_conflict(ls, lh, &nv.v);
luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls,
"variables in assignment");
assignment(ls, &nv, nvars+1);
}
else { /* assignment -> `=' explist1 */
int nexps;
checknext(ls, '=');
nexps = explist1(ls, &e);
if (nexps != nvars) {
adjust_assign(ls, nvars, nexps, &e);
if (nexps > nvars)
ls->fs->freereg -= nexps - nvars; /* remove extra values */
}
else {
luaK_setoneret(ls->fs, &e); /* close last expression */
luaK_storevar(ls->fs, &lh->v, &e);
return; /* avoid default */
}
}
init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
luaK_storevar(ls->fs, &lh->v, &e);
}
static int cond (LexState *ls) {
/* cond -> exp */
expdesc v;
expr(ls, &v); /* read condition */
if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
luaK_goiftrue(ls->fs, &v);
return v.f;
}
static void breakstat (LexState *ls) {
FuncState *fs = ls->fs;
BlockCnt *bl = fs->bl;
int upval = 0;
while (bl && !bl->isbreakable) {
upval |= bl->upval;
bl = bl->previous;
}
if (!bl)
luaX_syntaxerror(ls, "no loop to break");
if (upval)
luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
}
static void whilestat (LexState *ls, int line) {
/* whilestat -> WHILE cond DO block END */
FuncState *fs = ls->fs;
int whileinit;
int condexit;
BlockCnt bl;
luaX_next(ls); /* skip WHILE */
whileinit = luaK_getlabel(fs);
condexit = cond(ls);
enterblock(fs, &bl, 1);
checknext(ls, TK_DO);
block(ls);
luaK_patchlist(fs, luaK_jump(fs), whileinit);
check_match(ls, TK_END, TK_WHILE, line);
leaveblock(fs);
luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
}
static void repeatstat (LexState *ls, int line) {
/* repeatstat -> REPEAT block UNTIL cond */
int condexit;
FuncState *fs = ls->fs;
int repeat_init = luaK_getlabel(fs);
BlockCnt bl1, bl2;
enterblock(fs, &bl1, 1); /* loop block */
enterblock(fs, &bl2, 0); /* scope block */
luaX_next(ls); /* skip REPEAT */
chunk(ls);
check_match(ls, TK_UNTIL, TK_REPEAT, line);
condexit = cond(ls); /* read condition (inside scope block) */
if (!bl2.upval) { /* no upvalues? */
leaveblock(fs); /* finish scope */
luaK_patchlist(ls->fs, condexit, repeat_init); /* close the loop */
}
else { /* complete semantics when there are upvalues */
breakstat(ls); /* if condition then break */
luaK_patchtohere(ls->fs, condexit); /* else... */
leaveblock(fs); /* finish scope... */
luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init); /* and repeat */
}
leaveblock(fs); /* finish loop */
}
static int exp1 (LexState *ls) {
expdesc e;
int k;
expr(ls, &e);
k = e.k;
luaK_exp2nextreg(ls->fs, &e);
return k;
}
static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
/* forbody -> DO block */
BlockCnt bl;
FuncState *fs = ls->fs;
int prep, endfor;
adjustlocalvars(ls, 3); /* control variables */
checknext(ls, TK_DO);
prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
enterblock(fs, &bl, 0); /* scope for declared variables */
adjustlocalvars(ls, nvars);
luaK_reserveregs(fs, nvars);
block(ls);
leaveblock(fs); /* end of scope for declared variables */
luaK_patchtohere(fs, prep);
endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) :
luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars);
luaK_fixline(fs, line); /* pretend that `OP_FOR' starts the loop */
luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1);
}
static void fornum (LexState *ls, TString *varname, int line) {
/* fornum -> NAME = exp1,exp1[,exp1] forbody */
FuncState *fs = ls->fs;
int base = fs->freereg;
new_localvarliteral(ls, "(for index)", 0);
new_localvarliteral(ls, "(for limit)", 1);
new_localvarliteral(ls, "(for step)", 2);
new_localvar(ls, varname, 3);
checknext(ls, '=');
exp1(ls); /* initial value */
checknext(ls, ',');
exp1(ls); /* limit */
if (testnext(ls, ','))
exp1(ls); /* optional step */
else { /* default step = 1 */
luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
luaK_reserveregs(fs, 1);
}
forbody(ls, base, line, 1, 1);
}
static void forlist (LexState *ls, TString *indexname) {
/* forlist -> NAME {,NAME} IN explist1 forbody */
FuncState *fs = ls->fs;
expdesc e;
int nvars = 0;
int line;
int base = fs->freereg;
/* create control variables */
new_localvarliteral(ls, "(for generator)", nvars++);
new_localvarliteral(ls, "(for state)", nvars++);
new_localvarliteral(ls, "(for control)", nvars++);
/* create declared variables */
new_localvar(ls, indexname, nvars++);
while (testnext(ls, ','))
new_localvar(ls, str_checkname(ls), nvars++);
checknext(ls, TK_IN);
line = ls->linenumber;
adjust_assign(ls, 3, explist1(ls, &e), &e);
luaK_checkstack(fs, 3); /* extra space to call generator */
forbody(ls, base, line, nvars - 3, 0);
}
static void forstat (LexState *ls, int line) {
/* forstat -> FOR (fornum | forlist) END */
FuncState *fs = ls->fs;
TString *varname;
BlockCnt bl;
enterblock(fs, &bl, 1); /* scope for loop and control variables */
luaX_next(ls); /* skip `for' */
varname = str_checkname(ls); /* first variable name */
switch (ls->t.token) {
case '=': fornum(ls, varname, line); break;
case ',': case TK_IN: forlist(ls, varname); break;
default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
}
check_match(ls, TK_END, TK_FOR, line);
leaveblock(fs); /* loop scope (`break' jumps to this point) */
}
static int test_then_block (LexState *ls) {
/* test_then_block -> [IF | ELSEIF] cond THEN block */
int condexit;
luaX_next(ls); /* skip IF or ELSEIF */
condexit = cond(ls);
checknext(ls, TK_THEN);
block(ls); /* `then' part */
return condexit;
}
static void ifstat (LexState *ls, int line) {
/* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
FuncState *fs = ls->fs;
int flist;
int escapelist = NO_JUMP;
flist = test_then_block(ls); /* IF cond THEN block */
while (ls->t.token == TK_ELSEIF) {
luaK_concat(fs, &escapelist, luaK_jump(fs));
luaK_patchtohere(fs, flist);
flist = test_then_block(ls); /* ELSEIF cond THEN block */
}
if (ls->t.token == TK_ELSE) {
luaK_concat(fs, &escapelist, luaK_jump(fs));
luaK_patchtohere(fs, flist);
luaX_next(ls); /* skip ELSE (after patch, for correct line info) */
block(ls); /* `else' part */
}
else
luaK_concat(fs, &escapelist, flist);
luaK_patchtohere(fs, escapelist);
check_match(ls, TK_END, TK_IF, line);
}
static void localfunc (LexState *ls) {
expdesc v, b;
FuncState *fs = ls->fs;
new_localvar(ls, str_checkname(ls), 0);
init_exp(&v, VLOCAL, fs->freereg);
luaK_reserveregs(fs, 1);
adjustlocalvars(ls, 1);
body(ls, &b, 0, ls->linenumber);
luaK_storevar(fs, &v, &b);
/* debug information will only see the variable after this point! */
getlocvar(fs, fs->nactvar - 1).startpc = fs->pc;
}
static void localstat (LexState *ls) {
/* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
int nvars = 0;
int nexps;
expdesc e;
do {
new_localvar(ls, str_checkname(ls), nvars++);
} while (testnext(ls, ','));
if (testnext(ls, '='))
nexps = explist1(ls, &e);
else {
e.k = VVOID;
nexps = 0;
}
adjust_assign(ls, nvars, nexps, &e);
adjustlocalvars(ls, nvars);
}
static int funcname (LexState *ls, expdesc *v) {
/* funcname -> NAME {field} [`:' NAME] */
int needself = 0;
singlevar(ls, v);
while (ls->t.token == '.')
field(ls, v);
if (ls->t.token == ':') {
needself = 1;
field(ls, v);
}
return needself;
}
static void funcstat (LexState *ls, int line) {
/* funcstat -> FUNCTION funcname body */
int needself;
expdesc v, b;
luaX_next(ls); /* skip FUNCTION */
needself = funcname(ls, &v);
body(ls, &b, needself, line);
luaK_storevar(ls->fs, &v, &b);
luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
}
static void exprstat (LexState *ls) {
/* stat -> func | assignment */
FuncState *fs = ls->fs;
struct LHS_assign v;
primaryexp(ls, &v.v);
if (v.v.k == VCALL) /* stat -> func */
SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
else { /* stat -> assignment */
v.prev = NULL;
assignment(ls, &v, 1);
}
}
static void retstat (LexState *ls) {
/* stat -> RETURN explist */
FuncState *fs = ls->fs;
expdesc e;
int first, nret; /* registers with returned values */
luaX_next(ls); /* skip RETURN */
if (block_follow(ls->t.token) || ls->t.token == ';')
first = nret = 0; /* return no values */
else {
nret = explist1(ls, &e); /* optional return values */
if (hasmultret(e.k)) {
luaK_setmultret(fs, &e);
if (e.k == VCALL && nret == 1) { /* tail call? */
SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
}
first = fs->nactvar;
nret = LUA_MULTRET; /* return all values */
}
else {
if (nret == 1) /* only one single value? */
first = luaK_exp2anyreg(fs, &e);
else {
luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
first = fs->nactvar; /* return all `active' values */
lua_assert(nret == fs->freereg - first);
}
}
}
luaK_ret(fs, first, nret);
}
static int statement (LexState *ls) {
int line = ls->linenumber; /* may be needed for error messages */
switch (ls->t.token) {
case TK_IF: { /* stat -> ifstat */
ifstat(ls, line);
return 0;
}
case TK_WHILE: { /* stat -> whilestat */
whilestat(ls, line);
return 0;
}
case TK_DO: { /* stat -> DO block END */
luaX_next(ls); /* skip DO */
block(ls);
check_match(ls, TK_END, TK_DO, line);
return 0;
}
case TK_FOR: { /* stat -> forstat */
forstat(ls, line);
return 0;
}
case TK_REPEAT: { /* stat -> repeatstat */
repeatstat(ls, line);
return 0;
}
case TK_FUNCTION: {
funcstat(ls, line); /* stat -> funcstat */
return 0;
}
case TK_LOCAL: { /* stat -> localstat */
luaX_next(ls); /* skip LOCAL */
if (testnext(ls, TK_FUNCTION)) /* local function? */
localfunc(ls);
else
localstat(ls);
return 0;
}
case TK_RETURN: { /* stat -> retstat */
retstat(ls);
return 1; /* must be last statement */
}
case TK_BREAK: { /* stat -> breakstat */
luaX_next(ls); /* skip BREAK */
breakstat(ls);
return 1; /* must be last statement */
}
default: {
exprstat(ls);
return 0; /* to avoid warnings */
}
}
}
static void chunk (LexState *ls) {
/* chunk -> { stat [`;'] } */
int islast = 0;
enterlevel(ls);
while (!islast && !block_follow(ls->t.token)) {
islast = statement(ls);
testnext(ls, ';');
lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
ls->fs->freereg >= ls->fs->nactvar);
ls->fs->freereg = ls->fs->nactvar; /* free registers */
}
leavelevel(ls);
}
/* }====================================================================== */
| xLua/build/lua-5.1.5/src/lparser.c/0 | {
"file_path": "xLua/build/lua-5.1.5/src/lparser.c",
"repo_id": "xLua",
"token_count": 16150
} | 1,886 |
/*
** $Id: lualib.h,v 1.36.1.1 2007/12/27 13:02:25 roberto Exp $
** Lua standard libraries
** See Copyright Notice in lua.h
*/
#ifndef lualib_h
#define lualib_h
#include "lua.h"
/* Key to file-handle type */
#define LUA_FILEHANDLE "FILE*"
#define LUA_COLIBNAME "coroutine"
LUALIB_API int (luaopen_base) (lua_State *L);
#define LUA_TABLIBNAME "table"
LUALIB_API int (luaopen_table) (lua_State *L);
#define LUA_IOLIBNAME "io"
LUALIB_API int (luaopen_io) (lua_State *L);
#define LUA_OSLIBNAME "os"
LUALIB_API int (luaopen_os) (lua_State *L);
#define LUA_STRLIBNAME "string"
LUALIB_API int (luaopen_string) (lua_State *L);
#define LUA_MATHLIBNAME "math"
LUALIB_API int (luaopen_math) (lua_State *L);
#define LUA_DBLIBNAME "debug"
LUALIB_API int (luaopen_debug) (lua_State *L);
#define LUA_LOADLIBNAME "package"
LUALIB_API int (luaopen_package) (lua_State *L);
/* open all previous libraries */
LUALIB_API void (luaL_openlibs) (lua_State *L);
#ifndef lua_assert
#define lua_assert(x) ((void)0)
#endif
#endif
| xLua/build/lua-5.1.5/src/lualib.h/0 | {
"file_path": "xLua/build/lua-5.1.5/src/lualib.h",
"repo_id": "xLua",
"token_count": 449
} | 1,887 |
This is Lua 5.3.4, released on 12 Jan 2017.
For installation instructions, license details, and
further information about Lua, see doc/readme.html.
| xLua/build/lua-5.3.4/README/0 | {
"file_path": "xLua/build/lua-5.3.4/README",
"repo_id": "xLua",
"token_count": 42
} | 1,888 |
/*
** $Id: lapi.c $
** Lua API
** See Copyright Notice in lua.h
*/
#define lapi_c
#define LUA_CORE
#include "lprefix.h"
#include <limits.h>
#include <stdarg.h>
#include <string.h>
#include "lua.h"
#include "lapi.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "lundump.h"
#include "lvm.h"
const char lua_ident[] =
"$LuaVersion: " LUA_COPYRIGHT " $"
"$LuaAuthors: " LUA_AUTHORS " $";
/*
** Test for a valid index.
** '!ttisnil(o)' implies 'o != &G(L)->nilvalue', so it is not needed.
** However, it covers the most common cases in a faster way.
*/
#define isvalid(L, o) (!ttisnil(o) || o != &G(L)->nilvalue)
/* test for pseudo index */
#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX)
/* test for upvalue */
#define isupvalue(i) ((i) < LUA_REGISTRYINDEX)
static TValue *index2value (lua_State *L, int idx) {
CallInfo *ci = L->ci;
if (idx > 0) {
StkId o = ci->func + idx;
api_check(L, idx <= L->ci->top - (ci->func + 1), "unacceptable index");
if (o >= L->top) return &G(L)->nilvalue;
else return s2v(o);
}
else if (!ispseudo(idx)) { /* negative index */
api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
return s2v(L->top + idx);
}
else if (idx == LUA_REGISTRYINDEX)
return &G(L)->l_registry;
else { /* upvalues */
idx = LUA_REGISTRYINDEX - idx;
api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");
if (ttislcf(s2v(ci->func))) /* light C function? */
return &G(L)->nilvalue; /* it has no upvalues */
else {
CClosure *func = clCvalue(s2v(ci->func));
return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : &G(L)->nilvalue;
}
}
}
static StkId index2stack (lua_State *L, int idx) {
CallInfo *ci = L->ci;
if (idx > 0) {
StkId o = ci->func + idx;
api_check(L, o < L->top, "unacceptable index");
return o;
}
else { /* non-positive index */
api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
api_check(L, !ispseudo(idx), "invalid index");
return L->top + idx;
}
}
LUA_API int lua_checkstack (lua_State *L, int n) {
int res;
CallInfo *ci;
lua_lock(L);
ci = L->ci;
api_check(L, n >= 0, "negative 'n'");
if (L->stack_last - L->top > n) /* stack large enough? */
res = 1; /* yes; check is OK */
else { /* no; need to grow stack */
int inuse = cast_int(L->top - L->stack) + EXTRA_STACK;
if (inuse > LUAI_MAXSTACK - n) /* can grow without overflow? */
res = 0; /* no */
else /* try to grow stack */
res = luaD_growstack(L, n, 0);
}
if (res && ci->top < L->top + n)
ci->top = L->top + n; /* adjust frame top */
lua_unlock(L);
return res;
}
LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
int i;
if (from == to) return;
lua_lock(to);
api_checknelems(from, n);
api_check(from, G(from) == G(to), "moving among independent states");
api_check(from, to->ci->top - to->top >= n, "stack overflow");
from->top -= n;
for (i = 0; i < n; i++) {
setobjs2s(to, to->top, from->top + i);
to->top++; /* stack already checked by previous 'api_check' */
}
lua_unlock(to);
}
LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
lua_CFunction old;
lua_lock(L);
old = G(L)->panic;
G(L)->panic = panicf;
lua_unlock(L);
return old;
}
LUA_API lua_Number lua_version (lua_State *L) {
UNUSED(L);
return LUA_VERSION_NUM;
}
/*
** basic stack manipulation
*/
/*
** convert an acceptable stack index into an absolute index
*/
LUA_API int lua_absindex (lua_State *L, int idx) {
return (idx > 0 || ispseudo(idx))
? idx
: cast_int(L->top - L->ci->func) + idx;
}
LUA_API int lua_gettop (lua_State *L) {
return cast_int(L->top - (L->ci->func + 1));
}
LUA_API void lua_settop (lua_State *L, int idx) {
CallInfo *ci;
StkId func;
ptrdiff_t diff; /* difference for new top */
lua_lock(L);
ci = L->ci;
func = ci->func;
if (idx >= 0) {
api_check(L, idx <= ci->top - (func + 1), "new top too large");
diff = ((func + 1) + idx) - L->top;
for (; diff > 0; diff--)
setnilvalue(s2v(L->top++)); /* clear new slots */
}
else {
api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top");
diff = idx + 1; /* will "subtract" index (as it is negative) */
}
if (diff < 0 && hastocloseCfunc(ci->nresults))
luaF_close(L, L->top + diff, LUA_OK);
L->top += diff; /* correct top only after closing any upvalue */
lua_unlock(L);
}
/*
** Reverse the stack segment from 'from' to 'to'
** (auxiliary to 'lua_rotate')
** Note that we move(copy) only the value inside the stack.
** (We do not move additional fields that may exist.)
*/
static void reverse (lua_State *L, StkId from, StkId to) {
for (; from < to; from++, to--) {
TValue temp;
setobj(L, &temp, s2v(from));
setobjs2s(L, from, to);
setobj2s(L, to, &temp);
}
}
/*
** Let x = AB, where A is a prefix of length 'n'. Then,
** rotate x n == BA. But BA == (A^r . B^r)^r.
*/
LUA_API void lua_rotate (lua_State *L, int idx, int n) {
StkId p, t, m;
lua_lock(L);
t = L->top - 1; /* end of stack segment being rotated */
p = index2stack(L, idx); /* start of segment */
api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'");
m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */
reverse(L, p, m); /* reverse the prefix with length 'n' */
reverse(L, m + 1, t); /* reverse the suffix */
reverse(L, p, t); /* reverse the entire segment */
lua_unlock(L);
}
LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
TValue *fr, *to;
lua_lock(L);
fr = index2value(L, fromidx);
to = index2value(L, toidx);
api_check(L, isvalid(L, to), "invalid index");
setobj(L, to, fr);
if (isupvalue(toidx)) /* function upvalue? */
luaC_barrier(L, clCvalue(s2v(L->ci->func)), fr);
/* LUA_REGISTRYINDEX does not need gc barrier
(collector revisits it before finishing collection) */
lua_unlock(L);
}
LUA_API void lua_pushvalue (lua_State *L, int idx) {
lua_lock(L);
setobj2s(L, L->top, index2value(L, idx));
api_incr_top(L);
lua_unlock(L);
}
/*
** access functions (stack -> C)
*/
LUA_API int lua_type (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
return (isvalid(L, o) ? ttype(o) : LUA_TNONE);
}
LUA_API const char *lua_typename (lua_State *L, int t) {
UNUSED(L);
api_check(L, LUA_TNONE <= t && t < LUA_NUMTYPES, "invalid type");
return ttypename(t);
}
LUA_API int lua_iscfunction (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
return (ttislcf(o) || (ttisCclosure(o)));
}
LUA_API int lua_isinteger (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
return ttisinteger(o);
}
LUA_API int lua_isnumber (lua_State *L, int idx) {
lua_Number n;
const TValue *o = index2value(L, idx);
return tonumber(o, &n);
}
LUA_API int lua_isstring (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
return (ttisstring(o) || cvt2str(o));
}
LUA_API int lua_isuserdata (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
return (ttisfulluserdata(o) || ttislightuserdata(o));
}
LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
const TValue *o1 = index2value(L, index1);
const TValue *o2 = index2value(L, index2);
return (isvalid(L, o1) && isvalid(L, o2)) ? luaV_rawequalobj(o1, o2) : 0;
}
LUA_API void lua_arith (lua_State *L, int op) {
lua_lock(L);
if (op != LUA_OPUNM && op != LUA_OPBNOT)
api_checknelems(L, 2); /* all other operations expect two operands */
else { /* for unary operations, add fake 2nd operand */
api_checknelems(L, 1);
setobjs2s(L, L->top, L->top - 1);
api_incr_top(L);
}
/* first operand at top - 2, second at top - 1; result go to top - 2 */
luaO_arith(L, op, s2v(L->top - 2), s2v(L->top - 1), L->top - 2);
L->top--; /* remove second operand */
lua_unlock(L);
}
LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {
const TValue *o1;
const TValue *o2;
int i = 0;
lua_lock(L); /* may call tag method */
o1 = index2value(L, index1);
o2 = index2value(L, index2);
if (isvalid(L, o1) && isvalid(L, o2)) {
switch (op) {
case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break;
case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;
case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;
default: api_check(L, 0, "invalid option");
}
}
lua_unlock(L);
return i;
}
LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) {
size_t sz = luaO_str2num(s, s2v(L->top));
if (sz != 0)
api_incr_top(L);
return sz;
}
LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
lua_Number n = 0;
const TValue *o = index2value(L, idx);
int isnum = tonumber(o, &n);
if (pisnum)
*pisnum = isnum;
return n;
}
LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
lua_Integer res = 0;
const TValue *o = index2value(L, idx);
int isnum = tointeger(o, &res);
if (pisnum)
*pisnum = isnum;
return res;
}
LUA_API int lua_toboolean (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
return !l_isfalse(o);
}
LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
TValue *o;
lua_lock(L);
o = index2value(L, idx);
if (!ttisstring(o)) {
if (!cvt2str(o)) { /* not convertible? */
if (len != NULL) *len = 0;
lua_unlock(L);
return NULL;
}
luaO_tostring(L, o);
luaC_checkGC(L);
o = index2value(L, idx); /* previous call may reallocate the stack */
}
if (len != NULL)
*len = vslen(o);
lua_unlock(L);
return svalue(o);
}
LUA_API lua_Unsigned lua_rawlen (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
switch (ttypetag(o)) {
case LUA_VSHRSTR: return tsvalue(o)->shrlen;
case LUA_VLNGSTR: return tsvalue(o)->u.lnglen;
case LUA_VUSERDATA: return uvalue(o)->len;
case LUA_VTABLE: return luaH_getn(hvalue(o));
default: return 0;
}
}
LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
if (ttislcf(o)) return fvalue(o);
else if (ttisCclosure(o))
return clCvalue(o)->f;
else return NULL; /* not a C function */
}
static void *touserdata (const TValue *o) {
switch (ttype(o)) {
case LUA_TUSERDATA: return getudatamem(uvalue(o));
case LUA_TLIGHTUSERDATA: return pvalue(o);
default: return NULL;
}
}
LUA_API void *lua_touserdata (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
return touserdata(o);
}
LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
return (!ttisthread(o)) ? NULL : thvalue(o);
}
/*
** Returns a pointer to the internal representation of an object.
** Note that ANSI C does not allow the conversion of a pointer to
** function to a 'void*', so the conversion here goes through
** a 'size_t'. (As the returned pointer is only informative, this
** conversion should not be a problem.)
*/
LUA_API const void *lua_topointer (lua_State *L, int idx) {
const TValue *o = index2value(L, idx);
switch (ttypetag(o)) {
case LUA_VLCF: return cast_voidp(cast_sizet(fvalue(o)));
case LUA_VUSERDATA: case LUA_VLIGHTUSERDATA:
return touserdata(o);
default: {
if (iscollectable(o))
return gcvalue(o);
else
return NULL;
}
}
}
/*
** push functions (C -> stack)
*/
LUA_API void lua_pushnil (lua_State *L) {
lua_lock(L);
setnilvalue(s2v(L->top));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
lua_lock(L);
setfltvalue(s2v(L->top), n);
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
lua_lock(L);
setivalue(s2v(L->top), n);
api_incr_top(L);
lua_unlock(L);
}
/*
** Pushes on the stack a string with given length. Avoid using 's' when
** 'len' == 0 (as 's' can be NULL in that case), due to later use of
** 'memcmp' and 'memcpy'.
*/
LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {
TString *ts;
lua_lock(L);
ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len);
setsvalue2s(L, L->top, ts);
api_incr_top(L);
luaC_checkGC(L);
lua_unlock(L);
return getstr(ts);
}
LUA_API const char *lua_pushstring (lua_State *L, const char *s) {
lua_lock(L);
if (s == NULL)
setnilvalue(s2v(L->top));
else {
TString *ts;
ts = luaS_new(L, s);
setsvalue2s(L, L->top, ts);
s = getstr(ts); /* internal copy's address */
}
api_incr_top(L);
luaC_checkGC(L);
lua_unlock(L);
return s;
}
LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
va_list argp) {
const char *ret;
lua_lock(L);
ret = luaO_pushvfstring(L, fmt, argp);
luaC_checkGC(L);
lua_unlock(L);
return ret;
}
LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
const char *ret;
va_list argp;
lua_lock(L);
va_start(argp, fmt);
ret = luaO_pushvfstring(L, fmt, argp);
va_end(argp);
luaC_checkGC(L);
lua_unlock(L);
return ret;
}
LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
lua_lock(L);
if (n == 0) {
setfvalue(s2v(L->top), fn);
api_incr_top(L);
}
else {
CClosure *cl;
api_checknelems(L, n);
api_check(L, n <= MAXUPVAL, "upvalue index too large");
cl = luaF_newCclosure(L, n);
cl->f = fn;
L->top -= n;
while (n--) {
setobj2n(L, &cl->upvalue[n], s2v(L->top + n));
/* does not need barrier because closure is white */
lua_assert(iswhite(cl));
}
setclCvalue(L, s2v(L->top), cl);
api_incr_top(L);
luaC_checkGC(L);
}
lua_unlock(L);
}
LUA_API void lua_pushboolean (lua_State *L, int b) {
lua_lock(L);
if (b)
setbtvalue(s2v(L->top));
else
setbfvalue(s2v(L->top));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
lua_lock(L);
setpvalue(s2v(L->top), p);
api_incr_top(L);
lua_unlock(L);
}
LUA_API int lua_pushthread (lua_State *L) {
lua_lock(L);
setthvalue(L, s2v(L->top), L);
api_incr_top(L);
lua_unlock(L);
return (G(L)->mainthread == L);
}
/*
** get functions (Lua -> stack)
*/
static int auxgetstr (lua_State *L, const TValue *t, const char *k) {
const TValue *slot;
TString *str = luaS_new(L, k);
if (luaV_fastget(L, t, str, slot, luaH_getstr)) {
setobj2s(L, L->top, slot);
api_incr_top(L);
}
else {
setsvalue2s(L, L->top, str);
api_incr_top(L);
luaV_finishget(L, t, s2v(L->top - 1), L->top - 1, slot);
}
lua_unlock(L);
return ttype(s2v(L->top - 1));
}
LUA_API int lua_getglobal (lua_State *L, const char *name) {
Table *reg;
lua_lock(L);
reg = hvalue(&G(L)->l_registry);
return auxgetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name);
}
LUA_API int lua_gettable (lua_State *L, int idx) {
const TValue *slot;
TValue *t;
lua_lock(L);
t = index2value(L, idx);
if (luaV_fastget(L, t, s2v(L->top - 1), slot, luaH_get)) {
setobj2s(L, L->top - 1, slot);
}
else
luaV_finishget(L, t, s2v(L->top - 1), L->top - 1, slot);
lua_unlock(L);
return ttype(s2v(L->top - 1));
}
LUA_API int lua_getfield (lua_State *L, int idx, const char *k) {
lua_lock(L);
return auxgetstr(L, index2value(L, idx), k);
}
LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {
TValue *t;
const TValue *slot;
lua_lock(L);
t = index2value(L, idx);
if (luaV_fastgeti(L, t, n, slot)) {
setobj2s(L, L->top, slot);
}
else {
TValue aux;
setivalue(&aux, n);
luaV_finishget(L, t, &aux, L->top, slot);
}
api_incr_top(L);
lua_unlock(L);
return ttype(s2v(L->top - 1));
}
static int finishrawget (lua_State *L, const TValue *val) {
if (isempty(val)) /* avoid copying empty items to the stack */
setnilvalue(s2v(L->top));
else
setobj2s(L, L->top, val);
api_incr_top(L);
lua_unlock(L);
return ttype(s2v(L->top - 1));
}
static Table *gettable (lua_State *L, int idx) {
TValue *t = index2value(L, idx);
api_check(L, ttistable(t), "table expected");
return hvalue(t);
}
LUA_API int lua_rawget (lua_State *L, int idx) {
Table *t;
const TValue *val;
lua_lock(L);
api_checknelems(L, 1);
t = gettable(L, idx);
val = luaH_get(t, s2v(L->top - 1));
L->top--; /* remove key */
return finishrawget(L, val);
}
LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
Table *t;
lua_lock(L);
t = gettable(L, idx);
return finishrawget(L, luaH_getint(t, n));
}
LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {
Table *t;
TValue k;
lua_lock(L);
t = gettable(L, idx);
setpvalue(&k, cast_voidp(p));
return finishrawget(L, luaH_get(t, &k));
}
LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
Table *t;
lua_lock(L);
t = luaH_new(L);
sethvalue2s(L, L->top, t);
api_incr_top(L);
if (narray > 0 || nrec > 0)
luaH_resize(L, t, narray, nrec);
luaC_checkGC(L);
lua_unlock(L);
}
LUA_API int lua_getmetatable (lua_State *L, int objindex) {
const TValue *obj;
Table *mt;
int res = 0;
lua_lock(L);
obj = index2value(L, objindex);
switch (ttype(obj)) {
case LUA_TTABLE:
mt = hvalue(obj)->metatable;
break;
case LUA_TUSERDATA:
mt = uvalue(obj)->metatable;
break;
default:
mt = G(L)->mt[ttype(obj)];
break;
}
if (mt != NULL) {
sethvalue2s(L, L->top, mt);
api_incr_top(L);
res = 1;
}
lua_unlock(L);
return res;
}
LUA_API int lua_getiuservalue (lua_State *L, int idx, int n) {
TValue *o;
int t;
lua_lock(L);
o = index2value(L, idx);
api_check(L, ttisfulluserdata(o), "full userdata expected");
if (n <= 0 || n > uvalue(o)->nuvalue) {
setnilvalue(s2v(L->top));
t = LUA_TNONE;
}
else {
setobj2s(L, L->top, &uvalue(o)->uv[n - 1].uv);
t = ttype(s2v(L->top));
}
api_incr_top(L);
lua_unlock(L);
return t;
}
/*
** set functions (stack -> Lua)
*/
/*
** t[k] = value at the top of the stack (where 'k' is a string)
*/
static void auxsetstr (lua_State *L, const TValue *t, const char *k) {
const TValue *slot;
TString *str = luaS_new(L, k);
api_checknelems(L, 1);
if (luaV_fastget(L, t, str, slot, luaH_getstr)) {
luaV_finishfastset(L, t, slot, s2v(L->top - 1));
L->top--; /* pop value */
}
else {
setsvalue2s(L, L->top, str); /* push 'str' (to make it a TValue) */
api_incr_top(L);
luaV_finishset(L, t, s2v(L->top - 1), s2v(L->top - 2), slot);
L->top -= 2; /* pop value and key */
}
lua_unlock(L); /* lock done by caller */
}
LUA_API void lua_setglobal (lua_State *L, const char *name) {
Table *reg;
lua_lock(L); /* unlock done in 'auxsetstr' */
reg = hvalue(&G(L)->l_registry);
auxsetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name);
}
LUA_API void lua_settable (lua_State *L, int idx) {
TValue *t;
const TValue *slot;
lua_lock(L);
api_checknelems(L, 2);
t = index2value(L, idx);
if (luaV_fastget(L, t, s2v(L->top - 2), slot, luaH_get)) {
luaV_finishfastset(L, t, slot, s2v(L->top - 1));
}
else
luaV_finishset(L, t, s2v(L->top - 2), s2v(L->top - 1), slot);
L->top -= 2; /* pop index and value */
lua_unlock(L);
}
LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
lua_lock(L); /* unlock done in 'auxsetstr' */
auxsetstr(L, index2value(L, idx), k);
}
LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
TValue *t;
const TValue *slot;
lua_lock(L);
api_checknelems(L, 1);
t = index2value(L, idx);
if (luaV_fastgeti(L, t, n, slot)) {
luaV_finishfastset(L, t, slot, s2v(L->top - 1));
}
else {
TValue aux;
setivalue(&aux, n);
luaV_finishset(L, t, &aux, s2v(L->top - 1), slot);
}
L->top--; /* pop value */
lua_unlock(L);
}
static void aux_rawset (lua_State *L, int idx, TValue *key, int n) {
Table *t;
TValue *slot;
lua_lock(L);
api_checknelems(L, n);
t = gettable(L, idx);
slot = luaH_set(L, t, key);
setobj2t(L, slot, s2v(L->top - 1));
invalidateTMcache(t);
luaC_barrierback(L, obj2gco(t), s2v(L->top - 1));
L->top -= n;
lua_unlock(L);
}
LUA_API void lua_rawset (lua_State *L, int idx) {
aux_rawset(L, idx, s2v(L->top - 2), 2);
}
LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
TValue k;
setpvalue(&k, cast_voidp(p));
aux_rawset(L, idx, &k, 1);
}
LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
Table *t;
lua_lock(L);
api_checknelems(L, 1);
t = gettable(L, idx);
luaH_setint(L, t, n, s2v(L->top - 1));
luaC_barrierback(L, obj2gco(t), s2v(L->top - 1));
L->top--;
lua_unlock(L);
}
LUA_API int lua_setmetatable (lua_State *L, int objindex) {
TValue *obj;
Table *mt;
lua_lock(L);
api_checknelems(L, 1);
obj = index2value(L, objindex);
if (ttisnil(s2v(L->top - 1)))
mt = NULL;
else {
api_check(L, ttistable(s2v(L->top - 1)), "table expected");
mt = hvalue(s2v(L->top - 1));
}
switch (ttype(obj)) {
case LUA_TTABLE: {
hvalue(obj)->metatable = mt;
if (mt) {
luaC_objbarrier(L, gcvalue(obj), mt);
luaC_checkfinalizer(L, gcvalue(obj), mt);
}
break;
}
case LUA_TUSERDATA: {
uvalue(obj)->metatable = mt;
if (mt) {
luaC_objbarrier(L, uvalue(obj), mt);
luaC_checkfinalizer(L, gcvalue(obj), mt);
}
break;
}
default: {
G(L)->mt[ttype(obj)] = mt;
break;
}
}
L->top--;
lua_unlock(L);
return 1;
}
LUA_API int lua_setiuservalue (lua_State *L, int idx, int n) {
TValue *o;
int res;
lua_lock(L);
api_checknelems(L, 1);
o = index2value(L, idx);
api_check(L, ttisfulluserdata(o), "full userdata expected");
if (!(cast_uint(n) - 1u < cast_uint(uvalue(o)->nuvalue)))
res = 0; /* 'n' not in [1, uvalue(o)->nuvalue] */
else {
setobj(L, &uvalue(o)->uv[n - 1].uv, s2v(L->top - 1));
luaC_barrierback(L, gcvalue(o), s2v(L->top - 1));
res = 1;
}
L->top--;
lua_unlock(L);
return res;
}
/*
** 'load' and 'call' functions (run Lua code)
*/
#define checkresults(L,na,nr) \
api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \
"results from function overflow current stack size")
LUA_API void lua_callk (lua_State *L, int nargs, int nresults,
lua_KContext ctx, lua_KFunction k) {
StkId func;
lua_lock(L);
api_check(L, k == NULL || !isLua(L->ci),
"cannot use continuations inside hooks");
api_checknelems(L, nargs+1);
api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
checkresults(L, nargs, nresults);
func = L->top - (nargs+1);
if (k != NULL && yieldable(L)) { /* need to prepare continuation? */
L->ci->u.c.k = k; /* save continuation */
L->ci->u.c.ctx = ctx; /* save context */
luaD_call(L, func, nresults); /* do the call */
}
else /* no continuation or no yieldable */
luaD_callnoyield(L, func, nresults); /* just do the call */
adjustresults(L, nresults);
lua_unlock(L);
}
/*
** Execute a protected call.
*/
struct CallS { /* data to 'f_call' */
StkId func;
int nresults;
};
static void f_call (lua_State *L, void *ud) {
struct CallS *c = cast(struct CallS *, ud);
luaD_callnoyield(L, c->func, c->nresults);
}
LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
lua_KContext ctx, lua_KFunction k) {
struct CallS c;
int status;
ptrdiff_t func;
lua_lock(L);
api_check(L, k == NULL || !isLua(L->ci),
"cannot use continuations inside hooks");
api_checknelems(L, nargs+1);
api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
checkresults(L, nargs, nresults);
if (errfunc == 0)
func = 0;
else {
StkId o = index2stack(L, errfunc);
api_check(L, ttisfunction(s2v(o)), "error handler must be a function");
func = savestack(L, o);
}
c.func = L->top - (nargs+1); /* function to be called */
if (k == NULL || !yieldable(L)) { /* no continuation or no yieldable? */
c.nresults = nresults; /* do a 'conventional' protected call */
status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
}
else { /* prepare continuation (call is already protected by 'resume') */
CallInfo *ci = L->ci;
ci->u.c.k = k; /* save continuation */
ci->u.c.ctx = ctx; /* save context */
/* save information for error recovery */
ci->u2.funcidx = cast_int(savestack(L, c.func));
ci->u.c.old_errfunc = L->errfunc;
L->errfunc = func;
setoah(ci->callstatus, L->allowhook); /* save value of 'allowhook' */
ci->callstatus |= CIST_YPCALL; /* function can do error recovery */
luaD_call(L, c.func, nresults); /* do the call */
ci->callstatus &= ~CIST_YPCALL;
L->errfunc = ci->u.c.old_errfunc;
status = LUA_OK; /* if it is here, there were no errors */
}
adjustresults(L, nresults);
lua_unlock(L);
return status;
}
LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
const char *chunkname, const char *mode) {
ZIO z;
int status;
lua_lock(L);
if (!chunkname) chunkname = "?";
luaZ_init(L, &z, reader, data);
status = luaD_protectedparser(L, &z, chunkname, mode);
if (status == LUA_OK) { /* no errors? */
LClosure *f = clLvalue(s2v(L->top - 1)); /* get newly created function */
if (f->nupvalues >= 1) { /* does it have an upvalue? */
/* get global table from registry */
Table *reg = hvalue(&G(L)->l_registry);
const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
/* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
setobj(L, f->upvals[0]->v, gt);
luaC_barrier(L, f->upvals[0], gt);
}
}
lua_unlock(L);
return status;
}
LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {
int status;
TValue *o;
lua_lock(L);
api_checknelems(L, 1);
o = s2v(L->top - 1);
if (isLfunction(o))
status = luaU_dump(L, getproto(o), writer, data, strip);
else
status = 1;
lua_unlock(L);
return status;
}
LUA_API int lua_status (lua_State *L) {
return L->status;
}
/*
** Garbage-collection function
*/
LUA_API int lua_gc (lua_State *L, int what, ...) {
va_list argp;
int res = 0;
global_State *g;
lua_lock(L);
g = G(L);
va_start(argp, what);
switch (what) {
case LUA_GCSTOP: {
g->gcrunning = 0;
break;
}
case LUA_GCRESTART: {
luaE_setdebt(g, 0);
g->gcrunning = 1;
break;
}
case LUA_GCCOLLECT: {
luaC_fullgc(L, 0);
break;
}
case LUA_GCCOUNT: {
/* GC values are expressed in Kbytes: #bytes/2^10 */
res = cast_int(gettotalbytes(g) >> 10);
break;
}
case LUA_GCCOUNTB: {
res = cast_int(gettotalbytes(g) & 0x3ff);
break;
}
case LUA_GCSTEP: {
int data = va_arg(argp, int);
l_mem debt = 1; /* =1 to signal that it did an actual step */
lu_byte oldrunning = g->gcrunning;
g->gcrunning = 1; /* allow GC to run */
if (data == 0) {
luaE_setdebt(g, 0); /* do a basic step */
luaC_step(L);
}
else { /* add 'data' to total debt */
debt = cast(l_mem, data) * 1024 + g->GCdebt;
luaE_setdebt(g, debt);
luaC_checkGC(L);
}
g->gcrunning = oldrunning; /* restore previous state */
if (debt > 0 && g->gcstate == GCSpause) /* end of cycle? */
res = 1; /* signal it */
break;
}
case LUA_GCSETPAUSE: {
int data = va_arg(argp, int);
res = getgcparam(g->gcpause);
setgcparam(g->gcpause, data);
break;
}
case LUA_GCSETSTEPMUL: {
int data = va_arg(argp, int);
res = getgcparam(g->gcstepmul);
setgcparam(g->gcstepmul, data);
break;
}
case LUA_GCISRUNNING: {
res = g->gcrunning;
break;
}
case LUA_GCGEN: {
int minormul = va_arg(argp, int);
int majormul = va_arg(argp, int);
res = isdecGCmodegen(g) ? LUA_GCGEN : LUA_GCINC;
if (minormul != 0)
g->genminormul = minormul;
if (majormul != 0)
setgcparam(g->genmajormul, majormul);
luaC_changemode(L, KGC_GEN);
break;
}
case LUA_GCINC: {
int pause = va_arg(argp, int);
int stepmul = va_arg(argp, int);
int stepsize = va_arg(argp, int);
res = isdecGCmodegen(g) ? LUA_GCGEN : LUA_GCINC;
if (pause != 0)
setgcparam(g->gcpause, pause);
if (stepmul != 0)
setgcparam(g->gcstepmul, stepmul);
if (stepsize != 0)
g->gcstepsize = stepsize;
luaC_changemode(L, KGC_INC);
break;
}
default: res = -1; /* invalid option */
}
va_end(argp);
lua_unlock(L);
return res;
}
/*
** miscellaneous functions
*/
LUA_API int lua_error (lua_State *L) {
TValue *errobj;
lua_lock(L);
errobj = s2v(L->top - 1);
api_checknelems(L, 1);
/* error object is the memory error message? */
if (ttisshrstring(errobj) && eqshrstr(tsvalue(errobj), G(L)->memerrmsg))
luaM_error(L); /* raise a memory error */
else
luaG_errormsg(L); /* raise a regular error */
/* code unreachable; will unlock when control actually leaves the kernel */
return 0; /* to avoid warnings */
}
LUA_API int lua_next (lua_State *L, int idx) {
Table *t;
int more;
lua_lock(L);
api_checknelems(L, 1);
t = gettable(L, idx);
more = luaH_next(L, t, L->top - 1);
if (more) {
api_incr_top(L);
}
else /* no more elements */
L->top -= 1; /* remove key */
lua_unlock(L);
return more;
}
LUA_API void lua_toclose (lua_State *L, int idx) {
int nresults;
StkId o;
lua_lock(L);
o = index2stack(L, idx);
nresults = L->ci->nresults;
api_check(L, L->openupval == NULL || uplevel(L->openupval) <= o,
"marked index below or equal new one");
luaF_newtbcupval(L, o); /* create new to-be-closed upvalue */
if (!hastocloseCfunc(nresults)) /* function not marked yet? */
L->ci->nresults = codeNresults(nresults); /* mark it */
lua_assert(hastocloseCfunc(L->ci->nresults));
lua_unlock(L);
}
LUA_API void lua_concat (lua_State *L, int n) {
lua_lock(L);
api_checknelems(L, n);
if (n > 0)
luaV_concat(L, n);
else { /* nothing to concatenate */
setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); /* push empty string */
api_incr_top(L);
}
luaC_checkGC(L);
lua_unlock(L);
}
LUA_API void lua_len (lua_State *L, int idx) {
TValue *t;
lua_lock(L);
t = index2value(L, idx);
luaV_objlen(L, L->top, t);
api_incr_top(L);
lua_unlock(L);
}
LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
lua_Alloc f;
lua_lock(L);
if (ud) *ud = G(L)->ud;
f = G(L)->frealloc;
lua_unlock(L);
return f;
}
LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {
lua_lock(L);
G(L)->ud = ud;
G(L)->frealloc = f;
lua_unlock(L);
}
void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud) {
lua_lock(L);
G(L)->ud_warn = ud;
G(L)->warnf = f;
lua_unlock(L);
}
void lua_warning (lua_State *L, const char *msg, int tocont) {
lua_lock(L);
luaE_warning(L, msg, tocont);
lua_unlock(L);
}
LUA_API void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue) {
Udata *u;
lua_lock(L);
api_check(L, 0 <= nuvalue && nuvalue < USHRT_MAX, "invalid value");
u = luaS_newudata(L, size, nuvalue);
setuvalue(L, s2v(L->top), u);
api_incr_top(L);
luaC_checkGC(L);
lua_unlock(L);
return getudatamem(u);
}
static const char *aux_upvalue (TValue *fi, int n, TValue **val,
GCObject **owner) {
switch (ttypetag(fi)) {
case LUA_VCCL: { /* C closure */
CClosure *f = clCvalue(fi);
if (!(cast_uint(n) - 1u < cast_uint(f->nupvalues)))
return NULL; /* 'n' not in [1, f->nupvalues] */
*val = &f->upvalue[n-1];
if (owner) *owner = obj2gco(f);
return "";
}
case LUA_VLCL: { /* Lua closure */
LClosure *f = clLvalue(fi);
TString *name;
Proto *p = f->p;
if (!(cast_uint(n) - 1u < cast_uint(p->sizeupvalues)))
return NULL; /* 'n' not in [1, p->sizeupvalues] */
*val = f->upvals[n-1]->v;
if (owner) *owner = obj2gco(f->upvals[n - 1]);
name = p->upvalues[n-1].name;
return (name == NULL) ? "(no name)" : getstr(name);
}
default: return NULL; /* not a closure */
}
}
LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
const char *name;
TValue *val = NULL; /* to avoid warnings */
lua_lock(L);
name = aux_upvalue(index2value(L, funcindex), n, &val, NULL);
if (name) {
setobj2s(L, L->top, val);
api_incr_top(L);
}
lua_unlock(L);
return name;
}
LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
const char *name;
TValue *val = NULL; /* to avoid warnings */
GCObject *owner = NULL; /* to avoid warnings */
TValue *fi;
lua_lock(L);
fi = index2value(L, funcindex);
api_checknelems(L, 1);
name = aux_upvalue(fi, n, &val, &owner);
if (name) {
L->top--;
setobj(L, val, s2v(L->top));
luaC_barrier(L, owner, val);
}
lua_unlock(L);
return name;
}
static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
LClosure *f;
TValue *fi = index2value(L, fidx);
api_check(L, ttisLclosure(fi), "Lua function expected");
f = clLvalue(fi);
api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
if (pf) *pf = f;
return &f->upvals[n - 1]; /* get its upvalue pointer */
}
LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
TValue *fi = index2value(L, fidx);
switch (ttypetag(fi)) {
case LUA_VLCL: { /* lua closure */
return *getupvalref(L, fidx, n, NULL);
}
case LUA_VCCL: { /* C closure */
CClosure *f = clCvalue(fi);
api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");
return &f->upvalue[n - 1];
}
default: {
api_check(L, 0, "closure expected");
return NULL;
}
}
}
LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,
int fidx2, int n2) {
LClosure *f1;
UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
*up1 = *up2;
luaC_objbarrier(L, f1, *up1);
}
| xLua/build/lua-5.4.1/src/lapi.c/0 | {
"file_path": "xLua/build/lua-5.4.1/src/lapi.c",
"repo_id": "xLua",
"token_count": 16281
} | 1,889 |
/*
** $Id: lfunc.c $
** Auxiliary functions to manipulate prototypes and closures
** See Copyright Notice in lua.h
*/
#define lfunc_c
#define LUA_CORE
#include "lprefix.h"
#include <stddef.h>
#include "lua.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
CClosure *luaF_newCclosure (lua_State *L, int nupvals) {
GCObject *o = luaC_newobj(L, LUA_VCCL, sizeCclosure(nupvals));
CClosure *c = gco2ccl(o);
c->nupvalues = cast_byte(nupvals);
return c;
}
LClosure *luaF_newLclosure (lua_State *L, int nupvals) {
GCObject *o = luaC_newobj(L, LUA_VLCL, sizeLclosure(nupvals));
LClosure *c = gco2lcl(o);
c->p = NULL;
c->nupvalues = cast_byte(nupvals);
while (nupvals--) c->upvals[nupvals] = NULL;
return c;
}
/*
** fill a closure with new closed upvalues
*/
void luaF_initupvals (lua_State *L, LClosure *cl) {
int i;
for (i = 0; i < cl->nupvalues; i++) {
GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
UpVal *uv = gco2upv(o);
uv->v = &uv->u.value; /* make it closed */
setnilvalue(uv->v);
cl->upvals[i] = uv;
luaC_objbarrier(L, cl, o);
}
}
/*
** Create a new upvalue at the given level, and link it to the list of
** open upvalues of 'L' after entry 'prev'.
**/
static UpVal *newupval (lua_State *L, int tbc, StkId level, UpVal **prev) {
GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
UpVal *uv = gco2upv(o);
UpVal *next = *prev;
uv->v = s2v(level); /* current value lives in the stack */
uv->tbc = tbc;
uv->u.open.next = next; /* link it to list of open upvalues */
uv->u.open.previous = prev;
if (next)
next->u.open.previous = &uv->u.open.next;
*prev = uv;
if (!isintwups(L)) { /* thread not in list of threads with upvalues? */
L->twups = G(L)->twups; /* link it to the list */
G(L)->twups = L;
}
return uv;
}
/*
** Find and reuse, or create if it does not exist, an upvalue
** at the given level.
*/
UpVal *luaF_findupval (lua_State *L, StkId level) {
UpVal **pp = &L->openupval;
UpVal *p;
lua_assert(isintwups(L) || L->openupval == NULL);
while ((p = *pp) != NULL && uplevel(p) >= level) { /* search for it */
lua_assert(!isdead(G(L), p));
if (uplevel(p) == level) /* corresponding upvalue? */
return p; /* return it */
pp = &p->u.open.next;
}
/* not found: create a new upvalue after 'pp' */
return newupval(L, 0, level, pp);
}
static void callclose (lua_State *L, void *ud) {
UNUSED(ud);
luaD_callnoyield(L, L->top - 3, 0);
}
/*
** Prepare closing method plus its arguments for object 'obj' with
** error message 'err'. (This function assumes EXTRA_STACK.)
*/
static int prepclosingmethod (lua_State *L, TValue *obj, TValue *err) {
StkId top = L->top;
const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE);
if (ttisnil(tm)) /* no metamethod? */
return 0; /* nothing to call */
setobj2s(L, top, tm); /* will call metamethod... */
setobj2s(L, top + 1, obj); /* with 'self' as the 1st argument */
setobj2s(L, top + 2, err); /* and error msg. as 2nd argument */
L->top = top + 3; /* add function and arguments */
return 1;
}
/*
** Raise an error with message 'msg', inserting the name of the
** local variable at position 'level' in the stack.
*/
static void varerror (lua_State *L, StkId level, const char *msg) {
int idx = cast_int(level - L->ci->func);
const char *vname = luaG_findlocal(L, L->ci, idx, NULL);
if (vname == NULL) vname = "?";
luaG_runerror(L, msg, vname);
}
/*
** Prepare and call a closing method. If status is OK, code is still
** inside the original protected call, and so any error will be handled
** there. Otherwise, a previous error already activated the original
** protected call, and so the call to the closing method must be
** protected here. (A status == CLOSEPROTECT behaves like a previous
** error, to also run the closing method in protected mode).
** If status is OK, the call to the closing method will be pushed
** at the top of the stack. Otherwise, values are pushed after
** the 'level' of the upvalue being closed, as everything after
** that won't be used again.
*/
static int callclosemth (lua_State *L, StkId level, int status) {
TValue *uv = s2v(level); /* value being closed */
if (likely(status == LUA_OK)) {
if (prepclosingmethod(L, uv, &G(L)->nilvalue)) /* something to call? */
callclose(L, NULL); /* call closing method */
else if (!l_isfalse(uv)) /* non-closable non-false value? */
varerror(L, level, "attempt to close non-closable variable '%s'");
}
else { /* must close the object in protected mode */
ptrdiff_t oldtop;
level++; /* space for error message */
oldtop = savestack(L, level + 1); /* top will be after that */
luaD_seterrorobj(L, status, level); /* set error message */
if (prepclosingmethod(L, uv, s2v(level))) { /* something to call? */
int newstatus = luaD_pcall(L, callclose, NULL, oldtop, 0);
if (newstatus != LUA_OK && status == CLOSEPROTECT) /* first error? */
status = newstatus; /* this will be the new error */
else {
if (newstatus != LUA_OK) /* suppressed error? */
luaE_warnerror(L, "__close metamethod");
/* leave original error (or nil) on top */
L->top = restorestack(L, oldtop);
}
}
/* else no metamethod; ignore this case and keep original error */
}
return status;
}
/*
** Try to create a to-be-closed upvalue
** (can raise a memory-allocation error)
*/
static void trynewtbcupval (lua_State *L, void *ud) {
newupval(L, 1, cast(StkId, ud), &L->openupval);
}
/*
** Create a to-be-closed upvalue. If there is a memory error
** when creating the upvalue, the closing method must be called here,
** as there is no upvalue to call it later.
*/
void luaF_newtbcupval (lua_State *L, StkId level) {
TValue *obj = s2v(level);
lua_assert(L->openupval == NULL || uplevel(L->openupval) < level);
if (!l_isfalse(obj)) { /* false doesn't need to be closed */
int status;
const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE);
if (ttisnil(tm)) /* no metamethod? */
varerror(L, level, "variable '%s' got a non-closable value");
status = luaD_rawrunprotected(L, trynewtbcupval, level);
if (unlikely(status != LUA_OK)) { /* memory error creating upvalue? */
lua_assert(status == LUA_ERRMEM);
luaD_seterrorobj(L, LUA_ERRMEM, level + 1); /* save error message */
/* next call must succeed, as object is closable */
prepclosingmethod(L, s2v(level), s2v(level + 1));
callclose(L, NULL); /* call closing method */
luaD_throw(L, LUA_ERRMEM); /* throw memory error */
}
}
}
void luaF_unlinkupval (UpVal *uv) {
lua_assert(upisopen(uv));
*uv->u.open.previous = uv->u.open.next;
if (uv->u.open.next)
uv->u.open.next->u.open.previous = uv->u.open.previous;
}
int luaF_close (lua_State *L, StkId level, int status) {
UpVal *uv;
while ((uv = L->openupval) != NULL && uplevel(uv) >= level) {
TValue *slot = &uv->u.value; /* new position for value */
lua_assert(uplevel(uv) < L->top);
if (uv->tbc && status != NOCLOSINGMETH) {
/* must run closing method, which may change the stack */
ptrdiff_t levelrel = savestack(L, level);
status = callclosemth(L, uplevel(uv), status);
level = restorestack(L, levelrel);
}
luaF_unlinkupval(uv);
setobj(L, slot, uv->v); /* move value to upvalue slot */
uv->v = slot; /* now current value lives here */
if (!iswhite(uv)) { /* neither white nor dead? */
nw2black(uv); /* closed upvalues cannot be gray */
luaC_barrier(L, uv, slot);
}
}
return status;
}
Proto *luaF_newproto (lua_State *L) {
GCObject *o = luaC_newobj(L, LUA_VPROTO, sizeof(Proto));
Proto *f = gco2p(o);
f->k = NULL;
f->sizek = 0;
f->p = NULL;
f->sizep = 0;
f->code = NULL;
f->sizecode = 0;
f->lineinfo = NULL;
f->sizelineinfo = 0;
f->abslineinfo = NULL;
f->sizeabslineinfo = 0;
f->upvalues = NULL;
f->sizeupvalues = 0;
f->numparams = 0;
f->is_vararg = 0;
f->maxstacksize = 0;
f->locvars = NULL;
f->sizelocvars = 0;
f->linedefined = 0;
f->lastlinedefined = 0;
f->source = NULL;
return f;
}
void luaF_freeproto (lua_State *L, Proto *f) {
luaM_freearray(L, f->code, f->sizecode);
luaM_freearray(L, f->p, f->sizep);
luaM_freearray(L, f->k, f->sizek);
luaM_freearray(L, f->lineinfo, f->sizelineinfo);
luaM_freearray(L, f->abslineinfo, f->sizeabslineinfo);
luaM_freearray(L, f->locvars, f->sizelocvars);
luaM_freearray(L, f->upvalues, f->sizeupvalues);
luaM_free(L, f);
}
/*
** Look for n-th local variable at line 'line' in function 'func'.
** Returns NULL if not found.
*/
const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
int i;
for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {
if (pc < f->locvars[i].endpc) { /* is variable active? */
local_number--;
if (local_number == 0)
return getstr(f->locvars[i].varname);
}
}
return NULL; /* not found */
}
| xLua/build/lua-5.4.1/src/lfunc.c/0 | {
"file_path": "xLua/build/lua-5.4.1/src/lfunc.c",
"repo_id": "xLua",
"token_count": 3752
} | 1,890 |
/*
** $Id: lopcodes.c $
** Opcodes for Lua virtual machine
** See Copyright Notice in lua.h
*/
#define lopcodes_c
#define LUA_CORE
#include "lprefix.h"
#include "lopcodes.h"
/* ORDER OP */
LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {
/* MM OT IT T A mode opcode */
opmode(0, 0, 0, 0, 1, iABC) /* OP_MOVE */
,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADI */
,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADF */
,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADK */
,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADKX */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADFALSE */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LFALSESKIP */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADTRUE */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADNIL */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETUPVAL */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETUPVAL */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABUP */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABLE */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETI */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETFIELD */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABUP */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABLE */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETI */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETFIELD */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_NEWTABLE */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SELF */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDI */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUBK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_MULK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_MODK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_POWK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIVK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIVK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BANDK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BORK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXORK */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHRI */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHLI */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADD */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUB */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_MUL */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_MOD */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_POW */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIV */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIV */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BAND */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BOR */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXOR */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHL */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHR */
,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBIN */
,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINI*/
,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINK*/
,opmode(0, 0, 0, 0, 1, iABC) /* OP_UNM */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BNOT */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_NOT */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LEN */
,opmode(0, 0, 0, 0, 1, iABC) /* OP_CONCAT */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_CLOSE */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_TBC */
,opmode(0, 0, 0, 0, 0, isJ) /* OP_JMP */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQ */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_LT */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_LE */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQK */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQI */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_LTI */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_LEI */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_GTI */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_GEI */
,opmode(0, 0, 0, 1, 0, iABC) /* OP_TEST */
,opmode(0, 0, 0, 1, 1, iABC) /* OP_TESTSET */
,opmode(0, 1, 1, 0, 1, iABC) /* OP_CALL */
,opmode(0, 1, 1, 0, 1, iABC) /* OP_TAILCALL */
,opmode(0, 0, 1, 0, 0, iABC) /* OP_RETURN */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN0 */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN1 */
,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORLOOP */
,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORPREP */
,opmode(0, 0, 0, 0, 0, iABx) /* OP_TFORPREP */
,opmode(0, 0, 0, 0, 0, iABC) /* OP_TFORCALL */
,opmode(0, 0, 0, 0, 1, iABx) /* OP_TFORLOOP */
,opmode(0, 0, 1, 0, 0, iABC) /* OP_SETLIST */
,opmode(0, 0, 0, 0, 1, iABx) /* OP_CLOSURE */
,opmode(0, 1, 0, 0, 1, iABC) /* OP_VARARG */
,opmode(0, 0, 1, 0, 1, iABC) /* OP_VARARGPREP */
,opmode(0, 0, 0, 0, 0, iAx) /* OP_EXTRAARG */
};
| xLua/build/lua-5.4.1/src/lopcodes.c/0 | {
"file_path": "xLua/build/lua-5.4.1/src/lopcodes.c",
"repo_id": "xLua",
"token_count": 2345
} | 1,891 |
/*
** $Id: ltm.h $
** Tag methods
** See Copyright Notice in lua.h
*/
#ifndef ltm_h
#define ltm_h
#include "lobject.h"
/*
* WARNING: if you change the order of this enumeration,
* grep "ORDER TM" and "ORDER OP"
*/
typedef enum {
TM_INDEX,
TM_NEWINDEX,
TM_GC,
TM_MODE,
TM_LEN,
TM_EQ, /* last tag method with fast access */
TM_ADD,
TM_SUB,
TM_MUL,
TM_MOD,
TM_POW,
TM_DIV,
TM_IDIV,
TM_BAND,
TM_BOR,
TM_BXOR,
TM_SHL,
TM_SHR,
TM_UNM,
TM_BNOT,
TM_LT,
TM_LE,
TM_CONCAT,
TM_CALL,
TM_CLOSE,
TM_N /* number of elements in the enum */
} TMS;
/*
** Mask with 1 in all fast-access methods. A 1 in any of these bits
** in the flag of a (meta)table means the metatable does not have the
** corresponding metamethod field. (Bit 7 of the flag is used for
** 'isrealasize'.)
*/
#define maskflags (~(~0u << (TM_EQ + 1)))
/*
** Test whether there is no tagmethod.
** (Because tagmethods use raw accesses, the result may be an "empty" nil.)
*/
#define notm(tm) ttisnil(tm)
#define gfasttm(g,et,e) ((et) == NULL ? NULL : \
((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e]))
#define fasttm(l,et,e) gfasttm(G(l), et, e)
#define ttypename(x) luaT_typenames_[(x) + 1]
LUAI_DDEC(const char *const luaT_typenames_[LUA_TOTALTYPES];)
LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o);
LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);
LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o,
TMS event);
LUAI_FUNC void luaT_init (lua_State *L);
LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
const TValue *p2, const TValue *p3);
LUAI_FUNC void luaT_callTMres (lua_State *L, const TValue *f,
const TValue *p1, const TValue *p2, StkId p3);
LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
StkId res, TMS event);
LUAI_FUNC void luaT_tryconcatTM (lua_State *L);
LUAI_FUNC void luaT_trybinassocTM (lua_State *L, const TValue *p1,
const TValue *p2, int inv, StkId res, TMS event);
LUAI_FUNC void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2,
int inv, StkId res, TMS event);
LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1,
const TValue *p2, TMS event);
LUAI_FUNC int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2,
int inv, int isfloat, TMS event);
LUAI_FUNC void luaT_adjustvarargs (lua_State *L, int nfixparams,
struct CallInfo *ci, const Proto *p);
LUAI_FUNC void luaT_getvarargs (lua_State *L, struct CallInfo *ci,
StkId where, int wanted);
#endif
| xLua/build/lua-5.4.1/src/ltm.h/0 | {
"file_path": "xLua/build/lua-5.4.1/src/ltm.h",
"repo_id": "xLua",
"token_count": 1456
} | 1,892 |
mkdir build32 & pushd build32
cmake -DLUAC_COMPATIBLE_FORMAT=ON -G "Visual Studio 14 2015" ..
IF %ERRORLEVEL% NEQ 0 cmake -DLUAC_COMPATIBLE_FORMAT=ON -G "Visual Studio 15 2017" ..
popd
cmake --build build32 --config Release
pause | xLua/build/luac/make_win32.bat/0 | {
"file_path": "xLua/build/luac/make_win32.bat",
"repo_id": "xLua",
"token_count": 85
} | 1,893 |
/*
** Auxiliary library for the Lua/C API.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
**
** Major parts taken verbatim or adapted from the Lua interpreter.
** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
*/
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#define lib_aux_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lj_obj.h"
#include "lj_err.h"
#include "lj_state.h"
#include "lj_trace.h"
#include "lj_lib.h"
#if LJ_TARGET_POSIX
#include <sys/wait.h>
#endif
/* -- I/O error handling -------------------------------------------------- */
LUALIB_API int luaL_fileresult(lua_State *L, int stat, const char *fname)
{
if (stat) {
setboolV(L->top++, 1);
return 1;
} else {
int en = errno; /* Lua API calls may change this value. */
setnilV(L->top++);
if (fname)
lua_pushfstring(L, "%s: %s", fname, strerror(en));
else
lua_pushfstring(L, "%s", strerror(en));
setintV(L->top++, en);
lj_trace_abort(G(L));
return 3;
}
}
LUALIB_API int luaL_execresult(lua_State *L, int stat)
{
if (stat != -1) {
#if LJ_TARGET_POSIX
if (WIFSIGNALED(stat)) {
stat = WTERMSIG(stat);
setnilV(L->top++);
lua_pushliteral(L, "signal");
} else {
if (WIFEXITED(stat))
stat = WEXITSTATUS(stat);
if (stat == 0)
setboolV(L->top++, 1);
else
setnilV(L->top++);
lua_pushliteral(L, "exit");
}
#else
if (stat == 0)
setboolV(L->top++, 1);
else
setnilV(L->top++);
lua_pushliteral(L, "exit");
#endif
setintV(L->top++, stat);
return 3;
}
return luaL_fileresult(L, 0, NULL);
}
/* -- Module registration ------------------------------------------------- */
LUALIB_API const char *luaL_findtable(lua_State *L, int idx,
const char *fname, int szhint)
{
const char *e;
lua_pushvalue(L, idx);
do {
e = strchr(fname, '.');
if (e == NULL) e = fname + strlen(fname);
lua_pushlstring(L, fname, (size_t)(e - fname));
lua_rawget(L, -2);
if (lua_isnil(L, -1)) { /* no such field? */
lua_pop(L, 1); /* remove this nil */
lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
lua_pushlstring(L, fname, (size_t)(e - fname));
lua_pushvalue(L, -2);
lua_settable(L, -4); /* set new table into field */
} else if (!lua_istable(L, -1)) { /* field has a non-table value? */
lua_pop(L, 2); /* remove table and value */
return fname; /* return problematic part of the name */
}
lua_remove(L, -2); /* remove previous table */
fname = e + 1;
} while (*e == '.');
return NULL;
}
static int libsize(const luaL_Reg *l)
{
int size = 0;
for (; l->name; l++) size++;
return size;
}
LUALIB_API void luaL_openlib(lua_State *L, const char *libname,
const luaL_Reg *l, int nup)
{
lj_lib_checkfpu(L);
if (libname) {
int size = libsize(l);
/* check whether lib already exists */
luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 16);
lua_getfield(L, -1, libname); /* get _LOADED[libname] */
if (!lua_istable(L, -1)) { /* not found? */
lua_pop(L, 1); /* remove previous result */
/* try global variable (and create one if it does not exist) */
if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
lj_err_callerv(L, LJ_ERR_BADMODN, libname);
lua_pushvalue(L, -1);
lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
}
lua_remove(L, -2); /* remove _LOADED table */
lua_insert(L, -(nup+1)); /* move library table to below upvalues */
}
for (; l->name; l++) {
int i;
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -nup);
lua_pushcclosure(L, l->func, nup);
lua_setfield(L, -(nup+2), l->name);
}
lua_pop(L, nup); /* remove upvalues */
}
LUALIB_API void luaL_register(lua_State *L, const char *libname,
const luaL_Reg *l)
{
luaL_openlib(L, libname, l, 0);
}
LUALIB_API const char *luaL_gsub(lua_State *L, const char *s,
const char *p, const char *r)
{
const char *wild;
size_t l = strlen(p);
luaL_Buffer b;
luaL_buffinit(L, &b);
while ((wild = strstr(s, p)) != NULL) {
luaL_addlstring(&b, s, (size_t)(wild - s)); /* push prefix */
luaL_addstring(&b, r); /* push replacement in place of pattern */
s = wild + l; /* continue after `p' */
}
luaL_addstring(&b, s); /* push last suffix */
luaL_pushresult(&b);
return lua_tostring(L, -1);
}
/* -- Buffer handling ----------------------------------------------------- */
#define bufflen(B) ((size_t)((B)->p - (B)->buffer))
#define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
static int emptybuffer(luaL_Buffer *B)
{
size_t l = bufflen(B);
if (l == 0)
return 0; /* put nothing on stack */
lua_pushlstring(B->L, B->buffer, l);
B->p = B->buffer;
B->lvl++;
return 1;
}
static void adjuststack(luaL_Buffer *B)
{
if (B->lvl > 1) {
lua_State *L = B->L;
int toget = 1; /* number of levels to concat */
size_t toplen = lua_strlen(L, -1);
do {
size_t l = lua_strlen(L, -(toget+1));
if (!(B->lvl - toget + 1 >= LUA_MINSTACK/2 || toplen > l))
break;
toplen += l;
toget++;
} while (toget < B->lvl);
lua_concat(L, toget);
B->lvl = B->lvl - toget + 1;
}
}
LUALIB_API char *luaL_prepbuffer(luaL_Buffer *B)
{
if (emptybuffer(B))
adjuststack(B);
return B->buffer;
}
LUALIB_API void luaL_addlstring(luaL_Buffer *B, const char *s, size_t l)
{
while (l--)
luaL_addchar(B, *s++);
}
LUALIB_API void luaL_addstring(luaL_Buffer *B, const char *s)
{
luaL_addlstring(B, s, strlen(s));
}
LUALIB_API void luaL_pushresult(luaL_Buffer *B)
{
emptybuffer(B);
lua_concat(B->L, B->lvl);
B->lvl = 1;
}
LUALIB_API void luaL_addvalue(luaL_Buffer *B)
{
lua_State *L = B->L;
size_t vl;
const char *s = lua_tolstring(L, -1, &vl);
if (vl <= bufffree(B)) { /* fit into buffer? */
memcpy(B->p, s, vl); /* put it there */
B->p += vl;
lua_pop(L, 1); /* remove from stack */
} else {
if (emptybuffer(B))
lua_insert(L, -2); /* put buffer before new value */
B->lvl++; /* add new value into B stack */
adjuststack(B);
}
}
LUALIB_API void luaL_buffinit(lua_State *L, luaL_Buffer *B)
{
B->L = L;
B->p = B->buffer;
B->lvl = 0;
}
/* -- Reference management ------------------------------------------------ */
#define FREELIST_REF 0
/* Convert a stack index to an absolute index. */
#define abs_index(L, i) \
((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : lua_gettop(L) + (i) + 1)
LUALIB_API int luaL_ref(lua_State *L, int t)
{
int ref;
t = abs_index(L, t);
if (lua_isnil(L, -1)) {
lua_pop(L, 1); /* remove from stack */
return LUA_REFNIL; /* `nil' has a unique fixed reference */
}
lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
lua_pop(L, 1); /* remove it from stack */
if (ref != 0) { /* any free element? */
lua_rawgeti(L, t, ref); /* remove it from list */
lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
} else { /* no free elements */
ref = (int)lua_objlen(L, t);
ref++; /* create new reference */
}
lua_rawseti(L, t, ref);
return ref;
}
LUALIB_API void luaL_unref(lua_State *L, int t, int ref)
{
if (ref >= 0) {
t = abs_index(L, t);
lua_rawgeti(L, t, FREELIST_REF);
lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
lua_pushinteger(L, ref);
lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
}
}
/* -- Default allocator and panic function -------------------------------- */
static int panic(lua_State *L)
{
const char *s = lua_tostring(L, -1);
fputs("PANIC: unprotected error in call to Lua API (", stderr);
fputs(s ? s : "?", stderr);
fputc(')', stderr); fputc('\n', stderr);
fflush(stderr);
return 0;
}
#ifdef LUAJIT_USE_SYSMALLOC
#if LJ_64 && !defined(LUAJIT_USE_VALGRIND)
#error "Must use builtin allocator for 64 bit target"
#endif
static void *mem_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
{
(void)ud;
(void)osize;
if (nsize == 0) {
free(ptr);
return NULL;
} else {
return realloc(ptr, nsize);
}
}
LUALIB_API lua_State *luaL_newstate(void)
{
lua_State *L = lua_newstate(mem_alloc, NULL);
if (L) G(L)->panic = panic;
return L;
}
#else
#include "lj_alloc.h"
LUALIB_API lua_State *luaL_newstate(void)
{
lua_State *L;
void *ud = lj_alloc_create();
if (ud == NULL) return NULL;
#if LJ_64
L = lj_state_newstate(lj_alloc_f, ud);
#else
L = lua_newstate(lj_alloc_f, ud);
#endif
if (L) G(L)->panic = panic;
return L;
}
#if LJ_64
LUA_API lua_State *lua_newstate(lua_Alloc f, void *ud)
{
UNUSED(f); UNUSED(ud);
fputs("Must use luaL_newstate() for 64 bit target\n", stderr);
return NULL;
}
#endif
#endif
| xLua/build/luajit-2.1.0b2/src/lib_aux.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lib_aux.c",
"repo_id": "xLua",
"token_count": 4066
} | 1,894 |
/*
** Public Lua/C API.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
**
** Major portions taken verbatim or adapted from the Lua interpreter.
** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
*/
#define lj_api_c
#define LUA_CORE
#include "lj_obj.h"
#include "lj_gc.h"
#include "lj_err.h"
#include "lj_debug.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_func.h"
#include "lj_udata.h"
#include "lj_meta.h"
#include "lj_state.h"
#include "lj_bc.h"
#include "lj_frame.h"
#include "lj_trace.h"
#include "lj_vm.h"
#include "lj_strscan.h"
#include "lj_strfmt.h"
/* -- Common helper functions --------------------------------------------- */
#define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base))
#define api_checkvalidindex(L, i) api_check(L, (i) != niltv(L))
static TValue *index2adr(lua_State *L, int idx)
{
if (idx > 0) {
TValue *o = L->base + (idx - 1);
return o < L->top ? o : niltv(L);
} else if (idx > LUA_REGISTRYINDEX) {
api_check(L, idx != 0 && -idx <= L->top - L->base);
return L->top + idx;
} else if (idx == LUA_GLOBALSINDEX) {
TValue *o = &G(L)->tmptv;
settabV(L, o, tabref(L->env));
return o;
} else if (idx == LUA_REGISTRYINDEX) {
return registry(L);
} else {
GCfunc *fn = curr_func(L);
api_check(L, fn->c.gct == ~LJ_TFUNC && !isluafunc(fn));
if (idx == LUA_ENVIRONINDEX) {
TValue *o = &G(L)->tmptv;
settabV(L, o, tabref(fn->c.env));
return o;
} else {
idx = LUA_GLOBALSINDEX - idx;
return idx <= fn->c.nupvalues ? &fn->c.upvalue[idx-1] : niltv(L);
}
}
}
static TValue *stkindex2adr(lua_State *L, int idx)
{
if (idx > 0) {
TValue *o = L->base + (idx - 1);
return o < L->top ? o : niltv(L);
} else {
api_check(L, idx != 0 && -idx <= L->top - L->base);
return L->top + idx;
}
}
static GCtab *getcurrenv(lua_State *L)
{
GCfunc *fn = curr_func(L);
return fn->c.gct == ~LJ_TFUNC ? tabref(fn->c.env) : tabref(L->env);
}
/* -- Miscellaneous API functions ----------------------------------------- */
LUA_API int lua_status(lua_State *L)
{
return L->status;
}
LUA_API int lua_checkstack(lua_State *L, int size)
{
if (size > LUAI_MAXCSTACK || (L->top - L->base + size) > LUAI_MAXCSTACK) {
return 0; /* Stack overflow. */
} else if (size > 0) {
lj_state_checkstack(L, (MSize)size);
}
return 1;
}
LUALIB_API void luaL_checkstack(lua_State *L, int size, const char *msg)
{
if (!lua_checkstack(L, size))
lj_err_callerv(L, LJ_ERR_STKOVM, msg);
}
LUA_API void lua_xmove(lua_State *from, lua_State *to, int n)
{
TValue *f, *t;
if (from == to) return;
api_checknelems(from, n);
api_check(from, G(from) == G(to));
lj_state_checkstack(to, (MSize)n);
f = from->top;
t = to->top = to->top + n;
while (--n >= 0) copyTV(to, --t, --f);
from->top = f;
}
/* -- Stack manipulation -------------------------------------------------- */
LUA_API int lua_gettop(lua_State *L)
{
return (int)(L->top - L->base);
}
LUA_API void lua_settop(lua_State *L, int idx)
{
if (idx >= 0) {
api_check(L, idx <= tvref(L->maxstack) - L->base);
if (L->base + idx > L->top) {
if (L->base + idx >= tvref(L->maxstack))
lj_state_growstack(L, (MSize)idx - (MSize)(L->top - L->base));
do { setnilV(L->top++); } while (L->top < L->base + idx);
} else {
L->top = L->base + idx;
}
} else {
api_check(L, -(idx+1) <= (L->top - L->base));
L->top += idx+1; /* Shrinks top (idx < 0). */
}
}
LUA_API void lua_remove(lua_State *L, int idx)
{
TValue *p = stkindex2adr(L, idx);
api_checkvalidindex(L, p);
while (++p < L->top) copyTV(L, p-1, p);
L->top--;
}
LUA_API void lua_insert(lua_State *L, int idx)
{
TValue *q, *p = stkindex2adr(L, idx);
api_checkvalidindex(L, p);
for (q = L->top; q > p; q--) copyTV(L, q, q-1);
copyTV(L, p, L->top);
}
LUA_API void lua_replace(lua_State *L, int idx)
{
api_checknelems(L, 1);
if (idx == LUA_GLOBALSINDEX) {
api_check(L, tvistab(L->top-1));
/* NOBARRIER: A thread (i.e. L) is never black. */
setgcref(L->env, obj2gco(tabV(L->top-1)));
} else if (idx == LUA_ENVIRONINDEX) {
GCfunc *fn = curr_func(L);
if (fn->c.gct != ~LJ_TFUNC)
lj_err_msg(L, LJ_ERR_NOENV);
api_check(L, tvistab(L->top-1));
setgcref(fn->c.env, obj2gco(tabV(L->top-1)));
lj_gc_barrier(L, fn, L->top-1);
} else {
TValue *o = index2adr(L, idx);
api_checkvalidindex(L, o);
copyTV(L, o, L->top-1);
if (idx < LUA_GLOBALSINDEX) /* Need a barrier for upvalues. */
lj_gc_barrier(L, curr_func(L), L->top-1);
}
L->top--;
}
LUA_API void lua_pushvalue(lua_State *L, int idx)
{
copyTV(L, L->top, index2adr(L, idx));
incr_top(L);
}
/* -- Stack getters ------------------------------------------------------- */
LUA_API int lua_type(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
if (tvisnumber(o)) {
return LUA_TNUMBER;
#if LJ_64 && !LJ_GC64
} else if (tvislightud(o)) {
return LUA_TLIGHTUSERDATA;
#endif
} else if (o == niltv(L)) {
return LUA_TNONE;
} else { /* Magic internal/external tag conversion. ORDER LJ_T */
uint32_t t = ~itype(o);
#if LJ_64
int tt = (int)((U64x(75a06,98042110) >> 4*t) & 15u);
#else
int tt = (int)(((t < 8 ? 0x98042110u : 0x75a06u) >> 4*(t&7)) & 15u);
#endif
lua_assert(tt != LUA_TNIL || tvisnil(o));
return tt;
}
}
LUALIB_API void luaL_checktype(lua_State *L, int idx, int tt)
{
if (lua_type(L, idx) != tt)
lj_err_argt(L, idx, tt);
}
LUALIB_API void luaL_checkany(lua_State *L, int idx)
{
if (index2adr(L, idx) == niltv(L))
lj_err_arg(L, idx, LJ_ERR_NOVAL);
}
LUA_API const char *lua_typename(lua_State *L, int t)
{
UNUSED(L);
return lj_obj_typename[t+1];
}
LUA_API int lua_iscfunction(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
return tvisfunc(o) && !isluafunc(funcV(o));
}
LUA_API int lua_isnumber(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
TValue tmp;
return (tvisnumber(o) || (tvisstr(o) && lj_strscan_number(strV(o), &tmp)));
}
LUA_API int lua_isstring(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
return (tvisstr(o) || tvisnumber(o));
}
LUA_API int lua_isuserdata(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
return (tvisudata(o) || tvislightud(o));
}
LUA_API int lua_rawequal(lua_State *L, int idx1, int idx2)
{
cTValue *o1 = index2adr(L, idx1);
cTValue *o2 = index2adr(L, idx2);
return (o1 == niltv(L) || o2 == niltv(L)) ? 0 : lj_obj_equal(o1, o2);
}
LUA_API int lua_equal(lua_State *L, int idx1, int idx2)
{
cTValue *o1 = index2adr(L, idx1);
cTValue *o2 = index2adr(L, idx2);
if (tvisint(o1) && tvisint(o2)) {
return intV(o1) == intV(o2);
} else if (tvisnumber(o1) && tvisnumber(o2)) {
return numberVnum(o1) == numberVnum(o2);
} else if (itype(o1) != itype(o2)) {
return 0;
} else if (tvispri(o1)) {
return o1 != niltv(L) && o2 != niltv(L);
#if LJ_64 && !LJ_GC64
} else if (tvislightud(o1)) {
return o1->u64 == o2->u64;
#endif
} else if (gcrefeq(o1->gcr, o2->gcr)) {
return 1;
} else if (!tvistabud(o1)) {
return 0;
} else {
TValue *base = lj_meta_equal(L, gcV(o1), gcV(o2), 0);
if ((uintptr_t)base <= 1) {
return (int)(uintptr_t)base;
} else {
L->top = base+2;
lj_vm_call(L, base, 1+1);
L->top -= 2+LJ_FR2;
return tvistruecond(L->top+1+LJ_FR2);
}
}
}
LUA_API int lua_lessthan(lua_State *L, int idx1, int idx2)
{
cTValue *o1 = index2adr(L, idx1);
cTValue *o2 = index2adr(L, idx2);
if (o1 == niltv(L) || o2 == niltv(L)) {
return 0;
} else if (tvisint(o1) && tvisint(o2)) {
return intV(o1) < intV(o2);
} else if (tvisnumber(o1) && tvisnumber(o2)) {
return numberVnum(o1) < numberVnum(o2);
} else {
TValue *base = lj_meta_comp(L, o1, o2, 0);
if ((uintptr_t)base <= 1) {
return (int)(uintptr_t)base;
} else {
L->top = base+2;
lj_vm_call(L, base, 1+1);
L->top -= 2+LJ_FR2;
return tvistruecond(L->top+1+LJ_FR2);
}
}
}
LUA_API lua_Number lua_tonumber(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
TValue tmp;
if (LJ_LIKELY(tvisnumber(o)))
return numberVnum(o);
else if (tvisstr(o) && lj_strscan_num(strV(o), &tmp))
return numV(&tmp);
else
return 0;
}
LUALIB_API lua_Number luaL_checknumber(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
TValue tmp;
if (LJ_LIKELY(tvisnumber(o)))
return numberVnum(o);
else if (!(tvisstr(o) && lj_strscan_num(strV(o), &tmp)))
lj_err_argt(L, idx, LUA_TNUMBER);
return numV(&tmp);
}
LUALIB_API lua_Number luaL_optnumber(lua_State *L, int idx, lua_Number def)
{
cTValue *o = index2adr(L, idx);
TValue tmp;
if (LJ_LIKELY(tvisnumber(o)))
return numberVnum(o);
else if (tvisnil(o))
return def;
else if (!(tvisstr(o) && lj_strscan_num(strV(o), &tmp)))
lj_err_argt(L, idx, LUA_TNUMBER);
return numV(&tmp);
}
LUA_API lua_Integer lua_tointeger(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
TValue tmp;
lua_Number n;
if (LJ_LIKELY(tvisint(o))) {
return intV(o);
} else if (LJ_LIKELY(tvisnum(o))) {
n = numV(o);
} else {
if (!(tvisstr(o) && lj_strscan_number(strV(o), &tmp)))
return 0;
if (tvisint(&tmp))
return (lua_Integer)intV(&tmp);
n = numV(&tmp);
}
#if LJ_64
return (lua_Integer)n;
#else
return lj_num2int(n);
#endif
}
LUALIB_API lua_Integer luaL_checkinteger(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
TValue tmp;
lua_Number n;
if (LJ_LIKELY(tvisint(o))) {
return intV(o);
} else if (LJ_LIKELY(tvisnum(o))) {
n = numV(o);
} else {
if (!(tvisstr(o) && lj_strscan_number(strV(o), &tmp)))
lj_err_argt(L, idx, LUA_TNUMBER);
if (tvisint(&tmp))
return (lua_Integer)intV(&tmp);
n = numV(&tmp);
}
#if LJ_64
return (lua_Integer)n;
#else
return lj_num2int(n);
#endif
}
LUALIB_API lua_Integer luaL_optinteger(lua_State *L, int idx, lua_Integer def)
{
cTValue *o = index2adr(L, idx);
TValue tmp;
lua_Number n;
if (LJ_LIKELY(tvisint(o))) {
return intV(o);
} else if (LJ_LIKELY(tvisnum(o))) {
n = numV(o);
} else if (tvisnil(o)) {
return def;
} else {
if (!(tvisstr(o) && lj_strscan_number(strV(o), &tmp)))
lj_err_argt(L, idx, LUA_TNUMBER);
if (tvisint(&tmp))
return (lua_Integer)intV(&tmp);
n = numV(&tmp);
}
#if LJ_64
return (lua_Integer)n;
#else
return lj_num2int(n);
#endif
}
LUA_API int lua_toboolean(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
return tvistruecond(o);
}
LUA_API const char *lua_tolstring(lua_State *L, int idx, size_t *len)
{
TValue *o = index2adr(L, idx);
GCstr *s;
if (LJ_LIKELY(tvisstr(o))) {
s = strV(o);
} else if (tvisnumber(o)) {
lj_gc_check(L);
o = index2adr(L, idx); /* GC may move the stack. */
s = lj_strfmt_number(L, o);
setstrV(L, o, s);
} else {
if (len != NULL) *len = 0;
return NULL;
}
if (len != NULL) *len = s->len;
return strdata(s);
}
LUALIB_API const char *luaL_checklstring(lua_State *L, int idx, size_t *len)
{
TValue *o = index2adr(L, idx);
GCstr *s;
if (LJ_LIKELY(tvisstr(o))) {
s = strV(o);
} else if (tvisnumber(o)) {
lj_gc_check(L);
o = index2adr(L, idx); /* GC may move the stack. */
s = lj_strfmt_number(L, o);
setstrV(L, o, s);
} else {
lj_err_argt(L, idx, LUA_TSTRING);
}
if (len != NULL) *len = s->len;
return strdata(s);
}
LUALIB_API const char *luaL_optlstring(lua_State *L, int idx,
const char *def, size_t *len)
{
TValue *o = index2adr(L, idx);
GCstr *s;
if (LJ_LIKELY(tvisstr(o))) {
s = strV(o);
} else if (tvisnil(o)) {
if (len != NULL) *len = def ? strlen(def) : 0;
return def;
} else if (tvisnumber(o)) {
lj_gc_check(L);
o = index2adr(L, idx); /* GC may move the stack. */
s = lj_strfmt_number(L, o);
setstrV(L, o, s);
} else {
lj_err_argt(L, idx, LUA_TSTRING);
}
if (len != NULL) *len = s->len;
return strdata(s);
}
LUALIB_API int luaL_checkoption(lua_State *L, int idx, const char *def,
const char *const lst[])
{
ptrdiff_t i;
const char *s = lua_tolstring(L, idx, NULL);
if (s == NULL && (s = def) == NULL)
lj_err_argt(L, idx, LUA_TSTRING);
for (i = 0; lst[i]; i++)
if (strcmp(lst[i], s) == 0)
return (int)i;
lj_err_argv(L, idx, LJ_ERR_INVOPTM, s);
}
LUA_API size_t lua_objlen(lua_State *L, int idx)
{
TValue *o = index2adr(L, idx);
if (tvisstr(o)) {
return strV(o)->len;
} else if (tvistab(o)) {
return (size_t)lj_tab_len(tabV(o));
} else if (tvisudata(o)) {
return udataV(o)->len;
} else if (tvisnumber(o)) {
GCstr *s = lj_strfmt_number(L, o);
setstrV(L, o, s);
return s->len;
} else {
return 0;
}
}
LUA_API lua_CFunction lua_tocfunction(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
if (tvisfunc(o)) {
BCOp op = bc_op(*mref(funcV(o)->c.pc, BCIns));
if (op == BC_FUNCC || op == BC_FUNCCW)
return funcV(o)->c.f;
}
return NULL;
}
LUA_API void *lua_touserdata(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
if (tvisudata(o))
return uddata(udataV(o));
else if (tvislightud(o))
return lightudV(o);
else
return NULL;
}
LUA_API lua_State *lua_tothread(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
return (!tvisthread(o)) ? NULL : threadV(o);
}
LUA_API const void *lua_topointer(lua_State *L, int idx)
{
return lj_obj_ptr(index2adr(L, idx));
}
/* -- Stack setters (object creation) ------------------------------------- */
LUA_API void lua_pushnil(lua_State *L)
{
setnilV(L->top);
incr_top(L);
}
LUA_API void lua_pushnumber(lua_State *L, lua_Number n)
{
setnumV(L->top, n);
if (LJ_UNLIKELY(tvisnan(L->top)))
setnanV(L->top); /* Canonicalize injected NaNs. */
incr_top(L);
}
LUA_API void lua_pushinteger(lua_State *L, lua_Integer n)
{
setintptrV(L->top, n);
incr_top(L);
}
LUA_API void lua_pushlstring(lua_State *L, const char *str, size_t len)
{
GCstr *s;
lj_gc_check(L);
s = lj_str_new(L, str, len);
setstrV(L, L->top, s);
incr_top(L);
}
LUA_API void lua_pushstring(lua_State *L, const char *str)
{
if (str == NULL) {
setnilV(L->top);
} else {
GCstr *s;
lj_gc_check(L);
s = lj_str_newz(L, str);
setstrV(L, L->top, s);
}
incr_top(L);
}
LUA_API const char *lua_pushvfstring(lua_State *L, const char *fmt,
va_list argp)
{
lj_gc_check(L);
return lj_strfmt_pushvf(L, fmt, argp);
}
LUA_API const char *lua_pushfstring(lua_State *L, const char *fmt, ...)
{
const char *ret;
va_list argp;
lj_gc_check(L);
va_start(argp, fmt);
ret = lj_strfmt_pushvf(L, fmt, argp);
va_end(argp);
return ret;
}
LUA_API void lua_pushcclosure(lua_State *L, lua_CFunction f, int n)
{
GCfunc *fn;
lj_gc_check(L);
api_checknelems(L, n);
fn = lj_func_newC(L, (MSize)n, getcurrenv(L));
fn->c.f = f;
L->top -= n;
while (n--)
copyTV(L, &fn->c.upvalue[n], L->top+n);
setfuncV(L, L->top, fn);
lua_assert(iswhite(obj2gco(fn)));
incr_top(L);
}
LUA_API void lua_pushboolean(lua_State *L, int b)
{
setboolV(L->top, (b != 0));
incr_top(L);
}
LUA_API void lua_pushlightuserdata(lua_State *L, void *p)
{
setlightudV(L->top, checklightudptr(L, p));
incr_top(L);
}
LUA_API void lua_createtable(lua_State *L, int narray, int nrec)
{
lj_gc_check(L);
settabV(L, L->top, lj_tab_new_ah(L, narray, nrec));
incr_top(L);
}
LUALIB_API int luaL_newmetatable(lua_State *L, const char *tname)
{
GCtab *regt = tabV(registry(L));
TValue *tv = lj_tab_setstr(L, regt, lj_str_newz(L, tname));
if (tvisnil(tv)) {
GCtab *mt = lj_tab_new(L, 0, 1);
settabV(L, tv, mt);
settabV(L, L->top++, mt);
lj_gc_anybarriert(L, regt);
return 1;
} else {
copyTV(L, L->top++, tv);
return 0;
}
}
LUA_API int lua_pushthread(lua_State *L)
{
setthreadV(L, L->top, L);
incr_top(L);
return (mainthread(G(L)) == L);
}
LUA_API lua_State *lua_newthread(lua_State *L)
{
lua_State *L1;
lj_gc_check(L);
L1 = lj_state_new(L);
setthreadV(L, L->top, L1);
incr_top(L);
return L1;
}
LUA_API void *lua_newuserdata(lua_State *L, size_t size)
{
GCudata *ud;
lj_gc_check(L);
if (size > LJ_MAX_UDATA)
lj_err_msg(L, LJ_ERR_UDATAOV);
ud = lj_udata_new(L, (MSize)size, getcurrenv(L));
setudataV(L, L->top, ud);
incr_top(L);
return uddata(ud);
}
LUA_API void lua_concat(lua_State *L, int n)
{
api_checknelems(L, n);
if (n >= 2) {
n--;
do {
TValue *top = lj_meta_cat(L, L->top-1, -n);
if (top == NULL) {
L->top -= n;
break;
}
n -= (int)(L->top - top);
L->top = top+2;
lj_vm_call(L, top, 1+1);
L->top -= 1+LJ_FR2;
copyTV(L, L->top-1, L->top+LJ_FR2);
} while (--n > 0);
} else if (n == 0) { /* Push empty string. */
setstrV(L, L->top, &G(L)->strempty);
incr_top(L);
}
/* else n == 1: nothing to do. */
}
/* -- Object getters ------------------------------------------------------ */
LUA_API void lua_gettable(lua_State *L, int idx)
{
cTValue *v, *t = index2adr(L, idx);
api_checkvalidindex(L, t);
v = lj_meta_tget(L, t, L->top-1);
if (v == NULL) {
L->top += 2;
lj_vm_call(L, L->top-2, 1+1);
L->top -= 2+LJ_FR2;
v = L->top+1+LJ_FR2;
}
copyTV(L, L->top-1, v);
}
LUA_API void lua_getfield(lua_State *L, int idx, const char *k)
{
cTValue *v, *t = index2adr(L, idx);
TValue key;
api_checkvalidindex(L, t);
setstrV(L, &key, lj_str_newz(L, k));
v = lj_meta_tget(L, t, &key);
if (v == NULL) {
L->top += 2;
lj_vm_call(L, L->top-2, 1+1);
L->top -= 2+LJ_FR2;
v = L->top+1+LJ_FR2;
}
copyTV(L, L->top, v);
incr_top(L);
}
LUA_API void lua_rawget(lua_State *L, int idx)
{
cTValue *t = index2adr(L, idx);
api_check(L, tvistab(t));
copyTV(L, L->top-1, lj_tab_get(L, tabV(t), L->top-1));
}
LUA_API void lua_rawgeti(lua_State *L, int idx, int n)
{
cTValue *v, *t = index2adr(L, idx);
api_check(L, tvistab(t));
v = lj_tab_getint(tabV(t), n);
if (v) {
copyTV(L, L->top, v);
} else {
setnilV(L->top);
}
incr_top(L);
}
LUA_API int lua_getmetatable(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
GCtab *mt = NULL;
if (tvistab(o))
mt = tabref(tabV(o)->metatable);
else if (tvisudata(o))
mt = tabref(udataV(o)->metatable);
else
mt = tabref(basemt_obj(G(L), o));
if (mt == NULL)
return 0;
settabV(L, L->top, mt);
incr_top(L);
return 1;
}
LUALIB_API int luaL_getmetafield(lua_State *L, int idx, const char *field)
{
if (lua_getmetatable(L, idx)) {
cTValue *tv = lj_tab_getstr(tabV(L->top-1), lj_str_newz(L, field));
if (tv && !tvisnil(tv)) {
copyTV(L, L->top-1, tv);
return 1;
}
L->top--;
}
return 0;
}
LUA_API void lua_getfenv(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
api_checkvalidindex(L, o);
if (tvisfunc(o)) {
settabV(L, L->top, tabref(funcV(o)->c.env));
} else if (tvisudata(o)) {
settabV(L, L->top, tabref(udataV(o)->env));
} else if (tvisthread(o)) {
settabV(L, L->top, tabref(threadV(o)->env));
} else {
setnilV(L->top);
}
incr_top(L);
}
LUA_API int lua_next(lua_State *L, int idx)
{
cTValue *t = index2adr(L, idx);
int more;
api_check(L, tvistab(t));
more = lj_tab_next(L, tabV(t), L->top-1);
if (more) {
incr_top(L); /* Return new key and value slot. */
} else { /* End of traversal. */
L->top--; /* Remove key slot. */
}
return more;
}
LUA_API const char *lua_getupvalue(lua_State *L, int idx, int n)
{
TValue *val;
const char *name = lj_debug_uvnamev(index2adr(L, idx), (uint32_t)(n-1), &val);
if (name) {
copyTV(L, L->top, val);
incr_top(L);
}
return name;
}
LUA_API void *lua_upvalueid(lua_State *L, int idx, int n)
{
GCfunc *fn = funcV(index2adr(L, idx));
n--;
api_check(L, (uint32_t)n < fn->l.nupvalues);
return isluafunc(fn) ? (void *)gcref(fn->l.uvptr[n]) :
(void *)&fn->c.upvalue[n];
}
LUA_API void lua_upvaluejoin(lua_State *L, int idx1, int n1, int idx2, int n2)
{
GCfunc *fn1 = funcV(index2adr(L, idx1));
GCfunc *fn2 = funcV(index2adr(L, idx2));
n1--; n2--;
api_check(L, isluafunc(fn1) && (uint32_t)n1 < fn1->l.nupvalues);
api_check(L, isluafunc(fn2) && (uint32_t)n2 < fn2->l.nupvalues);
setgcrefr(fn1->l.uvptr[n1], fn2->l.uvptr[n2]);
lj_gc_objbarrier(L, fn1, gcref(fn1->l.uvptr[n1]));
}
LUALIB_API void *luaL_checkudata(lua_State *L, int idx, const char *tname)
{
cTValue *o = index2adr(L, idx);
if (tvisudata(o)) {
GCudata *ud = udataV(o);
cTValue *tv = lj_tab_getstr(tabV(registry(L)), lj_str_newz(L, tname));
if (tv && tvistab(tv) && tabV(tv) == tabref(ud->metatable))
return uddata(ud);
}
lj_err_argtype(L, idx, tname);
return NULL; /* unreachable */
}
/* -- Object setters ------------------------------------------------------ */
LUA_API void lua_settable(lua_State *L, int idx)
{
TValue *o;
cTValue *t = index2adr(L, idx);
api_checknelems(L, 2);
api_checkvalidindex(L, t);
o = lj_meta_tset(L, t, L->top-2);
if (o) {
/* NOBARRIER: lj_meta_tset ensures the table is not black. */
L->top -= 2;
copyTV(L, o, L->top+1);
} else {
TValue *base = L->top;
copyTV(L, base+2, base-3-2*LJ_FR2);
L->top = base+3;
lj_vm_call(L, base, 0+1);
L->top -= 3+LJ_FR2;
}
}
LUA_API void lua_setfield(lua_State *L, int idx, const char *k)
{
TValue *o;
TValue key;
cTValue *t = index2adr(L, idx);
api_checknelems(L, 1);
api_checkvalidindex(L, t);
setstrV(L, &key, lj_str_newz(L, k));
o = lj_meta_tset(L, t, &key);
if (o) {
/* NOBARRIER: lj_meta_tset ensures the table is not black. */
copyTV(L, o, --L->top);
} else {
TValue *base = L->top;
copyTV(L, base+2, base-3-2*LJ_FR2);
L->top = base+3;
lj_vm_call(L, base, 0+1);
L->top -= 2+LJ_FR2;
}
}
LUA_API void lua_rawset(lua_State *L, int idx)
{
GCtab *t = tabV(index2adr(L, idx));
TValue *dst, *key;
api_checknelems(L, 2);
key = L->top-2;
dst = lj_tab_set(L, t, key);
copyTV(L, dst, key+1);
lj_gc_anybarriert(L, t);
L->top = key;
}
LUA_API void lua_rawseti(lua_State *L, int idx, int n)
{
GCtab *t = tabV(index2adr(L, idx));
TValue *dst, *src;
api_checknelems(L, 1);
dst = lj_tab_setint(L, t, n);
src = L->top-1;
copyTV(L, dst, src);
lj_gc_barriert(L, t, dst);
L->top = src;
}
LUA_API int lua_setmetatable(lua_State *L, int idx)
{
global_State *g;
GCtab *mt;
cTValue *o = index2adr(L, idx);
api_checknelems(L, 1);
api_checkvalidindex(L, o);
if (tvisnil(L->top-1)) {
mt = NULL;
} else {
api_check(L, tvistab(L->top-1));
mt = tabV(L->top-1);
}
g = G(L);
if (tvistab(o)) {
setgcref(tabV(o)->metatable, obj2gco(mt));
if (mt)
lj_gc_objbarriert(L, tabV(o), mt);
} else if (tvisudata(o)) {
setgcref(udataV(o)->metatable, obj2gco(mt));
if (mt)
lj_gc_objbarrier(L, udataV(o), mt);
} else {
/* Flush cache, since traces specialize to basemt. But not during __gc. */
if (lj_trace_flushall(L))
lj_err_caller(L, LJ_ERR_NOGCMM);
if (tvisbool(o)) {
/* NOBARRIER: basemt is a GC root. */
setgcref(basemt_it(g, LJ_TTRUE), obj2gco(mt));
setgcref(basemt_it(g, LJ_TFALSE), obj2gco(mt));
} else {
/* NOBARRIER: basemt is a GC root. */
setgcref(basemt_obj(g, o), obj2gco(mt));
}
}
L->top--;
return 1;
}
LUA_API int lua_setfenv(lua_State *L, int idx)
{
cTValue *o = index2adr(L, idx);
GCtab *t;
api_checknelems(L, 1);
api_checkvalidindex(L, o);
api_check(L, tvistab(L->top-1));
t = tabV(L->top-1);
if (tvisfunc(o)) {
setgcref(funcV(o)->c.env, obj2gco(t));
} else if (tvisudata(o)) {
setgcref(udataV(o)->env, obj2gco(t));
} else if (tvisthread(o)) {
setgcref(threadV(o)->env, obj2gco(t));
} else {
L->top--;
return 0;
}
lj_gc_objbarrier(L, gcV(o), t);
L->top--;
return 1;
}
LUA_API const char *lua_setupvalue(lua_State *L, int idx, int n)
{
cTValue *f = index2adr(L, idx);
TValue *val;
const char *name;
api_checknelems(L, 1);
name = lj_debug_uvnamev(f, (uint32_t)(n-1), &val);
if (name) {
L->top--;
copyTV(L, val, L->top);
lj_gc_barrier(L, funcV(f), L->top);
}
return name;
}
/* -- Calls --------------------------------------------------------------- */
#if LJ_FR2
static TValue *api_call_base(lua_State *L, int nargs)
{
TValue *o = L->top, *base = o - nargs;
L->top = o+1;
for (; o > base; o--) copyTV(L, o, o-1);
setnilV(o);
return o+1;
}
#else
#define api_call_base(L, nargs) (L->top - (nargs))
#endif
LUA_API void lua_call(lua_State *L, int nargs, int nresults)
{
api_check(L, L->status == 0 || L->status == LUA_ERRERR);
api_checknelems(L, nargs+1);
lj_vm_call(L, api_call_base(L, nargs), nresults+1);
}
LUA_API int lua_pcall(lua_State *L, int nargs, int nresults, int errfunc)
{
global_State *g = G(L);
uint8_t oldh = hook_save(g);
ptrdiff_t ef;
int status;
api_check(L, L->status == 0 || L->status == LUA_ERRERR);
api_checknelems(L, nargs+1);
if (errfunc == 0) {
ef = 0;
} else {
cTValue *o = stkindex2adr(L, errfunc);
api_checkvalidindex(L, o);
ef = savestack(L, o);
}
status = lj_vm_pcall(L, api_call_base(L, nargs), nresults+1, ef);
if (status) hook_restore(g, oldh);
return status;
}
static TValue *cpcall(lua_State *L, lua_CFunction func, void *ud)
{
GCfunc *fn = lj_func_newC(L, 0, getcurrenv(L));
TValue *top = L->top;
fn->c.f = func;
setfuncV(L, top++, fn);
if (LJ_FR2) setnilV(top++);
setlightudV(top++, checklightudptr(L, ud));
cframe_nres(L->cframe) = 1+0; /* Zero results. */
L->top = top;
return top-1; /* Now call the newly allocated C function. */
}
LUA_API int lua_cpcall(lua_State *L, lua_CFunction func, void *ud)
{
global_State *g = G(L);
uint8_t oldh = hook_save(g);
int status;
api_check(L, L->status == 0 || L->status == LUA_ERRERR);
status = lj_vm_cpcall(L, func, ud, cpcall);
if (status) hook_restore(g, oldh);
return status;
}
LUALIB_API int luaL_callmeta(lua_State *L, int idx, const char *field)
{
if (luaL_getmetafield(L, idx, field)) {
TValue *top = L->top--;
if (LJ_FR2) setnilV(top++);
copyTV(L, top++, index2adr(L, idx));
L->top = top;
lj_vm_call(L, top-1, 1+1);
return 1;
}
return 0;
}
/* -- Coroutine yield and resume ------------------------------------------ */
LUA_API int lua_yield(lua_State *L, int nresults)
{
void *cf = L->cframe;
global_State *g = G(L);
if (cframe_canyield(cf)) {
cf = cframe_raw(cf);
if (!hook_active(g)) { /* Regular yield: move results down if needed. */
cTValue *f = L->top - nresults;
if (f > L->base) {
TValue *t = L->base;
while (--nresults >= 0) copyTV(L, t++, f++);
L->top = t;
}
L->cframe = NULL;
L->status = LUA_YIELD;
return -1;
} else { /* Yield from hook: add a pseudo-frame. */
TValue *top = L->top;
hook_leave(g);
(top++)->u64 = cframe_multres(cf);
setcont(top, lj_cont_hook);
if (LJ_FR2) top++;
setframe_pc(top, cframe_pc(cf)-1);
if (LJ_FR2) top++;
setframe_gc(top, obj2gco(L), LJ_TTHREAD);
setframe_ftsz(top, ((char *)(top+1)-(char *)L->base)+FRAME_CONT);
L->top = L->base = top+1;
#if LJ_TARGET_X64
lj_err_throw(L, LUA_YIELD);
#else
L->cframe = NULL;
L->status = LUA_YIELD;
lj_vm_unwind_c(cf, LUA_YIELD);
#endif
}
}
lj_err_msg(L, LJ_ERR_CYIELD);
return 0; /* unreachable */
}
LUA_API int lua_resume(lua_State *L, int nargs)
{
if (L->cframe == NULL && L->status <= LUA_YIELD)
return lj_vm_resume(L,
L->status == 0 ? api_call_base(L, nargs) : L->top - nargs,
0, 0);
L->top = L->base;
setstrV(L, L->top, lj_err_str(L, LJ_ERR_COSUSP));
incr_top(L);
return LUA_ERRRUN;
}
/* -- GC and memory management -------------------------------------------- */
LUA_API int lua_gc(lua_State *L, int what, int data)
{
global_State *g = G(L);
int res = 0;
switch (what) {
case LUA_GCSTOP:
g->gc.threshold = LJ_MAX_MEM;
break;
case LUA_GCRESTART:
g->gc.threshold = data == -1 ? (g->gc.total/100)*g->gc.pause : g->gc.total;
break;
case LUA_GCCOLLECT:
lj_gc_fullgc(L);
break;
case LUA_GCCOUNT:
res = (int)(g->gc.total >> 10);
break;
case LUA_GCCOUNTB:
res = (int)(g->gc.total & 0x3ff);
break;
case LUA_GCSTEP: {
GCSize a = (GCSize)data << 10;
g->gc.threshold = (a <= g->gc.total) ? (g->gc.total - a) : 0;
while (g->gc.total >= g->gc.threshold)
if (lj_gc_step(L) > 0) {
res = 1;
break;
}
break;
}
case LUA_GCSETPAUSE:
res = (int)(g->gc.pause);
g->gc.pause = (MSize)data;
break;
case LUA_GCSETSTEPMUL:
res = (int)(g->gc.stepmul);
g->gc.stepmul = (MSize)data;
break;
case LUA_GCISRUNNING:
res = (g->gc.threshold != LJ_MAX_MEM);
break;
default:
res = -1; /* Invalid option. */
}
return res;
}
LUA_API lua_Alloc lua_getallocf(lua_State *L, void **ud)
{
global_State *g = G(L);
if (ud) *ud = g->allocd;
return g->allocf;
}
LUA_API void lua_setallocf(lua_State *L, lua_Alloc f, void *ud)
{
global_State *g = G(L);
g->allocd = ud;
g->allocf = f;
}
| xLua/build/luajit-2.1.0b2/src/lj_api.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_api.c",
"repo_id": "xLua",
"token_count": 14764
} | 1,895 |
/*
** Fast function call recorder.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
*/
#define lj_ffrecord_c
#define LUA_CORE
#include "lj_obj.h"
#if LJ_HASJIT
#include "lj_err.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_frame.h"
#include "lj_bc.h"
#include "lj_ff.h"
#include "lj_ir.h"
#include "lj_jit.h"
#include "lj_ircall.h"
#include "lj_iropt.h"
#include "lj_trace.h"
#include "lj_record.h"
#include "lj_ffrecord.h"
#include "lj_crecord.h"
#include "lj_dispatch.h"
#include "lj_vm.h"
#include "lj_strscan.h"
#include "lj_strfmt.h"
/* Some local macros to save typing. Undef'd at the end. */
#define IR(ref) (&J->cur.ir[(ref)])
/* Pass IR on to next optimization in chain (FOLD). */
#define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J))
/* -- Fast function recording handlers ------------------------------------ */
/* Conventions for fast function call handlers:
**
** The argument slots start at J->base[0]. All of them are guaranteed to be
** valid and type-specialized references. J->base[J->maxslot] is set to 0
** as a sentinel. The runtime argument values start at rd->argv[0].
**
** In general fast functions should check for presence of all of their
** arguments and for the correct argument types. Some simplifications
** are allowed if the interpreter throws instead. But even if recording
** is aborted, the generated IR must be consistent (no zero-refs).
**
** The number of results in rd->nres is set to 1. Handlers that return
** a different number of results need to override it. A negative value
** prevents return processing (e.g. for pending calls).
**
** Results need to be stored starting at J->base[0]. Return processing
** moves them to the right slots later.
**
** The per-ffid auxiliary data is the value of the 2nd part of the
** LJLIB_REC() annotation. This allows handling similar functionality
** in a common handler.
*/
/* Type of handler to record a fast function. */
typedef void (LJ_FASTCALL *RecordFunc)(jit_State *J, RecordFFData *rd);
/* Get runtime value of int argument. */
static int32_t argv2int(jit_State *J, TValue *o)
{
if (!lj_strscan_numberobj(o))
lj_trace_err(J, LJ_TRERR_BADTYPE);
return tvisint(o) ? intV(o) : lj_num2int(numV(o));
}
/* Get runtime value of string argument. */
static GCstr *argv2str(jit_State *J, TValue *o)
{
if (LJ_LIKELY(tvisstr(o))) {
return strV(o);
} else {
GCstr *s;
if (!tvisnumber(o))
lj_trace_err(J, LJ_TRERR_BADTYPE);
s = lj_strfmt_number(J->L, o);
setstrV(J->L, o, s);
return s;
}
}
/* Return number of results wanted by caller. */
static ptrdiff_t results_wanted(jit_State *J)
{
TValue *frame = J->L->base-1;
if (frame_islua(frame))
return (ptrdiff_t)bc_b(frame_pc(frame)[-1]) - 1;
else
return -1;
}
/* Trace stitching: add continuation below frame to start a new trace. */
static void recff_stitch(jit_State *J)
{
ASMFunction cont = lj_cont_stitch;
lua_State *L = J->L;
TValue *base = L->base;
const BCIns *pc = frame_pc(base-1);
TValue *pframe = frame_prevl(base-1);
TRef trcont;
lua_assert(!LJ_FR2); /* TODO_FR2: handle frame shift. */
/* Move func + args up in Lua stack and insert continuation. */
memmove(&base[1], &base[-1], sizeof(TValue)*(J->maxslot+1));
setframe_ftsz(base+1, ((char *)(base+1) - (char *)pframe) + FRAME_CONT);
setcont(base, cont);
setframe_pc(base, pc);
setnilV(base-1); /* Incorrect, but rec_check_slots() won't run anymore. */
L->base += 2;
L->top += 2;
/* Ditto for the IR. */
memmove(&J->base[1], &J->base[-1], sizeof(TRef)*(J->maxslot+1));
#if LJ_64
trcont = lj_ir_kptr(J, (void *)((int64_t)cont-(int64_t)lj_vm_asm_begin));
#else
trcont = lj_ir_kptr(J, (void *)cont);
#endif
J->base[0] = trcont | TREF_CONT;
J->ktracep = lj_ir_k64_reserve(J);
lua_assert(irt_toitype_(IRT_P64) == LJ_TTRACE);
J->base[-1] = emitir(IRT(IR_XLOAD, IRT_P64), lj_ir_kptr(J, &J->ktracep->gcr), 0);
J->base += 2;
J->baseslot += 2;
J->framedepth++;
lj_record_stop(J, LJ_TRLINK_STITCH, 0);
/* Undo Lua stack changes. */
memmove(&base[-1], &base[1], sizeof(TValue)*(J->maxslot+1));
setframe_pc(base-1, pc);
L->base -= 2;
L->top -= 2;
}
/* Fallback handler for fast functions that are not recorded (yet). */
static void LJ_FASTCALL recff_nyi(jit_State *J, RecordFFData *rd)
{
if (J->cur.nins < (IRRef)J->param[JIT_P_minstitch] + REF_BASE) {
lj_trace_err_info(J, LJ_TRERR_TRACEUV);
} else {
/* Can only stitch from Lua call. */
if (J->framedepth && frame_islua(J->L->base-1)) {
BCOp op = bc_op(*frame_pc(J->L->base-1));
/* Stitched trace cannot start with *M op with variable # of args. */
if (!(op == BC_CALLM || op == BC_CALLMT ||
op == BC_RETM || op == BC_TSETM)) {
switch (J->fn->c.ffid) {
case FF_error:
case FF_debug_sethook:
case FF_jit_flush:
break; /* Don't stitch across special builtins. */
default:
recff_stitch(J); /* Use trace stitching. */
rd->nres = -1;
return;
}
}
}
/* Otherwise stop trace and return to interpreter. */
lj_record_stop(J, LJ_TRLINK_RETURN, 0);
rd->nres = -1;
}
}
/* Fallback handler for unsupported variants of fast functions. */
#define recff_nyiu recff_nyi
/* Must stop the trace for classic C functions with arbitrary side-effects. */
#define recff_c recff_nyi
/* Emit BUFHDR for the global temporary buffer. */
static TRef recff_bufhdr(jit_State *J)
{
return emitir(IRT(IR_BUFHDR, IRT_P32),
lj_ir_kptr(J, &J2G(J)->tmpbuf), IRBUFHDR_RESET);
}
/* -- Base library fast functions ----------------------------------------- */
static void LJ_FASTCALL recff_assert(jit_State *J, RecordFFData *rd)
{
/* Arguments already specialized. The interpreter throws for nil/false. */
rd->nres = J->maxslot; /* Pass through all arguments. */
}
static void LJ_FASTCALL recff_type(jit_State *J, RecordFFData *rd)
{
/* Arguments already specialized. Result is a constant string. Neat, huh? */
uint32_t t;
if (tvisnumber(&rd->argv[0]))
t = ~LJ_TNUMX;
else if (LJ_64 && !LJ_GC64 && tvislightud(&rd->argv[0]))
t = ~LJ_TLIGHTUD;
else
t = ~itype(&rd->argv[0]);
J->base[0] = lj_ir_kstr(J, strV(&J->fn->c.upvalue[t]));
UNUSED(rd);
}
static void LJ_FASTCALL recff_getmetatable(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
if (tr) {
RecordIndex ix;
ix.tab = tr;
copyTV(J->L, &ix.tabv, &rd->argv[0]);
if (lj_record_mm_lookup(J, &ix, MM_metatable))
J->base[0] = ix.mobj;
else
J->base[0] = ix.mt;
} /* else: Interpreter will throw. */
}
static void LJ_FASTCALL recff_setmetatable(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
TRef mt = J->base[1];
if (tref_istab(tr) && (tref_istab(mt) || (mt && tref_isnil(mt)))) {
TRef fref, mtref;
RecordIndex ix;
ix.tab = tr;
copyTV(J->L, &ix.tabv, &rd->argv[0]);
lj_record_mm_lookup(J, &ix, MM_metatable); /* Guard for no __metatable. */
fref = emitir(IRT(IR_FREF, IRT_P32), tr, IRFL_TAB_META);
mtref = tref_isnil(mt) ? lj_ir_knull(J, IRT_TAB) : mt;
emitir(IRT(IR_FSTORE, IRT_TAB), fref, mtref);
if (!tref_isnil(mt))
emitir(IRT(IR_TBAR, IRT_TAB), tr, 0);
J->base[0] = tr;
J->needsnap = 1;
} /* else: Interpreter will throw. */
}
static void LJ_FASTCALL recff_rawget(jit_State *J, RecordFFData *rd)
{
RecordIndex ix;
ix.tab = J->base[0]; ix.key = J->base[1];
if (tref_istab(ix.tab) && ix.key) {
ix.val = 0; ix.idxchain = 0;
settabV(J->L, &ix.tabv, tabV(&rd->argv[0]));
copyTV(J->L, &ix.keyv, &rd->argv[1]);
J->base[0] = lj_record_idx(J, &ix);
} /* else: Interpreter will throw. */
}
static void LJ_FASTCALL recff_rawset(jit_State *J, RecordFFData *rd)
{
RecordIndex ix;
ix.tab = J->base[0]; ix.key = J->base[1]; ix.val = J->base[2];
if (tref_istab(ix.tab) && ix.key && ix.val) {
ix.idxchain = 0;
settabV(J->L, &ix.tabv, tabV(&rd->argv[0]));
copyTV(J->L, &ix.keyv, &rd->argv[1]);
copyTV(J->L, &ix.valv, &rd->argv[2]);
lj_record_idx(J, &ix);
/* Pass through table at J->base[0] as result. */
} /* else: Interpreter will throw. */
}
static void LJ_FASTCALL recff_rawequal(jit_State *J, RecordFFData *rd)
{
TRef tra = J->base[0];
TRef trb = J->base[1];
if (tra && trb) {
int diff = lj_record_objcmp(J, tra, trb, &rd->argv[0], &rd->argv[1]);
J->base[0] = diff ? TREF_FALSE : TREF_TRUE;
} /* else: Interpreter will throw. */
}
#if LJ_52
static void LJ_FASTCALL recff_rawlen(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
if (tref_isstr(tr))
J->base[0] = emitir(IRTI(IR_FLOAD), tr, IRFL_STR_LEN);
else if (tref_istab(tr))
J->base[0] = lj_ir_call(J, IRCALL_lj_tab_len, tr);
/* else: Interpreter will throw. */
UNUSED(rd);
}
#endif
/* Determine mode of select() call. */
int32_t lj_ffrecord_select_mode(jit_State *J, TRef tr, TValue *tv)
{
if (tref_isstr(tr) && *strVdata(tv) == '#') { /* select('#', ...) */
if (strV(tv)->len == 1) {
emitir(IRTG(IR_EQ, IRT_STR), tr, lj_ir_kstr(J, strV(tv)));
} else {
TRef trptr = emitir(IRT(IR_STRREF, IRT_P32), tr, lj_ir_kint(J, 0));
TRef trchar = emitir(IRT(IR_XLOAD, IRT_U8), trptr, IRXLOAD_READONLY);
emitir(IRTG(IR_EQ, IRT_INT), trchar, lj_ir_kint(J, '#'));
}
return 0;
} else { /* select(n, ...) */
int32_t start = argv2int(J, tv);
if (start == 0) lj_trace_err(J, LJ_TRERR_BADTYPE); /* A bit misleading. */
return start;
}
}
static void LJ_FASTCALL recff_select(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
if (tr) {
ptrdiff_t start = lj_ffrecord_select_mode(J, tr, &rd->argv[0]);
if (start == 0) { /* select('#', ...) */
J->base[0] = lj_ir_kint(J, J->maxslot - 1);
} else if (tref_isk(tr)) { /* select(k, ...) */
ptrdiff_t n = (ptrdiff_t)J->maxslot;
if (start < 0) start += n;
else if (start > n) start = n;
rd->nres = n - start;
if (start >= 1) {
ptrdiff_t i;
for (i = 0; i < n - start; i++)
J->base[i] = J->base[start+i];
} /* else: Interpreter will throw. */
} else {
recff_nyiu(J, rd);
return;
}
} /* else: Interpreter will throw. */
}
static void LJ_FASTCALL recff_tonumber(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
TRef base = J->base[1];
if (tr && !tref_isnil(base)) {
base = lj_opt_narrow_toint(J, base);
if (!tref_isk(base) || IR(tref_ref(base))->i != 10) {
recff_nyiu(J, rd);
return;
}
}
if (tref_isnumber_str(tr)) {
if (tref_isstr(tr)) {
TValue tmp;
if (!lj_strscan_num(strV(&rd->argv[0]), &tmp)) {
recff_nyiu(J, rd); /* Would need an inverted STRTO for this case. */
return;
}
tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0);
}
#if LJ_HASFFI
} else if (tref_iscdata(tr)) {
lj_crecord_tonumber(J, rd);
return;
#endif
} else {
tr = TREF_NIL;
}
J->base[0] = tr;
UNUSED(rd);
}
static TValue *recff_metacall_cp(lua_State *L, lua_CFunction dummy, void *ud)
{
jit_State *J = (jit_State *)ud;
lj_record_tailcall(J, 0, 1);
UNUSED(L); UNUSED(dummy);
return NULL;
}
static int recff_metacall(jit_State *J, RecordFFData *rd, MMS mm)
{
RecordIndex ix;
ix.tab = J->base[0];
copyTV(J->L, &ix.tabv, &rd->argv[0]);
if (lj_record_mm_lookup(J, &ix, mm)) { /* Has metamethod? */
int errcode;
TValue argv0;
/* Temporarily insert metamethod below object. */
J->base[1] = J->base[0];
J->base[0] = ix.mobj;
copyTV(J->L, &argv0, &rd->argv[0]);
copyTV(J->L, &rd->argv[1], &rd->argv[0]);
copyTV(J->L, &rd->argv[0], &ix.mobjv);
/* Need to protect lj_record_tailcall because it may throw. */
errcode = lj_vm_cpcall(J->L, NULL, J, recff_metacall_cp);
/* Always undo Lua stack changes to avoid confusing the interpreter. */
copyTV(J->L, &rd->argv[0], &argv0);
if (errcode)
lj_err_throw(J->L, errcode); /* Propagate errors. */
rd->nres = -1; /* Pending call. */
return 1; /* Tailcalled to metamethod. */
}
return 0;
}
static void LJ_FASTCALL recff_tostring(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
if (tref_isstr(tr)) {
/* Ignore __tostring in the string base metatable. */
/* Pass on result in J->base[0]. */
} else if (tr && !recff_metacall(J, rd, MM_tostring)) {
if (tref_isnumber(tr)) {
J->base[0] = emitir(IRT(IR_TOSTR, IRT_STR), tr,
tref_isnum(tr) ? IRTOSTR_NUM : IRTOSTR_INT);
} else if (tref_ispri(tr)) {
J->base[0] = lj_ir_kstr(J, lj_strfmt_obj(J->L, &rd->argv[0]));
} else {
recff_nyiu(J, rd);
return;
}
}
}
static void LJ_FASTCALL recff_ipairs_aux(jit_State *J, RecordFFData *rd)
{
RecordIndex ix;
ix.tab = J->base[0];
if (tref_istab(ix.tab)) {
if (!tvisnumber(&rd->argv[1])) /* No support for string coercion. */
lj_trace_err(J, LJ_TRERR_BADTYPE);
setintV(&ix.keyv, numberVint(&rd->argv[1])+1);
settabV(J->L, &ix.tabv, tabV(&rd->argv[0]));
ix.val = 0; ix.idxchain = 0;
ix.key = lj_opt_narrow_toint(J, J->base[1]);
J->base[0] = ix.key = emitir(IRTI(IR_ADD), ix.key, lj_ir_kint(J, 1));
J->base[1] = lj_record_idx(J, &ix);
rd->nres = tref_isnil(J->base[1]) ? 0 : 2;
} /* else: Interpreter will throw. */
}
static void LJ_FASTCALL recff_xpairs(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
if (!((LJ_52 || (LJ_HASFFI && tref_iscdata(tr))) &&
recff_metacall(J, rd, MM_pairs + rd->data))) {
if (tref_istab(tr)) {
J->base[0] = lj_ir_kfunc(J, funcV(&J->fn->c.upvalue[0]));
J->base[1] = tr;
J->base[2] = rd->data ? lj_ir_kint(J, 0) : TREF_NIL;
rd->nres = 3;
} /* else: Interpreter will throw. */
}
}
static void LJ_FASTCALL recff_pcall(jit_State *J, RecordFFData *rd)
{
if (J->maxslot >= 1) {
lj_record_call(J, 0, J->maxslot - 1);
rd->nres = -1; /* Pending call. */
} /* else: Interpreter will throw. */
}
static TValue *recff_xpcall_cp(lua_State *L, lua_CFunction dummy, void *ud)
{
jit_State *J = (jit_State *)ud;
lj_record_call(J, 1, J->maxslot - 2);
UNUSED(L); UNUSED(dummy);
return NULL;
}
static void LJ_FASTCALL recff_xpcall(jit_State *J, RecordFFData *rd)
{
if (J->maxslot >= 2) {
TValue argv0, argv1;
TRef tmp;
int errcode;
lua_assert(!LJ_FR2); /* TODO_FR2: handle different frame setup. */
/* Swap function and traceback. */
tmp = J->base[0]; J->base[0] = J->base[1]; J->base[1] = tmp;
copyTV(J->L, &argv0, &rd->argv[0]);
copyTV(J->L, &argv1, &rd->argv[1]);
copyTV(J->L, &rd->argv[0], &argv1);
copyTV(J->L, &rd->argv[1], &argv0);
/* Need to protect lj_record_call because it may throw. */
errcode = lj_vm_cpcall(J->L, NULL, J, recff_xpcall_cp);
/* Always undo Lua stack swap to avoid confusing the interpreter. */
copyTV(J->L, &rd->argv[0], &argv0);
copyTV(J->L, &rd->argv[1], &argv1);
if (errcode)
lj_err_throw(J->L, errcode); /* Propagate errors. */
rd->nres = -1; /* Pending call. */
} /* else: Interpreter will throw. */
}
static void LJ_FASTCALL recff_getfenv(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
/* Only support getfenv(0) for now. */
if (tref_isint(tr) && tref_isk(tr) && IR(tref_ref(tr))->i == 0) {
TRef trl = emitir(IRT(IR_LREF, IRT_THREAD), 0, 0);
J->base[0] = emitir(IRT(IR_FLOAD, IRT_TAB), trl, IRFL_THREAD_ENV);
return;
}
recff_nyiu(J, rd);
}
/* -- Math library fast functions ----------------------------------------- */
static void LJ_FASTCALL recff_math_abs(jit_State *J, RecordFFData *rd)
{
TRef tr = lj_ir_tonum(J, J->base[0]);
J->base[0] = emitir(IRTN(IR_ABS), tr, lj_ir_knum_abs(J));
UNUSED(rd);
}
/* Record rounding functions math.floor and math.ceil. */
static void LJ_FASTCALL recff_math_round(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
if (!tref_isinteger(tr)) { /* Pass through integers unmodified. */
tr = emitir(IRTN(IR_FPMATH), lj_ir_tonum(J, tr), rd->data);
/* Result is integral (or NaN/Inf), but may not fit an int32_t. */
if (LJ_DUALNUM) { /* Try to narrow using a guarded conversion to int. */
lua_Number n = lj_vm_foldfpm(numberVnum(&rd->argv[0]), rd->data);
if (n == (lua_Number)lj_num2int(n))
tr = emitir(IRTGI(IR_CONV), tr, IRCONV_INT_NUM|IRCONV_CHECK);
}
J->base[0] = tr;
}
}
/* Record unary math.* functions, mapped to IR_FPMATH opcode. */
static void LJ_FASTCALL recff_math_unary(jit_State *J, RecordFFData *rd)
{
J->base[0] = emitir(IRTN(IR_FPMATH), lj_ir_tonum(J, J->base[0]), rd->data);
}
/* Record math.log. */
static void LJ_FASTCALL recff_math_log(jit_State *J, RecordFFData *rd)
{
TRef tr = lj_ir_tonum(J, J->base[0]);
if (J->base[1]) {
#ifdef LUAJIT_NO_LOG2
uint32_t fpm = IRFPM_LOG;
#else
uint32_t fpm = IRFPM_LOG2;
#endif
TRef trb = lj_ir_tonum(J, J->base[1]);
tr = emitir(IRTN(IR_FPMATH), tr, fpm);
trb = emitir(IRTN(IR_FPMATH), trb, fpm);
trb = emitir(IRTN(IR_DIV), lj_ir_knum_one(J), trb);
tr = emitir(IRTN(IR_MUL), tr, trb);
} else {
tr = emitir(IRTN(IR_FPMATH), tr, IRFPM_LOG);
}
J->base[0] = tr;
UNUSED(rd);
}
/* Record math.atan2. */
static void LJ_FASTCALL recff_math_atan2(jit_State *J, RecordFFData *rd)
{
TRef tr = lj_ir_tonum(J, J->base[0]);
TRef tr2 = lj_ir_tonum(J, J->base[1]);
J->base[0] = emitir(IRTN(IR_ATAN2), tr, tr2);
UNUSED(rd);
}
/* Record math.ldexp. */
static void LJ_FASTCALL recff_math_ldexp(jit_State *J, RecordFFData *rd)
{
TRef tr = lj_ir_tonum(J, J->base[0]);
#if LJ_TARGET_X86ORX64
TRef tr2 = lj_ir_tonum(J, J->base[1]);
#else
TRef tr2 = lj_opt_narrow_toint(J, J->base[1]);
#endif
J->base[0] = emitir(IRTN(IR_LDEXP), tr, tr2);
UNUSED(rd);
}
/* Record math.asin, math.acos, math.atan. */
static void LJ_FASTCALL recff_math_atrig(jit_State *J, RecordFFData *rd)
{
TRef y = lj_ir_tonum(J, J->base[0]);
TRef x = lj_ir_knum_one(J);
uint32_t ffid = rd->data;
if (ffid != FF_math_atan) {
TRef tmp = emitir(IRTN(IR_MUL), y, y);
tmp = emitir(IRTN(IR_SUB), x, tmp);
tmp = emitir(IRTN(IR_FPMATH), tmp, IRFPM_SQRT);
if (ffid == FF_math_asin) { x = tmp; } else { x = y; y = tmp; }
}
J->base[0] = emitir(IRTN(IR_ATAN2), y, x);
}
static void LJ_FASTCALL recff_math_htrig(jit_State *J, RecordFFData *rd)
{
TRef tr = lj_ir_tonum(J, J->base[0]);
J->base[0] = emitir(IRTN(IR_CALLN), tr, rd->data);
}
static void LJ_FASTCALL recff_math_modf(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
if (tref_isinteger(tr)) {
J->base[0] = tr;
J->base[1] = lj_ir_kint(J, 0);
} else {
TRef trt;
tr = lj_ir_tonum(J, tr);
trt = emitir(IRTN(IR_FPMATH), tr, IRFPM_TRUNC);
J->base[0] = trt;
J->base[1] = emitir(IRTN(IR_SUB), tr, trt);
}
rd->nres = 2;
}
static void LJ_FASTCALL recff_math_pow(jit_State *J, RecordFFData *rd)
{
TRef tr = lj_ir_tonum(J, J->base[0]);
if (!tref_isnumber_str(J->base[1]))
lj_trace_err(J, LJ_TRERR_BADTYPE);
J->base[0] = lj_opt_narrow_pow(J, tr, J->base[1], &rd->argv[1]);
UNUSED(rd);
}
static void LJ_FASTCALL recff_math_minmax(jit_State *J, RecordFFData *rd)
{
TRef tr = lj_ir_tonumber(J, J->base[0]);
uint32_t op = rd->data;
BCReg i;
for (i = 1; J->base[i] != 0; i++) {
TRef tr2 = lj_ir_tonumber(J, J->base[i]);
IRType t = IRT_INT;
if (!(tref_isinteger(tr) && tref_isinteger(tr2))) {
if (tref_isinteger(tr)) tr = emitir(IRTN(IR_CONV), tr, IRCONV_NUM_INT);
if (tref_isinteger(tr2)) tr2 = emitir(IRTN(IR_CONV), tr2, IRCONV_NUM_INT);
t = IRT_NUM;
}
tr = emitir(IRT(op, t), tr, tr2);
}
J->base[0] = tr;
}
static void LJ_FASTCALL recff_math_random(jit_State *J, RecordFFData *rd)
{
GCudata *ud = udataV(&J->fn->c.upvalue[0]);
TRef tr, one;
lj_ir_kgc(J, obj2gco(ud), IRT_UDATA); /* Prevent collection. */
tr = lj_ir_call(J, IRCALL_lj_math_random_step, lj_ir_kptr(J, uddata(ud)));
one = lj_ir_knum_one(J);
tr = emitir(IRTN(IR_SUB), tr, one);
if (J->base[0]) {
TRef tr1 = lj_ir_tonum(J, J->base[0]);
if (J->base[1]) { /* d = floor(d*(r2-r1+1.0)) + r1 */
TRef tr2 = lj_ir_tonum(J, J->base[1]);
tr2 = emitir(IRTN(IR_SUB), tr2, tr1);
tr2 = emitir(IRTN(IR_ADD), tr2, one);
tr = emitir(IRTN(IR_MUL), tr, tr2);
tr = emitir(IRTN(IR_FPMATH), tr, IRFPM_FLOOR);
tr = emitir(IRTN(IR_ADD), tr, tr1);
} else { /* d = floor(d*r1) + 1.0 */
tr = emitir(IRTN(IR_MUL), tr, tr1);
tr = emitir(IRTN(IR_FPMATH), tr, IRFPM_FLOOR);
tr = emitir(IRTN(IR_ADD), tr, one);
}
}
J->base[0] = tr;
UNUSED(rd);
}
/* -- Bit library fast functions ------------------------------------------ */
/* Record bit.tobit. */
static void LJ_FASTCALL recff_bit_tobit(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
#if LJ_HASFFI
if (tref_iscdata(tr)) { recff_bit64_tobit(J, rd); return; }
#endif
J->base[0] = lj_opt_narrow_tobit(J, tr);
UNUSED(rd);
}
/* Record unary bit.bnot, bit.bswap. */
static void LJ_FASTCALL recff_bit_unary(jit_State *J, RecordFFData *rd)
{
#if LJ_HASFFI
if (recff_bit64_unary(J, rd))
return;
#endif
J->base[0] = emitir(IRTI(rd->data), lj_opt_narrow_tobit(J, J->base[0]), 0);
}
/* Record N-ary bit.band, bit.bor, bit.bxor. */
static void LJ_FASTCALL recff_bit_nary(jit_State *J, RecordFFData *rd)
{
#if LJ_HASFFI
if (recff_bit64_nary(J, rd))
return;
#endif
{
TRef tr = lj_opt_narrow_tobit(J, J->base[0]);
uint32_t ot = IRTI(rd->data);
BCReg i;
for (i = 1; J->base[i] != 0; i++)
tr = emitir(ot, tr, lj_opt_narrow_tobit(J, J->base[i]));
J->base[0] = tr;
}
}
/* Record bit shifts. */
static void LJ_FASTCALL recff_bit_shift(jit_State *J, RecordFFData *rd)
{
#if LJ_HASFFI
if (recff_bit64_shift(J, rd))
return;
#endif
{
TRef tr = lj_opt_narrow_tobit(J, J->base[0]);
TRef tsh = lj_opt_narrow_tobit(J, J->base[1]);
IROp op = (IROp)rd->data;
if (!(op < IR_BROL ? LJ_TARGET_MASKSHIFT : LJ_TARGET_MASKROT) &&
!tref_isk(tsh))
tsh = emitir(IRTI(IR_BAND), tsh, lj_ir_kint(J, 31));
#ifdef LJ_TARGET_UNIFYROT
if (op == (LJ_TARGET_UNIFYROT == 1 ? IR_BROR : IR_BROL)) {
op = LJ_TARGET_UNIFYROT == 1 ? IR_BROL : IR_BROR;
tsh = emitir(IRTI(IR_NEG), tsh, tsh);
}
#endif
J->base[0] = emitir(IRTI(op), tr, tsh);
}
}
static void LJ_FASTCALL recff_bit_tohex(jit_State *J, RecordFFData *rd)
{
#if LJ_HASFFI
TRef hdr = recff_bufhdr(J);
TRef tr = recff_bit64_tohex(J, rd, hdr);
J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
#else
recff_nyiu(J, rd); /* Don't bother working around this NYI. */
#endif
}
/* -- String library fast functions --------------------------------------- */
/* Specialize to relative starting position for string. */
static TRef recff_string_start(jit_State *J, GCstr *s, int32_t *st, TRef tr,
TRef trlen, TRef tr0)
{
int32_t start = *st;
if (start < 0) {
emitir(IRTGI(IR_LT), tr, tr0);
tr = emitir(IRTI(IR_ADD), trlen, tr);
start = start + (int32_t)s->len;
emitir(start < 0 ? IRTGI(IR_LT) : IRTGI(IR_GE), tr, tr0);
if (start < 0) {
tr = tr0;
start = 0;
}
} else if (start == 0) {
emitir(IRTGI(IR_EQ), tr, tr0);
tr = tr0;
} else {
tr = emitir(IRTI(IR_ADD), tr, lj_ir_kint(J, -1));
emitir(IRTGI(IR_GE), tr, tr0);
start--;
}
*st = start;
return tr;
}
/* Handle string.byte (rd->data = 0) and string.sub (rd->data = 1). */
static void LJ_FASTCALL recff_string_range(jit_State *J, RecordFFData *rd)
{
TRef trstr = lj_ir_tostr(J, J->base[0]);
TRef trlen = emitir(IRTI(IR_FLOAD), trstr, IRFL_STR_LEN);
TRef tr0 = lj_ir_kint(J, 0);
TRef trstart, trend;
GCstr *str = argv2str(J, &rd->argv[0]);
int32_t start, end;
if (rd->data) { /* string.sub(str, start [,end]) */
start = argv2int(J, &rd->argv[1]);
trstart = lj_opt_narrow_toint(J, J->base[1]);
trend = J->base[2];
if (tref_isnil(trend)) {
trend = lj_ir_kint(J, -1);
end = -1;
} else {
trend = lj_opt_narrow_toint(J, trend);
end = argv2int(J, &rd->argv[2]);
}
} else { /* string.byte(str, [,start [,end]]) */
if (tref_isnil(J->base[1])) {
start = 1;
trstart = lj_ir_kint(J, 1);
} else {
start = argv2int(J, &rd->argv[1]);
trstart = lj_opt_narrow_toint(J, J->base[1]);
}
if (J->base[1] && !tref_isnil(J->base[2])) {
trend = lj_opt_narrow_toint(J, J->base[2]);
end = argv2int(J, &rd->argv[2]);
} else {
trend = trstart;
end = start;
}
}
if (end < 0) {
emitir(IRTGI(IR_LT), trend, tr0);
trend = emitir(IRTI(IR_ADD), emitir(IRTI(IR_ADD), trlen, trend),
lj_ir_kint(J, 1));
end = end+(int32_t)str->len+1;
} else if ((MSize)end <= str->len) {
emitir(IRTGI(IR_ULE), trend, trlen);
} else {
emitir(IRTGI(IR_UGT), trend, trlen);
end = (int32_t)str->len;
trend = trlen;
}
trstart = recff_string_start(J, str, &start, trstart, trlen, tr0);
if (rd->data) { /* Return string.sub result. */
if (end - start >= 0) {
/* Also handle empty range here, to avoid extra traces. */
TRef trptr, trslen = emitir(IRTI(IR_SUB), trend, trstart);
emitir(IRTGI(IR_GE), trslen, tr0);
trptr = emitir(IRT(IR_STRREF, IRT_P32), trstr, trstart);
J->base[0] = emitir(IRT(IR_SNEW, IRT_STR), trptr, trslen);
} else { /* Range underflow: return empty string. */
emitir(IRTGI(IR_LT), trend, trstart);
J->base[0] = lj_ir_kstr(J, &J2G(J)->strempty);
}
} else { /* Return string.byte result(s). */
ptrdiff_t i, len = end - start;
if (len > 0) {
TRef trslen = emitir(IRTI(IR_SUB), trend, trstart);
emitir(IRTGI(IR_EQ), trslen, lj_ir_kint(J, (int32_t)len));
if (J->baseslot + len > LJ_MAX_JSLOTS)
lj_trace_err_info(J, LJ_TRERR_STACKOV);
rd->nres = len;
for (i = 0; i < len; i++) {
TRef tmp = emitir(IRTI(IR_ADD), trstart, lj_ir_kint(J, (int32_t)i));
tmp = emitir(IRT(IR_STRREF, IRT_P32), trstr, tmp);
J->base[i] = emitir(IRT(IR_XLOAD, IRT_U8), tmp, IRXLOAD_READONLY);
}
} else { /* Empty range or range underflow: return no results. */
emitir(IRTGI(IR_LE), trend, trstart);
rd->nres = 0;
}
}
}
static void LJ_FASTCALL recff_string_char(jit_State *J, RecordFFData *rd)
{
TRef k255 = lj_ir_kint(J, 255);
BCReg i;
for (i = 0; J->base[i] != 0; i++) { /* Convert char values to strings. */
TRef tr = lj_opt_narrow_toint(J, J->base[i]);
emitir(IRTGI(IR_ULE), tr, k255);
J->base[i] = emitir(IRT(IR_TOSTR, IRT_STR), tr, IRTOSTR_CHAR);
}
if (i > 1) { /* Concatenate the strings, if there's more than one. */
TRef hdr = recff_bufhdr(J), tr = hdr;
for (i = 0; J->base[i] != 0; i++)
tr = emitir(IRT(IR_BUFPUT, IRT_P32), tr, J->base[i]);
J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
}
UNUSED(rd);
}
static void LJ_FASTCALL recff_string_rep(jit_State *J, RecordFFData *rd)
{
TRef str = lj_ir_tostr(J, J->base[0]);
TRef rep = lj_opt_narrow_toint(J, J->base[1]);
TRef hdr, tr, str2 = 0;
if (!tref_isnil(J->base[2])) {
TRef sep = lj_ir_tostr(J, J->base[2]);
int32_t vrep = argv2int(J, &rd->argv[1]);
emitir(IRTGI(vrep > 1 ? IR_GT : IR_LE), rep, lj_ir_kint(J, 1));
if (vrep > 1) {
TRef hdr2 = recff_bufhdr(J);
TRef tr2 = emitir(IRT(IR_BUFPUT, IRT_P32), hdr2, sep);
tr2 = emitir(IRT(IR_BUFPUT, IRT_P32), tr2, str);
str2 = emitir(IRT(IR_BUFSTR, IRT_STR), tr2, hdr2);
}
}
tr = hdr = recff_bufhdr(J);
if (str2) {
tr = emitir(IRT(IR_BUFPUT, IRT_P32), tr, str);
str = str2;
rep = emitir(IRTI(IR_ADD), rep, lj_ir_kint(J, -1));
}
tr = lj_ir_call(J, IRCALL_lj_buf_putstr_rep, tr, str, rep);
J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
}
static void LJ_FASTCALL recff_string_op(jit_State *J, RecordFFData *rd)
{
TRef str = lj_ir_tostr(J, J->base[0]);
TRef hdr = recff_bufhdr(J);
TRef tr = lj_ir_call(J, rd->data, hdr, str);
J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
}
static void LJ_FASTCALL recff_string_find(jit_State *J, RecordFFData *rd)
{
TRef trstr = lj_ir_tostr(J, J->base[0]);
TRef trpat = lj_ir_tostr(J, J->base[1]);
TRef trlen = emitir(IRTI(IR_FLOAD), trstr, IRFL_STR_LEN);
TRef tr0 = lj_ir_kint(J, 0);
TRef trstart;
GCstr *str = argv2str(J, &rd->argv[0]);
GCstr *pat = argv2str(J, &rd->argv[1]);
int32_t start;
J->needsnap = 1;
if (tref_isnil(J->base[2])) {
trstart = lj_ir_kint(J, 1);
start = 1;
} else {
trstart = lj_opt_narrow_toint(J, J->base[2]);
start = argv2int(J, &rd->argv[2]);
}
trstart = recff_string_start(J, str, &start, trstart, trlen, tr0);
if ((MSize)start <= str->len) {
emitir(IRTGI(IR_ULE), trstart, trlen);
} else {
emitir(IRTGI(IR_UGT), trstart, trlen);
#if LJ_52
J->base[0] = TREF_NIL;
return;
#else
trstart = trlen;
start = str->len;
#endif
}
/* Fixed arg or no pattern matching chars? (Specialized to pattern string.) */
if ((J->base[2] && tref_istruecond(J->base[3])) ||
(emitir(IRTG(IR_EQ, IRT_STR), trpat, lj_ir_kstr(J, pat)),
!lj_str_haspattern(pat))) { /* Search for fixed string. */
TRef trsptr = emitir(IRT(IR_STRREF, IRT_P32), trstr, trstart);
TRef trpptr = emitir(IRT(IR_STRREF, IRT_P32), trpat, tr0);
TRef trslen = emitir(IRTI(IR_SUB), trlen, trstart);
TRef trplen = emitir(IRTI(IR_FLOAD), trpat, IRFL_STR_LEN);
TRef tr = lj_ir_call(J, IRCALL_lj_str_find, trsptr, trpptr, trslen, trplen);
TRef trp0 = lj_ir_kkptr(J, NULL);
if (lj_str_find(strdata(str)+(MSize)start, strdata(pat),
str->len-(MSize)start, pat->len)) {
TRef pos;
emitir(IRTG(IR_NE, IRT_P32), tr, trp0);
pos = emitir(IRTI(IR_SUB), tr, emitir(IRT(IR_STRREF, IRT_P32), trstr, tr0));
J->base[0] = emitir(IRTI(IR_ADD), pos, lj_ir_kint(J, 1));
J->base[1] = emitir(IRTI(IR_ADD), pos, trplen);
rd->nres = 2;
} else {
emitir(IRTG(IR_EQ, IRT_P32), tr, trp0);
J->base[0] = TREF_NIL;
}
} else { /* Search for pattern. */
recff_nyiu(J, rd);
return;
}
}
static void LJ_FASTCALL recff_string_format(jit_State *J, RecordFFData *rd)
{
TRef trfmt = lj_ir_tostr(J, J->base[0]);
GCstr *fmt = argv2str(J, &rd->argv[0]);
int arg = 1;
TRef hdr, tr;
FormatState fs;
SFormat sf;
/* Specialize to the format string. */
emitir(IRTG(IR_EQ, IRT_STR), trfmt, lj_ir_kstr(J, fmt));
tr = hdr = recff_bufhdr(J);
lj_strfmt_init(&fs, strdata(fmt), fmt->len);
while ((sf = lj_strfmt_parse(&fs)) != STRFMT_EOF) { /* Parse format. */
TRef tra = sf == STRFMT_LIT ? 0 : J->base[arg++];
TRef trsf = lj_ir_kint(J, (int32_t)sf);
IRCallID id;
switch (STRFMT_TYPE(sf)) {
case STRFMT_LIT:
tr = emitir(IRT(IR_BUFPUT, IRT_P32), tr,
lj_ir_kstr(J, lj_str_new(J->L, fs.str, fs.len)));
break;
case STRFMT_INT:
id = IRCALL_lj_strfmt_putfnum_int;
handle_int:
if (!tref_isinteger(tra))
goto handle_num;
if (sf == STRFMT_INT) { /* Shortcut for plain %d. */
tr = emitir(IRT(IR_BUFPUT, IRT_P32), tr,
emitir(IRT(IR_TOSTR, IRT_STR), tra, IRTOSTR_INT));
} else {
#if LJ_HASFFI
tra = emitir(IRT(IR_CONV, IRT_U64), tra,
(IRT_INT|(IRT_U64<<5)|IRCONV_SEXT));
tr = lj_ir_call(J, IRCALL_lj_strfmt_putfxint, tr, trsf, tra);
lj_needsplit(J);
#else
recff_nyiu(J, rd); /* Don't bother working around this NYI. */
return;
#endif
}
break;
case STRFMT_UINT:
id = IRCALL_lj_strfmt_putfnum_uint;
goto handle_int;
case STRFMT_NUM:
id = IRCALL_lj_strfmt_putfnum;
handle_num:
tra = lj_ir_tonum(J, tra);
tr = lj_ir_call(J, id, tr, trsf, tra);
if (LJ_SOFTFP) lj_needsplit(J);
break;
case STRFMT_STR:
if (!tref_isstr(tra)) {
recff_nyiu(J, rd); /* NYI: __tostring and non-string types for %s. */
return;
}
if (sf == STRFMT_STR) /* Shortcut for plain %s. */
tr = emitir(IRT(IR_BUFPUT, IRT_P32), tr, tra);
else if ((sf & STRFMT_T_QUOTED))
tr = lj_ir_call(J, IRCALL_lj_strfmt_putquoted, tr, tra);
else
tr = lj_ir_call(J, IRCALL_lj_strfmt_putfstr, tr, trsf, tra);
break;
case STRFMT_CHAR:
tra = lj_opt_narrow_toint(J, tra);
if (sf == STRFMT_CHAR) /* Shortcut for plain %c. */
tr = emitir(IRT(IR_BUFPUT, IRT_P32), tr,
emitir(IRT(IR_TOSTR, IRT_STR), tra, IRTOSTR_CHAR));
else
tr = lj_ir_call(J, IRCALL_lj_strfmt_putfchar, tr, trsf, tra);
break;
case STRFMT_PTR: /* NYI */
case STRFMT_ERR:
default:
recff_nyiu(J, rd);
return;
}
}
J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
}
/* -- Table library fast functions ---------------------------------------- */
static void LJ_FASTCALL recff_table_insert(jit_State *J, RecordFFData *rd)
{
RecordIndex ix;
ix.tab = J->base[0];
ix.val = J->base[1];
rd->nres = 0;
if (tref_istab(ix.tab) && ix.val) {
if (!J->base[2]) { /* Simple push: t[#t+1] = v */
TRef trlen = lj_ir_call(J, IRCALL_lj_tab_len, ix.tab);
GCtab *t = tabV(&rd->argv[0]);
ix.key = emitir(IRTI(IR_ADD), trlen, lj_ir_kint(J, 1));
settabV(J->L, &ix.tabv, t);
setintV(&ix.keyv, lj_tab_len(t) + 1);
ix.idxchain = 0;
lj_record_idx(J, &ix); /* Set new value. */
} else { /* Complex case: insert in the middle. */
recff_nyiu(J, rd);
return;
}
} /* else: Interpreter will throw. */
}
static void LJ_FASTCALL recff_table_concat(jit_State *J, RecordFFData *rd)
{
TRef tab = J->base[0];
if (tref_istab(tab)) {
TRef sep = !tref_isnil(J->base[1]) ?
lj_ir_tostr(J, J->base[1]) : lj_ir_knull(J, IRT_STR);
TRef tri = (J->base[1] && !tref_isnil(J->base[2])) ?
lj_opt_narrow_toint(J, J->base[2]) : lj_ir_kint(J, 1);
TRef tre = (J->base[1] && J->base[2] && !tref_isnil(J->base[3])) ?
lj_opt_narrow_toint(J, J->base[3]) :
lj_ir_call(J, IRCALL_lj_tab_len, tab);
TRef hdr = recff_bufhdr(J);
TRef tr = lj_ir_call(J, IRCALL_lj_buf_puttab, hdr, tab, sep, tri, tre);
emitir(IRTG(IR_NE, IRT_PTR), tr, lj_ir_kptr(J, NULL));
J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
} /* else: Interpreter will throw. */
UNUSED(rd);
}
static void LJ_FASTCALL recff_table_new(jit_State *J, RecordFFData *rd)
{
TRef tra = lj_opt_narrow_toint(J, J->base[0]);
TRef trh = lj_opt_narrow_toint(J, J->base[1]);
J->base[0] = lj_ir_call(J, IRCALL_lj_tab_new_ah, tra, trh);
UNUSED(rd);
}
static void LJ_FASTCALL recff_table_clear(jit_State *J, RecordFFData *rd)
{
TRef tr = J->base[0];
if (tref_istab(tr)) {
rd->nres = 0;
lj_ir_call(J, IRCALL_lj_tab_clear, tr);
J->needsnap = 1;
} /* else: Interpreter will throw. */
}
/* -- I/O library fast functions ------------------------------------------ */
/* Get FILE* for I/O function. Any I/O error aborts recording, so there's
** no need to encode the alternate cases for any of the guards.
*/
static TRef recff_io_fp(jit_State *J, TRef *udp, int32_t id)
{
TRef tr, ud, fp;
if (id) { /* io.func() */
tr = lj_ir_kptr(J, &J2G(J)->gcroot[id]);
ud = emitir(IRT(IR_XLOAD, IRT_UDATA), tr, 0);
} else { /* fp:method() */
ud = J->base[0];
if (!tref_isudata(ud))
lj_trace_err(J, LJ_TRERR_BADTYPE);
tr = emitir(IRT(IR_FLOAD, IRT_U8), ud, IRFL_UDATA_UDTYPE);
emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, UDTYPE_IO_FILE));
}
*udp = ud;
fp = emitir(IRT(IR_FLOAD, IRT_PTR), ud, IRFL_UDATA_FILE);
emitir(IRTG(IR_NE, IRT_PTR), fp, lj_ir_knull(J, IRT_PTR));
return fp;
}
static void LJ_FASTCALL recff_io_write(jit_State *J, RecordFFData *rd)
{
TRef ud, fp = recff_io_fp(J, &ud, rd->data);
TRef zero = lj_ir_kint(J, 0);
TRef one = lj_ir_kint(J, 1);
ptrdiff_t i = rd->data == 0 ? 1 : 0;
for (; J->base[i]; i++) {
TRef str = lj_ir_tostr(J, J->base[i]);
TRef buf = emitir(IRT(IR_STRREF, IRT_P32), str, zero);
TRef len = emitir(IRTI(IR_FLOAD), str, IRFL_STR_LEN);
if (tref_isk(len) && IR(tref_ref(len))->i == 1) {
IRIns *irs = IR(tref_ref(str));
TRef tr = (irs->o == IR_TOSTR && irs->op2 == IRTOSTR_CHAR) ?
irs->op1 :
emitir(IRT(IR_XLOAD, IRT_U8), buf, IRXLOAD_READONLY);
tr = lj_ir_call(J, IRCALL_fputc, tr, fp);
if (results_wanted(J) != 0) /* Check result only if not ignored. */
emitir(IRTGI(IR_NE), tr, lj_ir_kint(J, -1));
} else {
TRef tr = lj_ir_call(J, IRCALL_fwrite, buf, one, len, fp);
if (results_wanted(J) != 0) /* Check result only if not ignored. */
emitir(IRTGI(IR_EQ), tr, len);
}
}
J->base[0] = LJ_52 ? ud : TREF_TRUE;
}
static void LJ_FASTCALL recff_io_flush(jit_State *J, RecordFFData *rd)
{
TRef ud, fp = recff_io_fp(J, &ud, rd->data);
TRef tr = lj_ir_call(J, IRCALL_fflush, fp);
if (results_wanted(J) != 0) /* Check result only if not ignored. */
emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, 0));
J->base[0] = TREF_TRUE;
}
/* -- Debug library fast functions ---------------------------------------- */
static void LJ_FASTCALL recff_debug_getmetatable(jit_State *J, RecordFFData *rd)
{
GCtab *mt;
TRef mtref;
TRef tr = J->base[0];
if (tref_istab(tr)) {
mt = tabref(tabV(&rd->argv[0])->metatable);
mtref = emitir(IRT(IR_FLOAD, IRT_TAB), tr, IRFL_TAB_META);
} else if (tref_isudata(tr)) {
mt = tabref(udataV(&rd->argv[0])->metatable);
mtref = emitir(IRT(IR_FLOAD, IRT_TAB), tr, IRFL_UDATA_META);
} else {
mt = tabref(basemt_obj(J2G(J), &rd->argv[0]));
J->base[0] = mt ? lj_ir_ktab(J, mt) : TREF_NIL;
return;
}
emitir(IRTG(mt ? IR_NE : IR_EQ, IRT_TAB), mtref, lj_ir_knull(J, IRT_TAB));
J->base[0] = mt ? mtref : TREF_NIL;
}
/* -- Record calls to fast functions -------------------------------------- */
#include "lj_recdef.h"
static uint32_t recdef_lookup(GCfunc *fn)
{
if (fn->c.ffid < sizeof(recff_idmap)/sizeof(recff_idmap[0]))
return recff_idmap[fn->c.ffid];
else
return 0;
}
/* Record entry to a fast function or C function. */
void lj_ffrecord_func(jit_State *J)
{
RecordFFData rd;
uint32_t m = recdef_lookup(J->fn);
rd.data = m & 0xff;
rd.nres = 1; /* Default is one result. */
rd.argv = J->L->base;
J->base[J->maxslot] = 0; /* Mark end of arguments. */
(recff_func[m >> 8])(J, &rd); /* Call recff_* handler. */
if (rd.nres >= 0) {
if (J->postproc == LJ_POST_NONE) J->postproc = LJ_POST_FFRETRY;
lj_record_ret(J, 0, rd.nres);
}
}
#undef IR
#undef emitir
#endif
| xLua/build/luajit-2.1.0b2/src/lj_ffrecord.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_ffrecord.c",
"repo_id": "xLua",
"token_count": 18716
} | 1,896 |
/*
** ARM64 instruction emitter.
** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
**
** Contributed by Djordje Kovacevic and Stefan Pejic from RT-RK.com.
** Sponsored by Cisco Systems, Inc.
*/
/* -- Constant encoding --------------------------------------------------- */
static uint64_t get_k64val(ASMState *as, IRRef ref)
{
IRIns *ir = IR(ref);
if (ir->o == IR_KINT64) {
return ir_kint64(ir)->u64;
} else if (ir->o == IR_KGC) {
return (uint64_t)ir_kgc(ir);
} else if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
return (uint64_t)ir_kptr(ir);
} else {
lj_assertA(ir->o == IR_KINT || ir->o == IR_KNULL,
"bad 64 bit const IR op %d", ir->o);
return ir->i; /* Sign-extended. */
}
}
/* Encode constant in K12 format for data processing instructions. */
static uint32_t emit_isk12(int64_t n)
{
uint64_t k = (n < 0) ? -n : n;
uint32_t m = (n < 0) ? 0x40000000 : 0;
if (k < 0x1000) {
return A64I_K12|m|A64F_U12(k);
} else if ((k & 0xfff000) == k) {
return A64I_K12|m|0x400000|A64F_U12(k>>12);
}
return 0;
}
#define emit_clz64(n) __builtin_clzll(n)
#define emit_ctz64(n) __builtin_ctzll(n)
/* Encode constant in K13 format for logical data processing instructions. */
static uint32_t emit_isk13(uint64_t n, int is64)
{
int inv = 0, w = 128, lz, tz;
if (n & 1) { n = ~n; w = 64; inv = 1; } /* Avoid wrap-around of ones. */
if (!n) return 0; /* Neither all-zero nor all-ones are allowed. */
do { /* Find the repeat width. */
if (is64 && (uint32_t)(n^(n>>32))) break;
n = (uint32_t)n;
if (!n) return 0; /* Ditto when passing n=0xffffffff and is64=0. */
w = 32; if ((n^(n>>16)) & 0xffff) break;
n = n & 0xffff; w = 16; if ((n^(n>>8)) & 0xff) break;
n = n & 0xff; w = 8; if ((n^(n>>4)) & 0xf) break;
n = n & 0xf; w = 4; if ((n^(n>>2)) & 0x3) break;
n = n & 0x3; w = 2;
} while (0);
lz = emit_clz64(n);
tz = emit_ctz64(n);
if ((int64_t)(n << lz) >> (lz+tz) != -1ll) return 0; /* Non-contiguous? */
if (inv)
return A64I_K13 | (((lz-w) & 127) << 16) | (((lz+tz-w-1) & 63) << 10);
else
return A64I_K13 | ((w-tz) << 16) | (((63-lz-tz-w-w) & 63) << 10);
}
static uint32_t emit_isfpk64(uint64_t n)
{
uint64_t etop9 = ((n >> 54) & 0x1ff);
if ((n << 16) == 0 && (etop9 == 0x100 || etop9 == 0x0ff)) {
return (uint32_t)(((n >> 48) & 0x7f) | ((n >> 56) & 0x80));
}
return ~0u;
}
/* -- Emit basic instructions --------------------------------------------- */
static void emit_dnma(ASMState *as, A64Ins ai, Reg rd, Reg rn, Reg rm, Reg ra)
{
*--as->mcp = ai | A64F_D(rd) | A64F_N(rn) | A64F_M(rm) | A64F_A(ra);
}
static void emit_dnm(ASMState *as, A64Ins ai, Reg rd, Reg rn, Reg rm)
{
*--as->mcp = ai | A64F_D(rd) | A64F_N(rn) | A64F_M(rm);
}
static void emit_dm(ASMState *as, A64Ins ai, Reg rd, Reg rm)
{
*--as->mcp = ai | A64F_D(rd) | A64F_M(rm);
}
static void emit_dn(ASMState *as, A64Ins ai, Reg rd, Reg rn)
{
*--as->mcp = ai | A64F_D(rd) | A64F_N(rn);
}
static void emit_nm(ASMState *as, A64Ins ai, Reg rn, Reg rm)
{
*--as->mcp = ai | A64F_N(rn) | A64F_M(rm);
}
static void emit_d(ASMState *as, A64Ins ai, Reg rd)
{
*--as->mcp = ai | A64F_D(rd);
}
static void emit_n(ASMState *as, A64Ins ai, Reg rn)
{
*--as->mcp = ai | A64F_N(rn);
}
static int emit_checkofs(A64Ins ai, int64_t ofs)
{
int scale = (ai >> 30) & 3;
if (ofs < 0 || (ofs & ((1<<scale)-1))) {
return (ofs >= -256 && ofs <= 255) ? -1 : 0;
} else {
return (ofs < (4096<<scale)) ? 1 : 0;
}
}
static void emit_lso(ASMState *as, A64Ins ai, Reg rd, Reg rn, int64_t ofs)
{
int ot = emit_checkofs(ai, ofs), sc = (ai >> 30) & 3;
lj_assertA(ot, "load/store offset %d out of range", ofs);
/* Combine LDR/STR pairs to LDP/STP. */
if ((sc == 2 || sc == 3) &&
(!(ai & 0x400000) || rd != rn) &&
as->mcp != as->mcloop) {
uint32_t prev = *as->mcp & ~A64F_D(31);
int ofsm = ofs - (1<<sc), ofsp = ofs + (1<<sc);
A64Ins aip;
if (prev == (ai | A64F_N(rn) | A64F_U12(ofsm>>sc)) ||
prev == ((ai^A64I_LS_U) | A64F_N(rn) | A64F_S9(ofsm&0x1ff))) {
aip = (A64F_A(rd) | A64F_D(*as->mcp & 31));
} else if (prev == (ai | A64F_N(rn) | A64F_U12(ofsp>>sc)) ||
prev == ((ai^A64I_LS_U) | A64F_N(rn) | A64F_S9(ofsp&0x1ff))) {
aip = (A64F_D(rd) | A64F_A(*as->mcp & 31));
ofsm = ofs;
} else {
goto nopair;
}
if (ofsm >= (int)((unsigned int)-64<<sc) && ofsm <= (63<<sc)) {
*as->mcp = aip | A64F_N(rn) | ((ofsm >> sc) << 15) |
(ai ^ ((ai == A64I_LDRx || ai == A64I_STRx) ? 0x50000000 : 0x90000000));
return;
}
}
nopair:
if (ot == 1)
*--as->mcp = ai | A64F_D(rd) | A64F_N(rn) | A64F_U12(ofs >> sc);
else
*--as->mcp = (ai^A64I_LS_U) | A64F_D(rd) | A64F_N(rn) | A64F_S9(ofs & 0x1ff);
}
/* -- Emit loads/stores --------------------------------------------------- */
/* Prefer rematerialization of BASE/L from global_State over spills. */
#define emit_canremat(ref) ((ref) <= ASMREF_L)
/* Try to find an N-step delta relative to other consts with N < lim. */
static int emit_kdelta(ASMState *as, Reg rd, uint64_t k, int lim)
{
RegSet work = (~as->freeset & RSET_GPR) | RID2RSET(RID_GL);
if (lim <= 1) return 0; /* Can't beat that. */
while (work) {
Reg r = rset_picktop(work);
IRRef ref = regcost_ref(as->cost[r]);
lj_assertA(r != rd, "dest reg %d not free", rd);
if (ref < REF_TRUE) {
uint64_t kx = ra_iskref(ref) ? (uint64_t)ra_krefk(as, ref) :
get_k64val(as, ref);
int64_t delta = (int64_t)(k - kx);
if (delta == 0) {
emit_dm(as, A64I_MOVx, rd, r);
return 1;
} else {
uint32_t k12 = emit_isk12(delta < 0 ? -delta : delta);
if (k12) {
emit_dn(as, (delta < 0 ? A64I_SUBx : A64I_ADDx)^k12, rd, r);
return 1;
}
/* Do other ops or multi-step deltas pay off? Probably not.
** E.g. XOR rarely helps with pointer consts.
*/
}
}
rset_clear(work, r);
}
return 0; /* Failed. */
}
static void emit_loadk(ASMState *as, Reg rd, uint64_t u64, int is64)
{
int i, zeros = 0, ones = 0, neg;
if (!is64) u64 = (int64_t)(int32_t)u64; /* Sign-extend. */
/* Count homogeneous 16 bit fragments. */
for (i = 0; i < 4; i++) {
uint64_t frag = (u64 >> i*16) & 0xffff;
zeros += (frag == 0);
ones += (frag == 0xffff);
}
neg = ones > zeros; /* Use MOVN if it pays off. */
if ((neg ? ones : zeros) < 3) { /* Need 2+ ins. Try shorter K13 encoding. */
uint32_t k13 = emit_isk13(u64, is64);
if (k13) {
emit_dn(as, (is64|A64I_ORRw)^k13, rd, RID_ZERO);
return;
}
}
if (!emit_kdelta(as, rd, u64, 4 - (neg ? ones : zeros))) {
int shift = 0, lshift = 0;
uint64_t n64 = neg ? ~u64 : u64;
if (n64 != 0) {
/* Find first/last fragment to be filled. */
shift = (63-emit_clz64(n64)) & ~15;
lshift = emit_ctz64(n64) & ~15;
}
/* MOVK requires the original value (u64). */
while (shift > lshift) {
uint32_t u16 = (u64 >> shift) & 0xffff;
/* Skip fragments that are correctly filled by MOVN/MOVZ. */
if (u16 != (neg ? 0xffff : 0))
emit_d(as, is64 | A64I_MOVKw | A64F_U16(u16) | A64F_LSL16(shift), rd);
shift -= 16;
}
/* But MOVN needs an inverted value (n64). */
emit_d(as, (neg ? A64I_MOVNx : A64I_MOVZx) |
A64F_U16((n64 >> lshift) & 0xffff) | A64F_LSL16(lshift), rd);
}
}
/* Load a 32 bit constant into a GPR. */
#define emit_loadi(as, rd, i) emit_loadk(as, rd, i, 0)
/* Load a 64 bit constant into a GPR. */
#define emit_loadu64(as, rd, i) emit_loadk(as, rd, i, A64I_X)
#define emit_loada(as, r, addr) emit_loadu64(as, (r), (uintptr_t)(addr))
#define glofs(as, k) \
((intptr_t)((uintptr_t)(k) - (uintptr_t)&J2GG(as->J)->g))
#define mcpofs(as, k) \
((intptr_t)((uintptr_t)(k) - (uintptr_t)(as->mcp - 1)))
#define checkmcpofs(as, k) \
(A64F_S_OK(mcpofs(as, k)>>2, 19))
static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow);
/* Get/set from constant pointer. */
static void emit_lsptr(ASMState *as, A64Ins ai, Reg r, void *p)
{
/* First, check if ip + offset is in range. */
if ((ai & 0x00400000) && checkmcpofs(as, p)) {
emit_d(as, A64I_LDRLx | A64F_S19(mcpofs(as, p)>>2), r);
} else {
Reg base = RID_GL; /* Next, try GL + offset. */
int64_t ofs = glofs(as, p);
if (!emit_checkofs(ai, ofs)) { /* Else split up into base reg + offset. */
int64_t i64 = i64ptr(p);
base = ra_allock(as, (i64 & ~0x7fffull), rset_exclude(RSET_GPR, r));
ofs = i64 & 0x7fffull;
}
emit_lso(as, ai, r, base, ofs);
}
}
/* Load 64 bit IR constant into register. */
static void emit_loadk64(ASMState *as, Reg r, IRIns *ir)
{
const uint64_t *k = &ir_k64(ir)->u64;
int64_t ofs;
if (r >= RID_MAX_GPR) {
uint32_t fpk = emit_isfpk64(*k);
if (fpk != ~0u) {
emit_d(as, A64I_FMOV_DI | A64F_FP8(fpk), (r & 31));
return;
}
}
ofs = glofs(as, k);
if (emit_checkofs(A64I_LDRx, ofs)) {
emit_lso(as, r >= RID_MAX_GPR ? A64I_LDRd : A64I_LDRx,
(r & 31), RID_GL, ofs);
} else {
if (r >= RID_MAX_GPR) {
emit_dn(as, A64I_FMOV_D_R, (r & 31), RID_TMP);
r = RID_TMP;
}
if (checkmcpofs(as, k))
emit_d(as, A64I_LDRLx | A64F_S19(mcpofs(as, k)>>2), r);
else
emit_loadu64(as, r, *k);
}
}
/* Get/set global_State fields. */
#define emit_getgl(as, r, field) \
emit_lsptr(as, A64I_LDRx, (r), (void *)&J2G(as->J)->field)
#define emit_setgl(as, r, field) \
emit_lsptr(as, A64I_STRx, (r), (void *)&J2G(as->J)->field)
/* Trace number is determined from pc of exit instruction. */
#define emit_setvmstate(as, i) UNUSED(i)
/* -- Emit control-flow instructions -------------------------------------- */
/* Label for internal jumps. */
typedef MCode *MCLabel;
/* Return label pointing to current PC. */
#define emit_label(as) ((as)->mcp)
static void emit_cond_branch(ASMState *as, A64CC cond, MCode *target)
{
MCode *p = --as->mcp;
ptrdiff_t delta = target - p;
lj_assertA(A64F_S_OK(delta, 19), "branch target out of range");
*p = A64I_BCC | A64F_S19(delta) | cond;
}
static void emit_branch(ASMState *as, A64Ins ai, MCode *target)
{
MCode *p = --as->mcp;
ptrdiff_t delta = target - p;
lj_assertA(A64F_S_OK(delta, 26), "branch target out of range");
*p = ai | A64F_S26(delta);
}
static void emit_tnb(ASMState *as, A64Ins ai, Reg r, uint32_t bit, MCode *target)
{
MCode *p = --as->mcp;
ptrdiff_t delta = target - p;
lj_assertA(bit < 63, "bit number out of range");
lj_assertA(A64F_S_OK(delta, 14), "branch target out of range");
if (bit > 31) ai |= A64I_X;
*p = ai | A64F_BIT(bit & 31) | A64F_S14(delta) | r;
}
static void emit_cnb(ASMState *as, A64Ins ai, Reg r, MCode *target)
{
MCode *p = --as->mcp;
ptrdiff_t delta = target - p;
lj_assertA(A64F_S_OK(delta, 19), "branch target out of range");
*p = ai | A64F_S19(delta) | r;
}
#define emit_jmp(as, target) emit_branch(as, A64I_B, (target))
static void emit_call(ASMState *as, void *target)
{
MCode *p = --as->mcp;
ptrdiff_t delta = (char *)target - (char *)p;
if (A64F_S_OK(delta>>2, 26)) {
*p = A64I_BL | A64F_S26(delta>>2);
} else { /* Target out of range: need indirect call. But don't use R0-R7. */
Reg r = ra_allock(as, i64ptr(target),
RSET_RANGE(RID_X8, RID_MAX_GPR)-RSET_FIXED);
*p = A64I_BLR | A64F_N(r);
}
}
/* -- Emit generic operations --------------------------------------------- */
/* Generic move between two regs. */
static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src)
{
if (dst >= RID_MAX_GPR) {
emit_dn(as, irt_isnum(ir->t) ? A64I_FMOV_D : A64I_FMOV_S,
(dst & 31), (src & 31));
return;
}
if (as->mcp != as->mcloop) { /* Swap early registers for loads/stores. */
MCode ins = *as->mcp, swp = (src^dst);
if ((ins & 0xbf800000) == 0xb9000000) {
if (!((ins ^ (dst << 5)) & 0x000003e0))
*as->mcp = ins ^ (swp << 5); /* Swap N in load/store. */
if (!(ins & 0x00400000) && !((ins ^ dst) & 0x0000001f))
*as->mcp = ins ^ swp; /* Swap D in store. */
}
}
emit_dm(as, A64I_MOVx, dst, src);
}
/* Generic load of register with base and (small) offset address. */
static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
{
if (r >= RID_MAX_GPR)
emit_lso(as, irt_isnum(ir->t) ? A64I_LDRd : A64I_LDRs, (r & 31), base, ofs);
else
emit_lso(as, irt_is64(ir->t) ? A64I_LDRx : A64I_LDRw, r, base, ofs);
}
/* Generic store of register with base and (small) offset address. */
static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
{
if (r >= RID_MAX_GPR)
emit_lso(as, irt_isnum(ir->t) ? A64I_STRd : A64I_STRs, (r & 31), base, ofs);
else
emit_lso(as, irt_is64(ir->t) ? A64I_STRx : A64I_STRw, r, base, ofs);
}
/* Emit an arithmetic operation with a constant operand. */
static void emit_opk(ASMState *as, A64Ins ai, Reg dest, Reg src,
int32_t i, RegSet allow)
{
uint32_t k = emit_isk12(i);
if (k)
emit_dn(as, ai^k, dest, src);
else
emit_dnm(as, ai, dest, src, ra_allock(as, i, allow));
}
/* Add offset to pointer. */
static void emit_addptr(ASMState *as, Reg r, int32_t ofs)
{
if (ofs)
emit_opk(as, ofs < 0 ? A64I_SUBx : A64I_ADDx, r, r,
ofs < 0 ? -ofs : ofs, rset_exclude(RSET_GPR, r));
}
#define emit_spsub(as, ofs) emit_addptr(as, RID_SP, -(ofs))
| xLua/build/luajit-2.1.0b3/src/lj_emit_arm64.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lj_emit_arm64.h",
"repo_id": "xLua",
"token_count": 6480
} | 1,897 |
/*
** Object de/serialization.
** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
*/
#define lj_serialize_c
#define LUA_CORE
#include "lj_obj.h"
#if LJ_HASBUFFER
#include "lj_err.h"
#include "lj_buf.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_udata.h"
#if LJ_HASFFI
#include "lj_ctype.h"
#include "lj_cdata.h"
#endif
#if LJ_HASJIT
#include "lj_ir.h"
#endif
#include "lj_serialize.h"
/* Tags for internal serialization format. */
enum {
SER_TAG_NIL, /* 0x00 */
SER_TAG_FALSE,
SER_TAG_TRUE,
SER_TAG_NULL,
SER_TAG_LIGHTUD32,
SER_TAG_LIGHTUD64,
SER_TAG_INT,
SER_TAG_NUM,
SER_TAG_TAB, /* 0x08 */
SER_TAG_DICT_MT = SER_TAG_TAB+6,
SER_TAG_DICT_STR,
SER_TAG_INT64, /* 0x10 */
SER_TAG_UINT64,
SER_TAG_COMPLEX,
SER_TAG_0x13,
SER_TAG_0x14,
SER_TAG_0x15,
SER_TAG_0x16,
SER_TAG_0x17,
SER_TAG_0x18, /* 0x18 */
SER_TAG_0x19,
SER_TAG_0x1a,
SER_TAG_0x1b,
SER_TAG_0x1c,
SER_TAG_0x1d,
SER_TAG_0x1e,
SER_TAG_0x1f,
SER_TAG_STR, /* 0x20 + str->len */
};
LJ_STATIC_ASSERT((SER_TAG_TAB & 7) == 0);
/* -- Helper functions ---------------------------------------------------- */
static LJ_AINLINE char *serialize_more(char *w, SBufExt *sbx, MSize sz)
{
if (LJ_UNLIKELY(sz > (MSize)(sbx->e - w))) {
sbx->w = w;
w = lj_buf_more2((SBuf *)sbx, sz);
}
return w;
}
/* Write U124 to buffer. */
static LJ_NOINLINE char *serialize_wu124_(char *w, uint32_t v)
{
if (v < 0x1fe0) {
v -= 0xe0;
*w++ = (char)(0xe0 | (v >> 8)); *w++ = (char)v;
} else {
*w++ = (char)0xff;
#if LJ_BE
v = lj_bswap(v);
#endif
memcpy(w, &v, 4); w += 4;
}
return w;
}
static LJ_AINLINE char *serialize_wu124(char *w, uint32_t v)
{
if (LJ_LIKELY(v < 0xe0)) {
*w++ = (char)v;
return w;
} else {
return serialize_wu124_(w, v);
}
}
static LJ_NOINLINE char *serialize_ru124_(char *r, char *w, uint32_t *pv)
{
uint32_t v = *pv;
if (v != 0xff) {
if (r >= w) return NULL;
v = ((v & 0x1f) << 8) + *(uint8_t *)r + 0xe0; r++;
} else {
if (r + 4 > w) return NULL;
v = lj_getu32(r); r += 4;
#if LJ_BE
v = lj_bswap(v);
#endif
}
*pv = v;
return r;
}
static LJ_AINLINE char *serialize_ru124(char *r, char *w, uint32_t *pv)
{
if (LJ_LIKELY(r < w)) {
uint32_t v = *(uint8_t *)r; r++;
*pv = v;
if (LJ_UNLIKELY(v >= 0xe0)) {
r = serialize_ru124_(r, w, pv);
}
return r;
}
return NULL;
}
/* Prepare string dictionary for use (once). */
void LJ_FASTCALL lj_serialize_dict_prep_str(lua_State *L, GCtab *dict)
{
if (!dict->hmask) { /* No hash part means not prepared, yet. */
MSize i, len = lj_tab_len(dict);
if (!len) return;
lj_tab_resize(L, dict, dict->asize, hsize2hbits(len));
for (i = 1; i <= len && i < dict->asize; i++) {
cTValue *o = arrayslot(dict, i);
if (tvisstr(o)) {
if (!lj_tab_getstr(dict, strV(o))) { /* Ignore dups. */
lj_tab_newkey(L, dict, o)->u64 = (uint64_t)(i-1);
}
} else if (!tvisfalse(o)) {
lj_err_caller(L, LJ_ERR_BUFFER_BADOPT);
}
}
}
}
/* Prepare metatable dictionary for use (once). */
void LJ_FASTCALL lj_serialize_dict_prep_mt(lua_State *L, GCtab *dict)
{
if (!dict->hmask) { /* No hash part means not prepared, yet. */
MSize i, len = lj_tab_len(dict);
if (!len) return;
lj_tab_resize(L, dict, dict->asize, hsize2hbits(len));
for (i = 1; i <= len && i < dict->asize; i++) {
cTValue *o = arrayslot(dict, i);
if (tvistab(o)) {
if (tvisnil(lj_tab_get(L, dict, o))) { /* Ignore dups. */
lj_tab_newkey(L, dict, o)->u64 = (uint64_t)(i-1);
}
} else if (!tvisfalse(o)) {
lj_err_caller(L, LJ_ERR_BUFFER_BADOPT);
}
}
}
}
/* -- Internal serializer ------------------------------------------------- */
/* Put serialized object into buffer. */
static char *serialize_put(char *w, SBufExt *sbx, cTValue *o)
{
if (LJ_LIKELY(tvisstr(o))) {
const GCstr *str = strV(o);
MSize len = str->len;
w = serialize_more(w, sbx, 5+len);
w = serialize_wu124(w, SER_TAG_STR + len);
w = lj_buf_wmem(w, strdata(str), len);
} else if (tvisint(o)) {
uint32_t x = LJ_BE ? lj_bswap((uint32_t)intV(o)) : (uint32_t)intV(o);
w = serialize_more(w, sbx, 1+4);
*w++ = SER_TAG_INT; memcpy(w, &x, 4); w += 4;
} else if (tvisnum(o)) {
uint64_t x = LJ_BE ? lj_bswap64(o->u64) : o->u64;
w = serialize_more(w, sbx, 1+sizeof(lua_Number));
*w++ = SER_TAG_NUM; memcpy(w, &x, 8); w += 8;
} else if (tvispri(o)) {
w = serialize_more(w, sbx, 1);
*w++ = (char)(SER_TAG_NIL + ~itype(o));
} else if (tvistab(o)) {
const GCtab *t = tabV(o);
uint32_t narray = 0, nhash = 0, one = 2;
if (sbx->depth <= 0) lj_err_caller(sbufL(sbx), LJ_ERR_BUFFER_DEPTH);
sbx->depth--;
if (t->asize > 0) { /* Determine max. length of array part. */
ptrdiff_t i;
TValue *array = tvref(t->array);
for (i = (ptrdiff_t)t->asize-1; i >= 0; i--)
if (!tvisnil(&array[i]))
break;
narray = (uint32_t)(i+1);
if (narray && tvisnil(&array[0])) one = 4;
}
if (t->hmask > 0) { /* Count number of used hash slots. */
uint32_t i, hmask = t->hmask;
Node *node = noderef(t->node);
for (i = 0; i <= hmask; i++)
nhash += !tvisnil(&node[i].val);
}
/* Write metatable index. */
if (LJ_UNLIKELY(tabref(sbx->dict_mt)) && tabref(t->metatable)) {
TValue mto;
Node *n;
settabV(sbufL(sbx), &mto, tabref(t->metatable));
n = hashgcref(tabref(sbx->dict_mt), mto.gcr);
do {
if (n->key.u64 == mto.u64) {
uint32_t idx = n->val.u32.lo;
w = serialize_more(w, sbx, 1+5);
*w++ = SER_TAG_DICT_MT;
w = serialize_wu124(w, idx);
break;
}
} while ((n = nextnode(n)));
}
/* Write number of array slots and hash slots. */
w = serialize_more(w, sbx, 1+2*5);
*w++ = (char)(SER_TAG_TAB + (nhash ? 1 : 0) + (narray ? one : 0));
if (narray) w = serialize_wu124(w, narray);
if (nhash) w = serialize_wu124(w, nhash);
if (narray) { /* Write array entries. */
cTValue *oa = tvref(t->array) + (one >> 2);
cTValue *oe = tvref(t->array) + narray;
while (oa < oe) w = serialize_put(w, sbx, oa++);
}
if (nhash) { /* Write hash entries. */
const Node *node = noderef(t->node) + t->hmask;
GCtab *dict_str = tabref(sbx->dict_str);
if (LJ_UNLIKELY(dict_str)) {
for (;; node--)
if (!tvisnil(&node->val)) {
if (LJ_LIKELY(tvisstr(&node->key))) {
/* Inlined lj_tab_getstr is 30% faster. */
const GCstr *str = strV(&node->key);
Node *n = hashstr(dict_str, str);
do {
if (tvisstr(&n->key) && strV(&n->key) == str) {
uint32_t idx = n->val.u32.lo;
w = serialize_more(w, sbx, 1+5);
*w++ = SER_TAG_DICT_STR;
w = serialize_wu124(w, idx);
break;
}
n = nextnode(n);
if (!n) {
MSize len = str->len;
w = serialize_more(w, sbx, 5+len);
w = serialize_wu124(w, SER_TAG_STR + len);
w = lj_buf_wmem(w, strdata(str), len);
break;
}
} while (1);
} else {
w = serialize_put(w, sbx, &node->key);
}
w = serialize_put(w, sbx, &node->val);
if (--nhash == 0) break;
}
} else {
for (;; node--)
if (!tvisnil(&node->val)) {
w = serialize_put(w, sbx, &node->key);
w = serialize_put(w, sbx, &node->val);
if (--nhash == 0) break;
}
}
}
sbx->depth++;
#if LJ_HASFFI
} else if (tviscdata(o)) {
CTState *cts = ctype_cts(sbufL(sbx));
CType *s = ctype_raw(cts, cdataV(o)->ctypeid);
uint8_t *sp = cdataptr(cdataV(o));
if (ctype_isinteger(s->info) && s->size == 8) {
w = serialize_more(w, sbx, 1+8);
*w++ = (s->info & CTF_UNSIGNED) ? SER_TAG_UINT64 : SER_TAG_INT64;
#if LJ_BE
{ uint64_t u = lj_bswap64(*(uint64_t *)sp); memcpy(w, &u, 8); }
#else
memcpy(w, sp, 8);
#endif
w += 8;
} else if (ctype_iscomplex(s->info) && s->size == 16) {
w = serialize_more(w, sbx, 1+16);
*w++ = SER_TAG_COMPLEX;
#if LJ_BE
{ /* Only swap the doubles. The re/im order stays the same. */
uint64_t u = lj_bswap64(((uint64_t *)sp)[0]); memcpy(w, &u, 8);
u = lj_bswap64(((uint64_t *)sp)[1]); memcpy(w+8, &u, 8);
}
#else
memcpy(w, sp, 16);
#endif
w += 16;
} else {
goto badenc; /* NYI other cdata */
}
#endif
} else if (tvislightud(o)) {
uintptr_t ud = (uintptr_t)lightudV(G(sbufL(sbx)), o);
w = serialize_more(w, sbx, 1+sizeof(ud));
if (ud == 0) {
*w++ = SER_TAG_NULL;
} else if (LJ_32 || checku32(ud)) {
#if LJ_BE && LJ_64
ud = lj_bswap64(ud);
#elif LJ_BE
ud = lj_bswap(ud);
#endif
*w++ = SER_TAG_LIGHTUD32; memcpy(w, &ud, 4); w += 4;
#if LJ_64
} else {
#if LJ_BE
ud = lj_bswap64(ud);
#endif
*w++ = SER_TAG_LIGHTUD64; memcpy(w, &ud, 8); w += 8;
#endif
}
} else {
/* NYI userdata */
#if LJ_HASFFI
badenc:
#endif
lj_err_callerv(sbufL(sbx), LJ_ERR_BUFFER_BADENC, lj_typename(o));
}
return w;
}
/* Get serialized object from buffer. */
static char *serialize_get(char *r, SBufExt *sbx, TValue *o)
{
char *w = sbx->w;
uint32_t tp;
r = serialize_ru124(r, w, &tp); if (LJ_UNLIKELY(!r)) goto eob;
if (LJ_LIKELY(tp >= SER_TAG_STR)) {
uint32_t len = tp - SER_TAG_STR;
if (LJ_UNLIKELY(len > (uint32_t)(w - r))) goto eob;
setstrV(sbufL(sbx), o, lj_str_new(sbufL(sbx), r, len));
r += len;
} else if (tp == SER_TAG_INT) {
if (LJ_UNLIKELY(r + 4 > w)) goto eob;
setintV(o, (int32_t)(LJ_BE ? lj_bswap(lj_getu32(r)) : lj_getu32(r)));
r += 4;
} else if (tp == SER_TAG_NUM) {
if (LJ_UNLIKELY(r + 8 > w)) goto eob;
memcpy(o, r, 8); r += 8;
#if LJ_BE
o->u64 = lj_bswap64(o->u64);
#endif
if (!tvisnum(o)) setnanV(o); /* Fix non-canonical NaNs. */
} else if (tp <= SER_TAG_TRUE) {
setpriV(o, ~tp);
} else if (tp == SER_TAG_DICT_STR) {
GCtab *dict_str;
uint32_t idx;
r = serialize_ru124(r, w, &idx); if (LJ_UNLIKELY(!r)) goto eob;
idx++;
dict_str = tabref(sbx->dict_str);
if (dict_str && idx < dict_str->asize && tvisstr(arrayslot(dict_str, idx)))
copyTV(sbufL(sbx), o, arrayslot(dict_str, idx));
else
lj_err_callerv(sbufL(sbx), LJ_ERR_BUFFER_BADDICTX, idx);
} else if (tp >= SER_TAG_TAB && tp <= SER_TAG_DICT_MT) {
uint32_t narray = 0, nhash = 0;
GCtab *t, *mt = NULL;
if (sbx->depth <= 0) lj_err_caller(sbufL(sbx), LJ_ERR_BUFFER_DEPTH);
sbx->depth--;
if (tp == SER_TAG_DICT_MT) {
GCtab *dict_mt;
uint32_t idx;
r = serialize_ru124(r, w, &idx); if (LJ_UNLIKELY(!r)) goto eob;
idx++;
dict_mt = tabref(sbx->dict_mt);
if (dict_mt && idx < dict_mt->asize && tvistab(arrayslot(dict_mt, idx)))
mt = tabV(arrayslot(dict_mt, idx));
else
lj_err_callerv(sbufL(sbx), LJ_ERR_BUFFER_BADDICTX, idx);
r = serialize_ru124(r, w, &tp); if (LJ_UNLIKELY(!r)) goto eob;
if (!(tp >= SER_TAG_TAB && tp < SER_TAG_DICT_MT)) goto badtag;
}
if (tp >= SER_TAG_TAB+2) {
r = serialize_ru124(r, w, &narray); if (LJ_UNLIKELY(!r)) goto eob;
}
if ((tp & 1)) {
r = serialize_ru124(r, w, &nhash); if (LJ_UNLIKELY(!r)) goto eob;
}
t = lj_tab_new(sbufL(sbx), narray, hsize2hbits(nhash));
/* NOBARRIER: The table is new (marked white). */
setgcref(t->metatable, obj2gco(mt));
settabV(sbufL(sbx), o, t);
if (narray) {
TValue *oa = tvref(t->array) + (tp >= SER_TAG_TAB+4);
TValue *oe = tvref(t->array) + narray;
while (oa < oe) r = serialize_get(r, sbx, oa++);
}
if (nhash) {
do {
TValue k, *v;
r = serialize_get(r, sbx, &k);
v = lj_tab_set(sbufL(sbx), t, &k);
if (LJ_UNLIKELY(!tvisnil(v)))
lj_err_caller(sbufL(sbx), LJ_ERR_BUFFER_DUPKEY);
r = serialize_get(r, sbx, v);
} while (--nhash);
}
sbx->depth++;
#if LJ_HASFFI
} else if (tp >= SER_TAG_INT64 && tp <= SER_TAG_COMPLEX) {
uint32_t sz = tp == SER_TAG_COMPLEX ? 16 : 8;
GCcdata *cd;
if (LJ_UNLIKELY(r + sz > w)) goto eob;
cd = lj_cdata_new_(sbufL(sbx),
tp == SER_TAG_INT64 ? CTID_INT64 :
tp == SER_TAG_UINT64 ? CTID_UINT64 : CTID_COMPLEX_DOUBLE,
sz);
memcpy(cdataptr(cd), r, sz); r += sz;
#if LJ_BE
*(uint64_t *)cdataptr(cd) = lj_bswap64(*(uint64_t *)cdataptr(cd));
if (sz == 16)
((uint64_t *)cdataptr(cd))[1] = lj_bswap64(((uint64_t *)cdataptr(cd))[1]);
#endif
if (sz == 16) { /* Fix non-canonical NaNs. */
TValue *cdo = (TValue *)cdataptr(cd);
if (!tvisnum(&cdo[0])) setnanV(&cdo[0]);
if (!tvisnum(&cdo[1])) setnanV(&cdo[1]);
}
setcdataV(sbufL(sbx), o, cd);
#endif
} else if (tp <= (LJ_64 ? SER_TAG_LIGHTUD64 : SER_TAG_LIGHTUD32)) {
uintptr_t ud = 0;
if (tp == SER_TAG_LIGHTUD32) {
if (LJ_UNLIKELY(r + 4 > w)) goto eob;
ud = (uintptr_t)(LJ_BE ? lj_bswap(lj_getu32(r)) : lj_getu32(r));
r += 4;
}
#if LJ_64
else if (tp == SER_TAG_LIGHTUD64) {
if (LJ_UNLIKELY(r + 8 > w)) goto eob;
memcpy(&ud, r, 8); r += 8;
#if LJ_BE
ud = lj_bswap64(ud);
#endif
}
setrawlightudV(o, lj_lightud_intern(sbufL(sbx), (void *)ud));
#else
setrawlightudV(o, (void *)ud);
#endif
} else {
badtag:
lj_err_callerv(sbufL(sbx), LJ_ERR_BUFFER_BADDEC, tp);
}
return r;
eob:
lj_err_caller(sbufL(sbx), LJ_ERR_BUFFER_EOB);
return NULL;
}
/* -- External serialization API ------------------------------------------ */
/* Encode to buffer. */
SBufExt * LJ_FASTCALL lj_serialize_put(SBufExt *sbx, cTValue *o)
{
sbx->depth = LJ_SERIALIZE_DEPTH;
sbx->w = serialize_put(sbx->w, sbx, o);
return sbx;
}
/* Decode from buffer. */
char * LJ_FASTCALL lj_serialize_get(SBufExt *sbx, TValue *o)
{
sbx->depth = LJ_SERIALIZE_DEPTH;
return serialize_get(sbx->r, sbx, o);
}
/* Stand-alone encoding, borrowing from global temporary buffer. */
GCstr * LJ_FASTCALL lj_serialize_encode(lua_State *L, cTValue *o)
{
SBufExt sbx;
char *w;
memset(&sbx, 0, sizeof(SBufExt));
lj_bufx_set_borrow(L, &sbx, &G(L)->tmpbuf);
sbx.depth = LJ_SERIALIZE_DEPTH;
w = serialize_put(sbx.w, &sbx, o);
return lj_str_new(L, sbx.b, (size_t)(w - sbx.b));
}
/* Stand-alone decoding, copy-on-write from string. */
void lj_serialize_decode(lua_State *L, TValue *o, GCstr *str)
{
SBufExt sbx;
char *r;
memset(&sbx, 0, sizeof(SBufExt));
lj_bufx_set_cow(L, &sbx, strdata(str), str->len);
/* No need to set sbx.cowref here. */
sbx.depth = LJ_SERIALIZE_DEPTH;
r = serialize_get(sbx.r, &sbx, o);
if (r != sbx.w) lj_err_caller(L, LJ_ERR_BUFFER_LEFTOV);
}
#if LJ_HASJIT
/* Peek into buffer to find the result IRType for specialization purposes. */
LJ_FUNC MSize LJ_FASTCALL lj_serialize_peektype(SBufExt *sbx)
{
uint32_t tp;
if (serialize_ru124(sbx->r, sbx->w, &tp)) {
/* This must match the handling of all tags in the decoder above. */
switch (tp) {
case SER_TAG_NIL: return IRT_NIL;
case SER_TAG_FALSE: return IRT_FALSE;
case SER_TAG_TRUE: return IRT_TRUE;
case SER_TAG_NULL: case SER_TAG_LIGHTUD32: case SER_TAG_LIGHTUD64:
return IRT_LIGHTUD;
case SER_TAG_INT: return LJ_DUALNUM ? IRT_INT : IRT_NUM;
case SER_TAG_NUM: return IRT_NUM;
case SER_TAG_TAB: case SER_TAG_TAB+1: case SER_TAG_TAB+2:
case SER_TAG_TAB+3: case SER_TAG_TAB+4: case SER_TAG_TAB+5:
case SER_TAG_DICT_MT:
return IRT_TAB;
case SER_TAG_INT64: case SER_TAG_UINT64: case SER_TAG_COMPLEX:
return IRT_CDATA;
case SER_TAG_DICT_STR:
default:
return IRT_STR;
}
}
return IRT_NIL; /* Will fail on actual decode. */
}
#endif
#endif
| xLua/build/luajit-2.1.0b3/src/lj_serialize.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lj_serialize.c",
"repo_id": "xLua",
"token_count": 8047
} | 1,898 |
#ifndef MIME_H
#define MIME_H
/*=========================================================================*\
* Core MIME support
* LuaSocket toolkit
*
* This module provides functions to implement transfer content encodings
* and formatting conforming to RFC 2045. It is used by mime.lua, which
* provide a higher level interface to this functionality.
\*=========================================================================*/
#include "lua.h"
/*-------------------------------------------------------------------------*\
* Current MIME library version
\*-------------------------------------------------------------------------*/
#define MIME_VERSION "MIME 1.0.3"
#define MIME_COPYRIGHT "Copyright (C) 2004-2013 Diego Nehab"
#define MIME_AUTHORS "Diego Nehab"
/*-------------------------------------------------------------------------*\
* This macro prefixes all exported API functions
\*-------------------------------------------------------------------------*/
#ifndef MIME_API
#define MIME_API extern
#endif
MIME_API int luaopen_mime_core(lua_State *L);
#endif /* MIME_H */
| xLua/build/luasocket/mime.h/0 | {
"file_path": "xLua/build/luasocket/mime.h",
"repo_id": "xLua",
"token_count": 256
} | 1,899 |
#ifndef USOCKET_H
#define USOCKET_H
/*=========================================================================*\
* Socket compatibilization module for Unix
* LuaSocket toolkit
\*=========================================================================*/
/*=========================================================================*\
* BSD include files
\*=========================================================================*/
/* error codes */
#include <errno.h>
/* close function */
#include <unistd.h>
/* fnctnl function and associated constants */
#include <fcntl.h>
/* struct sockaddr */
#include <sys/types.h>
/* socket function */
#include <sys/socket.h>
/* struct timeval */
#include <sys/time.h>
/* gethostbyname and gethostbyaddr functions */
#include <netdb.h>
/* sigpipe handling */
#include <signal.h>
/* IP stuff*/
#include <netinet/in.h>
#include <arpa/inet.h>
/* TCP options (nagle algorithm disable) */
#include <netinet/tcp.h>
#include <net/if.h>
#ifndef SO_REUSEPORT
#define SO_REUSEPORT SO_REUSEADDR
#endif
/* Some platforms use IPV6_JOIN_GROUP instead if
* IPV6_ADD_MEMBERSHIP. The semantics are same, though. */
#ifndef IPV6_ADD_MEMBERSHIP
#ifdef IPV6_JOIN_GROUP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif /* IPV6_JOIN_GROUP */
#endif /* !IPV6_ADD_MEMBERSHIP */
/* Same with IPV6_DROP_MEMBERSHIP / IPV6_LEAVE_GROUP. */
#ifndef IPV6_DROP_MEMBERSHIP
#ifdef IPV6_LEAVE_GROUP
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif /* IPV6_LEAVE_GROUP */
#endif /* !IPV6_DROP_MEMBERSHIP */
typedef int t_socket;
typedef t_socket *p_socket;
typedef struct sockaddr_storage t_sockaddr_storage;
#define SOCKET_INVALID (-1)
#endif /* USOCKET_H */
| xLua/build/luasocket/usocket.h/0 | {
"file_path": "xLua/build/luasocket/usocket.h",
"repo_id": "xLua",
"token_count": 597
} | 1,900 |
set CUR_DIR=%~dp0
cd %CUR_DIR%
del /s/q buildnx64
mkdir buildnx64 & pushd buildnx64
rem fix for io_tmpfile & os_tmpname
echo #if !__ASSEMBLER__ > switch_fix.h
echo static inline struct _IO_FILE* tmpfile(){ return 0; } >> switch_fix.h
echo static inline char* tmpnam(char* n){ return 0; } >> switch_fix.h
echo #endif >> switch_fix.h
set "NINTENDO_SDK_ROOT_CMAKE=%NINTENDO_SDK_ROOT:\=/%"
cmake -DCMAKE_C_COMPILER="%NINTENDO_SDK_ROOT_CMAKE%/Compilers/NX/nx/aarch64/bin/clang.exe" ^
-DCMAKE_CXX_COMPILER="%NINTENDO_SDK_ROOT_CMAKE%/Compilers/NX/nx/aarch64/bin/clang++.exe" ^
-G "Unix Makefiles" -DCMAKE_SYSTEM_NAME=Switch ^
-DCMAKE_C_FLAGS="-includeswitch_fix.h -I%CUR_DIR%buildnx64" ^
..
popd
cmake --build buildnx64 --config Release
mkdir plugin_lua53\Plugins\Switch
copy /Y buildnx64\libxlua.a plugin_lua53\Plugins\Switch\libxlua.a
rem may need to set package.cpath = "" in lua
rem as any read attempt to undefined location will crash
| xLua/build/make_nx64_lua53.bat/0 | {
"file_path": "xLua/build/make_nx64_lua53.bat",
"repo_id": "xLua",
"token_count": 410
} | 1,901 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>介绍 — XLua</title>
<meta charset="utf-8">
<meta name="description" content="XLua">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="/xLua/public/css/page.css">
<script src="/xLua/public/js/vue.js"></script>
<script src="/xLua/public/js/jquery.js"></script>
</head>
<body>
<nav class="nav">
<div class="border">
<img src="/xLua/public/images/logo.png" />
<button class="hiden-in-phone">V2.1</button>
<button id="btn-menu" class="hiden-in-pc">菜单</button>
<ul class="nav-link hiden-in-phone">
<!--li>
<form id="search-form">
<input type="text" id="search-query" class="search-query">
</form>
</li!-->
<li><a href="https://github.com/Tencent/xLua" class="nav-link-li">下载项目</a></li>
<li><a href="/xLua/public/v1/guide/use.html" class="nav-link-li">使用案例</a></li>
<li><a href="/xLua/public/v1/guide/version.html" class="nav-link-li">更新记录</a></li>
<li><a href="/xLua/public/v1/guide/contribution.html" class="nav-link-li">贡献指南</li>
<li><a href="/xLua/public/v1/guide/index.html" class="nav-link-li current">教程</a></li>
<li><a href="/xLua/public/" class="nav-link-li current">首页</a></li>
</ul>
</div>
</nav>
<div id="container" class="container clear">
<section class="sidebar clearfix">
<ul>
<li><h3>基础</h3></li>
<li>
<p><a href="/xLua/public/v1/guide/index.html" class="sidebar-link current">介绍</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/version.html" class="sidebar-link">更新记录</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/use.html" class="sidebar-link">商业案例</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/faq.html" class="sidebar-link">FAQ</a></p>
</li>
<li><h3>教程</h3></li>
<li>
<p><a href="/xLua/public/v1/guide/tutorial.html" class="sidebar-link">从零开始</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/configure.html" class="sidebar-link">XLua的配置</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/api.html" class="sidebar-link">C# API</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/crtdel-3rd.html" class="sidebar-link">添加删除第三方库</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/gc-optimization.html" class="sidebar-link">GC优化指南</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/performance-analysis.html" class="sidebar-link">性能分析工具</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/signature.html" class="sidebar-link">数字签名</a></p>
</li>
<li><h3>其他</h3></li>
<li>
<p><a href="/xLua/public/v1/guide/hotfix.html" class="sidebar-link">热标识</a></p>
</li>
<li>
<p><a href="/xLua/public/v1/guide/features.html" class="sidebar-link">特性</a></p>
</li>
</ul>
</section>
<article class="clearfix">
<h2 id="XLua"><a href="#XLua" class="headerlink" title="XLua"></a>XLua</h2><p><a href="https://github.com/Tencent/xLua/blob/master/LICENSE.TXT"><img src="http://img.shields.io/badge/license-MIT-blue.svg" alt="license"></a> <a href="https://github.com/Tencent/xLua/releases"><img src="https://img.shields.io/badge/release-v2.1.8-blue.svg" alt="release"></a> <a href="https://github.com/Tencent/xLua/pulls"><img src="https://img.shields.io/badge/PRs-welcome-blue.svg" alt="PRs Welcome"></a></p>
<h3 id="C-下Lua编程支持"><a href="#C-下Lua编程支持" class="headerlink" title="C#下Lua编程支持"></a>C#下Lua编程支持</h3><p>xLua为Unity、 .Net、 Mono等C#环境增加Lua脚本编程的能力,借助xLua,这些Lua代码可以方便的和C#相互调用。</p>
<h3 id="xLua的突破"><a href="#xLua的突破" class="headerlink" title="xLua的突破"></a>xLua的突破</h3><p>xLua在功能、性能、易用性都有不少突破,这几方面分别最具代表性的是:</p>
<ul>
<li>可以运行时把C#实现(方法,操作符,属性,事件等等)替换成lua实现;</li>
<li>出色的GC优化,自定义struct,枚举在Lua和C#间传递无C# gc alloc;</li>
<li>编辑器下无需生成代码,开发更轻量;</li>
</ul>
<blockquote>
<p>更详细的特性、平台支持介绍请看<a href="features.html">这里</a>。</p>
</blockquote>
<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><p>打开zip包,你会看到一个Assets目录,这目录就对应Unity工程的Assets目录,保持这目录结构放到你的Unity工程。</p>
<p>如果希望安装到其它目录,请看<a href="faq.html">FAQ</a>相关介绍。</p>
<h3 id="lua5-3-vs-luajit"><a href="#lua5-3-vs-luajit" class="headerlink" title="lua5.3 vs luajit"></a>lua5.3 vs luajit</h3><p>xLua有两个版本,分别集成了lua5.3和luajit,一个项目只能选择其一。这两个版本C#代码是一样的,不同的是Plugins部分。</p>
<p>lua5.3的特性更丰富些,比如支持原生64位整数,支持苹果bitcode,支持utf8等。出现问题因为是纯c代码,也好定位。比起luajit,lua对安装包的影响也更小。</p>
<p>而luajit胜在性能,如果其jit不出问题的话,可以比lua高一个数量级。目前luajit作者不打算维护luajit,在找人接替其维护,后续发展不太明朗。</p>
<p>项目可以根据自己情况判断哪个更适合。因为目前lua53版本使用较多,所以xLua工程Plugins目录下默认配套是lua53版本。</p>
<h3 id="快速入门"><a href="#快速入门" class="headerlink" title="快速入门"></a>快速入门</h3><p>一个完整的例子仅需3行代码:</p>
<p>安装好xLua,建一个MonoBehaviour拖到场景,在Start加入如下代码:</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">XLua.LuaEnv luaenv = <span class="keyword">new</span> XLua.LuaEnv();</div><div class="line">luaenv.DoString(<span class="string">"CS.UnityEngine.Debug.Log('hello world')"</span>);</div><div class="line">luaenv.Dispose();</div></pre></td></tr></table></figure>
<p>1、DoString参数为string,可输入任意合法的Lua代码,本示例在lua里调用C#的UnityEngine.Debug.Log打印了个日志。</p>
<p>2、一个LuaEnv实例对应Lua虚拟机,出于开销的考虑,建议全局唯一。</p>
<p>C#主动调用lua也很简单,比如要调用lua的系统函数,推荐方式是:</p>
<ul>
<li>声明</li>
</ul>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">[<span class="meta">XLua.CSharpCallLua</span>]</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">delegate</span> <span class="keyword">double</span> <span class="title">LuaMax</span>(<span class="params"><span class="keyword">double</span> a, <span class="keyword">double</span> b</span>)</span>;</div></pre></td></tr></table></figure>
<ul>
<li>绑定</li>
</ul>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line"><span class="keyword">var</span> max = luaenv.Global.GetInPath<LuaMax>(<span class="string">"math.max"</span>);</div></pre></td></tr></table></figure>
<ul>
<li>调用</li>
</ul>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">Debug.Log(<span class="string">"max:"</span> + max(<span class="number">32</span>, <span class="number">12</span>));</div></pre></td></tr></table></figure>
<p>建议绑定一次,重复使用。生成了代码的话,调用max是不产生gc alloc的。</p>
<h3 id="热补丁"><a href="#热补丁" class="headerlink" title="热补丁"></a>热补丁</h3><ul>
<li>侵入性小,老项目原有代码不做任何调整就可使用。</li>
<li>运行时影响小,不打补丁基本和原有程序一样。</li>
<li>出问题了可以用Lua来打补丁,这时才会走到lua代码逻辑;</li>
</ul>
<blockquote>
<p><a href="hotfix.html">这里</a>是使用指南。</p>
</blockquote>
<h3 id="更多示例"><a href="#更多示例" class="headerlink" title="更多示例"></a>更多示例</h3><ul>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/01_Helloworld/">01_Helloworld</a>: 快速入门的例子。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/02_U3DScripting/">02_U3DScripting</a>: 展示怎么用lua来写MonoBehaviour。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/03_UIEvent/">03_UIEvent</a>: 展示怎么用lua来写UI逻辑。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/04_LuaObjectOrented/">04_LuaObjectOrented</a>: 展示lua面向对象和C#的配合。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/05_NoGc/">05_NoGc</a>: 展示怎么去避免值类型的GC。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/06_Coroutine/">06_Coroutine</a>: 展示lua协程怎么和Unity协程相配合。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/07_AsyncTest/">07_AsyncTest</a>: 展示怎么用lua协程来把异步逻辑同步化。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/08_Hotfix/">08_Hotfix</a>: 热补丁的示例(需要开启热补丁特性,如何开启请看<a href="Assets/XLua/Doc/hotfix.md">指南</a>)。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/09_GenericMethod/">09_GenericMethod</a>: 泛化函数支持的演示。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/10_SignatureLoader/">10_SignatureLoader</a>: 展示如何读取经数字签名的lua脚本,参见<a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Doc/signature.md">数字签名</a>的文档介绍。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Examples/11_RawObject/">11_RawObject</a>: 当C#参数是object时,如何把一个lua number指定以boxing后的int传递过去。</li>
</ul>
<h3 id="文档"><a href="#文档" class="headerlink" title="文档"></a>文档</h3><ul>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Doc/XLua教程.doc">XLua教程.doc</a>:教程,其配套代码<a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Tutorial/">这里</a>。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Doc/configure.md">XLua的配置</a>:介绍如何配置xLua。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Doc/XLua增加删除第三方lua库.doc">XLua增加删除第三方lua库.doc</a>:如何增删第三方lua扩展库。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Doc/XLua_API.doc">XLua API.doc</a>:API文档。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Doc/custom_generate.md">生成引擎二次开发指南</a>:介绍如何做生成引擎的二次开发。</li>
<li><a href="https://github.com/Tencent/xLua/tree/master/Assets/XLua/Doc/hotfix.md">热补丁操作指南</a>:介绍如何使用热补丁特性。</li>
</ul>
<h3 id="技术支持"><a href="#技术支持" class="headerlink" title="技术支持"></a>技术支持</h3><blockquote>
<p>QQ群:612705778 验证答案:有问题先找FAQ</p>
</blockquote>
<div class="footer">
发现错误?想参与编辑?
<a href="https://github.com/Tencent/xLua/tree/master/docs/source/src/v1/guide/index.md" target="_blank">
在 Github 上编辑此页!
</a>
</div>
</article>
<div class="sub-nav hiden-in-phone">
<dl id="sub-nav">
<dt>本文内容</dt>
<dd v-for="(ele, index) in sub_nav">
<a v-bind:href="ele.href">{{ ele.name }}</a>
</dd>
</dl>
</div>
</div>
<footer>
<div>
<p>© Copyright 2017 Tencent All Rights Reserved</p>
<p>Tencent 2017</p>
</div>
</footer>
<script>
var vm = new Vue({
el : '#container',
data: {
sub_nav : [ ]
},
created:function(){
var obj = [];
$("article h3").each(function(){
obj.push({name : $(this).find("a").attr("title") , href : "#"+$(this).attr("id") });
});
this.sub_nav = obj;
}
});
var isShow = false;
$("nav").on("click","#btn-menu" , function(){
if(!isShow){
if($(document).scrollTop() > $(".sidebar").height() - 100){
$('html, body').animate({scrollTop:0} , 300, "swing",function(){
$(".sidebar").fadeIn();
$(".container").animate({"left" : "15rem"}, 500,"swing");
});
}else{
$(".sidebar").fadeIn();
$(".container").animate({"left" : "15rem"}, 500,"swing");
}
}else{
$(".sidebar").fadeOut();
$(".container").animate({"left" : "0rem"}, 500,"swing");
}
isShow = !isShow;
});
$(".container").on("click" , "article" , function(){
if(isShow){
$(".sidebar").fadeOut();
$(".container").animate({"left" : "0rem"}, 500,"swing");
isShow = false;
}
});
</script>
</body>
</html> | xLua/docs/public/v1/guide/index.html/0 | {
"file_path": "xLua/docs/public/v1/guide/index.html",
"repo_id": "xLua",
"token_count": 8348
} | 1,902 |
---
title: XLua的配置
type: guide
order: 100
---
## XLua的配置
xLua所有的配置都支持三种方式:`打标签`, `静态列表`, `动态列表`。
配置有两必须两建议:
* 列表方式均必须是static的字段/属性
* 列表方式均必须放到一个static类
* 建议不用标签方式
* 建议列表方式配置放Editor目录
### 打标签
xLua用白名单来指明生成哪些代码,而白名单通过attribute来配置,比如你想从lua调用c#的某个类,希望生成适配代码,你可以为这个类型打一个LuaCallCSharp标签:
~~~csharp
[LuaCallCSharp]
publicclassA
{
}
~~~
该方式方便,但在il2cpp下会增加不少的代码量,不建议使用。
### 静态列表
有时我们无法直接给一个类型打标签,比如系统api,没源码的库,或者实例化的泛化类型,这时你可以在一个静态类里声明一个静态字段,该字段的类型除BlackList和AdditionalProperties之外只要实现了IEnumerable<Type>就可以了(这两个例外后面具体会说),然后为这字段加上标签:
~~~csharp
[LuaCallCSharp]
public static List<Type> mymodule_lua_call_cs_list = new List<Type>()
{
typeof(GameObject),
typeof(Dictionary<string, int>),
};
~~~
这个字段需要放到一个 **静态类** 里头,建议放到 **Editor目录** 。
### 动态列表
声明一个静态属性,打上相应的标签即可。
```csharp
[Hotfix]
public static List<Type> by_property
{
get
{
return (from type in Assembly.GetExecutingAssembly().GetTypes()
where type.Namespace == "XXXX"
select type).ToList();
}
}
```
Getter是代码,你可以实现很多效果,比如按名字空间配置,按程序集配置等等。
这个属性需要放到一个 **静态类** 里头,建议放到 **Editor目录** 。
### LuaCallCSharp
一个C#类型加了这个配置,xLua会生成这个类型的适配代码(包括构造该类型实例,访问其成员属性、方法,静态属性、方法),否则将会尝试用性能较低的反射方式来访问。
一个类型的扩展方法(Extension Methods)加了这配置,也会生成适配代码并追加到被扩展类型的成员方法上。
xLua只会生成加了该配置的类型,不会自动生成其父类的适配代码,当访问子类对象的父类方法,如果该父类加了LuaCallCSharp配置,则执行父类的适配代码,否则会尝试用反射来访问。
反射访问除了性能不佳之外,在il2cpp下还有可能因为代码剪裁而导致无法访问,后者可以通过下面介绍的ReflectionUse标签来避免。
### ReflectionUse
一个C#类型类型加了这个配置,xLua会生成link.xml阻止il2cpp的代码剪裁。
对于扩展方法,必须加上LuaCallCSharp或者ReflectionUse才可以被访问到。
建议所有要在Lua访问的类型,要么加LuaCallCSharp,要么加上ReflectionUse,这才能够保证在各平台都能正常运行。
### CSharpCallLua
如果希望把一个lua函数适配到一个C# delegate(一类是C#侧各种回调:UI事件,delegate参数,比如List<T>:ForEach;另外一类场景是通过LuaTable的Get函数指明一个lua函数绑定到一个delegate)。或者把一个lua table适配到一个C# interface,该delegate或者interface需要加上该配置。
### GCOptimize
一个C#纯值类型(注:指的是一个只包含值类型的struct,可以嵌套其它只包含值类型的struct)或者C#枚举值加上了这个配置。xLua会为该类型生成gc优化代码,效果是该值类型在lua和c#间传递不产生(C#)gc alloc,该类型的数组访问也不产生gc。各种无GC的场景,可以参考05\_NoGc例子。
除枚举之外,包含无参构造函数的复杂类型,都会生成lua table到该类型,以及改类型的一维数组的转换代码,这将会优化这个转换的性能,包括更少的gc alloc。
### AdditionalProperties
这个是GCOptimize的扩展配置,有的时候,一些struct喜欢把field做成是私有的,通过property来访问field,这时就需要用到该配置(默认情况下GCOptimize只对public的field打解包)。
标签方式比较简单,配置方式复杂一点,要求是Dictionary<Type, List<string>>类型,Dictionary的Key是要生效的类型,Value是属性名列表。可以参考XLua对几个UnityEngine下值类型的配置,SysGCOptimize类。
### BlackList
如果你不要生成一个类型的一些成员的适配代码,你可以通过这个配置来实现。
标签方式比较简单,对应的成员上加就可以了。
由于考虑到有可能需要把重载函数的其中一个重载列入黑名单,配置方式比较复杂,类型是List<List<string>>,对于每个成员,在第一层List有一个条目,第二层List是个string的列表,第一个string是类型的全路径名,第二个string是成员名,如果成员是一个方法,还需要从第三个string开始,把其参数的类型全路径全列出来。
例如下面是对GameObject的一个属性以及FileInfo的一个方法列入黑名单:
```csharp
[BlackList]
public static List<List<string>> BlackList = new List<List<string>>() {
new List<string>(){"UnityEngine.GameObject", "networkView"},
new List<string>(){"System.IO.FileInfo", "GetAccessControl", "System.Security.AccessControl.AccessControlSections"},
};
```
### 下面是生成期配置,必须放到Editor目录下
**CSObjectWrapEditor.GenPath**
配置生成代码的放置路径,类型是string。默认放在"Assets/XLua/Gen/"下。
**CSObjectWrapEditor.GenCodeMenu**
该配置用于生成引擎的二次开发,一个无参数函数加了这个标签,在执行"XLua/Generate Code"菜单时会触发这个函数的调用。 | xLua/docs/source/src/v1/guide/configure.md/0 | {
"file_path": "xLua/docs/source/src/v1/guide/configure.md",
"repo_id": "xLua",
"token_count": 3681
} | 1,903 |
<article class="clearfix">
<%- page.content %>
<div class="footer">
发现错误?想参与编辑?
<a href="<%- theme.modify_github %><%- page.path.replace(/\.html$/, '.md') %>" target="_blank">
在 Github 上编辑此页!
</a>
</div>
</article>
<div class="sub-nav hiden-in-phone">
<dl id="sub-nav">
<dt>本文内容</dt>
<dd v-for="(ele, index) in sub_nav">
<a v-bind:href="ele.href">{{ ele.name }}</a>
</dd>
</dl>
</div> | xLua/docs/source/themes/catlib/layout/partials/article.ejs/0 | {
"file_path": "xLua/docs/source/themes/catlib/layout/partials/article.ejs",
"repo_id": "xLua",
"token_count": 293
} | 1,904 |
/*
(C) 2019 David Lettier
lettier.com
*/
#version 150
uniform vec2 pi;
uniform float osg_FrameTime;
uniform sampler2D colorTexture;
uniform vec2 enabled;
out vec4 fragColor;
void main() {
float amount = 0.01;
vec2 texSize = textureSize(colorTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
vec4 color = texture(colorTexture, texCoord);
if (enabled.x == 1) {
float randomIntensity =
fract
( 10000
* sin
(
( gl_FragCoord.x
+ gl_FragCoord.y
* osg_FrameTime
)
* pi.y
)
);
amount *= randomIntensity;
color.rgb += amount;
}
fragColor = color;
}
| 3d-game-shaders-for-beginners/demonstration/shaders/fragment/film-grain.frag/0 | {
"file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/film-grain.frag",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 349
} | 0 |
/*
(C) 2019 David Lettier
lettier.com
*/
#version 150
uniform sampler2D colorTexture;
uniform sampler2D positionTexture;
uniform vec2 parameters;
uniform vec2 enabled;
out vec4 fragColor;
void main() {
// Must be odd.
int pixelSize = int(parameters.x);
vec2 texSize = textureSize(colorTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
// Avoid the background.
vec4 position = texture(positionTexture, texCoord);
if (enabled.x != 1 || position.a <= 0.0) {
fragColor = texture(colorTexture, texCoord);
return;
}
float x = int(gl_FragCoord.x) % pixelSize;
float y = int(gl_FragCoord.y) % pixelSize;
x = floor(pixelSize / 2.0) - x;
y = floor(pixelSize / 2.0) - y;
x = gl_FragCoord.x + x;
y = gl_FragCoord.y + y;
vec2 uv = vec2(x, y) / texSize;
fragColor = texture(colorTexture, uv);
}
| 3d-game-shaders-for-beginners/demonstration/shaders/fragment/pixelize.frag/0 | {
"file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/pixelize.frag",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 353
} | 1 |
BSD 3-Clause License
Copyright (c) 2019, David Lettier
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| 3d-game-shaders-for-beginners/demonstration/src/LICENSE/0 | {
"file_path": "3d-game-shaders-for-beginners/demonstration/src/LICENSE",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 405
} | 2 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:title" content="Foam | 3D Game Shaders For Beginners" />
<meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:title" content="Foam | 3D Game Shaders For Beginners" />
<meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="author" content="David Lettier" />
<title>Foam | 3D Game Shaders For Beginners</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
</style>
<style>
code.sourceCode > span { display: inline-block; line-height: 1.25; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
background-color: #232629;
color: #7a7c7d;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; }
div.sourceCode
{ color: #cfcfc2; background-color: #232629; }
@media screen {
code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span. { color: #cfcfc2; } /* Normal */
code span.al { color: #95da4c; } /* Alert */
code span.an { color: #3f8058; } /* Annotation */
code span.at { color: #2980b9; } /* Attribute */
code span.bn { color: #f67400; } /* BaseN */
code span.bu { color: #7f8c8d; } /* BuiltIn */
code span.cf { color: #fdbc4b; } /* ControlFlow */
code span.ch { color: #3daee9; } /* Char */
code span.cn { color: #27aeae; } /* Constant */
code span.co { color: #7a7c7d; } /* Comment */
code span.cv { color: #7f8c8d; } /* CommentVar */
code span.do { color: #a43340; } /* Documentation */
code span.dt { color: #2980b9; } /* DataType */
code span.dv { color: #f67400; } /* DecVal */
code span.er { color: #da4453; } /* Error */
code span.ex { color: #0099ff; } /* Extension */
code span.fl { color: #f67400; } /* Float */
code span.fu { color: #8e44ad; } /* Function */
code span.im { color: #27ae60; } /* Import */
code span.in { color: #c45b00; } /* Information */
code span.kw { color: #cfcfc2; } /* Keyword */
code span.op { color: #cfcfc2; } /* Operator */
code span.ot { color: #27ae60; } /* Other */
code span.pp { color: #27ae60; } /* Preprocessor */
code span.re { color: #2980b9; } /* RegionMarker */
code span.sc { color: #3daee9; } /* SpecialChar */
code span.ss { color: #da4453; } /* SpecialString */
code span.st { color: #f44f4f; } /* String */
code span.va { color: #27aeae; } /* Variable */
code span.vs { color: #da4453; } /* VerbatimString */
code span.wa { color: #da4453; } /* Warning */
</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p><a href="screen-space-refraction.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="flow-mapping.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
<h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1>
<h2 id="foam">Foam</h2>
<p align="center">
<img src="https://i.imgur.com/SVLPYKn.gif" alt="Foam" title="Foam">
</p>
<p>Foam is typically used when simulating some body of water. Anywhere the water's flow is disrupted, you add some foam. The foam isn't much by itself but it can really connect the water with the rest of the scene.</p>
<p align="center">
<img src="https://i.imgur.com/HCqvd8c.gif" alt="Lava River" title="Lava River">
</p>
<p>But don't stop at just water. You can use the same technique to make a river of lava for example.</p>
<h3 id="vertex-positions">Vertex Positions</h3>
<p>Like <a href="screen-space-refraction.html">screen space refraction</a>, you'll need both the foreground and background vertex positions. The foreground being the scene with the foamy surface and the background being the scene without the foamy surface. Referrer back to <a href="ssao.html#vertex-positions">SSAO</a> for the details on how to acquire the vertex positions in view space.</p>
<h3 id="mask">Mask</h3>
<p align="center">
<img src="https://i.imgur.com/N6TWBw8.gif" alt="Foam Mask" title="Foam Mask">
</p>
<p>You'll need to texture your scene with a foam mask. The demo masks everything off except the water. For the water, it textures it with a foam pattern.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a><span class="co">// ...</span></span>
<span id="cb1-2"><a href="#cb1-2"></a></span>
<span id="cb1-3"><a href="#cb1-3"></a>uniform sampler2D foamPatternTexture;</span>
<span id="cb1-4"><a href="#cb1-4"></a></span>
<span id="cb1-5"><a href="#cb1-5"></a>in vec2 diffuseCoord;</span>
<span id="cb1-6"><a href="#cb1-6"></a></span>
<span id="cb1-7"><a href="#cb1-7"></a>out vec4 fragColor;</span>
<span id="cb1-8"><a href="#cb1-8"></a></span>
<span id="cb1-9"><a href="#cb1-9"></a><span class="dt">void</span> main() {</span>
<span id="cb1-10"><a href="#cb1-10"></a> vec4 foamPattern = texture(foamPatternTexture, diffuseCoord);</span>
<span id="cb1-11"><a href="#cb1-11"></a></span>
<span id="cb1-12"><a href="#cb1-12"></a> fragColor = vec4(vec3(dot(foamPattern.rgb, vec3(<span class="dv">1</span>)) / <span class="dv">3</span>), <span class="dv">1</span>);</span>
<span id="cb1-13"><a href="#cb1-13"></a>}</span></code></pre></div>
<p>Here you see the fragment shader that generates the foam mask. It takes a foam pattern texture and UV maps it to the scene's geometry using the diffuse UV coordinates. For every model, except the water, the shader is given a solid black texture as the <code>foamPatternTexture</code>.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a> <span class="co">// ...</span></span>
<span id="cb2-2"><a href="#cb2-2"></a></span>
<span id="cb2-3"><a href="#cb2-3"></a> fragColor = vec4(vec3(dot(foamPattern.rgb, vec3(<span class="dv">1</span>)) / <span class="dv">3</span>), <span class="dv">1</span>);</span>
<span id="cb2-4"><a href="#cb2-4"></a></span>
<span id="cb2-5"><a href="#cb2-5"></a> <span class="co">// ...</span></span></code></pre></div>
<p>The fragment color is converted to greyscale, as a precaution, since the foam shader expects the foam mask to be greyscale.</p>
<h3 id="uniforms">Uniforms</h3>
<div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a><span class="co">// ...</span></span>
<span id="cb3-2"><a href="#cb3-2"></a></span>
<span id="cb3-3"><a href="#cb3-3"></a>uniform sampler2D maskTexture;</span>
<span id="cb3-4"><a href="#cb3-4"></a>uniform sampler2D positionFromTexture;</span>
<span id="cb3-5"><a href="#cb3-5"></a>uniform sampler2D positionToTexture;</span>
<span id="cb3-6"><a href="#cb3-6"></a></span>
<span id="cb3-7"><a href="#cb3-7"></a><span class="co">// ...</span></span></code></pre></div>
<p>The foam shader accepts a mask texture, the foreground vertex positions (<code>positionFromTexture</code>), and the background vertex positions (<code>positionToTexture</code>).</p>
<h3 id="parameters">Parameters</h3>
<div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1"></a> <span class="co">// ...</span></span>
<span id="cb4-2"><a href="#cb4-2"></a></span>
<span id="cb4-3"><a href="#cb4-3"></a> <span class="dt">float</span> foamDepth = <span class="dv">4</span>;</span>
<span id="cb4-4"><a href="#cb4-4"></a> vec4 foamColor = vec4(<span class="fl">0.8</span>, <span class="fl">0.85</span>, <span class="fl">0.92</span>, <span class="dv">1</span>);</span>
<span id="cb4-5"><a href="#cb4-5"></a></span>
<span id="cb4-6"><a href="#cb4-6"></a> <span class="co">// ...</span></span></code></pre></div>
<p>The adjustable parameters for the foam shader are the foam depth and color. The foam depth controls how much foam is shown. As the foam depth increases, the amount of foam shown increases.</p>
<h3 id="distance">Distance</h3>
<div class="sourceCode" id="cb5"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb5-1"><a href="#cb5-1"></a> <span class="co">// ...</span></span>
<span id="cb5-2"><a href="#cb5-2"></a></span>
<span id="cb5-3"><a href="#cb5-3"></a> vec4 positionFrom = texture(positionFromTexture, texCoord);</span>
<span id="cb5-4"><a href="#cb5-4"></a> vec4 positionTo = texture(positionToTexture, texCoord);</span>
<span id="cb5-5"><a href="#cb5-5"></a></span>
<span id="cb5-6"><a href="#cb5-6"></a> <span class="dt">float</span> depth = (positionTo.xyz - positionFrom.xyz).y;</span>
<span id="cb5-7"><a href="#cb5-7"></a></span>
<span id="cb5-8"><a href="#cb5-8"></a> <span class="co">// ...</span></span></code></pre></div>
<p>Compute the distance from the foreground position to the background position. Since the positions are in view (camera) space, we only need the y value since it goes into the screen.</p>
<h3 id="amount">Amount</h3>
<div class="sourceCode" id="cb6"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb6-1"><a href="#cb6-1"></a> <span class="co">// ...</span></span>
<span id="cb6-2"><a href="#cb6-2"></a></span>
<span id="cb6-3"><a href="#cb6-3"></a> <span class="dt">float</span> amount = clamp(depth / foamDepth.x, <span class="dv">0</span>, <span class="dv">1</span>);</span>
<span id="cb6-4"><a href="#cb6-4"></a> amount = <span class="dv">1</span> - amount;</span>
<span id="cb6-5"><a href="#cb6-5"></a> amount *= mask.r;</span>
<span id="cb6-6"><a href="#cb6-6"></a> amount = amount * amount / (<span class="dv">2</span> * (amount * amount - amount) + <span class="dv">1</span>);</span>
<span id="cb6-7"><a href="#cb6-7"></a></span>
<span id="cb6-8"><a href="#cb6-8"></a> <span class="co">// ...</span></span></code></pre></div>
<p>The amount of foam is based on the depth, the foam depth parameter, and the mask value.</p>
<p align="center">
<img src="https://i.imgur.com/CDIPmin.png" alt="Easing equation." title="Easing equation.">
</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb7-1"><a href="#cb7-1"></a> <span class="co">// ...</span></span>
<span id="cb7-2"><a href="#cb7-2"></a></span>
<span id="cb7-3"><a href="#cb7-3"></a> amount = amount * amount / (<span class="dv">2</span> * (amount * amount - amount) + <span class="dv">1</span>);</span>
<span id="cb7-4"><a href="#cb7-4"></a></span>
<span id="cb7-5"><a href="#cb7-5"></a> <span class="co">// ...</span></span></code></pre></div>
<p>Reshape the amount using the ease in and out easing function. This will give a lot of foam near depth zero and little to no foam near <code>foamDepth</code>.</p>
<h3 id="fragment-color">Fragment Color</h3>
<div class="sourceCode" id="cb8"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb8-1"><a href="#cb8-1"></a> <span class="co">// ...</span></span>
<span id="cb8-2"><a href="#cb8-2"></a></span>
<span id="cb8-3"><a href="#cb8-3"></a> fragColor = mix(vec4(<span class="dv">0</span>), foamColor, amount);</span>
<span id="cb8-4"><a href="#cb8-4"></a></span>
<span id="cb8-5"><a href="#cb8-5"></a> <span class="co">// ...</span></span></code></pre></div>
<p>The fragment color is a mix between transparent black and the foam color based on the amount.</p>
<h3 id="source">Source</h3>
<ul>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/base.vert" target="_blank" rel="noopener noreferrer">base.vert</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/basic.vert" target="_blank" rel="noopener noreferrer">basic.vert</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/position.frag" target="_blank" rel="noopener noreferrer">position.frag</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/foam-mask.frag" target="_blank" rel="noopener noreferrer">foam-mask.frag</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/foam.frag" target="_blank" rel="noopener noreferrer">foam.frag</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/base-combine.frag" target="_blank" rel="noopener noreferrer">base-combine.frag</a></li>
</ul>
<h2 id="copyright">Copyright</h2>
<p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p>
<p><a href="screen-space-refraction.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="flow-mapping.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
</body>
</html>
| 3d-game-shaders-for-beginners/docs/foam.html/0 | {
"file_path": "3d-game-shaders-for-beginners/docs/foam.html",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 6227
} | 3 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:title" content="Running The Demo | 3D Game Shaders For Beginners" />
<meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:title" content="Running The Demo | 3D Game Shaders For Beginners" />
<meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="author" content="David Lettier" />
<title>Running The Demo | 3D Game Shaders For Beginners</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
</style>
<style>
code.sourceCode > span { display: inline-block; line-height: 1.25; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
background-color: #232629;
color: #7a7c7d;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; }
div.sourceCode
{ color: #cfcfc2; background-color: #232629; }
@media screen {
code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span. { color: #cfcfc2; } /* Normal */
code span.al { color: #95da4c; } /* Alert */
code span.an { color: #3f8058; } /* Annotation */
code span.at { color: #2980b9; } /* Attribute */
code span.bn { color: #f67400; } /* BaseN */
code span.bu { color: #7f8c8d; } /* BuiltIn */
code span.cf { color: #fdbc4b; } /* ControlFlow */
code span.ch { color: #3daee9; } /* Char */
code span.cn { color: #27aeae; } /* Constant */
code span.co { color: #7a7c7d; } /* Comment */
code span.cv { color: #7f8c8d; } /* CommentVar */
code span.do { color: #a43340; } /* Documentation */
code span.dt { color: #2980b9; } /* DataType */
code span.dv { color: #f67400; } /* DecVal */
code span.er { color: #da4453; } /* Error */
code span.ex { color: #0099ff; } /* Extension */
code span.fl { color: #f67400; } /* Float */
code span.fu { color: #8e44ad; } /* Function */
code span.im { color: #27ae60; } /* Import */
code span.in { color: #c45b00; } /* Information */
code span.kw { color: #cfcfc2; } /* Keyword */
code span.op { color: #cfcfc2; } /* Operator */
code span.ot { color: #27ae60; } /* Other */
code span.pp { color: #27ae60; } /* Preprocessor */
code span.re { color: #2980b9; } /* RegionMarker */
code span.sc { color: #3daee9; } /* SpecialChar */
code span.ss { color: #da4453; } /* SpecialString */
code span.st { color: #f44f4f; } /* String */
code span.va { color: #27aeae; } /* Variable */
code span.vs { color: #da4453; } /* VerbatimString */
code span.wa { color: #da4453; } /* Warning */
</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p><a href="building-the-demo.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="reference-frames.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
<h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1>
<h2 id="running-the-demo">Running The Demo</h2>
<p align="center">
<img src="https://i.imgur.com/y5XcReP.gif" alt="Running The Demo" title="Running The Demo">
</p>
<p>After you've built the example code, you can now run the executable or demo.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb1-1"><a href="#cb1-1"></a><span class="ex">./3d-game-shaders-for-beginners</span></span></code></pre></div>
<p>Here's how you run it on Linux or Mac.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb2-1"><a href="#cb2-1"></a><span class="ex">3d-game-shaders-for-beginners.exe</span></span></code></pre></div>
<p>Here's how you run it on Windows.</p>
<h3 id="demo-controls">Demo Controls</h3>
<p>The demo comes with both keyboard and mouse controls to move the camera around, toggle on and off the different effects, adjust the fog, and view the various different framebuffer textures.</p>
<h4 id="mouse">Mouse</h4>
<p>You can rotate the scene around by holding down the <kbd>Left Mouse</kbd> button and dragging. Hold down the <kbd>Right Mouse</kbd> button and drag to move up, down, left, and/or right. To zoom in, roll the <kbd>Mouse Wheel</kbd> forward. To zoom out, roll the <kbd>Mouse Wheel</kbd> backward.</p>
<p>You can also change the focus point using the mouse. To change the focus point, click anywhere on the scene using the <kbd>Middle Mouse</kbd> button.</p>
<h4 id="keyboard">Keyboard</h4>
<ul>
<li><kbd>w</kbd> to rotate the scene down.</li>
<li><kbd>a</kbd> to rotate the scene clockwise.</li>
<li><kbd>s</kbd> to rotate the scene up.</li>
<li><kbd>d</kbd> to rotate the scene counterclockwise.</li>
<li><kbd>z</kbd> to zoom in to the scene.</li>
<li><kbd>x</kbd> to zoom out of the scene.</li>
<li><kbd>⬅</kbd> to move left.</li>
<li><kbd>➡</kbd> to move right.</li>
<li><kbd>⬆</kbd> to move up.</li>
<li><kbd>⬇</kbd> to move down.</li>
</ul>
<p></p>
<ul>
<li><kbd>1</kbd> to show midday.</li>
<li><kbd>2</kbd> to show midnight.</li>
</ul>
<p></p>
<ul>
<li><kbd>Delete</kbd> to toggle the sound.</li>
<li><kbd>3</kbd> to toggle fresnel.</li>
<li><kbd>4</kbd> to toggle rim lighting.</li>
<li><kbd>5</kbd> to toggle particles.</li>
<li><kbd>6</kbd> to toggle motion blur.</li>
<li><kbd>7</kbd> to toggle Kuwahara filtering.</li>
<li><kbd>8</kbd> to toggle cel shading.</li>
<li><kbd>9</kbd> to toggle lookup table processing.</li>
<li><kbd>0</kbd> to toggle between Phong and Blinn-Phong.</li>
<li><kbd>y</kbd> to toggle SSAO.</li>
<li><kbd>u</kbd> to toggle outlining.</li>
<li><kbd>i</kbd> to toggle bloom.</li>
<li><kbd>o</kbd> to toggle normal mapping.</li>
<li><kbd>p</kbd> to toggle fog.</li>
<li><kbd>h</kbd> to toggle depth of field.</li>
<li><kbd>j</kbd> to toggle posterization.</li>
<li><kbd>k</kbd> to toggle pixelization.</li>
<li><kbd>l</kbd> to toggle sharpen.</li>
<li><kbd>n</kbd> to toggle film grain.</li>
<li><kbd>m</kbd> to toggle screen space reflection.</li>
<li><kbd>,</kbd> to toggle screen space refraction.</li>
<li><kbd>.</kbd> to toggle flow mapping.</li>
<li><kbd>/</kbd> to toggle the sun animation.</li>
<li><kbd>\</kbd> to toggle chromatic aberration.</li>
</ul>
<p></p>
<ul>
<li><kbd>r</kbd> to reset the scene.</li>
</ul>
<p></p>
<ul>
<li><kbd>[</kbd> to decrease the fog near distance.</li>
<li><kbd>Shift</kbd>+<kbd>[</kbd> to increase the fog near distance.</li>
<li><kbd>]</kbd> to increase the fog far distance.</li>
<li><kbd>Shift</kbd>+<kbd>]</kbd> to decrease the fog far distance.</li>
</ul>
<p></p>
<ul>
<li><kbd>Shift</kbd>+<kbd>-</kbd> to decrease the amount of foam.</li>
<li><kbd>-</kbd> to increase the amount of foam.</li>
</ul>
<p></p>
<ul>
<li><kbd>Shift</kbd>+<kbd>=</kbd> to decrease the relative index of refraction.</li>
<li><kbd>=</kbd> to increase the relative index of refraction.</li>
</ul>
<p></p>
<ul>
<li><kbd>Tab</kbd> to move forward through the framebuffer textures.</li>
<li><kbd>Shift</kbd>+<kbd>Tab</kbd> to move backward through the framebuffer textures.</li>
</ul>
<h2 id="copyright">Copyright</h2>
<p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p>
<p><a href="building-the-demo.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="reference-frames.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
</body>
</html>
| 3d-game-shaders-for-beginners/docs/running-the-demo.html/0 | {
"file_path": "3d-game-shaders-for-beginners/docs/running-the-demo.html",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 4174
} | 4 |
[:arrow_backward:](sharpen.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](film-grain.md)
# 3D Game Shaders For Beginners
## Dilation
<p align="center">
<img src="https://i.imgur.com/z751O74.gif" alt="Dilation" title="Dilation">
</p>
Dilation dilates or enlarges the brighter areas of an image while at the same time,
contracts or shrinks the darker areas of an image.
This tends to create a pillowy look.
You can use dilation for a glow/bloom effect or to add bokeh to your [depth of field](depth-of-field.md).
```c
// ...
int size = int(parameters.x);
float separation = parameters.y;
float minThreshold = 0.1;
float maxThreshold = 0.3;
// ...
```
The `size` and `separation` parameters control how dilated the image becomes.
A larger `size` will increase the dilation at the cost of performance.
A larger `separation` will increase the dilation at the cost of quality.
The `minThreshold` and `maxThreshold` parameters control which parts of the image become dilated.
```c
// ...
vec2 texSize = textureSize(colorTexture, 0).xy;
vec2 fragCoord = gl_FragCoord.xy;
fragColor = texture(colorTexture, fragCoord / texSize);
// ...
```
Sample the color at the current fragment's position.
```c
// ...
float mx = 0.0;
vec4 cmx = fragColor;
for (int i = -size; i <= size; ++i) {
for (int j = -size; j <= size; ++j) {
// ...
}
}
// ...
```
Loop through a `size` by `size` window, centered at the current fragment position.
As you loop, find the brightest color based on the surrounding greyscale values.
<p align="center">
<img src="https://i.imgur.com/X3uIyIL.png" alt="Dilation Window" title="Dilation Window">
</p>
```c
// ...
// For a rectangular shape.
//if (false);
// For a diamond shape;
//if (!(abs(i) <= size - abs(j))) { continue; }
// For a circular shape.
if (!(distance(vec2(i, j), vec2(0, 0)) <= size)) { continue; }
// ...
```
The window shape will determine the shape of the dilated parts of the image.
For a rectangular shape, you can use every fragment covered by the window.
For any other shape, skip the fragments that fall outside the desired shape.
```c
// ...
vec4 c =
texture
( colorTexture
, ( gl_FragCoord.xy
+ (vec2(i, j) * separation)
)
/ texSize
);
// ...
```
Sample a fragment color from the surrounding window.
```c
// ...
float mxt = dot(c.rgb, vec3(0.21, 0.72, 0.07));
// ...
```
Convert the sampled color to a greyscale value.
```c
// ...
if (mxt > mx) {
mx = mxt;
cmx = c;
}
// ...
```
If the sampled greyscale value is larger than the current maximum greyscale value,
update the maximum greyscale value and its corresponding color.
```c
// ...
fragColor.rgb =
mix
( fragColor.rgb
, cmx.rgb
, smoothstep(minThreshold, maxThreshold, mx)
);
// ...
```
The new fragment color is a mixture between the existing fragment color and
the brightest color found.
If the maximum greyscale value found is less than `minThreshold`,
the fragment color is unchanged.
If the maximum greyscale value is greater than `maxThreshold`,
the fragment color is replaced with the brightest color found.
For any other case,
the fragment color is a mix between the current fragment color and the brightest color.
### Source
- [main.cxx](../demonstration/src/main.cxx)
- [basic.vert](../demonstration/shaders/vertex/basic.vert)
- [dilation.frag](../demonstration/shaders/fragment/dilation.frag)
## Copyright
(C) 2020 David Lettier
<br>
[lettier.com](https://www.lettier.com)
[:arrow_backward:](sharpen.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](film-grain.md)
| 3d-game-shaders-for-beginners/sections/dilation.md/0 | {
"file_path": "3d-game-shaders-for-beginners/sections/dilation.md",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 1482
} | 5 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef airsim_core_ClockFactory_hpp
#define airsim_core_ClockFactory_hpp
#include "ScalableClock.hpp"
#include <memory>
namespace msr
{
namespace airlib
{
class ClockFactory
{
public:
//output of this function should not be stored as pointer might change
static ClockBase* get(std::shared_ptr<ClockBase> val = nullptr)
{
static std::shared_ptr<ClockBase> clock;
if (val != nullptr)
clock = val;
if (clock == nullptr)
clock = std::make_shared<ScalableClock>();
return clock.get();
}
//don't allow multiple instances of this class
ClockFactory(ClockFactory const&) = delete;
void operator=(ClockFactory const&) = delete;
private:
//disallow instance creation
ClockFactory() {}
};
}
} //namespace
#endif
| AirSim/AirLib/include/common/ClockFactory.hpp/0 | {
"file_path": "AirSim/AirLib/include/common/ClockFactory.hpp",
"repo_id": "AirSim",
"token_count": 399
} | 6 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef airsim_core_StateReporterWrapper_hpp
#define airsim_core_StateReporterWrapper_hpp
#include <sstream>
#include <string>
#include <iomanip>
#include "common/Common.hpp"
#include "common_utils/OnlineStats.hpp"
#include "common/FrequencyLimiter.hpp"
#include "UpdatableObject.hpp"
#include "StateReporter.hpp"
namespace msr
{
namespace airlib
{
class StateReporterWrapper : public UpdatableObject
{
public:
static constexpr real_T DefaultReportFreq = 3.0f;
StateReporterWrapper(bool enabled = false, int float_precision = 3, bool is_scientific_notation = false)
{
initialize(enabled, float_precision, is_scientific_notation);
}
void initialize(bool enabled = false, int float_precision = 3, bool is_scientific_notation = false)
{
enabled_ = enabled;
report_.initialize(float_precision, is_scientific_notation);
report_freq_.initialize(DefaultReportFreq);
}
void clearReport()
{
report_.clear();
is_wait_complete = false;
}
//*** Start: UpdatableState implementation ***//
virtual void resetImplementation() override
{
last_time_ = clock()->nowNanos();
clearReport();
dt_stats_.clear();
report_freq_.reset();
}
virtual void failResetUpdateOrdering(std::string err) override
{
// Do nothing.
// Disable checks for reset/update sequence because
// this object may get created but not used.
}
virtual void update() override
{
UpdatableObject::update();
TTimeDelta dt = clock()->updateSince(last_time_);
if (enabled_) {
dt_stats_.insert(dt);
report_freq_.update();
is_wait_complete = is_wait_complete || report_freq_.isWaitComplete();
}
}
virtual void reportState(StateReporter& reporter) override
{
//TODO: perhaps we should be using supplied reporter?
unused(reporter);
//write dt stats
report_.writeNameOnly("dt");
report_.writeValueOnly(dt_stats_.mean());
report_.writeValueOnly(dt_stats_.variance());
report_.writeValueOnly(dt_stats_.size(), true);
}
//*** End: UpdatableState implementation ***//
bool canReport()
{
return enabled_ && is_wait_complete;
}
StateReporter* getReporter()
{
return &report_;
}
string getOutput()
{
return report_.getOutput();
}
void setReportFreq(real_T freq)
{
report_freq_.initialize(freq);
}
void setEnable(bool enable)
{
if (enable == enabled_)
return;
enabled_ = enable;
if (enable)
report_freq_.initialize(DefaultReportFreq);
else
report_freq_.initialize(0);
}
bool getEnable()
{
return enabled_;
}
private:
typedef common_utils::OnlineStats OnlineStats;
StateReporter report_;
OnlineStats dt_stats_;
FrequencyLimiter report_freq_;
bool enabled_;
bool is_wait_complete = false;
TTimePoint last_time_;
};
}
} //namespace
#endif
| AirSim/AirLib/include/common/StateReporterWrapper.hpp/0 | {
"file_path": "AirSim/AirLib/include/common/StateReporterWrapper.hpp",
"repo_id": "AirSim",
"token_count": 1670
} | 7 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef commn_utils_sincos_hpp
#define commn_utils_sincos_hpp
#include <random>
namespace common_utils
{
template <typename TReturn, typename TDistribution, unsigned int Seed = 42>
class RandomGenerator
{
public:
//for uniform distribution supply min and max (inclusive)
//for gaussian distribution supply mean and sigma
template <typename... DistArgs>
RandomGenerator(DistArgs... dist_args)
: dist_(dist_args...), rand_(Seed)
{
}
void seed(int val)
{
rand_.seed(val);
}
TReturn next()
{
return static_cast<TReturn>(dist_(rand_));
}
void reset()
{
rand_.seed(Seed);
dist_.reset();
}
private:
TDistribution dist_;
std::mt19937 rand_;
};
typedef RandomGenerator<double, std::uniform_real_distribution<double>> RandomGeneratorD;
typedef RandomGenerator<float, std::uniform_real_distribution<float>> RandomGeneratorF;
typedef RandomGenerator<int, std::uniform_int_distribution<int>> RandomGeneratorI;
typedef RandomGenerator<unsigned int, std::uniform_int_distribution<unsigned int>> RandomGeneratorUI;
//TODO: below we should have float instead of double but VC++2017 has a bug :(
typedef RandomGenerator<float, std::normal_distribution<double>> RandomGeneratorGaussianF;
typedef RandomGenerator<double, std::normal_distribution<double>> RandomGeneratorGaussianD;
}
#endif
| AirSim/AirLib/include/common/common_utils/RandomGenerator.hpp/0 | {
"file_path": "AirSim/AirLib/include/common/common_utils/RandomGenerator.hpp",
"repo_id": "AirSim",
"token_count": 527
} | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.