diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index d3422af..0000000 --- a/.editorconfig +++ /dev/null @@ -1,119 +0,0 @@ -# To learn more about .editorconfig see https://aka.ms/editorconfigdocs -############################### -# Core EditorConfig Options # -############################### -# All files -[*] -indent_size = 4 -insert_final_newline = true -charset = utf -indent_style = space - -[*.{cs,csx,vb,vbx}] - -############################### -# .NET Coding Conventions # -############################### -[*.{cs,vb}] -# Organize usings -dotnet_sort_system_directives_first = true -# this. preferences -dotnet_style_qualification_for_field = false:silent -dotnet_style_qualification_for_property = false:silent -dotnet_style_qualification_for_method = false:silent -dotnet_style_qualification_for_event = false:silent -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true:silent -dotnet_style_predefined_type_for_member_access = true:silent -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent -dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent -dotnet_style_readonly_field = true:suggestion -# Expression-level preferences -dotnet_style_object_initializer = true:suggestion -dotnet_style_collection_initializer = true:suggestion -dotnet_style_explicit_tuple_names = true:suggestion -dotnet_style_null_propagation = true:suggestion -dotnet_style_coalesce_expression = true:suggestion -dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent -dotnet_style_prefer_inferred_tuple_names = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion -dotnet_style_prefer_auto_properties = true:silent -dotnet_style_prefer_conditional_expression_over_assignment = true:silent -dotnet_style_prefer_conditional_expression_over_return = true:silent -############################### -# Naming Conventions # -############################### -# Style Definitions -dotnet_naming_style.pascal_case_style.capitalization = pascal_case -# Use PascalCase for constant fields -dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields -dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style -dotnet_naming_symbols.constant_fields.applicable_kinds = field -dotnet_naming_symbols.constant_fields.applicable_accessibilities = * -dotnet_naming_symbols.constant_fields.required_modifiers = const - -############################### -# C# Coding Conventions # -############################### -[*.cs] -# var preferences -csharp_style_var_for_built_in_types = true:silent -csharp_style_var_when_type_is_apparent = true:silent -csharp_style_var_elsewhere = true:silent -# Expression-bodied members -csharp_style_expression_bodied_methods = false:silent -csharp_style_expression_bodied_constructors = false:silent -csharp_style_expression_bodied_operators = false:silent -csharp_style_expression_bodied_properties = true:silent -csharp_style_expression_bodied_indexers = true:silent -csharp_style_expression_bodied_accessors = true:silent -# Pattern matching preferences -csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion -csharp_style_pattern_matching_over_as_with_null_check = true:suggestion -# Null-checking preferences -csharp_style_throw_expression = true:suggestion -csharp_style_conditional_delegate_call = true:suggestion -# Modifier preferences -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion -# Expression-level preferences -csharp_prefer_braces = true:silent -csharp_style_deconstructed_variable_declaration = true:suggestion -csharp_prefer_simple_default_expression = true:suggestion -csharp_style_pattern_local_over_anonymous_function = true:suggestion -csharp_style_inlined_variable_declaration = true:suggestion -############################### -# C# Formatting Rules # -############################### -# New line preferences -csharp_new_line_before_open_brace = all -csharp_new_line_before_else = true -csharp_new_line_before_catch = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_between_query_expression_clauses = true -# Indentation preferences -csharp_indent_case_contents = true -csharp_indent_switch_labels = true -csharp_indent_labels = flush_left -# Space preferences -csharp_space_after_cast = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_around_binary_operators = before_and_after -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -# Wrapping preferences -csharp_preserve_single_line_statements = true -csharp_preserve_single_line_blocks = true diff --git a/Demos/CubeRotation.cs b/Demos/CubeRotation.cs deleted file mode 100644 index f4a089d..0000000 --- a/Demos/CubeRotation.cs +++ /dev/null @@ -1,28 +0,0 @@ -using UnityEngine; - -public class CubeRotation : MonoBehaviour { - - private float yawSpeed = 1f; - private float pitchSpeed = 1f; - private float rollSpeed = 1f; - - void Update () { - - if (Input.GetKey("a")) - yawSpeed += 1; - if (Input.GetKey("d") && yawSpeed > 0) - yawSpeed -= 1; - - if (Input.GetKey("w")) - pitchSpeed += 1; - if (Input.GetKey("s") && pitchSpeed > 0) - pitchSpeed -= 1; - - if (Input.GetKey("e")) - rollSpeed += 1; - if (Input.GetKey("q") && rollSpeed > 0) - rollSpeed -= 1; - - transform.rotation *= Quaternion.Euler(yawSpeed * Time.deltaTime, pitchSpeed * Time.deltaTime, rollSpeed * Time.deltaTime); - } -} diff --git a/Demos/Demo_IncomingStreams.unity b/Demos/Demo_IncomingStreams.unity deleted file mode 100644 index 37b8489..0000000 --- a/Demos/Demo_IncomingStreams.unity +++ /dev/null @@ -1,446 +0,0 @@ -%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: 7 - 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_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, g: 0, b: 0, a: 1} ---- !u!157 &3 -LightmapSettings: - m_ObjectHideFlags: 0 - serializedVersion: 7 - m_GIWorkflowMode: 1 - m_GISettings: - serializedVersion: 2 - m_BounceScale: 1 - m_IndirectOutputScale: 1 - m_AlbedoBoost: 1 - m_TemporalCoherenceThreshold: 1 - m_EnvironmentLightingMode: 0 - m_EnableBakedLightmaps: 1 - m_EnableRealtimeLightmaps: 1 - m_LightmapEditorSettings: - serializedVersion: 4 - m_Resolution: 2 - m_BakeResolution: 40 - m_TextureWidth: 1024 - m_TextureHeight: 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_DirectLightInLightProbes: 1 - m_FinalGather: 0 - m_FinalGatherFiltering: 1 - m_FinalGatherRayCount: 256 - m_ReflectionCompression: 2 - m_LightingDataAsset: {fileID: 0} - m_RuntimeCPUUsage: 25 ---- !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 - accuratePlacement: 0 - m_NavMeshData: {fileID: 0} ---- !u!1 &68353125 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 5 - m_Component: - - component: {fileID: 68353127} - - component: {fileID: 68353126} - m_Layer: 0 - m_Name: Resolver - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!114 &68353126 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 68353125} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 4bc033cd2cffec7459d6fa31ad6a961b, type: 3} - m_Name: - m_EditorClassIdentifier: - knownStreams: [] - forgetStreamAfter: 1 - onStreamFound: - m_PersistentCalls: - m_Calls: - - m_Target: {fileID: 193850119} - m_MethodName: AStreamIsFound - m_Mode: 0 - m_Arguments: - m_ObjectArgument: {fileID: 0} - m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine - m_IntArgument: 0 - m_FloatArgument: 0 - m_StringArgument: - m_BoolArgument: 0 - m_CallState: 2 - m_TypeName: Assets.LSL4Unity.Scripts.StreamEvent, Assembly-CSharp, Version=0.0.0.0, - Culture=neutral, PublicKeyToken=null - onStreamLost: - m_PersistentCalls: - m_Calls: - - m_Target: {fileID: 193850119} - m_MethodName: AStreamGotLost - m_Mode: 0 - m_Arguments: - m_ObjectArgument: {fileID: 0} - m_ObjectArgumentAssemblyTypeName: UnityEngine.Object, UnityEngine - m_IntArgument: 0 - m_FloatArgument: 0 - m_StringArgument: - m_BoolArgument: 0 - m_CallState: 2 - m_TypeName: Assets.LSL4Unity.Scripts.StreamEvent, Assembly-CSharp, Version=0.0.0.0, - Culture=neutral, PublicKeyToken=null ---- !u!4 &68353127 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 68353125} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: -0.7427908, y: -2.570417, z: 15.226566} - 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 &193850114 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 5 - m_Component: - - component: {fileID: 193850115} - - component: {fileID: 193850118} - - component: {fileID: 193850117} - - component: {fileID: 193850116} - - component: {fileID: 193850119} - m_Layer: 0 - m_Name: AObjectListeningToAStream - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!4 &193850115 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 193850114} - 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: 753183517} - m_RootOrder: 0 - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!23 &193850116 -MeshRenderer: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 193850114} - m_Enabled: 1 - m_CastShadows: 1 - m_ReceiveShadows: 1 - m_MotionVectors: 1 - m_LightProbeUsage: 1 - m_ReflectionProbeUsage: 1 - 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: 1 - m_IgnoreNormalsForChartDetection: 0 - m_ImportantGI: 0 - m_SelectedEditorRenderState: 3 - m_MinimumChartSize: 4 - m_AutoUVMaxDistance: 0.5 - m_AutoUVMaxAngle: 89 - m_LightmapParameters: {fileID: 0} - m_SortingLayerID: 0 - m_SortingOrder: 0 ---- !u!136 &193850117 -CapsuleCollider: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 193850114} - m_Material: {fileID: 0} - m_IsTrigger: 0 - m_Enabled: 1 - m_Radius: 0.5 - m_Height: 2 - m_Direction: 1 - m_Center: {x: 0, y: 0, z: 0} ---- !u!33 &193850118 -MeshFilter: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 193850114} - m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} ---- !u!114 &193850119 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 193850114} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 5ba4ed7276e95054fb35c620c2207e28, type: 3} - m_Name: - m_EditorClassIdentifier: - StreamName: RandomSpehricalData - StreamType: 3DCoord - targetTransform: {fileID: 193850115} - useX: 0 - useY: 1 - useZ: 0 ---- !u!1 &576020205 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 5 - m_Component: - - component: {fileID: 576020210} - - component: {fileID: 576020209} - - component: {fileID: 576020208} - - component: {fileID: 576020207} - - component: {fileID: 576020206} - 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 &576020206 -AudioListener: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 576020205} - m_Enabled: 1 ---- !u!124 &576020207 -Behaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 576020205} - m_Enabled: 1 ---- !u!92 &576020208 -Behaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 576020205} - m_Enabled: 1 ---- !u!20 &576020209 -Camera: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 576020205} - m_Enabled: 1 - serializedVersion: 2 - m_ClearFlags: 1 - m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} - 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: 0 - m_OcclusionCulling: 1 - m_StereoConvergence: 10 - m_StereoSeparation: 0.022 - m_StereoMirrorMode: 0 ---- !u!4 &576020210 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 576020205} - 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} ---- !u!1 &753183515 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 5 - m_Component: - - component: {fileID: 753183517} - m_Layer: 0 - m_Name: IncomingStreams - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!4 &753183517 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 753183515} - 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: 193850115} - m_Father: {fileID: 0} - m_RootOrder: 2 - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} ---- !u!1 &1295183507 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 5 - m_Component: - - component: {fileID: 1295183509} - - component: {fileID: 1295183508} - 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 &1295183508 -Light: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1295183507} - m_Enabled: 1 - serializedVersion: 7 - 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_AreaSize: {x: 1, y: 1} - m_BounceIntensity: 1 - m_ShadowRadius: 0 - m_ShadowAngle: 0 ---- !u!4 &1295183509 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1295183507} - 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} diff --git a/Demos/Demo_RotatingCube.unity b/Demos/Demo_RotatingCube.unity deleted file mode 100644 index c0e2330..0000000 --- a/Demos/Demo_RotatingCube.unity +++ /dev/null @@ -1,1068 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!29 &1 -SceneSettings: - m_ObjectHideFlags: 0 - m_PVSData: - m_PVSObjectsArray: [] - m_PVSPortalsArray: [] - m_OcclusionBakeSettings: - smallestOccluder: 5 - smallestHole: 0.25 - backfaceThreshold: 100 ---- !u!104 &2 -RenderSettings: - m_ObjectHideFlags: 0 - serializedVersion: 7 - 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_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, g: 0, b: 0, a: 1} ---- !u!157 &3 -LightmapSettings: - m_ObjectHideFlags: 0 - serializedVersion: 7 - m_GIWorkflowMode: 1 - m_GISettings: - serializedVersion: 2 - m_BounceScale: 1 - m_IndirectOutputScale: 1 - m_AlbedoBoost: 1 - m_TemporalCoherenceThreshold: 1 - m_EnvironmentLightingMode: 0 - m_EnableBakedLightmaps: 1 - m_EnableRealtimeLightmaps: 1 - m_LightmapEditorSettings: - serializedVersion: 4 - m_Resolution: 2 - m_BakeResolution: 40 - m_TextureWidth: 1024 - m_TextureHeight: 1024 - m_AO: 0 - m_AOMaxDistance: 1 - m_CompAOExponent: 0 - m_CompAOExponentDirect: 0 - m_Padding: 2 - m_LightmapParameters: {fileID: 0} - m_LightmapsBakeMode: 1 - m_TextureCompression: 1 - m_DirectLightInLightProbes: 1 - m_FinalGather: 0 - m_FinalGatherFiltering: 1 - m_FinalGatherRayCount: 1024 - m_ReflectionCompression: 2 - m_LightingDataAsset: {fileID: 0} - m_RuntimeCPUUsage: 25 ---- !u!196 &4 -NavMeshSettings: - serializedVersion: 2 - m_ObjectHideFlags: 0 - m_BuildSettings: - serializedVersion: 2 - agentRadius: 0.5 - agentHeight: 2 - agentSlope: 45 - agentClimb: 0.4 - ledgeDropHeight: 0 - maxJumpAcrossDistance: 0 - accuratePlacement: 0 - minRegionArea: 2 - cellSize: 0.16666667 - manualCellSize: 0 - m_NavMeshData: {fileID: 0} ---- !u!1 &168384544 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 4: {fileID: 168384546} - - 108: {fileID: 168384545} - m_Layer: 0 - m_Name: Point light - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!108 &168384545 -Light: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 168384544} - m_Enabled: 1 - serializedVersion: 7 - m_Type: 2 - m_Color: {r: 1, g: 1, b: 1, a: 1} - m_Intensity: 2.92 - m_Range: 13.52 - m_SpotAngle: 30 - m_CookieSize: 10 - m_Shadows: - m_Type: 0 - 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_AreaSize: {x: 1, y: 1} - m_BounceIntensity: 1 - m_ShadowRadius: 0 - m_ShadowAngle: 0 ---- !u!4 &168384546 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 168384544} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: -2.942, y: 2.717, z: -2.96} - m_LocalScale: {x: 1, y: 1, z: 1} - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 0} - m_RootOrder: 3 ---- !u!1 &188701591 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 224: {fileID: 188701592} - - 222: {fileID: 188701594} - - 114: {fileID: 188701593} - m_Layer: 5 - m_Name: StreamName - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!224 &188701592 -RectTransform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 188701591} - 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 1493122582} - m_RootOrder: 1 - m_AnchorMin: {x: 0, y: 0.5} - m_AnchorMax: {x: 0, y: 0.5} - m_AnchoredPosition: {x: 583.09, y: -5} - m_SizeDelta: {x: 300, y: 30} - m_Pivot: {x: 0.5, y: 0.5} ---- !u!114 &188701593 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 188701591} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_Material: {fileID: 0} - m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} - m_RaycastTarget: 1 - m_OnCullStateChanged: - m_PersistentCalls: - m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - m_FontData: - m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} - m_FontSize: 14 - m_FontStyle: 0 - m_BestFit: 0 - m_MinSize: 10 - m_MaxSize: 40 - m_Alignment: 0 - m_AlignByGeometry: 0 - m_RichText: 1 - m_HorizontalOverflow: 0 - m_VerticalOverflow: 0 - m_LineSpacing: 1 - m_Text: 'StreamName - -' ---- !u!222 &188701594 -CanvasRenderer: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 188701591} ---- !u!1 &213106542 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 224: {fileID: 213106543} - - 222: {fileID: 213106545} - - 114: {fileID: 213106544} - m_Layer: 5 - m_Name: Control Hint - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!224 &213106543 -RectTransform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 213106542} - 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 1493122582} - m_RootOrder: 5 - m_AnchorMin: {x: 0, y: 0.5} - m_AnchorMax: {x: 0, y: 0.5} - m_AnchoredPosition: {x: 568, y: -145} - m_SizeDelta: {x: 300, y: 33.56} - m_Pivot: {x: 0.5, y: 0.5} ---- !u!114 &213106544 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 213106542} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_Material: {fileID: 0} - m_Color: {r: 1, g: 1, b: 1, a: 1} - m_RaycastTarget: 1 - m_OnCullStateChanged: - m_PersistentCalls: - m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - m_FontData: - m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} - m_FontSize: 14 - m_FontStyle: 0 - m_BestFit: 0 - m_MinSize: 10 - m_MaxSize: 40 - m_Alignment: 0 - m_AlignByGeometry: 0 - m_RichText: 1 - m_HorizontalOverflow: 0 - m_VerticalOverflow: 0 - m_LineSpacing: 1 - m_Text: "Use WASDQE to control \nrotation speed\n" ---- !u!222 &213106545 -CanvasRenderer: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 213106542} ---- !u!1 &616096998 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 224: {fileID: 616097001} - - 222: {fileID: 616097000} - - 114: {fileID: 616096999} - m_Layer: 5 - m_Name: ConsumerLabel - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!114 &616096999 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 616096998} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_Material: {fileID: 0} - m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} - m_RaycastTarget: 1 - m_OnCullStateChanged: - m_PersistentCalls: - m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - m_FontData: - m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} - m_FontSize: 14 - m_FontStyle: 0 - m_BestFit: 0 - m_MinSize: 10 - m_MaxSize: 40 - m_Alignment: 0 - m_AlignByGeometry: 0 - m_RichText: 1 - m_HorizontalOverflow: 0 - m_VerticalOverflow: 0 - m_LineSpacing: 1 - m_Text: HasConsumerLabel ---- !u!222 &616097000 -CanvasRenderer: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 616096998} ---- !u!224 &616097001 -RectTransform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 616096998} - 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 1493122582} - m_RootOrder: 4 - m_AnchorMin: {x: 0, y: 0.5} - m_AnchorMax: {x: 0, y: 0.5} - m_AnchoredPosition: {x: 583.09, y: -91} - m_SizeDelta: {x: 300, y: 30} - m_Pivot: {x: 0.5, y: 0.5} ---- !u!1 &616749567 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 4: {fileID: 616749569} - - 114: {fileID: 616749568} - - 114: {fileID: 616749570} - m_Layer: 0 - m_Name: LSLDemoOutlets - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!114 &616749568 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 616749567} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 357857a4b3c756d4aa4c765f4b02f577, type: 3} - m_Name: - m_EditorClassIdentifier: - StreamName: BeMoBI.Unity.Orientation.DemoCube - StreamType: Unity.Quaternion - ChannelCount: 4 - sampling: 1 - sampleSource: {fileID: 1685184794} ---- !u!4 &616749569 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 616749567} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: -0.38264617, y: 3.2569156, z: -5.0278473} - m_LocalScale: {x: 1, y: 1, z: 1} - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 0} - m_RootOrder: 1 ---- !u!114 &616749570 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 616749567} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 01c23d6a1fd35524fbcfcb4c996f6439, type: 3} - m_Name: - m_EditorClassIdentifier: - sampleSource: {fileID: 1685184794} - StreamName: BeMoBI.Unity.DemoCube - StreamType: Unity.Transform - StreamRotationAsQuaternion: 1 - StreamRotationAsEuler: 1 - StreamPosition: 1 ---- !u!1 &1472627653 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 4: {fileID: 1472627656} - - 114: {fileID: 1472627655} - - 114: {fileID: 1472627654} - m_Layer: 0 - m_Name: LSLDemoMarker - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!114 &1472627654 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1472627653} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 04edb71db3ae93943b11404c7012e4e8, type: 3} - m_Name: - m_EditorClassIdentifier: - markerStream: {fileID: 1472627655} ---- !u!114 &1472627655 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1472627653} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 42f6a5f2a177ae14badbe859d5c565d2, type: 3} - m_Name: - m_EditorClassIdentifier: - lslStreamName: Unity_LSL_DEMO - lslStreamType: markers ---- !u!4 &1472627656 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1472627653} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: 0.83268976, y: -15.148477, z: 18.056757} - m_LocalScale: {x: 1, y: 1, z: 1} - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 0} - m_RootOrder: 6 ---- !u!1 &1493122577 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 224: {fileID: 1493122582} - - 223: {fileID: 1493122581} - - 114: {fileID: 1493122580} - - 114: {fileID: 1493122579} - - 114: {fileID: 1493122578} - m_Layer: 5 - m_Name: Canvas - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!114 &1493122578 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1493122577} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 1a5f5978f3c997a4e83f46f049b25b66, type: 3} - m_Name: - m_EditorClassIdentifier: - outlet: {fileID: 616749568} - StreamNameLabel: {fileID: 188701593} - StreamTypeLabel: {fileID: 1564915515} - DataRate: {fileID: 1855208413} - HasConsumerLabel: {fileID: 616096999} ---- !u!114 &1493122579 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1493122577} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 1301386320, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_IgnoreReversedGraphics: 1 - m_BlockingObjects: 0 - m_BlockingMask: - serializedVersion: 2 - m_Bits: 4294967295 ---- !u!114 &1493122580 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1493122577} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 1980459831, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_UiScaleMode: 0 - m_ReferencePixelsPerUnit: 100 - m_ScaleFactor: 1 - m_ReferenceResolution: {x: 800, y: 600} - m_ScreenMatchMode: 0 - m_MatchWidthOrHeight: 0 - m_PhysicalUnit: 3 - m_FallbackScreenDPI: 96 - m_DefaultSpriteDPI: 96 - m_DynamicPixelsPerUnit: 1 ---- !u!223 &1493122581 -Canvas: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1493122577} - m_Enabled: 1 - serializedVersion: 2 - m_RenderMode: 0 - m_Camera: {fileID: 0} - m_PlaneDistance: 100 - m_PixelPerfect: 0 - m_ReceivesEvents: 1 - m_OverrideSorting: 0 - m_OverridePixelPerfect: 0 - m_SortingBucketNormalizedSize: 0 - m_SortingLayerID: 0 - m_SortingOrder: 0 - m_TargetDisplay: 0 ---- !u!224 &1493122582 -RectTransform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1493122577} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: 0, y: 0, z: 0} - m_LocalScale: {x: 0, y: 0, z: 0} - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: - - {fileID: 1510576537} - - {fileID: 188701592} - - {fileID: 1564915514} - - {fileID: 1855208415} - - {fileID: 616097001} - - {fileID: 213106543} - m_Father: {fileID: 0} - m_RootOrder: 4 - m_AnchorMin: {x: 0, y: 0} - m_AnchorMax: {x: 0, y: 0} - m_AnchoredPosition: {x: 0, y: 0} - m_SizeDelta: {x: 0, y: 0} - m_Pivot: {x: 0, y: 0} ---- !u!1 &1509328175 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 4: {fileID: 1509328178} - - 114: {fileID: 1509328177} - - 114: {fileID: 1509328176} - m_Layer: 0 - m_Name: EventSystem - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!114 &1509328176 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1509328175} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 1077351063, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_HorizontalAxis: Horizontal - m_VerticalAxis: Vertical - m_SubmitButton: Submit - m_CancelButton: Cancel - m_InputActionsPerSecond: 10 - m_RepeatDelay: 0.5 - m_ForceModuleActive: 0 ---- !u!114 &1509328177 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1509328175} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: -619905303, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_FirstSelected: {fileID: 0} - m_sendNavigationEvents: 1 - m_DragThreshold: 5 ---- !u!4 &1509328178 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1509328175} - 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 0} - m_RootOrder: 5 ---- !u!1 &1510576536 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 224: {fileID: 1510576537} - - 222: {fileID: 1510576539} - - 114: {fileID: 1510576538} - m_Layer: 5 - m_Name: Panel - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!224 &1510576537 -RectTransform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1510576536} - 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 1493122582} - m_RootOrder: 0 - m_AnchorMin: {x: 0, y: 0.5} - m_AnchorMax: {x: 0, y: 0.5} - m_AnchoredPosition: {x: 413.69, y: 36} - m_SizeDelta: {x: 300, y: 150} - m_Pivot: {x: 0, y: 1} ---- !u!114 &1510576538 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1510576536} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_Material: {fileID: 0} - m_Color: {r: 1, g: 1, b: 1, a: 0.392} - m_RaycastTarget: 1 - m_OnCullStateChanged: - m_PersistentCalls: - m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} - m_Type: 1 - m_PreserveAspect: 0 - m_FillCenter: 1 - m_FillMethod: 4 - m_FillAmount: 1 - m_FillClockwise: 1 - m_FillOrigin: 0 ---- !u!222 &1510576539 -CanvasRenderer: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1510576536} ---- !u!1 &1564915513 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 224: {fileID: 1564915514} - - 222: {fileID: 1564915516} - - 114: {fileID: 1564915515} - m_Layer: 5 - m_Name: StreamType - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!224 &1564915514 -RectTransform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1564915513} - 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 1493122582} - m_RootOrder: 2 - m_AnchorMin: {x: 0, y: 0.5} - m_AnchorMax: {x: 0, y: 0.5} - m_AnchoredPosition: {x: 583.09, y: -30} - m_SizeDelta: {x: 300, y: 30} - m_Pivot: {x: 0.5, y: 0.5} ---- !u!114 &1564915515 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1564915513} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_Material: {fileID: 0} - m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} - m_RaycastTarget: 1 - m_OnCullStateChanged: - m_PersistentCalls: - m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - m_FontData: - m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} - m_FontSize: 14 - m_FontStyle: 0 - m_BestFit: 0 - m_MinSize: 10 - m_MaxSize: 40 - m_Alignment: 0 - m_AlignByGeometry: 0 - m_RichText: 1 - m_HorizontalOverflow: 0 - m_VerticalOverflow: 0 - m_LineSpacing: 1 - m_Text: StreamType ---- !u!222 &1564915516 -CanvasRenderer: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1564915513} ---- !u!1 &1685184789 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 4: {fileID: 1685184794} - - 33: {fileID: 1685184793} - - 65: {fileID: 1685184792} - - 23: {fileID: 1685184791} - - 114: {fileID: 1685184790} - m_Layer: 0 - m_Name: Cube - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!114 &1685184790 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1685184789} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 89ccfd963e304fe4c89df7f836670980, type: 3} - m_Name: - m_EditorClassIdentifier: ---- !u!23 &1685184791 -MeshRenderer: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1685184789} - m_Enabled: 1 - m_CastShadows: 1 - m_ReceiveShadows: 1 - m_MotionVectors: 1 - m_LightProbeUsage: 1 - m_ReflectionProbeUsage: 1 - m_Materials: - - {fileID: 10303, guid: 0000000000000000f000000000000000, type: 0} - m_SubsetIndices: - m_StaticBatchRoot: {fileID: 0} - m_ProbeAnchor: {fileID: 0} - m_LightProbeVolumeOverride: {fileID: 0} - m_ScaleInLightmap: 1 - m_PreserveUVs: 1 - m_IgnoreNormalsForChartDetection: 0 - m_ImportantGI: 0 - m_SelectedWireframeHidden: 0 - m_MinimumChartSize: 4 - m_AutoUVMaxDistance: 0.5 - m_AutoUVMaxAngle: 89 - m_LightmapParameters: {fileID: 0} - m_SortingLayerID: 0 - m_SortingOrder: 0 ---- !u!65 &1685184792 -BoxCollider: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1685184789} - 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!33 &1685184793 -MeshFilter: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1685184789} - m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} ---- !u!4 &1685184794 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1685184789} - 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 0} - m_RootOrder: 2 ---- !u!1 &1764292827 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 4: {fileID: 1764292832} - - 20: {fileID: 1764292831} - - 92: {fileID: 1764292830} - - 124: {fileID: 1764292829} - - 81: {fileID: 1764292828} - 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 &1764292828 -AudioListener: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1764292827} - m_Enabled: 1 ---- !u!124 &1764292829 -Behaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1764292827} - m_Enabled: 1 ---- !u!92 &1764292830 -Behaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1764292827} - m_Enabled: 1 ---- !u!20 &1764292831 -Camera: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1764292827} - m_Enabled: 1 - serializedVersion: 2 - m_ClearFlags: 1 - m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0.019607844} - 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: 0 - m_OcclusionCulling: 1 - m_StereoConvergence: 10 - m_StereoSeparation: 0.022 - m_StereoMirrorMode: 0 ---- !u!4 &1764292832 -Transform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1764292827} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: 1.353, y: 0.42, z: -4.72} - m_LocalScale: {x: 1, y: 1, z: 1} - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 0} - m_RootOrder: 0 ---- !u!1 &1855208412 -GameObject: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - serializedVersion: 4 - m_Component: - - 224: {fileID: 1855208415} - - 222: {fileID: 1855208414} - - 114: {fileID: 1855208413} - m_Layer: 5 - m_Name: DataRate - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 1 ---- !u!114 &1855208413 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1855208412} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} - m_Name: - m_EditorClassIdentifier: - m_Material: {fileID: 0} - m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} - m_RaycastTarget: 1 - m_OnCullStateChanged: - m_PersistentCalls: - m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null - m_FontData: - m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} - m_FontSize: 14 - m_FontStyle: 0 - m_BestFit: 0 - m_MinSize: 10 - m_MaxSize: 40 - m_Alignment: 0 - m_AlignByGeometry: 0 - m_RichText: 1 - m_HorizontalOverflow: 0 - m_VerticalOverflow: 0 - m_LineSpacing: 1 - m_Text: StreamType ---- !u!222 &1855208414 -CanvasRenderer: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1855208412} ---- !u!224 &1855208415 -RectTransform: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 1855208412} - 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_Children: [] - m_Father: {fileID: 1493122582} - m_RootOrder: 3 - m_AnchorMin: {x: 0, y: 0.5} - m_AnchorMax: {x: 0, y: 0.5} - m_AnchoredPosition: {x: 583.09, y: -56} - m_SizeDelta: {x: 300, y: 30} - m_Pivot: {x: 0.5, y: 0.5} diff --git a/Demos/LSLTransformDemoOutlet.cs b/Demos/LSLTransformDemoOutlet.cs deleted file mode 100644 index 66af4b7..0000000 --- a/Demos/LSLTransformDemoOutlet.cs +++ /dev/null @@ -1,94 +0,0 @@ -using UnityEngine; -using LSL; -using Assets.LSL4Unity.Scripts; -using Assets.LSL4Unity.Scripts.Common; - -namespace Assets.LSL4Unity.Demo -{ - /// - /// An reusable example of an outlet which provides the orientation of an entity to LSL - /// - public class LSLTransformDemoOutlet : MonoBehaviour - { - private const string unique_source_id = "D256CFBDBA3145978CFA641403219531"; - - private liblsl.StreamOutlet outlet; - private liblsl.StreamInfo streamInfo; - public liblsl.StreamInfo GetStreamInfo() - { - return streamInfo; - } - /// - /// Use a array to reduce allocation costs - /// - private float[] currentSample; - - private double dataRate; - - public double GetDataRate() - { - return dataRate; - } - - public bool HasConsumer() - { - if(outlet != null) - return outlet.have_consumers(); - - return false; - } - - public string StreamName = "BeMoBI.Unity.Orientation."; - public string StreamType = "Unity.Quaternion"; - public int ChannelCount = 4; - - public MomentForSampling sampling; - - public Transform sampleSource; - - void Start() - { - // initialize the array once - currentSample = new float[ChannelCount]; - - dataRate = LSLUtils.GetSamplingRateFor(sampling); - - streamInfo = new liblsl.StreamInfo(StreamName, StreamType, ChannelCount, dataRate, liblsl.channel_format_t.cf_float32, unique_source_id); - - outlet = new liblsl.StreamOutlet(streamInfo); - } - - private void pushSample() - { - if (outlet == null) - return; - var rotation = sampleSource.rotation; - - // reuse the array for each sample to reduce allocation costs - currentSample[0] = rotation.x; - currentSample[1] = rotation.y; - currentSample[2] = rotation.z; - currentSample[3] = rotation.w; - - outlet.push_sample(currentSample, liblsl.local_clock()); - } - - void FixedUpdate() - { - if (sampling == MomentForSampling.FixedUpdate) - pushSample(); - } - - void Update() - { - if (sampling == MomentForSampling.Update) - pushSample(); - } - - void LateUpdate() - { - if (sampling == MomentForSampling.LateUpdate) - pushSample(); - } - } -} \ No newline at end of file diff --git a/Demos/RandomMarker.cs b/Demos/RandomMarker.cs deleted file mode 100644 index bf23ca2..0000000 --- a/Demos/RandomMarker.cs +++ /dev/null @@ -1,36 +0,0 @@ -using UnityEngine; -using System.Collections; -using UnityEngine.Assertions; -using System; - -// Don't forget the Namespace import -using Assets.LSL4Unity.Scripts; - -public class RandomMarker : MonoBehaviour { - - public LSLMarkerStream markerStream; - - void Start () { - - Assert.IsNotNull(markerStream, "You forgot to assign the reference to a marker stream implementation!"); - - if (markerStream != null) - StartCoroutine(WriteContinouslyMarkerEachSecond()); - } - - IEnumerator WriteContinouslyMarkerEachSecond() - { - while (true) - { - // an example for demonstrating the usage of marker stream - var currentMarker = GetARandomMarker(); - markerStream.Write(currentMarker); - yield return new WaitForSecondsRealtime(1f); - } - } - - private string GetARandomMarker() - { - return UnityEngine.Random.value > 0.5 ? "A" : "B"; - } -} diff --git a/Demos/StreamInfo.cs b/Demos/StreamInfo.cs deleted file mode 100644 index 4dd1b62..0000000 --- a/Demos/StreamInfo.cs +++ /dev/null @@ -1,44 +0,0 @@ -using UnityEngine; -using UnityEngine.UI; -using System.Collections; -using Assets.LSL4Unity.Scripts; - -namespace Assets.LSL4Unity.Demo -{ - public class StreamInfo : MonoBehaviour - { - public LSLTransformDemoOutlet outlet; - - public Text StreamNameLabel; - - public Text StreamTypeLabel; - - public Text DataRate; - - public Text HasConsumerLabel; - - // Use this for initialization - void Start() - { - StreamNameLabel.text = outlet.StreamName; - StreamTypeLabel.text = outlet.StreamType; - DataRate.text = string.Format("Data Rate: {0}", outlet.GetDataRate()); - HasConsumerLabel.text = "Has no consumers"; - } - - // Update is called once per frame - void Update() - { - if (outlet.HasConsumer()) { - HasConsumerLabel.text = "Has consumers"; - HasConsumerLabel.color = Color.green; - } - else { - - HasConsumerLabel.text = "No Consumers"; - HasConsumerLabel.color = Color.black; - } - } - } - -} \ No newline at end of file diff --git a/Documentation~/LSL4Unity.md b/Documentation~/LSL4Unity.md new file mode 100644 index 0000000..e69de29 diff --git a/Editor.meta b/Editor.meta index 57bd03b..718f374 100644 --- a/Editor.meta +++ b/Editor.meta @@ -1,5 +1,8 @@ fileFormatVersion: 2 -guid: 5e82588594329bf4dbd22c7cd696c59a +guid: fd64d970370da344d8547cccef2cfb76 folderAsset: yes DefaultImporter: + externalObjects: {} userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/BuildHooks.cs b/Editor/BuildHooks.cs deleted file mode 100644 index edc01fc..0000000 --- a/Editor/BuildHooks.cs +++ /dev/null @@ -1,72 +0,0 @@ -using UnityEngine; -using UnityEditor.Callbacks; -using UnityEditor; -using System.IO; - -namespace Assets.LSL4Unity.EditorExtensions -{ - - public class BuildHooks { - - const string LIB_LSL_NAME = "liblsl"; - const string PLUGIN_DIR = "Plugins"; - - [PostProcessBuildAttribute(1)] - public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) - { - var buildName = Path.GetFileNameWithoutExtension(pathToBuiltProject); - - var buildHostDirectory = pathToBuiltProject.Replace(Path.GetFileName(pathToBuiltProject), ""); - - var dataDirectoryName = buildName + "_Data"; - - var pathToDataDirectory = Path.Combine(buildHostDirectory, dataDirectoryName); - - var pluginDirectory = Path.Combine(pathToDataDirectory, PLUGIN_DIR); - - if (target == BuildTarget.StandaloneWindows) - { - RenameLibFile(pluginDirectory, LSLEditorIntegration.lib32Name, LSLEditorIntegration.lib64Name, LSLEditorIntegration.DLL_ENDING); - } - else if(target == BuildTarget.StandaloneWindows64) - { - RenameLibFile(pluginDirectory, LSLEditorIntegration.lib64Name, LSLEditorIntegration.lib32Name, LSLEditorIntegration.DLL_ENDING); - } - - if (target == BuildTarget.StandaloneLinux) - { - RenameLibFile(pluginDirectory, LSLEditorIntegration.lib32Name, LSLEditorIntegration.lib64Name, LSLEditorIntegration.SO_ENDING); - } - else if (target == BuildTarget.StandaloneLinux64) - { - RenameLibFile(pluginDirectory, LSLEditorIntegration.lib64Name, LSLEditorIntegration.lib32Name, LSLEditorIntegration.SO_ENDING); - } - - if (target == BuildTarget.StandaloneOSXIntel) - { - RenameLibFile(pluginDirectory, LSLEditorIntegration.lib32Name, LSLEditorIntegration.lib64Name, LSLEditorIntegration.BUNDLE_ENDING); - } - else if (target == BuildTarget.StandaloneOSXIntel64) - { - RenameLibFile(pluginDirectory, LSLEditorIntegration.lib64Name, LSLEditorIntegration.lib32Name, LSLEditorIntegration.BUNDLE_ENDING); - } - } - - private static void RenameLibFile(string pluginDirectory , string sourceName, string nameOfObsoleteFile, string fileEnding) - { - var obsoleteFile = Path.Combine(pluginDirectory, nameOfObsoleteFile + fileEnding); - - Debug.Log("[LSL BUILD Hook] Delete obsolete file: " + obsoleteFile); - - File.Delete(obsoleteFile); - - var sourceFile = Path.Combine(pluginDirectory, sourceName + fileEnding); - - var targetFile = Path.Combine(pluginDirectory, LIB_LSL_NAME + fileEnding); - - Debug.Log(string.Format("[LSL BUILD Hook] Renaming: {0} to {1}", sourceFile, targetFile)); - - File.Move(sourceFile, targetFile); - } - } -} \ No newline at end of file diff --git a/Editor/BuildHooks.cs.meta b/Editor/BuildHooks.cs.meta deleted file mode 100644 index 198eb7b..0000000 --- a/Editor/BuildHooks.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: ce236d38c36d60d49b321747e75788a3 -timeCreated: 1470253905 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/LSLEditorIntegration.cs b/Editor/LSLEditorIntegration.cs index 05b7a5d..d33815c 100644 --- a/Editor/LSLEditorIntegration.cs +++ b/Editor/LSLEditorIntegration.cs @@ -4,7 +4,7 @@ using System.Linq; using UnityEngine.Assertions; -namespace Assets.LSL4Unity.EditorExtensions +namespace LSL4Unity.EditorExtensions { public class LSLEditorIntegration { @@ -16,10 +16,6 @@ public class LSLEditorIntegration public const string SO_ENDING = ".so"; public const string BUNDLE_ENDING = ".bundle"; - static readonly string wrapperFileName = "LSL.cs"; - static readonly string assetSubFolder = "LSL4Unity"; - static readonly string libFolder = "Plugins"; - [MenuItem("LSL/Show Streams")] static void OpenLSLWindow() { @@ -29,40 +25,5 @@ static void OpenLSLWindow() window.ShowUtility(); } - - [MenuItem("LSL/Show Streams", true)] - static bool ValidateOpenLSLWindow() - { - string assetDirectory = Application.dataPath; - - bool lib64Available = false; - bool lib32Available = false; - bool apiAvailable = false; - - - var results = Directory.GetDirectories(assetDirectory, assetSubFolder, SearchOption.AllDirectories); - - Assert.IsTrue(results.Any(), "Expecting a directory named: '" + assetSubFolder + "' containing the content inlcuding this script! Did you renamed it?"); - - var root = results.Single(); - - lib32Available = File.Exists(Path.Combine(root, Path.Combine(libFolder, lib32Name + DLL_ENDING))); - lib64Available = File.Exists(Path.Combine(root, Path.Combine(libFolder, lib64Name + DLL_ENDING))); - - lib32Available &= File.Exists(Path.Combine(root, Path.Combine(libFolder, lib32Name + SO_ENDING))); - lib64Available &= File.Exists(Path.Combine(root, Path.Combine(libFolder, lib64Name + SO_ENDING))); - - lib32Available &= File.Exists(Path.Combine(root, Path.Combine(libFolder, lib32Name + BUNDLE_ENDING))); - lib64Available &= File.Exists(Path.Combine(root, Path.Combine(libFolder, lib64Name + BUNDLE_ENDING))); - - apiAvailable = File.Exists(Path.Combine(root, wrapperFileName)); - - if ((lib64Available || lib32Available) && apiAvailable) - return true; - - Debug.LogError("LabStreamingLayer libraries not available! See " + wikiURL + " for installation instructions"); - return false; - } - } } \ No newline at end of file diff --git a/Editor/LSLEditorIntegration.cs.meta b/Editor/LSLEditorIntegration.cs.meta index ea9569a..76b06f5 100644 --- a/Editor/LSLEditorIntegration.cs.meta +++ b/Editor/LSLEditorIntegration.cs.meta @@ -1,8 +1,11 @@ fileFormatVersion: 2 guid: a584fbae3b9105d4682f492c03b0b5ae MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/LSLEditorWindow.cs b/Editor/LSLEditorWindow.cs index 6c313cd..e1e9987 100644 --- a/Editor/LSLEditorWindow.cs +++ b/Editor/LSLEditorWindow.cs @@ -3,7 +3,7 @@ using LSL; using System.Collections.Generic; -namespace Assets.LSL4Unity.EditorExtensions +namespace LSL4Unity.EditorExtensions { public class LSLShowStreamsWindow : EditorWindow { @@ -18,15 +18,15 @@ public class LSLShowStreamsWindow : EditorWindow private Vector2 scrollVector; private string streamLookUpResult; - private liblsl.ContinuousResolver resolver; + private ContinuousResolver resolver; private string lslVersionInfos; public void Init() { - resolver = new liblsl.ContinuousResolver(); + resolver = new ContinuousResolver(); - var libVersion = liblsl.library_version(); - var protocolVersion = liblsl.protocol_version(); + var libVersion = LSL.LSL.library_version(); + var protocolVersion = LSL.LSL.protocol_version(); var lib_major = libVersion / 100; var lib_minor = libVersion % 100; @@ -38,7 +38,7 @@ public void Init() this.titleContent = new GUIContent("LSL Utility"); } - liblsl.StreamInfo[] streamInfos = null; + StreamInfo[] streamInfos = null; void OnGUI() { diff --git a/Editor/LSLEditorWindow.cs.meta b/Editor/LSLEditorWindow.cs.meta index 732d9fd..36d751f 100644 --- a/Editor/LSLEditorWindow.cs.meta +++ b/Editor/LSLEditorWindow.cs.meta @@ -1,8 +1,11 @@ fileFormatVersion: 2 guid: 4aad5d6d1330577488c1ea0566032d3e MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/ScriptOrderManagement.cs b/Editor/ScriptOrderManagement.cs index b2ffe01..d8d5b61 100644 --- a/Editor/ScriptOrderManagement.cs +++ b/Editor/ScriptOrderManagement.cs @@ -2,7 +2,7 @@ using UnityEditor; using System; -namespace Assets.LSL4Unity.EditorExtensions +namespace LSL4Unity.EditorExtensions { [InitializeOnLoad] class ScriptOrderManagement diff --git a/Editor/ScriptOrderManagement.cs.meta b/Editor/ScriptOrderManagement.cs.meta index 7c44100..43d56b5 100644 --- a/Editor/ScriptOrderManagement.cs.meta +++ b/Editor/ScriptOrderManagement.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 guid: f2af7dca2ffa031458c43da8ce2fbbce -timeCreated: 1475325030 -licenseType: Free MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Editor/TimeSyncEditor.cs b/Editor/TimeSyncEditor.cs index 98a0c3f..7b62ed6 100644 --- a/Editor/TimeSyncEditor.cs +++ b/Editor/TimeSyncEditor.cs @@ -1,12 +1,12 @@ using UnityEngine; using UnityEditor; using System.Collections; -using Assets.LSL4Unity.Scripts; +using LSL4Unity.Utils; -namespace Assets.LSL4Unity.EditorExtensions +namespace LSL4Unity.EditorExtensions { - [CustomEditor(typeof(LSLTimeSync))] + [CustomEditor(typeof(TimeSync))] public class TimeSyncEditor : Editor { public override void OnInspectorGUI() diff --git a/Editor/TimeSyncEditor.cs.meta b/Editor/TimeSyncEditor.cs.meta index fb2a2c3..7208920 100644 --- a/Editor/TimeSyncEditor.cs.meta +++ b/Editor/TimeSyncEditor.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 guid: 9e65dd4b56fb29e4f85792c448fc3e0e -timeCreated: 1475324253 -licenseType: Free MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Editor/labstreaminglayer.LSL4Unity.Editor.asmdef b/Editor/labstreaminglayer.LSL4Unity.Editor.asmdef new file mode 100644 index 0000000..424d8d0 --- /dev/null +++ b/Editor/labstreaminglayer.LSL4Unity.Editor.asmdef @@ -0,0 +1,18 @@ +{ + "name": "labstreaminglayer.LSL4Unity.Editor", + "rootNamespace": "", + "references": [ + "labstreaminglayer.LSL4Unity.Runtime" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Editor/labstreaminglayer.LSL4Unity.Editor.asmdef.meta b/Editor/labstreaminglayer.LSL4Unity.Editor.asmdef.meta new file mode 100644 index 0000000..f4d35c5 --- /dev/null +++ b/Editor/labstreaminglayer.LSL4Unity.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 52d2e833f2d76e148a388b7b9d3072aa +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Demos/Demo_IncomingStreams.unity.meta b/LICENSE.meta similarity index 53% rename from Demos/Demo_IncomingStreams.unity.meta rename to LICENSE.meta index 1a5502a..cfbf7a8 100644 --- a/Demos/Demo_IncomingStreams.unity.meta +++ b/LICENSE.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 3550c01a8d2673149a51d237ef66a00b -timeCreated: 1482333848 -licenseType: Free +guid: 965884b07216b144e8148626c8b6d0fd DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/LSL.cs b/LSL.cs deleted file mode 100644 index 3f5307d..0000000 --- a/LSL.cs +++ /dev/null @@ -1,1208 +0,0 @@ -#define LSL4UnityLibrary -using System; -using System.Runtime.InteropServices; - -namespace LSL -{ - /// - /// C# API for the lab streaming layer. - /// - /// The lab streaming layer provides a set of functions to make instrument data accessible - /// in real time within a lab network. From there, streams can be picked up by recording programs, - /// viewing programs or custom experiment applications that access data streams in real time. - /// - /// The API covers two areas: - /// - The "push API" allows to create stream outlets and to push data (regular or irregular measurement - /// time series, event data, coded audio/video frames, etc.) into them. - /// - The "pull API" allows to create stream inlets and read time-synched experiment data from them - /// (for recording, viewing or experiment control). - /// - /// - - public class liblsl - { - /// Constant to indicate that a stream has variable sampling rate. - public const double IRREGULAR_RATE = 0.0; - - /** - * Constant to indicate that a sample has the next successive time stamp. - * This is an optional optimization to transmit less data per sample. - * The stamp is then deduced from the preceding one according to the stream's sampling rate - * (in the case of an irregular rate, the same time stamp as before will is assumed). - */ - public const double DEDUCED_TIMESTAMP = -1.0; - - /** - A very large time duration (> 1 year) for timeout values. - Note that significantly larger numbers can cause the timeout to be invalid on some operating systems (e.g., 32-bit UNIX). - */ - public const double FOREVER = 32000000.0; - - /// Data format of a channel (each transmitted sample holds an array of channels). - public enum channel_format_t : int - { - cf_float32 = 1, // For up to 24-bit precision measurements in the appropriate physical unit - // (e.g., microvolts). Integers from -16777216 to 16777216 are represented accurately. - cf_double64 = 2, // For universal numeric data as long as permitted by network & disk budget. - // The largest representable integer is 53-bit. - cf_string = 3, // For variable-length ASCII strings or data blobs, such as video frames, - // complex event descriptions, etc. - cf_int32 = 4, // For high-rate digitized formats that require 32-bit precision. Depends critically on - // meta-data to represent meaningful units. Useful for application event codes or other coded data. - cf_int16 = 5, // For very high rate signals (40Khz+) or consumer-grade audio - // (for professional audio float is recommended). - cf_int8 = 6, // For binary signals or other coded data. - // Not recommended for encoding string data. - cf_int64 = 7, // For now only for future compatibility. Support for this type is not yet exposed in all languages. - // Also, some builds of liblsl will not be able to send or receive data of this type. - cf_undefined = 0 // Can not be transmitted. - }; - - /** - * Post-processing options for stream inlets. - */ - public enum processing_options_t : int - { - post_none = 0, // No automatic post-processing; return the ground-truth time stamps for manual post-processing - // (this is the default behavior of the inlet). - post_clocksync = 1, // Perform automatic clock synchronization; equivalent to manually adding the time_correction() value - // to the received time stamps. - post_dejitter = 2, // Remove jitter from time stamps. This will apply a smoothing algorithm to the received time stamps; - // the smoothing needs to see a minimum number of samples (30-120 seconds worst-case) until the remaining - // jitter is consistently below 1ms. - post_monotonize = 4, // Force the time-stamps to be monotonically ascending (only makes sense if timestamps are dejittered). - post_threadsafe = 8, // Post-processing is thread-safe (same inlet can be read from by multiple threads); uses somewhat more CPU. - post_ALL = 1 | 2 | 4 | 8// The combination of all possible post-processing options. - }; - - /** - * Protocol version. - * The major version is protocol_version() / 100; - * The minor version is protocol_version() % 100; - * Clients with different minor versions are protocol-compatible with each other - * while clients with different major versions will refuse to work together. - */ - public static int protocol_version() { return dll.lsl_protocol_version(); } - - /** - * Version of the liblsl library. - * The major version is library_version() / 100; - * The minor version is library_version() % 100; - */ - public static int library_version() { return dll.lsl_library_version(); } - - /** - * Obtain a local system time stamp in seconds. The resolution is better than a millisecond. - * This reading can be used to assign time stamps to samples as they are being acquired. - * If the "age" of a sample is known at a particular time (e.g., from USB transmission - * delays), it can be used as an offset to local_clock() to obtain a better estimate of - * when a sample was actually captured. See stream_outlet::push_sample() for a use case. - */ - public static double local_clock() { return dll.lsl_local_clock(); } - - // ========================== - // === Stream Declaration === - // ========================== - - /** - * The stream_info object stores the declaration of a data stream. - * Represents the following information: - * a) stream data format (#channels, channel format) - * b) core information (stream name, content type, sampling rate) - * c) optional meta-data about the stream content (channel labels, measurement units, etc.) - * - * Whenever a program wants to provide a new stream on the lab network it will typically first - * create a stream_info to describe its properties and then construct a stream_outlet with it to create - * the stream on the network. Recipients who discover the outlet can query the stream_info; it is also - * written to disk when recording the stream (playing a similar role as a file header). - */ - - public class StreamInfo - { - /** - * Construct a new StreamInfo object. - * Core stream information is specified here. Any remaining meta-data can be added later. - * @param name Name of the stream. Describes the device (or product series) that this stream makes available - * (for use by programs, experimenters or data analysts). Cannot be empty. - * @param type Content type of the stream. Please see https://github.com/sccn/xdf/wiki/Meta-Data (or web search for: - * XDF meta-data) for pre-defined content-type names, but you can also make up your own. - * The content type is the preferred way to find streams (as opposed to searching by name). - * @param channel_count Number of channels per sample. This stays constant for the lifetime of the stream. - * @param nominal_srate The sampling rate (in Hz) as advertised by the data source, if regular (otherwise set to IRREGULAR_RATE). - * @param channel_format Format/type of each channel. If your channels have different formats, consider supplying - * multiple streams or use the largest type that can hold them all (such as cf_double64). - * @param source_id Unique identifier of the device or source of the data, if available (such as the serial number). - * This is critical for system robustness since it allows recipients to recover from failure even after the - * serving app, device or computer crashes (just by finding a stream with the same source id on the network again). - * Therefore, it is highly recommended to always try to provide whatever information can uniquely identify the data source itself. - */ - public StreamInfo(string name, string type, int channel_count = 1, double nominal_srate = IRREGULAR_RATE, channel_format_t channel_format = channel_format_t.cf_float32, string source_id = "") { obj = dll.lsl_create_streaminfo(name, type, channel_count, nominal_srate, channel_format, source_id); } - public StreamInfo(IntPtr handle) { obj = handle; } - - /// Destroy a previously created streaminfo object. - ~StreamInfo() { dll.lsl_destroy_streaminfo(obj); } - - // ======================== - // === Core Information === - // ======================== - // (these fields are assigned at construction) - - /** - * Name of the stream. - * This is a human-readable name. For streams offered by device modules, it refers to the type of device or product series - * that is generating the data of the stream. If the source is an application, the name may be a more generic or specific identifier. - * Multiple streams with the same name can coexist, though potentially at the cost of ambiguity (for the recording app or experimenter). - */ - public string name() { return Marshal.PtrToStringAnsi(dll.lsl_get_name(obj)); } - - - /** - * Content type of the stream. - * The content type is a short string such as "EEG", "Gaze" which describes the content carried by the channel (if known). - * If a stream contains mixed content this value need not be assigned but may instead be stored in the description of channel types. - * To be useful to applications and automated processing systems using the recommended content types is preferred. - * Content types usually follow those pre-defined in https://github.com/sccn/xdf/wiki/Meta-Data (or web search for: XDF meta-data). - */ - public string type() { return Marshal.PtrToStringAnsi(dll.lsl_get_type(obj)); } - - /** - * Number of channels of the stream. - * A stream has at least one channel; the channel count stays constant for all samples. - */ - public int channel_count() { return dll.lsl_get_channel_count(obj); } - - /** - * Sampling rate of the stream, according to the source (in Hz). - * If a stream is irregularly sampled, this should be set to IRREGULAR_RATE. - * - * Note that no data will be lost even if this sampling rate is incorrect or if a device has temporary - * hiccups, since all samples will be recorded anyway (except for those dropped by the device itself). However, - * when the recording is imported into an application, a good importer may correct such errors more accurately - * if the advertised sampling rate was close to the specs of the device. - */ - public double nominal_srate() { return dll.lsl_get_nominal_srate(obj); } - - /** - * Channel format of the stream. - * All channels in a stream have the same format. However, a device might offer multiple time-synched streams - * each with its own format. - */ - public channel_format_t channel_format() { return dll.lsl_get_channel_format(obj); } - - /** - * Unique identifier of the stream's source, if available. - * The unique source (or device) identifier is an optional piece of information that, if available, allows that - * endpoints (such as the recording program) can re-acquire a stream automatically once it is back online. - */ - public string source_id() { return Marshal.PtrToStringAnsi(dll.lsl_get_source_id(obj)); } - - - // ====================================== - // === Additional Hosting Information === - // ====================================== - // (these fields are implicitly assigned once bound to an outlet/inlet) - - /** - * Protocol version used to deliver the stream. - */ - public int version() { return dll.lsl_get_version(obj); } - - /** - * Creation time stamp of the stream. - * This is the time stamp when the stream was first created - * (as determined via local_clock() on the providing machine). - */ - public double created_at() { return dll.lsl_get_created_at(obj); } - - /** - * Unique ID of the stream outlet instance (once assigned). - * This is a unique identifier of the stream outlet, and is guaranteed to be different - * across multiple instantiations of the same outlet (e.g., after a re-start). - */ - public string uid() { return Marshal.PtrToStringAnsi(dll.lsl_get_uid(obj)); } - - /** - * Session ID for the given stream. - * The session id is an optional human-assigned identifier of the recording session. - * While it is rarely used, it can be used to prevent concurrent recording activitites - * on the same sub-network (e.g., in multiple experiment areas) from seeing each other's streams - * (assigned via a configuration file by the experimenter, see Network Connectivity in the LSL wiki). - */ - public string session_id() { return Marshal.PtrToStringAnsi(dll.lsl_get_session_id(obj)); } - - /** - * Hostname of the providing machine. - */ - public string hostname() { return Marshal.PtrToStringAnsi(dll.lsl_get_hostname(obj)); } - - - // ======================== - // === Data Description === - // ======================== - - /** - * Extended description of the stream. - * It is highly recommended that at least the channel labels are described here. - * See code examples on the LSL wiki. Other information, such as amplifier settings, - * measurement units if deviating from defaults, setup information, subject information, etc., - * can be specified here, as well. Meta-data recommendations follow the XDF file format project - * (github.com/sccn/xdf/wiki/Meta-Data or web search for: XDF meta-data). - * - * Important: if you use a stream content type for which meta-data recommendations exist, please - * try to lay out your meta-data in agreement with these recommendations for compatibility with other applications. - */ - public XMLElement desc() { return new XMLElement(dll.lsl_get_desc(obj)); } - - /** - * Retrieve the entire stream_info in XML format. - * This yields an XML document (in string form) whose top-level element is . The info element contains - * one element for each field of the stream_info class, including: - * a) the core elements , , , , , - * b) the misc elements , , , , , , , , , - * c) the extended description element with user-defined sub-elements. - */ - public string as_xml() - { - IntPtr pXml = dll.lsl_get_xml(obj); - string strXml = Marshal.PtrToStringAnsi(pXml); - dll.lsl_destroy_string(pXml); - return strXml; - } - - - /** - * Get access to the underlying handle. - */ - public IntPtr handle() { return obj; } - - private IntPtr obj; - } - - - // ======================= - // ==== Stream Outlet ==== - // ======================= - - /** - * A stream outlet. - * Outlets are used to make streaming data (and the meta-data) available on the lab network. - */ - public class StreamOutlet - { - /** - * Establish a new stream outlet. This makes the stream discoverable. - * @param info The stream information to use for creating this stream. Stays constant over the lifetime of the outlet. - * @param chunk_size Optionally the desired chunk granularity (in samples) for transmission. If unspecified, - * each push operation yields one chunk. Inlets can override this setting. - * @param max_buffered Optionally the maximum amount of data to buffer (in seconds if there is a nominal - * sampling rate, otherwise x100 in samples). The default is 6 minutes of data. - */ - public StreamOutlet(StreamInfo info, int chunk_size = 0, int max_buffered = 360) { obj = dll.lsl_create_outlet(info.handle(), chunk_size, max_buffered); } - - /** - * Destructor. - * The stream will no longer be discoverable after destruction and all paired inlets will stop delivering data. - */ - ~StreamOutlet() { dll.lsl_destroy_outlet(obj); } - - - // ======================================== - // === Pushing a sample into the outlet === - // ======================================== - - /** - * Push an array of values as a sample into the outlet. - * Each entry in the vector corresponds to one channel. - * @param data An array of values to push (one for each channel). - * @param timestamp Optionally the capture time of the sample, in agreement with local_clock(); if omitted, the current time is used. - * @param pushthrough Optionally whether to push the sample through to the receivers instead of buffering it with subsequent samples. - * Note that the chunk_size, if specified at outlet construction, takes precedence over the pushthrough flag. - */ - public void push_sample(float[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_ftp(obj, data, timestamp, pushthrough ? 1 : 0); } - public void push_sample(double[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_dtp(obj, data, timestamp, pushthrough ? 1 : 0); } - public void push_sample(int[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_itp(obj, data, timestamp, pushthrough ? 1 : 0); } - public void push_sample(short[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_stp(obj, data, timestamp, pushthrough ? 1 : 0); } - public void push_sample(char[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_ctp(obj, data, timestamp, pushthrough ? 1 : 0); } - public void push_sample(string[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_strtp(obj, data, timestamp, pushthrough ? 1 : 0); } - - - // =================================================== - // === Pushing an chunk of samples into the outlet === - // =================================================== - - /** - * Push a chunk of samples into the outlet. Single timestamp provided. - * @param data A rectangular array of values for multiple samples. - * @param timestamp Optionally the capture time of the most recent sample, in agreement with local_clock(); if omitted, the current time is used. - * The time stamps of other samples are automatically derived based on the sampling rate of the stream. - * @param pushthrough Optionally whether to push the chunk through to the receivers instead of buffering it with subsequent samples. - * Note that the chunk_size, if specified at outlet construction, takes precedence over the pushthrough flag. - */ - public void push_chunk(float[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_ftp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } - public void push_chunk(double[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_dtp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } - public void push_chunk(int[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_itp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } - public void push_chunk(short[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_stp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } - public void push_chunk(char[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_ctp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } - public void push_chunk(string[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_strtp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } - - /** - * Push a chunk of multiplexed samples into the outlet. One timestamp per sample is provided. - * @param data A rectangular array of values for multiple samples. - * @param timestamps An array of timestamp values holding time stamps for each sample in the data buffer. - * @param pushthrough Optionally whether to push the chunk through to the receivers instead of buffering it with subsequent samples. - * Note that the chunk_size, if specified at outlet construction, takes precedence over the pushthrough flag. - */ - public void push_chunk(float[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_ftnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } - public void push_chunk(double[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_dtnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } - public void push_chunk(int[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_itnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } - public void push_chunk(short[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_stnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } - public void push_chunk(char[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_ctnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } - public void push_chunk(string[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_strtnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } - - - // =============================== - // === Miscellaneous Functions === - // =============================== - - /** - * Check whether consumers are currently registered. - * While it does not hurt, there is technically no reason to push samples if there is no consumer. - */ - public bool have_consumers() { return dll.lsl_have_consumers(obj) > 0; } - - /** - * Wait until some consumer shows up (without wasting resources). - * @return True if the wait was successful, false if the timeout expired. - */ - public bool wait_for_consumers(double timeout = FOREVER) { return dll.lsl_wait_for_consumers(obj) > 0; } - - /** - * Retrieve the stream info provided by this outlet. - * This is what was used to create the stream (and also has the Additional Network Information fields assigned). - */ - public StreamInfo info() { return new StreamInfo(dll.lsl_get_info(obj)); } - - private IntPtr obj; - } - - - // =========================== - // ==== Resolve Functions ==== - // =========================== - - /** - * Resolve all streams on the network. - * This function returns all currently available streams from any outlet on the network. - * The network is usually the subnet specified at the local router, but may also include - * a multicast group of machines (given that the network supports it), or list of hostnames. - * These details may optionally be customized by the experimenter in a configuration file - * (see Network Connectivity in the LSL wiki). - * This is the default mechanism used by the browsing programs and the recording program. - * @param wait_time The waiting time for the operation, in seconds, to search for streams. - * Warning: If this is too short (less than 0.5s) only a subset (or none) of the - * outlets that are present on the network may be returned. - * @return An array of stream info objects (excluding their desc field), any of which can - * subsequently be used to open an inlet. The full info can be retrieve from the inlet. - */ - public static StreamInfo[] resolve_streams(double wait_time = 1.0) - { - IntPtr[] buf = new IntPtr[1024]; int num = dll.lsl_resolve_all(buf, (uint)buf.Length, wait_time); - StreamInfo[] res = new StreamInfo[num]; - for (int k = 0; k < num; k++) - res[k] = new StreamInfo(buf[k]); - return res; - } - - /** - * Resolve all streams with a specific value for a given property. - * If the goal is to resolve a specific stream, this method is preferred over resolving all streams and then selecting the desired one. - * @param prop The stream_info property that should have a specific value (e.g., "name", "type", "source_id", or "desc/manufaturer"). - * @param value The string value that the property should have (e.g., "EEG" as the type property). - * @param minimum Optionally return at least this number of streams. - * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout). - * If the timeout expires, less than the desired number of streams (possibly none) will be returned. - * @return An array of matching stream info objects (excluding their meta-data), any of - * which can subsequently be used to open an inlet. - */ - public static StreamInfo[] resolve_stream(string prop, string value, int minimum = 1, double timeout = FOREVER) - { - IntPtr[] buf = new IntPtr[1024]; int num = dll.lsl_resolve_byprop(buf, (uint)buf.Length, prop, value, minimum, timeout); - StreamInfo[] res = new StreamInfo[num]; - for (int k = 0; k < num; k++) - res[k] = new StreamInfo(buf[k]); - return res; - } - - /** - * Resolve all streams that match a given predicate. - * Advanced query that allows to impose more conditions on the retrieved streams; the given string is an XPath 1.0 - * predicate for the node (omitting the surrounding []'s), see also http://en.wikipedia.org/w/index.php?title=XPath_1.0&oldid=474981951. - * @param pred The predicate string, e.g. "name='BioSemi'" or "type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32" - * @param minimum Return at least this number of streams. - * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout). - * If the timeout expires, less than the desired number of streams (possibly none) will be returned. - * @return An array of matching stream info objects (excluding their meta-data), any of - * which can subsequently be used to open an inlet. - */ - public static StreamInfo[] resolve_stream(string pred, int minimum = 1, double timeout = FOREVER) - { - IntPtr[] buf = new IntPtr[1024]; int num = dll.lsl_resolve_bypred(buf, (uint)buf.Length, pred, minimum, timeout); - StreamInfo[] res = new StreamInfo[num]; - for (int k = 0; k < num; k++) - res[k] = new StreamInfo(buf[k]); - return res; - } - - - // ====================== - // ==== Stream Inlet ==== - // ====================== - - /** - * A stream inlet. - * Inlets are used to receive streaming data (and meta-data) from the lab network. - */ - public class StreamInlet - { - /** - * Construct a new stream inlet from a resolved stream info. - * @param info A resolved stream info object (as coming from one of the resolver functions). - * Note: the stream_inlet may also be constructed with a fully-specified stream_info, - * if the desired channel format and count is already known up-front, but this is - * strongly discouraged and should only ever be done if there is no time to resolve the - * stream up-front (e.g., due to limitations in the client program). - * @param max_buflen Optionally the maximum amount of data to buffer (in seconds if there is a nominal - * sampling rate, otherwise x100 in samples). Recording applications want to use a fairly - * large buffer size here, while real-time applications would only buffer as much as - * they need to perform their next calculation. - * @param max_chunklen Optionally the maximum size, in samples, at which chunks are transmitted - * (the default corresponds to the chunk sizes used by the sender). - * Recording applications can use a generous size here (leaving it to the network how - * to pack things), while real-time applications may want a finer (perhaps 1-sample) granularity. - If left unspecified (=0), the sender determines the chunk granularity. - * @param recover Try to silently recover lost streams that are recoverable (=those that that have a source_id set). - * In all other cases (recover is false or the stream is not recoverable) functions may throw a - * LostException if the stream's source is lost (e.g., due to an app or computer crash). - */ - public StreamInlet(StreamInfo info, int max_buflen = 360, int max_chunklen = 0, bool recover = true, processing_options_t postproc_flags = processing_options_t.proc_none) - { - obj = dll.lsl_create_inlet(info.handle(), max_buflen, max_chunklen, recover ? 1 : 0); - dll.lsl_set_postprocessing(obj, postproc_flags); - } - - /** - * Destructor. - * The inlet will automatically disconnect if destroyed. - */ - ~StreamInlet() { dll.lsl_destroy_inlet(obj); } - - /** - * Retrieve the complete information of the given stream, including the extended description. - * Can be invoked at any time of the stream's lifetime. - * @param timeout Timeout of the operation (default: no timeout). - * @throws TimeoutException (if the timeout expires), or LostException (if the stream source has been lost). - */ - public StreamInfo info(double timeout = FOREVER) { int ec = 0; IntPtr res = dll.lsl_get_fullinfo(obj, timeout, ref ec); check_error(ec); return new StreamInfo(res); } - - /** - * Subscribe to the data stream. - * All samples pushed in at the other end from this moment onwards will be queued and - * eventually be delivered in response to pull_sample() or pull_chunk() calls. - * Pulling a sample without some preceding open_stream is permitted (the stream will then be opened implicitly). - * @param timeout Optional timeout of the operation (default: no timeout). - * @throws TimeoutException (if the timeout expires), or LostException (if the stream source has been lost). - */ - public void open_stream(double timeout = FOREVER) { int ec = 0; dll.lsl_open_stream(obj, timeout, ref ec); check_error(ec); } - - /** - * Set post-processing flags to use. By default, the inlet performs NO post-processing and returns the - * ground-truth time stamps, which can then be manually synchronized using time_correction(), and then - * smoothed/dejittered if desired. This function allows automating these two and possibly more operations. - * Warning: when you enable this, you will no longer receive or be able to recover the original time stamps. - * @param flags An integer that is the result of bitwise OR'ing one or more options from processing_options_t - * together (e.g., post_clocksync|post_dejitter); the default is to enable all options. - */ - public void set_postprocessing() { set_postprocessing(processing_options_t.post_ALL); } - public void set_postprocessing(processing_options_t post_flags) { dll.lsl_set_postprocessing(obj, post_flags); } - - /** - * Drop the current data stream. - * All samples that are still buffered or in flight will be dropped and transmission - * and buffering of data for this inlet will be stopped. If an application stops being - * interested in data from a source (temporarily or not) but keeps the outlet alive, - * it should call close_stream() to not waste unnecessary system and network - * resources. - */ - public void close_stream() { dll.lsl_close_stream(obj); } - - /** - * Retrieve an estimated time correction offset for the given stream. - * The first call to this function takes several miliseconds until a reliable first estimate is obtained. - * Subsequent calls are instantaneous (and rely on periodic background updates). - * The precision of these estimates should be below 1 ms (empirically within +/-0.2 ms). - * @timeout Timeout to acquire the first time-correction estimate (default: no timeout). - * @return The time correction estimate. This is the number that needs to be added to a time stamp - * that was remotely generated via lsl_local_clock() to map it into the local clock domain of this machine. - * @throws TimeoutException (if the timeout expires), or LostException (if the stream source has been lost). - */ - public double time_correction(double timeout = FOREVER) { int ec = 0; double res = dll.lsl_time_correction(obj, timeout, ref ec); check_error(ec); return res; } - - // ======================================= - // === Pulling a sample from the inlet === - // ======================================= - - /** - * Pull a sample from the inlet and read it into an array of values. - * Handles type checking & conversion. - * @param sample An array to hold the resulting values. - * @param timeout The timeout for this operation, if any. Use 0.0 to make the function non-blocking. - * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was available. - * To remap this time stamp to the local clock, add the value returned by .time_correction() to it. - * @throws LostException (if the stream source has been lost). - */ - public double pull_sample(float[] sample, double timeout = FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_f(obj, sample, sample.Length, timeout, ref ec); check_error(ec); return res; } - public double pull_sample(double[] sample, double timeout = FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_d(obj, sample, sample.Length, timeout, ref ec); check_error(ec); return res; } - public double pull_sample(int[] sample, double timeout = FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_i(obj, sample, sample.Length, timeout, ref ec); check_error(ec); return res; } - public double pull_sample(short[] sample, double timeout = FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_s(obj, sample, sample.Length, timeout, ref ec); check_error(ec); return res; } - public double pull_sample(char[] sample, double timeout = FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_c(obj, sample, sample.Length, timeout, ref ec); check_error(ec); return res; } - public double pull_sample(string[] sample, double timeout = FOREVER) - { - int ec = 0; - IntPtr[] tmp = new IntPtr[sample.Length]; - double res = dll.lsl_pull_sample_str(obj, tmp, tmp.Length, timeout, ref ec); check_error(ec); - try - { - for (int k = 0; k < tmp.Length; k++) - sample[k] = Marshal.PtrToStringAnsi(tmp[k]); - } - finally - { - for (int k = 0; k < tmp.Length; k++) - dll.lsl_destroy_string(tmp[k]); - } - return res; - } - - - // ================================================= - // === Pulling a chunk of samples from the inlet === - // ================================================= - - /** - * Pull a chunk of data from the inlet. - * @param data_buffer A pre-allocated buffer where the channel data shall be stored. - * @param timestamp_buffer A pre-allocated buffer where time stamps shall be stored. - * @param timeout Optionally the timeout for this operation, if any. When the timeout expires, the function - * may return before the entire buffer is filled. The default value of 0.0 will retrieve only - * data available for immediate pickup. - * @return samples_written Number of samples written to the data and timestamp buffers. - * @throws LostException (if the stream source has been lost). - */ - public int pull_chunk(float[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_f(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); check_error(ec); return (int)res / data_buffer.GetLength(1); } - public int pull_chunk(double[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_d(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); check_error(ec); return (int)res / data_buffer.GetLength(1); } - public int pull_chunk(int[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_i(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); check_error(ec); return (int)res / data_buffer.GetLength(1); } - public int pull_chunk(short[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_s(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); check_error(ec); return (int)res / data_buffer.GetLength(1); } - public int pull_chunk(char[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_c(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); check_error(ec); return (int)res / data_buffer.GetLength(1); } - public int pull_chunk(string[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) - { - int ec = 0; - IntPtr[,] tmp = new IntPtr[data_buffer.GetLength(0), data_buffer.GetLength(1)]; - uint res = dll.lsl_pull_chunk_str(obj, tmp, timestamp_buffer, (uint)tmp.Length, (uint)timestamp_buffer.Length, timeout, ref ec); - check_error(ec); - try - { - for (int s = 0; s < tmp.GetLength(0); s++) - for (int c = 0; c < tmp.GetLength(1); c++) - data_buffer[s, c] = Marshal.PtrToStringAnsi(tmp[s, c]); - } - finally - { - for (int s = 0; s < tmp.GetLength(0); s++) - for (int c = 0; c < tmp.GetLength(1); c++) - dll.lsl_destroy_string(tmp[s, c]); - } - return (int)res / data_buffer.GetLength(1); - } - - /** - * Query whether samples are currently available for immediate pickup. - * Note that it is not a good idea to use samples_available() to determine whether - * a pull_*() call would block: to be sure, set the pull timeout to 0.0 or an acceptably - * low value. If the underlying implementation supports it, the value will be the number of - * samples available (otherwise it will be 1 or 0). - */ - public int samples_available() { return (int)dll.lsl_samples_available(obj); } - - /** - * Query whether the clock was potentially reset since the last call to was_clock_reset(). - * This is a rarely-used function that is only useful to applications that combine multiple time_correction - * values to estimate precise clock drift; it allows to tolerate cases where the source machine was - * hot-swapped or restarted in between two measurements. - */ - public bool was_clock_reset() { return (int)dll.lsl_was_clock_reset(obj) != 0; } - - private IntPtr obj; - } - - - // ===================== - // ==== XML Element ==== - // ===================== - - /** - * A lightweight XML element tree; models the .desc() field of stream_info. - * Has a name and can have multiple named children or have text content as value; attributes are omitted. - * Insider note: The interface is modeled after a subset of pugixml's node type and is compatible with it. - * See also http://pugixml.googlecode.com/svn/tags/latest/docs/manual/access.html for additional documentation. - */ - public struct XMLElement - { - public XMLElement(IntPtr handle) { obj = handle; } - - // === Tree Navigation === - - /// Get the first child of the element. - public XMLElement first_child() { return new XMLElement(dll.lsl_first_child(obj)); } - - /// Get the last child of the element. - public XMLElement last_child() { return new XMLElement(dll.lsl_last_child(obj)); } - - /// Get the next sibling in the children list of the parent node. - public XMLElement next_sibling() { return new XMLElement(dll.lsl_next_sibling(obj)); } - - /// Get the previous sibling in the children list of the parent node. - public XMLElement previous_sibling() { return new XMLElement(dll.lsl_previous_sibling(obj)); } - - /// Get the parent node. - public XMLElement parent() { return new XMLElement(dll.lsl_parent(obj)); } - - - // === Tree Navigation by Name === - - /// Get a child with a specified name. - public XMLElement child(string name) { return new XMLElement(dll.lsl_child(obj, name)); } - - /// Get the next sibling with the specified name. - public XMLElement next_sibling(string name) { return new XMLElement(dll.lsl_next_sibling_n(obj, name)); } - - /// Get the previous sibling with the specified name. - public XMLElement previous_sibling(string name) { return new XMLElement(dll.lsl_previous_sibling_n(obj, name)); } - - - // === Content Queries === - - /// Whether this node is empty. - public bool empty() { return dll.lsl_empty(obj) != 0; } - - /// Whether this is a text body (instead of an XML element). True both for plain char data and CData. - public bool is_text() { return dll.lsl_is_text(obj) != 0; } - - /// Name of the element. - public string name() { return Marshal.PtrToStringAnsi(dll.lsl_name(obj)); } - - /// Value of the element. - public string value() { return Marshal.PtrToStringAnsi(dll.lsl_value(obj)); } - - /// Get child value (value of the first child that is text). - public string child_value() { return Marshal.PtrToStringAnsi(dll.lsl_child_value(obj)); } - - /// Get child value of a child with a specified name. - public string child_value(string name) { return Marshal.PtrToStringAnsi(dll.lsl_child_value_n(obj, name)); } - - - // === Modification === - - /** - * Append a child node with a given name, which has a (nameless) plain-text child with the given text value. - */ - public XMLElement append_child_value(string name, string value) { return new XMLElement(dll.lsl_append_child_value(obj, name, value)); } - - /** - * Prepend a child node with a given name, which has a (nameless) plain-text child with the given text value. - */ - public XMLElement prepend_child_value(string name, string value) { return new XMLElement(dll.lsl_prepend_child_value(obj, name, value)); } - - /** - * Set the text value of the (nameless) plain-text child of a named child node. - */ - public bool set_child_value(string name, string value) { return dll.lsl_set_child_value(obj, name, value) != 0; } - - /** - * Set the element's name. - * @return False if the node is empty. - */ - public bool set_name(string rhs) { return dll.lsl_set_name(obj, rhs) != 0; } - - /** - * Set the element's value. - * @return False if the node is empty. - */ - public bool set_value(string rhs) { return dll.lsl_set_value(obj, rhs) != 0; } - - /// Append a child element with the specified name. - public XMLElement append_child(string name) { return new XMLElement(dll.lsl_append_child(obj, name)); } - - /// Prepend a child element with the specified name. - public XMLElement prepend_child(string name) { return new XMLElement(dll.lsl_prepend_child(obj, name)); } - - /// Append a copy of the specified element as a child. - public XMLElement append_copy(XMLElement e) { return new XMLElement(dll.lsl_append_copy(obj, e.obj)); } - - /// Prepend a child element with the specified name. - public XMLElement prepend_copy(XMLElement e) { return new XMLElement(dll.lsl_prepend_copy(obj, e.obj)); } - - /// Remove a child element with the specified name. - public void remove_child(string name) { dll.lsl_remove_child_n(obj, name); } - - /// Remove a specified child element. - public void remove_child(XMLElement e) { dll.lsl_remove_child(obj, e.obj); } - - IntPtr obj; - } - - - // =========================== - // === Continuous Resolver === - // =========================== - - /** - * A convenience class that resolves streams continuously in the background throughout - * its lifetime and which can be queried at any time for the set of streams that are currently - * visible on the network. - */ - - public class ContinuousResolver - { - /** - * Construct a new continuous_resolver that resolves all streams on the network. - * This is analogous to the functionality offered by the free function resolve_streams(). - * @param forget_after When a stream is no longer visible on the network (e.g., because it was shut down), - * this is the time in seconds after which it is no longer reported by the resolver. - */ - public ContinuousResolver() { obj = dll.lsl_create_continuous_resolver(5.0); } - public ContinuousResolver(double forget_after) { obj = dll.lsl_create_continuous_resolver(forget_after); } - - /** - * Construct a new continuous_resolver that resolves all streams with a specific value for a given property. - * This is analogous to the functionality provided by the free function resolve_stream(prop,value). - * @param prop The stream_info property that should have a specific value (e.g., "name", "type", "source_id", or "desc/manufaturer"). - * @param value The string value that the property should have (e.g., "EEG" as the type property). - * @param forget_after When a stream is no longer visible on the network (e.g., because it was shut down), - * this is the time in seconds after which it is no longer reported by the resolver. - */ - public ContinuousResolver(string prop, string value) { obj = dll.lsl_create_continuous_resolver_byprop(prop, value, 5.0); } - public ContinuousResolver(string prop, string value, double forget_after) { obj = dll.lsl_create_continuous_resolver_byprop(prop, value, forget_after); } - - /** - * Construct a new continuous_resolver that resolves all streams that match a given XPath 1.0 predicate. - * This is analogous to the functionality provided by the free function resolve_stream(pred). - * @param pred The predicate string, e.g. "name='BioSemi'" or "type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32" - * @param forget_after When a stream is no longer visible on the network (e.g., because it was shut down), - * this is the time in seconds after which it is no longer reported by the resolver. - */ - public ContinuousResolver(string pred) { obj = dll.lsl_create_continuous_resolver_bypred(pred, 5.0); } - public ContinuousResolver(string pred, double forget_after) { obj = dll.lsl_create_continuous_resolver_bypred(pred, forget_after); } - - /** - * Destructor. - */ - ~ContinuousResolver() { dll.lsl_destroy_continuous_resolver(obj); } - - /** - * Obtain the set of currently present streams on the network (i.e. resolve result). - * @return An array of matching stream info objects (excluding their meta-data), any of - * which can subsequently be used to open an inlet. - */ - public StreamInfo[] results() - { - IntPtr[] buf = new IntPtr[1024]; - int num = dll.lsl_resolver_results(obj, buf, (uint)buf.Length); - StreamInfo[] res = new StreamInfo[num]; - for (int k = 0; k < num; k++) - res[k] = new StreamInfo(buf[k]); - return res; - } - - private IntPtr obj; - } - - // ======================= - // === Exception Types === - // ======================= - - /** - * Exception class that indicates that a stream inlet's source has been irrecoverably lost. - */ - public class LostException : System.Exception - { - public LostException() { } - public LostException(string message) { } - public LostException(string message, System.Exception inner) { } - protected LostException(System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) - { } - } - - /** - * Exception class that indicates that an internal error has occurred inside liblsl. - */ - public class InternalException : System.Exception - { - public InternalException() { } - public InternalException(string message) { } - public InternalException(string message, System.Exception inner) { } - protected InternalException(System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) - { } - } - - /** - * Check an error condition and throw an exception if appropriate. - */ - public static void check_error(int ec) - { - if (ec < 0) - switch (ec) - { - case -1: throw new TimeoutException("The operation failed due to a timeout."); - case -2: throw new LostException("The stream has been lost."); - case -3: throw new ArgumentException("An argument was incorrectly specified (e.g., wrong format or wrong length)."); - case -4: throw new InternalException("An internal internal error has occurred."); - default: throw new Exception("An unknown error has occurred."); - } - } - - - - // === Internal: C library function definitions. === - - class dll - { - -#if (UNITY_EDITOR_WIN && UNITY_EDITOR_64) - const string libname = "liblsl64"; -#elif UNITY_EDITOR_WIN - const string libname = "liblsl32"; -#elif UNITY_STANDALONE_WIN - // a build hook will took care that the correct dll will be renamed after a successfull build - const string libname = "liblsl"; -#elif (UNITY_EDITOR_LINUX && UNITY_EDITOR_64) || UNITY_STANDALONE_LINUX - const string libname = "liblsl64.so"; -#elif UNITY_EDITOR_LINUX - const string libname = "liblsl32.so"; -#elif UNITY_STANDALONE_LINUX - const string libname = "liblsl.so"; -#elif Unity_EDITOR_OSX || UNITY_STANDALONE_OSX - //32-bit dylib no longer provided. - const string libname = "liblsl64"; -#elif UNITY_STANDALONE_OSX - const string libname = "liblsl"; -#elif UNITY_ANDROID - const string libname = "lslAndroid"; -#endif - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_protocol_version(); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_library_version(); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_local_clock(); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_create_streaminfo(string name, string type, int channel_count, double nominal_srate, channel_format_t channel_format, string source_id); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_destroy_streaminfo(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_name(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_type(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_get_channel_count(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_get_nominal_srate(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern channel_format_t lsl_get_channel_format(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_source_id(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_get_version(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_get_created_at(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_uid(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_session_id(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_hostname(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_desc(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_xml(IntPtr info); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_create_outlet(IntPtr info, int chunk_size, int max_buffered); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern void lsl_destroy_outlet(IntPtr obj); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_sample_ftp(IntPtr obj, float[] data, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_sample_dtp(IntPtr obj, double[] data, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_sample_itp(IntPtr obj, int[] data, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_sample_stp(IntPtr obj, short[] data, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_sample_ctp(IntPtr obj, char[] data, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_sample_strtp(IntPtr obj, string[] data, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_sample_buftp(IntPtr obj, char[][] data, uint[] lengths, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_ftp(IntPtr obj, float[,] data, uint data_elements, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_ftnp(IntPtr obj, float[,] data, uint data_elements, double[] timestamps, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_dtp(IntPtr obj, double[,] data, uint data_elements, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_dtnp(IntPtr obj, double[,] data, uint data_elements, double[] timestamps, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_itp(IntPtr obj, int[,] data, uint data_elements, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_itnp(IntPtr obj, int[,] data, uint data_elements, double[] timestamps, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_stp(IntPtr obj, short[,] data, uint data_elements, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_stnp(IntPtr obj, short[,] data, uint data_elements, double[] timestamps, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_ctp(IntPtr obj, char[,] data, uint data_elements, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_ctnp(IntPtr obj, char[,] data, uint data_elements, double[] timestamps, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_strtp(IntPtr obj, string[,] data, uint data_elements, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_strtnp(IntPtr obj, string[,] data, uint data_elements, double[] timestamps, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_buftp(IntPtr obj, char[][] data, uint[] lengths, uint data_elements, double timestamp, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_push_chunk_buftnp(IntPtr obj, char[][] data, uint[] lengths, uint data_elements, double[] timestamps, int pushthrough); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_have_consumers(IntPtr obj); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_wait_for_consumers(IntPtr obj); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_info(IntPtr obj); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_resolve_all(IntPtr[] buffer, uint buffer_elements, double wait_time); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_resolve_byprop(IntPtr[] buffer, uint buffer_elements, string prop, string value, int minimum, double wait_time); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_resolve_bypred(IntPtr[] buffer, uint buffer_elements, string pred, int minimum, double wait_time); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_create_inlet(IntPtr info, int max_buflen, int max_chunklen, int recover); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern void lsl_destroy_inlet(IntPtr obj); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_get_fullinfo(IntPtr obj, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern void lsl_open_stream(IntPtr obj, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern void lsl_close_stream(IntPtr obj); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_time_correction(IntPtr obj, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_set_postprocessing(IntPtr obj, processing_options_t flags); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_pull_sample_f(IntPtr obj, float[] buffer, int buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_pull_sample_d(IntPtr obj, double[] buffer, int buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_pull_sample_i(IntPtr obj, int[] buffer, int buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_pull_sample_s(IntPtr obj, short[] buffer, int buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_pull_sample_c(IntPtr obj, char[] buffer, int buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_pull_sample_str(IntPtr obj, IntPtr[] buffer, int buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern double lsl_pull_sample_buf(IntPtr obj, char[][] buffer, uint[] buffer_lengths, int buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern void lsl_destroy_string(IntPtr str); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern uint lsl_pull_chunk_f(IntPtr obj, float[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern uint lsl_pull_chunk_d(IntPtr obj, double[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern uint lsl_pull_chunk_i(IntPtr obj, int[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern uint lsl_pull_chunk_s(IntPtr obj, short[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern uint lsl_pull_chunk_c(IntPtr obj, char[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern uint lsl_pull_chunk_str(IntPtr obj, IntPtr[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern uint lsl_pull_chunk_buf(IntPtr obj, char[][,] data_buffer, uint[,] lengths_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern uint lsl_samples_available(IntPtr obj); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern uint lsl_was_clock_reset(IntPtr obj); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_first_child(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_last_child(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_next_sibling(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_previous_sibling(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_parent(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_child(IntPtr e, string name); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_next_sibling_n(IntPtr e, string name); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_previous_sibling_n(IntPtr e, string name); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_empty(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_is_text(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_name(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_value(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_child_value(IntPtr e); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_child_value_n(IntPtr e, string name); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_append_child_value(IntPtr e, string name, string value); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_prepend_child_value(IntPtr e, string name, string value); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_set_child_value(IntPtr e, string name, string value); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_set_name(IntPtr e, string rhs); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_set_value(IntPtr e, string rhs); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_append_child(IntPtr e, string name); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_prepend_child(IntPtr e, string name); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_append_copy(IntPtr e, IntPtr e2); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_prepend_copy(IntPtr e, IntPtr e2); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern void lsl_remove_child_n(IntPtr e, string name); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern void lsl_remove_child(IntPtr e, IntPtr e2); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_create_continuous_resolver(double forget_after); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_create_continuous_resolver_byprop(string prop, string value, double forget_after); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern IntPtr lsl_create_continuous_resolver_bypred(string pred, double forget_after); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern int lsl_resolver_results(IntPtr obj, IntPtr[] buffer, uint buffer_elements); - - [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] - public static extern void lsl_destroy_continuous_resolver(IntPtr obj); - } - } -} diff --git a/LSL.cs.meta b/LSL.cs.meta deleted file mode 100644 index cca68c6..0000000 --- a/LSL.cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 56980b66c061a714db92254f447b7292 -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: diff --git a/Plugins.meta b/Plugins.meta index d6a3d21..9c4715d 100644 --- a/Plugins.meta +++ b/Plugins.meta @@ -1,9 +1,8 @@ fileFormatVersion: 2 -guid: 9ff57f792c67a60419748e2bbc277796 +guid: ea06985163fd5274fbf931754d5f5980 folderAsset: yes -timeCreated: 1490478329 -licenseType: Free DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/Scripts/Examples.meta b/Plugins/LSL/Windows.meta similarity index 57% rename from Scripts/Examples.meta rename to Plugins/LSL/Windows.meta index 6bcce04..c8a159a 100644 --- a/Scripts/Examples.meta +++ b/Plugins/LSL/Windows.meta @@ -1,9 +1,8 @@ fileFormatVersion: 2 -guid: 6659c9ee82049744b8389fb20566159f +guid: cefd2a2cdb521ee40b697c5910ee0fa4 folderAsset: yes -timeCreated: 1469175164 -licenseType: Free DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/Demos.meta b/Plugins/LSL/Windows/x64.meta similarity index 57% rename from Demos.meta rename to Plugins/LSL/Windows/x64.meta index 4baef76..02f5288 100644 --- a/Demos.meta +++ b/Plugins/LSL/Windows/x64.meta @@ -1,9 +1,8 @@ fileFormatVersion: 2 -guid: 2ca0d7588caddeb419150aa68a92a048 +guid: a5db2c3ba9f99634fbd3e70272a45e41 folderAsset: yes -timeCreated: 1470245112 -licenseType: Free DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/Plugins/LSL/Windows/x64/lsl.dll b/Plugins/LSL/Windows/x64/lsl.dll new file mode 100644 index 0000000..049546d Binary files /dev/null and b/Plugins/LSL/Windows/x64/lsl.dll differ diff --git a/Plugins/LSL/Windows/x64/lsl.dll.meta b/Plugins/LSL/Windows/x64/lsl.dll.meta new file mode 100644 index 0000000..fc300ea --- /dev/null +++ b/Plugins/LSL/Windows/x64/lsl.dll.meta @@ -0,0 +1,63 @@ +fileFormatVersion: 2 +guid: 84f455e7a1d9f2146b97c2c3652d492a +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 1 + Exclude Win64: 0 + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Windows + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: x86_64 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/Windows/x64/lsl.lib b/Plugins/LSL/Windows/x64/lsl.lib new file mode 100644 index 0000000..cfb383b Binary files /dev/null and b/Plugins/LSL/Windows/x64/lsl.lib differ diff --git a/Demos/Demo_RotatingCube.unity.meta b/Plugins/LSL/Windows/x64/lsl.lib.meta similarity index 53% rename from Demos/Demo_RotatingCube.unity.meta rename to Plugins/LSL/Windows/x64/lsl.lib.meta index 1ed776b..786e480 100644 --- a/Demos/Demo_RotatingCube.unity.meta +++ b/Plugins/LSL/Windows/x64/lsl.lib.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 2ffabf00099d5d949bff8fc861a8f09a -timeCreated: 1470244953 -licenseType: Free +guid: 7b063fb4701ed9649a0900751435af06 DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/Plugins/LSL/Windows/x86.meta b/Plugins/LSL/Windows/x86.meta new file mode 100644 index 0000000..3dd61d0 --- /dev/null +++ b/Plugins/LSL/Windows/x86.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 947bfa33b7e753e4ab7d1666b0d82cc4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/Windows/x86/lsl.dll b/Plugins/LSL/Windows/x86/lsl.dll new file mode 100644 index 0000000..f6b3ec6 Binary files /dev/null and b/Plugins/LSL/Windows/x86/lsl.dll differ diff --git a/Plugins/LSL/Windows/x86/lsl.dll.meta b/Plugins/LSL/Windows/x86/lsl.dll.meta new file mode 100644 index 0000000..773c5ba --- /dev/null +++ b/Plugins/LSL/Windows/x86/lsl.dll.meta @@ -0,0 +1,63 @@ +fileFormatVersion: 2 +guid: 799c670a87bbcae4db410bd6526e4519 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 0 + Exclude Win64: 1 + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86 + DefaultValueInitialized: true + OS: Windows + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: x86 + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: None + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/Windows/x86/lsl.lib b/Plugins/LSL/Windows/x86/lsl.lib new file mode 100644 index 0000000..5bdd6e3 Binary files /dev/null and b/Plugins/LSL/Windows/x86/lsl.lib differ diff --git a/Plugins/LSL/Windows/x86/lsl.lib.meta b/Plugins/LSL/Windows/x86/lsl.lib.meta new file mode 100644 index 0000000..e815337 --- /dev/null +++ b/Plugins/LSL/Windows/x86/lsl.lib.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 891f7a0df3849994792c2e6ece11ace8 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include.meta b/Plugins/LSL/include.meta new file mode 100644 index 0000000..1b7d31d --- /dev/null +++ b/Plugins/LSL/include.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e91dee10b228ebd44ba71ee63da5bc60 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl.meta b/Plugins/LSL/include/lsl.meta new file mode 100644 index 0000000..b275ed6 --- /dev/null +++ b/Plugins/LSL/include/lsl.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7a365d7b8b3510648a160b589d4644fe +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl/common.h b/Plugins/LSL/include/lsl/common.h new file mode 100644 index 0000000..3c81c79 --- /dev/null +++ b/Plugins/LSL/include/lsl/common.h @@ -0,0 +1,229 @@ +#pragma once + +//! @file common.h Global constants for liblsl + +#if defined(LIBLSL_FFI) +// Skip any typedefs that might confuse a FFI header parser, e.g. cffi +#elif defined(_MSC_VER) && _MSC_VER < 1600 +typedef signed char int8_t; +typedef signed short int16_t; +typedef signed int int32_t; +typedef signed long long int64_t; +typedef unsigned int uint32_t; +#else +#include +#endif + +#if defined(_MSC_VER) && _MSC_VER < 1900 +#define __func__ __FUNCTION__ +#endif + +/// LIBLSL_C_API expands function attributes needed for the linker +#if defined(LIBLSL_STATIC) || defined(LIBLSL_FFI) +#define LIBLSL_C_API +#elif defined _WIN32 || defined __CYGWIN__ +#if defined LIBLSL_EXPORTS +#define LIBLSL_C_API __declspec(dllexport) +#else +#define LIBLSL_C_API __declspec(dllimport) +#ifndef LSLNOAUTOLINK +#pragma comment(lib, "lsl.lib") +#endif +#endif +#pragma warning(disable : 4275) +#else // Linux / OS X +#define LIBLSL_C_API __attribute__((visibility("default"))) +#endif + +/// Constant to indicate that a stream has variable sampling rate. +#define LSL_IRREGULAR_RATE 0.0 + +/** + * Constant to indicate that a sample has the next successive time stamp. + * + * This is an optional optimization to transmit less data per sample. + * The stamp is then deduced from the preceding one according to the stream's + * sampling rate (in the case of an irregular rate, the same time stamp as + * before will is assumed). */ +#define LSL_DEDUCED_TIMESTAMP -1.0 + +/// A very large time value (ca. 1 year); can be used in timeouts. +#define LSL_FOREVER 32000000.0 + +/** + * Constant to indicate that there is no preference about how a data stream + * shall be chunked for transmission. + * (can be used for the chunking parameters in the inlet or the outlet). + */ +#define LSL_NO_PREFERENCE 0 + +/// Data format of a channel (each transmitted sample holds an array of channels), 4 bytes wide +typedef enum { + /** For up to 24-bit precision measurements in the appropriate physical unit (e.g., microvolts). + * Integers from -16777216 to 16777216 are represented accurately. */ + cft_float32 = 1, + /** For universal numeric data as long as permitted by network & disk budget. + * The largest representable integer is 53-bit. */ + cft_double64 = 2, + /** For variable-length ASCII strings or data blobs, such as video frames, complex event + descriptions, etc. */ + cft_string = 3, + /** For high-rate digitized formats that require 32-bit precision. + * Depends critically on meta-data to represent meaningful units. + * Useful for application event codes or other coded data. */ + cft_int32 = 4, + /** For very high rate signals (40Khz+) or consumer-grade audio. + * For professional audio float is recommended. */ + cft_int16 = 5, + /// For binary signals or other coded data. Not recommended for encoding string data. + cft_int8 = 6, + /** 64 bit integers. Support for this type is not yet exposed in all languages. + * Also, some builds of liblsl will not be able to send or receive data of this type. */ + cft_int64 = 7, + /// Can not be transmitted. + cft_undefined = 0, + + // prevent compilers from assuming an instance fits in a single byte + _cft_maxval = 0x7f000000 +} lsl_channel_format_t; + +// Abort compilation if lsl_channel_format_t isn't exactly 4 bytes wide +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +_Static_assert(sizeof(lsl_channel_format_t) == 4, "lsl_channel_format_t size breaks the LSL ABI"); +#elif defined(__cplusplus) && __cplusplus >= 201103L +static_assert (sizeof(lsl_channel_format_t) == 4, "lsl_channel_format_t size breaks the LSL ABI"); +#elif !defined(LIBLSL_FFI) +static char _lsl_channel_format_size_check[1 - 2*!(sizeof(lsl_channel_format_t)==4)]; +#endif + +/// Post-processing options for stream inlets. +typedef enum { + /** No automatic post-processing; return the ground-truth time stamps for manual + post-processing. This is the default behavior of the inlet. */ + proc_none = 0, + + /** Perform automatic clock synchronization; equivalent to manually adding the time_correction() + value to the received time stamps. */ + proc_clocksync = 1, + + /** Remove jitter from time stamps. + * + * This will apply a smoothing algorithm to the received time stamps; the smoothing needs to see + * a minimum number of samples (30-120 seconds worst-case) until the remaining jitter is + * consistently below 1ms. */ + proc_dejitter = 2, + + /** Force the time-stamps to be monotonically ascending. + * + * Only makes sense if timestamps are dejittered. */ + proc_monotonize = 4, + + /** Post-processing is thread-safe (same inlet can be read from by multiple threads); + * uses somewhat more CPU. */ + proc_threadsafe = 8, + + /// The combination of all possible post-processing options. + proc_ALL = 1 | 2 | 4 | 8, + + // prevent compilers from assuming an instance fits in a single byte + _proc_maxval = 0x7f000000 +} lsl_processing_options_t; + +/// Possible error codes. +typedef enum { + /// No error occurred + lsl_no_error = 0, + + /// The operation failed due to a timeout. + lsl_timeout_error = -1, + + /// The stream has been lost. + lsl_lost_error = -2, + + /// An argument was incorrectly specified (e.g., wrong format or wrong length). + lsl_argument_error = -3, + + /// Some other internal error has happened. + lsl_internal_error = -4, + + // prevent compilers from assuming an instance fits in a single byte + _lsl_error_code_maxval = 0x7f000000 +} lsl_error_code_t; + +/// Flags for outlet_ex and inlet_ex +typedef enum { + /// Keep legacy behavior: max_buffered / max_buflen is in seconds; use asynch transfer. + transp_default = 0, + + /// The supplied max_buf value is in samples. + transp_bufsize_samples = 1, + + /// The supplied max_buf should be scaled by 0.001. + transp_bufsize_thousandths = 2, + + // prevent compilers from assuming an instance fits in a single byte + _lsl_transport_options_maxval = 0x7f000000 +} lsl_transport_options_t; + +/// Return an explanation for the last error +extern LIBLSL_C_API const char *lsl_last_error(void); + +/** + * LSL version the binary was compiled against + * + * Used either to check if the same version is used + * (`if(lsl_protocol_version()!=LIBLSL_COMPILE_HEADER_VERSION`) … + * or to require a certain set of features: + * ``` + * #if LIBLSL_COMPILE_HEADER_VERSION > 113 + * do_stuff(); + * #endif + * ``` + * */ +#define LIBLSL_COMPILE_HEADER_VERSION 114 + +/** + * Protocol version. + * + * The major version is `protocol_version() / 100;` + * The minor version is `protocol_version() % 100;` + * + * Clients with different minor versions are protocol-compatible while clients + * with different major versions will refuse to work together. + */ +extern LIBLSL_C_API int32_t lsl_protocol_version(); + +/** + * Version of the liblsl library. + * + * The major version is `library_version() / 100;` + * The minor version is `library_version() % 100;` + */ +extern LIBLSL_C_API int32_t lsl_library_version(); + +/** + * Get a string containing library information. + * + * The format of the string shouldn't be used for anything important except giving a debugging + * person a good idea which exact library version is used. */ +extern LIBLSL_C_API const char *lsl_library_info(void); + +/** + * Obtain a local system time stamp in seconds. + * + * The resolution is better than a millisecond. + * This reading can be used to assign time stamps to samples as they are being acquired. + * If the "age" of a sample is known at a particular time (e.g., from USB transmission + * delays), it can be used as an offset to lsl_local_clock() to obtain a better estimate of + * when a sample was actually captured. See lsl_push_sample() for a use case. + */ +extern LIBLSL_C_API double lsl_local_clock(); + +/** + * Deallocate a string that has been transferred to the application. + * + * Rarely used: the only use case is to deallocate the contents of + * string-valued samples received from LSL in an application where + * no free() method is available (e.g., in some scripting languages). + */ +extern LIBLSL_C_API void lsl_destroy_string(char *s); diff --git a/Plugins/LSL/include/lsl/common.h.meta b/Plugins/LSL/include/lsl/common.h.meta new file mode 100644 index 0000000..0f60a43 --- /dev/null +++ b/Plugins/LSL/include/lsl/common.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 2d7b3e9ecf417334fa6fa9648f418ff1 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl/inlet.h b/Plugins/LSL/include/lsl/inlet.h new file mode 100644 index 0000000..78aa60d --- /dev/null +++ b/Plugins/LSL/include/lsl/inlet.h @@ -0,0 +1,309 @@ +#pragma once +#include "common.h" +#include "types.h" + + +/// @file inlet.h Stream inlet functions + +/** @defgroup lsl_inlet The lsl_inlet object + * @{ + */ + +/** + * Construct a new stream inlet from a resolved stream info. + * @param info A resolved stream info object (as coming from one of the resolver functions). + * @note The inlet makes a copy of the info object at its construction. + * @note The stream_inlet may also be constructed with a fully-specified stream_info, if the desired + * channel format and count is already known up-front, but this is strongly discouraged and should + * only ever be done if there is no time to resolve the stream up-front (e.g., due to limitations + * in the client program). + * @param max_buflen Optionally the maximum amount of data to buffer (in seconds if there is a + * nominal sampling rate, otherwise x100 in samples). + * + * Recording applications want to use a fairly large buffer size here, while real-time applications + * would only buffer as much as they need to perform their next calculation. + * + * A good default is 360, which corresponds to 6 minutes of data. + * @param max_chunklen Optionally the maximum size, in samples, at which chunks are transmitted. + * If specified as 0, the chunk sizes preferred by the sender are used. + * Recording applications can use a generous size here (leaving it to the network how to pack + * things), while real-time applications may want a finer (perhaps 1-sample) granularity. + * @param recover Try to silently recover lost streams that are recoverable (=those that that have a + * source_id set). + * + * It is generally a good idea to enable this, unless the application wants to act in a special way + * when a data provider has temporarily crashed. + * + * If recover is 0 or the stream is not recoverable, most outlet functions will return an + * #lsl_lost_error if the stream's source is lost. + * @return A newly created lsl_inlet handle or NULL in the event that an error occurred. + */ +extern LIBLSL_C_API lsl_inlet lsl_create_inlet(lsl_streaminfo info, int32_t max_buflen, int32_t max_chunklen, int32_t recover); +/** @copydoc lsl_create_inlet() + * @param flags An integer that is the result of bitwise OR'ing one or more options from + * #lsl_transport_options_t together (e.g., #transp_bufsize_samples) + */ +extern LIBLSL_C_API lsl_inlet lsl_create_inlet_ex(lsl_streaminfo info, int32_t max_buflen, + int32_t max_chunklen, int32_t recover, lsl_transport_options_t flags); + +/** +* Destructor. +* The inlet will automatically disconnect if destroyed. +*/ +extern LIBLSL_C_API void lsl_destroy_inlet(lsl_inlet in); + +/** + * Retrieve the complete information of the given stream, including the extended description. + * Can be invoked at any time of the stream's lifetime. + * @param in The lsl_inlet object to act on. + * @param timeout Timeout of the operation. Use LSL_FOREVER to effectively disable it. + * @param[out] ec Error code: if nonzero, can be either lsl_timeout_error (if the timeout has + * expired) or #lsl_lost_error (if the stream source has been lost). + * @return A copy of the full streaminfo of the inlet or NULL in the event that an error happened. + * @note It is the user's responsibility to destroy it when it is no longer needed. + */ +extern LIBLSL_C_API lsl_streaminfo lsl_get_fullinfo(lsl_inlet in, double timeout, int32_t *ec); + +/** + * Subscribe to the data stream. + * + * All samples pushed in at the other end from this moment onwards will be queued and + * eventually be delivered in response to pull_sample() calls. + * Pulling a sample without some preceding lsl_open_stream() is permitted (the stream will then be + * opened implicitly). + * @param in The lsl_inlet object to act on. + * @param timeout Optional timeout of the operation. Use LSL_FOREVER to effectively disable it. + * @param[out] ec Error code: if nonzero, can be either #lsl_timeout_error (if the timeout has + * expired) or lsl_lost_error (if the stream source has been lost). + */ +extern LIBLSL_C_API void lsl_open_stream(lsl_inlet in, double timeout, int32_t *ec); + +/** +* Drop the current data stream. +* +* All samples that are still buffered or in flight will be dropped and transmission +* and buffering of data for this inlet will be stopped. If an application stops being +* interested in data from a source (temporarily or not) but keeps the outlet alive, +* it should call lsl_close_stream() to not waste unnecessary system and network +* resources. +*/ +extern LIBLSL_C_API void lsl_close_stream(lsl_inlet in); + +/** + * @brief Retrieve an estimated time correction offset for the given stream. + * + * The first call to this function takes several milliseconds until a reliable first estimate is + * obtained. Subsequent calls are instantaneous (and rely on periodic background updates). + * + * On a well-behaved network, the precision of these estimates should be below 1 ms (empirically it + * is within +/-0.2 ms). + * + * To get a measure of whether the network is well-behaved, use #lsl_time_correction_ex and check + * uncertainty (which maps to round-trip-time). 0.2 ms is typical of wired networks. + * + * 2 ms is typical of wireless networks. The number can be much higher on poor networks. + * + * @param in The lsl_inlet object to act on. + * @param timeout Timeout to acquire the first time-correction estimate. + * Use LSL_FOREVER to defuse the timeout. + * @param[out] ec Error code: if nonzero, can be either #lsl_timeout_error (if the timeout has + * expired) or lsl_lost_error (if the stream source has been lost). + * @return The time correction estimate. + * This is the number that needs to be added to a time stamp that was remotely generated via + * lsl_local_clock() to map it into the local clock domain of this machine. + */ +extern LIBLSL_C_API double lsl_time_correction(lsl_inlet in, double timeout, int32_t *ec); +/** @copydoc lsl_time_correction() + * @param remote_time The current time of the remote computer that was used to generate this + * time_correction. + * If desired, the client can fit time_correction vs remote_time to improve the real-time + * time_correction further. + * @param uncertainty The maximum uncertainty of the given time correction. + */ +extern LIBLSL_C_API double lsl_time_correction_ex(lsl_inlet in, double *remote_time, double *uncertainty, double timeout, int32_t *ec); + + +/** + * Set post-processing flags to use. + * + * By default, the inlet performs NO post-processing and returns the ground-truth time stamps, which + * can then be manually synchronized using time_correction(), and then smoothed/dejittered if + * desired. + * + * This function allows automating these two and possibly more operations. + * @warning When you enable this, you will no longer receive or be able to recover the original time + * stamps. + * @param in The lsl_inlet object to act on. + * @param flags An integer that is the result of bitwise OR'ing one or more options from + * #lsl_processing_options_t together (e.g., #proc_clocksync|#proc_dejitter); + * a good setting is to use #proc_ALL. + * @return The error code: if nonzero, can be #lsl_argument_error if an unknown flag was passed in. + */ +extern LIBLSL_C_API int32_t lsl_set_postprocessing(lsl_inlet in, uint32_t flags); + + +/* === Pulling a sample from the inlet === */ + +/** + * Pull a sample from the inlet and read it into a pointer to values. + * Handles type checking & conversion. + * @param in The #lsl_inlet object to act on. + * @param[out] buffer A pointer to hold the resulting values. + * @param buffer_elements The number of samples allocated in the buffer. + * @attention It is the responsibility of the user to allocate enough memory. + * @param timeout The timeout for this operation, if any. + * Use #LSL_FOREVER to effectively disable it. It is also permitted to use 0.0 here; + * in this case a sample is only returned if one is currently buffered. + * @param[out] ec Error code: can be either no error or #lsl_lost_error + * (if the stream source has been lost).
+ * @note If the timeout expires before a new sample was received the function returns 0.0; + * ec is *not* set to #lsl_timeout_error (because this case is not considered an error condition). + * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was + * available. To remap this time stamp to the local clock, add the value returned by + * lsl_time_correction() to it. + * @{ + */ +extern LIBLSL_C_API double lsl_pull_sample_f(lsl_inlet in, float *buffer, int32_t buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API double lsl_pull_sample_d(lsl_inlet in, double *buffer, int32_t buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API double lsl_pull_sample_l(lsl_inlet in, int64_t *buffer, int32_t buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API double lsl_pull_sample_i(lsl_inlet in, int32_t *buffer, int32_t buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API double lsl_pull_sample_s(lsl_inlet in, int16_t *buffer, int32_t buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API double lsl_pull_sample_c(lsl_inlet in, char *buffer, int32_t buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API double lsl_pull_sample_str(lsl_inlet in, char **buffer, int32_t buffer_elements, double timeout, int32_t *ec); +///@} + +/** @copydoc lsl_pull_sample_f + * These strings may contains 0's, therefore the lengths are read into the buffer_lengths array. + * @param buffer_lengths + * A pointer to an array that holds the resulting lengths for each returned binary string.*/ +extern LIBLSL_C_API double lsl_pull_sample_buf(lsl_inlet in, char **buffer, uint32_t *buffer_lengths, int32_t buffer_elements, double timeout, int32_t *ec); + +/** + * Pull a sample from the inlet and read it into a custom struct or buffer. + * + * Overall size checking but no type checking or conversion are done. + * Do not use for variable-size/string-formatted streams. + * @param in The #lsl_inlet object to act on. + * @param[out] buffer A pointer to hold the resulting values. + * @param buffer_bytes Length of the array held by buffer in bytes, not items + * @param timeout The timeout for this operation, if any. + * Use #LSL_FOREVER to effectively disable it. It is also permitted to use 0.0 here; + * in this case a sample is only returned if one is currently buffered. + * @param[out] ec Error code: can be either no error or #lsl_lost_error + * (if the stream source has been lost).
+ * @note If the timeout expires before a new sample was received the function returns 0.0; + * ec is *not* set to #lsl_timeout_error (because this case is not considered an error condition). + * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was + * available. To remap this time stamp to the local clock, add the value returned by + * lsl_time_correction() to it. + */ +extern LIBLSL_C_API double lsl_pull_sample_v(lsl_inlet in, void *buffer, int32_t buffer_bytes, double timeout, int32_t *ec); + +/** + * Pull a chunk of data from the inlet and read it into a buffer. + * + * Handles type checking & conversion. + * + * @attention Note that the provided data buffer size is measured in channel values (e.g. floats) + * rather than in samples. + * @param in The lsl_inlet object to act on. + * @param[out] data_buffer A pointer to a buffer of data values where the results shall be stored. + * @param[out] timestamp_buffer A pointer to a double buffer where time stamps shall be stored. + * + * If this is NULL, no time stamps will be returned. + * @param data_buffer_elements The size of the data buffer, in channel data elements (of type T). + * Must be a multiple of the stream's channel count. + * @param timestamp_buffer_elements The size of the timestamp buffer. + * + * If a timestamp buffer is provided then this must correspond to the same number of samples as + * data_buffer_elements. + * @param timeout The timeout for this operation, if any. + * + * When the timeout expires, the function may return before the entire buffer is filled. + * The default value of 0.0 will retrieve only data available for immediate pickup. + * @param[out] ec Error code: can be either no error or #lsl_lost_error (if the stream source has + * been lost). + * @note if the timeout expires before a new sample was received the function returns 0.0; + * ec is *not* set to #lsl_timeout_error (because this case is not considered an error condition). + * @return data_elements_written Number of channel data elements written to the data buffer. + * @{ + */ +extern LIBLSL_C_API unsigned long lsl_pull_chunk_f(lsl_inlet in, float *data_buffer, double *timestamp_buffer, unsigned long data_buffer_elements, unsigned long timestamp_buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API unsigned long lsl_pull_chunk_d(lsl_inlet in, double *data_buffer, double *timestamp_buffer, unsigned long data_buffer_elements, unsigned long timestamp_buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API unsigned long lsl_pull_chunk_l(lsl_inlet in, int64_t *data_buffer, double *timestamp_buffer, unsigned long data_buffer_elements, unsigned long timestamp_buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API unsigned long lsl_pull_chunk_i(lsl_inlet in, int32_t *data_buffer, double *timestamp_buffer, unsigned long data_buffer_elements, unsigned long timestamp_buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API unsigned long lsl_pull_chunk_s(lsl_inlet in, int16_t *data_buffer, double *timestamp_buffer, unsigned long data_buffer_elements, unsigned long timestamp_buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API unsigned long lsl_pull_chunk_c(lsl_inlet in, char *data_buffer, double *timestamp_buffer, unsigned long data_buffer_elements, unsigned long timestamp_buffer_elements, double timeout, int32_t *ec); +extern LIBLSL_C_API unsigned long lsl_pull_chunk_str(lsl_inlet in, char **data_buffer, double *timestamp_buffer, unsigned long data_buffer_elements, unsigned long timestamp_buffer_elements, double timeout, int32_t *ec); + +///@} + +/** + * Pull a chunk of data from the inlet and read it into an array of binary strings. + * + * These strings may contains 0's, therefore the lengths are read into the lengths_buffer array. + * Handles type checking & conversion. + * IMPORTANT: Note that the provided data buffer size is measured in channel values (e.g., floats) + * rather than in samples. + * @param in The lsl_inlet object to act on. + * @param[out] data_buffer A pointer to a buffer of data values where the results shall be stored. + * @param[out] lengths_buffer A pointer to an array that holds the resulting lengths for each + * returned binary string. + * @param timestamp_buffer A pointer to a buffer of timestamp values where time stamps shall be + * stored. If this is NULL, no time stamps will be returned. + * @param data_buffer_elements The size of the data buffer, in channel data elements (of type T). + * Must be a multiple of the stream's channel count. + * @param timestamp_buffer_elements The size of the timestamp buffer. If a timestamp buffer is + * provided then this must correspond to the same number of samples as data_buffer_elements. + * @param timeout The timeout for this operation, if any. + * + * When the timeout expires, the function may return before the entire buffer is filled. + * + * The default value of 0.0 will retrieve only data available for immediate pickup. + * @param[out] ec Error code: can be either no error or #lsl_lost_error (if the stream source has + * been lost). + * @note If the timeout expires before a new sample was received the function returns 0.0; ec is + * *not* set to #lsl_timeout_error (because this case is not considered an error condition). + * @return data_elements_written Number of channel data elements written to the data buffer. + */ + +extern LIBLSL_C_API unsigned long lsl_pull_chunk_buf(lsl_inlet in, char **data_buffer, uint32_t *lengths_buffer, double *timestamp_buffer, unsigned long data_buffer_elements, unsigned long timestamp_buffer_elements, double timeout, int32_t *ec); + +/** +* Query whether samples are currently available for immediate pickup. +* +* Note that it is not a good idea to use samples_available() to determine whether +* a pull_*() call would block: to be sure, set the pull timeout to 0.0 or an acceptably +* low value. If the underlying implementation supports it, the value will be the number of +* samples available (otherwise it will be 1 or 0). +*/ +extern LIBLSL_C_API uint32_t lsl_samples_available(lsl_inlet in); + +/// Drop all queued not-yet pulled samples, return the nr of dropped samples +extern LIBLSL_C_API uint32_t lsl_inlet_flush(lsl_inlet in); + +/** +* Query whether the clock was potentially reset since the last call to lsl_was_clock_reset(). +* +* This is rarely-used function is only needed for applications that combine multiple time_correction +* values to estimate precise clock drift if they should tolerate cases where the source machine was +* hot-swapped or restarted. +*/ +extern LIBLSL_C_API uint32_t lsl_was_clock_reset(lsl_inlet in); + +/** + * Override the half-time (forget factor) of the time-stamp smoothing. + * + * The default is 90 seconds unless a different value is set in the config file. + * + * Using a longer window will yield lower jitter in the time stamps, but longer windows will have + * trouble tracking changes in the clock rate (usually due to temperature changes); the default is + * able to track changes up to 10 degrees C per minute sufficiently well. + * @param in The lsl_inlet object to act on. + * @param value The new value, in seconds. This is the time after which a past sample + * will be weighted by 1/2 in the exponential smoothing window. + * @return The error code: if nonzero, can be #lsl_argument_error if an unknown flag was passed in. + */ +extern LIBLSL_C_API int32_t lsl_smoothing_halftime(lsl_inlet in, float value); + +/// @} diff --git a/Plugins/LSL/include/lsl/inlet.h.meta b/Plugins/LSL/include/lsl/inlet.h.meta new file mode 100644 index 0000000..6cc9fdc --- /dev/null +++ b/Plugins/LSL/include/lsl/inlet.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 5a599aa25f58b334fa30904f06c9c716 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl/outlet.h b/Plugins/LSL/include/lsl/outlet.h new file mode 100644 index 0000000..87c3253 --- /dev/null +++ b/Plugins/LSL/include/lsl/outlet.h @@ -0,0 +1,251 @@ +#pragma once +#include "./common.h" +#include "types.h" + +/// @file outlet.h Stream outlet functions + +/** @defgroup outlet The lsl_outlet object + * + * This object represents an outlet sending data to all connected inlets. + * + * The data is pushed sample-by-sample or chunk-by-chunk into the outlet, and can consist of single- + * or multichannel data, regular or irregular sampling rate, with uniform value types (integers, + * floats, doubles, strings). + * + * Streams can have arbitrary XML meta-data (akin to a file header). + * By creating an outlet the stream is made visible to a collection of computers (defined by the + * network settings/layout) where one can subscribe to it by creating an inlet. + * @{ + */ + +/** + * Establish a new stream outlet. This makes the stream discoverable. + * @param info The stream information to use for creating this stream. + * Stays constant over the lifetime of the outlet. + * @note the outlet makes a copy of the streaminfo object upon construction (so the old info should + * still be destroyed.) + * @param chunk_size Optionally the desired chunk granularity (in samples) for transmission. + * If specified as 0, each push operation yields one chunk. + * Stream recipients can have this setting bypassed. + * @param max_buffered Optionally the maximum amount of data to buffer (in seconds if there is a + * nominal sampling rate, otherwise x100 in samples). A good default is 360, which corresponds to 6 + * minutes of data. Note that, for high-bandwidth data you will almost certainly want to use a lower + * value here to avoid running out of RAM. + * @return A newly created lsl_outlet handle or NULL in the event that an error occurred. + */ +extern LIBLSL_C_API lsl_outlet lsl_create_outlet(lsl_streaminfo info, int32_t chunk_size, int32_t max_buffered); +/** @copydoc lsl_create_outlet() + * @param flags An integer that is the result of bitwise OR'ing one or more options from + * #lsl_transport_options_t together (e.g., #transp_bufsize_samples|#transp_bufsize_thousandths) + */ +extern LIBLSL_C_API lsl_outlet lsl_create_outlet_ex( + lsl_streaminfo info, int32_t chunk_size, int32_t max_buffered, lsl_transport_options_t flags); + +/** + * Destroy an outlet. + * The outlet will no longer be discoverable after destruction and all connected inlets will stop + * delivering data. + */ +extern LIBLSL_C_API void lsl_destroy_outlet(lsl_outlet out); + +/** Push a pointer to some values as a sample into the outlet. + * Handles type checking & conversion. + * @param out The lsl_outlet object through which to push the data. + * @param data A pointer to values to push. The number of values pointed to must be no less than the + * number of channels in the sample. + * #lsl_local_clock(); if omitted, the current time is used. + * @return Error code of the operation or lsl_no_error if successful (usually attributed to the + * wrong data type). + * @{ + */ +extern LIBLSL_C_API int32_t lsl_push_sample_f(lsl_outlet out, const float *data); +extern LIBLSL_C_API int32_t lsl_push_sample_d(lsl_outlet out, const double *data); +extern LIBLSL_C_API int32_t lsl_push_sample_l(lsl_outlet out, const int64_t *data); +extern LIBLSL_C_API int32_t lsl_push_sample_i(lsl_outlet out, const int32_t *data); +extern LIBLSL_C_API int32_t lsl_push_sample_s(lsl_outlet out, const int16_t *data); +extern LIBLSL_C_API int32_t lsl_push_sample_c(lsl_outlet out, const char *data); +extern LIBLSL_C_API int32_t lsl_push_sample_str(lsl_outlet out, const char **data); +extern LIBLSL_C_API int32_t lsl_push_sample_v(lsl_outlet out, const void *data); +/// @} +/** @copydoc lsl_push_sample_f + * @param timestamp Optionally the capture time of the sample, in agreement with + * @{ + */ +extern LIBLSL_C_API int32_t lsl_push_sample_ft(lsl_outlet out, const float *data, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_sample_dt(lsl_outlet out, const double *data, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_sample_lt(lsl_outlet out, const int64_t *data, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_sample_it(lsl_outlet out, const int32_t *data, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_sample_st(lsl_outlet out, const int16_t *data, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_sample_ct(lsl_outlet out, const char *data, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_sample_strt(lsl_outlet out, const char **data, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_sample_vt(lsl_outlet out, const void *data, double timestamp); +/// @} +/** @copydoc lsl_push_sample_ft + * @param pushthrough Whether to push the sample through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + * @{ + */ +extern LIBLSL_C_API int32_t lsl_push_sample_ftp(lsl_outlet out, const float *data, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_sample_dtp(lsl_outlet out, const double *data, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_sample_ltp(lsl_outlet out, const int64_t *data, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_sample_itp(lsl_outlet out, const int32_t *data, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_sample_stp(lsl_outlet out, const int16_t *data, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_sample_ctp(lsl_outlet out, const char *data, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_sample_strtp(lsl_outlet out, const char **data, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_sample_vtp(lsl_outlet out, const void *data, double timestamp, int32_t pushthrough); +///@} + +/** @copybrief lsl_push_sample_ftp + * @see lsl_push_sample_ftp + * @param out The lsl_outlet object through which to push the data. + * @param data A pointer to values to push. The number of values pointed to must be no less than the + * number of channels in the sample. + * @param lengths A pointer the number of elements to push for each channel (string lengths). + */ +extern LIBLSL_C_API int32_t lsl_push_sample_buf(lsl_outlet out, const char **data, const uint32_t *lengths); +/** @copydoc lsl_push_sample_buf + * @param timestamp @see lsl_push_sample_ftp */ +extern LIBLSL_C_API int32_t lsl_push_sample_buft(lsl_outlet out, const char **data, const uint32_t *lengths, double timestamp); +/** @copydoc lsl_push_sample_buft + * @param pushthrough @see lsl_push_sample_ftp */ +extern LIBLSL_C_API int32_t lsl_push_sample_buftp(lsl_outlet out, const char **data, const uint32_t *lengths, double timestamp, int32_t pushthrough); + +/** Push a chunk of multiplexed samples into the outlet. One timestamp per sample is provided. + * + * @attention Note that the provided buffer size is measured in channel values (e.g. floats) rather + * than in samples. + * + * Handles type checking & conversion. + * @param out The lsl_outlet object through which to push the data. + * @param data A buffer of channel values holding the data for zero or more successive samples to + * send. + * @param data_elements The number of data values (of type T) in the data buffer. Must be a multiple + * of the channel count. + * @return Error code of the operation (usually attributed to the wrong data type). + * @{ + */ +extern LIBLSL_C_API int32_t lsl_push_chunk_f(lsl_outlet out, const float *data, unsigned long data_elements); +extern LIBLSL_C_API int32_t lsl_push_chunk_d(lsl_outlet out, const double *data, unsigned long data_elements); +extern LIBLSL_C_API int32_t lsl_push_chunk_l(lsl_outlet out, const int64_t *data, unsigned long data_elements); +extern LIBLSL_C_API int32_t lsl_push_chunk_i(lsl_outlet out, const int32_t *data, unsigned long data_elements); +extern LIBLSL_C_API int32_t lsl_push_chunk_s(lsl_outlet out, const int16_t *data, unsigned long data_elements); +extern LIBLSL_C_API int32_t lsl_push_chunk_c(lsl_outlet out, const char *data, unsigned long data_elements); +extern LIBLSL_C_API int32_t lsl_push_chunk_str(lsl_outlet out, const char **data, unsigned long data_elements); +/// @} + +/** @copydoc lsl_push_chunk_f + * @param timestamp Optionally the capture time of the most recent sample, in agreement with + * lsl_local_clock(); if omitted, the current time is used. + * The time stamps of other samples are automatically derived based on the sampling rate of the + * stream. + * @{ + */ +extern LIBLSL_C_API int32_t lsl_push_chunk_ft(lsl_outlet out, const float *data, unsigned long data_elements, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_chunk_dt(lsl_outlet out, const double *data, unsigned long data_elements, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_chunk_lt(lsl_outlet out, const int64_t *data, unsigned long data_elements, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_chunk_it(lsl_outlet out, const int32_t *data, unsigned long data_elements, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_chunk_st(lsl_outlet out, const int16_t *data, unsigned long data_elements, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_chunk_ct(lsl_outlet out, const char *data, unsigned long data_elements, double timestamp); +extern LIBLSL_C_API int32_t lsl_push_chunk_strt(lsl_outlet out, const char **data, unsigned long data_elements, double timestamp); +/// @} + +/** @copydoc lsl_push_chunk_ft + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + * @{ + */ +extern LIBLSL_C_API int32_t lsl_push_chunk_ftp(lsl_outlet out, const float *data, unsigned long data_elements, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_dtp(lsl_outlet out, const double *data, unsigned long data_elements, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_ltp(lsl_outlet out, const int64_t *data, unsigned long data_elements, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_itp(lsl_outlet out, const int32_t *data, unsigned long data_elements, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_stp(lsl_outlet out, const int16_t *data, unsigned long data_elements, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_ctp(lsl_outlet out, const char *data, unsigned long data_elements, double timestamp, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_strtp(lsl_outlet out, const char **data, unsigned long data_elements, double timestamp, int32_t pushthrough); +/// @} +/** @copydoc lsl_push_chunk_f + * @param timestamps Buffer holding one time stamp for each sample in the data buffer. + * @{ + */ +extern LIBLSL_C_API int32_t lsl_push_chunk_ftn(lsl_outlet out, const float *data, unsigned long data_elements, const double *timestamps); +extern LIBLSL_C_API int32_t lsl_push_chunk_dtn(lsl_outlet out, const double *data, unsigned long data_elements, const double *timestamps); +extern LIBLSL_C_API int32_t lsl_push_chunk_ltn(lsl_outlet out, const int64_t *data, unsigned long data_elements, const double *timestamps); +extern LIBLSL_C_API int32_t lsl_push_chunk_itn(lsl_outlet out, const int32_t *data, unsigned long data_elements, const double *timestamps); +extern LIBLSL_C_API int32_t lsl_push_chunk_stn(lsl_outlet out, const int16_t *data, unsigned long data_elements, const double *timestamps); +extern LIBLSL_C_API int32_t lsl_push_chunk_ctn(lsl_outlet out, const char *data, unsigned long data_elements, const double *timestamps); +extern LIBLSL_C_API int32_t lsl_push_chunk_strtn(lsl_outlet out, const char **data, unsigned long data_elements, const double *timestamps); +/// @} + +/** @copydoc lsl_push_chunk_ftn + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + * @{ + */ +extern LIBLSL_C_API int32_t lsl_push_chunk_ftnp(lsl_outlet out, const float *data, unsigned long data_elements, const double *timestamps, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_dtnp(lsl_outlet out, const double *data, unsigned long data_elements, const double *timestamps, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_ltnp(lsl_outlet out, const int64_t *data, unsigned long data_elements, const double *timestamps, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_itnp(lsl_outlet out, const int32_t *data, unsigned long data_elements, const double *timestamps, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_stnp(lsl_outlet out, const int16_t *data, unsigned long data_elements, const double *timestamps, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_ctnp(lsl_outlet out, const char *data, unsigned long data_elements, const double *timestamps, int32_t pushthrough); +extern LIBLSL_C_API int32_t lsl_push_chunk_strtnp(lsl_outlet out, const char **data, unsigned long data_elements, const double *timestamps, int32_t pushthrough); +///@} + +/** @copybrief lsl_push_chunk_ftp + * @sa lsl_push_chunk_ftp + * @param out The lsl_outlet object through which to push the data. + * @param data An array of channel values holding the data to push. + * @param lengths Pointer the number of elements to push for each value (string lengths) so that + * `size(data[i])==lengths[i]`. + * @param data_elements The number of data values in the data buffer. + * Must be a multiple of the channel count. + */ +extern LIBLSL_C_API int32_t lsl_push_chunk_buf(lsl_outlet out, const char **data, const uint32_t *lengths, unsigned long data_elements); + +/** @copydoc lsl_push_chunk_buf @sa lsl_push_chunk_ftp @sa lsl_push_chunk_buf + * @param timestamp Optionally the capture time of the most recent sample, in agreement with + * lsl_local_clock(); if omitted, the current time is used. + * The time stamps of other samples are automatically derived based on the sampling rate of the + * stream. */ +extern LIBLSL_C_API int32_t lsl_push_chunk_buft(lsl_outlet out, const char **data, const uint32_t *lengths, unsigned long data_elements, double timestamp); + +/** @copydoc lsl_push_chunk_buft @sa lsl_push_chunk_ftp @sa lsl_push_chunk_buf + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. */ +extern LIBLSL_C_API int32_t lsl_push_chunk_buftp(lsl_outlet out, const char **data, const uint32_t *lengths, unsigned long data_elements, double timestamp, int32_t pushthrough); + +/** @copydoc lsl_push_chunk_buf @sa lsl_push_chunk_ftp @sa lsl_push_chunk_buf + * @param timestamps Buffer holding one time stamp for each sample in the data buffer. */ +extern LIBLSL_C_API int32_t lsl_push_chunk_buftn(lsl_outlet out, const char **data, const uint32_t *lengths, unsigned long data_elements, const double *timestamps); + +/** @copydoc lsl_push_chunk_buftn @sa lsl_push_chunk_ftp @sa lsl_push_chunk_buf + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. */ +extern LIBLSL_C_API int32_t lsl_push_chunk_buftnp(lsl_outlet out, const char **data, const uint32_t *lengths, unsigned long data_elements, const double *timestamps, int32_t pushthrough); + +/** +* Check whether consumers are currently registered. +* While it does not hurt, there is technically no reason to push samples if there is no consumer. +*/ +extern LIBLSL_C_API int32_t lsl_have_consumers(lsl_outlet out); + +/** +* Wait until some consumer shows up (without wasting resources). +* @return True if the wait was successful, false if the timeout expired. +*/ +extern LIBLSL_C_API int32_t lsl_wait_for_consumers(lsl_outlet out, double timeout); + +/** + * Retrieve a handle to the stream info provided by this outlet. + * This is what was used to create the stream (and also has the Additional Network Information + * fields assigned). + * @return A copy of the streaminfo of the outlet or NULL in the event that an error occurred. + * @note It is the user's responsibility to destroy it when it is no longer needed. + * @sa lsl_destroy_string() + */ +extern LIBLSL_C_API lsl_streaminfo lsl_get_info(lsl_outlet out); + +///@} diff --git a/Plugins/LSL/include/lsl/outlet.h.meta b/Plugins/LSL/include/lsl/outlet.h.meta new file mode 100644 index 0000000..3ba5499 --- /dev/null +++ b/Plugins/LSL/include/lsl/outlet.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: b5a5da73169dcd745897d63bdd82ebd3 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl/resolver.h b/Plugins/LSL/include/lsl/resolver.h new file mode 100644 index 0000000..db7419f --- /dev/null +++ b/Plugins/LSL/include/lsl/resolver.h @@ -0,0 +1,156 @@ +#pragma once +#include "common.h" +#include "types.h" + +/// @file resolver.h Stream resolution functions + +/** @defgroup continuous_resolver The lsl_continuous_resolver + * @ingroup resolve + * + * Streams can be resolved at a single timepoint once (@ref resolve) or continuously in the + * background. + * @{ + */ + +/** + * Construct a new #lsl_continuous_resolver that resolves all streams on the network. + * + * This is analogous to the functionality offered by the free function lsl_resolve_streams(). + * @param forget_after When a stream is no longer visible on the network (e.g. because it was shut + * down), this is the time in seconds after which it is no longer reported by the resolver. + * + * The recommended default value is 5.0. + */ +extern LIBLSL_C_API lsl_continuous_resolver lsl_create_continuous_resolver(double forget_after); + +/** + * Construct a new lsl_continuous_resolver that resolves all streams with a specific value for a given + * property. + * + * This is analogous to the functionality provided by the free function lsl_resolve_byprop() + * @param prop The #lsl_streaminfo property that should have a specific value (e.g., "name", "type", + * "source_id", or "desc/manufaturer"). + * @param value The string value that the property should have (e.g., "EEG" as the type property). + * @param forget_after When a stream is no longer visible on the network (e.g., because it was shut + * down), this is the time in seconds after which it is no longer reported by the resolver. + * The recommended default value is 5.0. + */ +extern LIBLSL_C_API lsl_continuous_resolver lsl_create_continuous_resolver_byprop(const char *prop, const char *value, double forget_after); + +/** + * Construct a new lsl_continuous_resolver that resolves all streams that match a given XPath 1.0 + * predicate. + * + * This is analogous to the functionality provided by the free function lsl_resolve_bypred() + * @param pred The predicate string, e.g. + * `"name='BioSemi'" or "type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32"` + * @param forget_after When a stream is no longer visible on the network (e.g., because it was shut + * down), this is the time in seconds after which it is no longer reported by the resolver. + * The recommended default value is 5.0. + */ +extern LIBLSL_C_API lsl_continuous_resolver lsl_create_continuous_resolver_bypred(const char *pred, double forget_after); + +/** + * Obtain the set of currently present streams on the network (i.e. resolve result). + * + * @param res A continuous resolver (previously created with one of the + * lsl_create_continuous_resolver() functions). + * @param buffer A user-allocated buffer to hold the current resolve results.
+ * @attention It is the user's responsibility to either destroy the resulting streaminfo objects or + * to pass them back to the LSL during during creation of an inlet. + * @attention The stream_infos returned by the resolver are only short versions that do not include + * the lsl_get_desc() field (which can be arbitrarily big). + * + * To obtain the full stream information you need to call lsl_get_info() on the inlet after you have + * created one. + * @param buffer_elements The user-provided buffer length. + * @return The number of results written into the buffer (never more than the provided # of slots) + * or a negative number if an error has occurred (values corresponding to #lsl_error_code_t). + */ +extern LIBLSL_C_API int32_t lsl_resolver_results(lsl_continuous_resolver res, lsl_streaminfo *buffer, uint32_t buffer_elements); + +/// Destructor for the continuous resolver. +extern LIBLSL_C_API void lsl_destroy_continuous_resolver(lsl_continuous_resolver res); + +/// @} + +/** @defgroup resolve Resolving streams on the network + * @{*/ + +/** + * Resolve all streams on the network. + * + * This function returns all currently available streams from any outlet on the network. + * The network is usually the subnet specified at the local router, but may also include a multicast + * group of machines (given that the network supports it), or a list of hostnames.
+ * These details may optionally be customized by the experimenter in a configuration file + * (see page Network Connectivity in the LSL wiki). + * This is the default mechanism used by the browsing programs and the recording program. + * @param[out] buffer A user-allocated buffer to hold the resolve results. + * @attention It is the user's responsibility to either destroy the resulting streaminfo objects or + * to pass them back to the LSL during during creation of an inlet. + * + * @attention The stream_info's returned by the resolver are only short versions that do not include + * the lsl_get_desc() field (which can be arbitrarily big). + * To obtain the full stream information you need to call lsl_get_info() on the inlet after you have + * created one. + * @param buffer_elements The user-provided buffer length. + * @param wait_time The waiting time for the operation, in seconds, to search for streams. + * The recommended wait time is 1 second (or 2 for a busy and large recording operation). + * @warning If this is too short (<0.5s) only a subset (or none) of the outlets that are present on + * the network may be returned. + * @return The number of results written into the buffer (never more than the provided # of slots) + * or a negative number if an error has occurred (values corresponding to lsl_error_code_t). + */ +extern LIBLSL_C_API int32_t lsl_resolve_all(lsl_streaminfo *buffer, uint32_t buffer_elements, double wait_time); + +/** + * Resolve all streams with a given value for a property. + * + * If the goal is to resolve a specific stream, this method is preferred over resolving all streams + * and then selecting the desired one. + * @param[out] buffer A user-allocated buffer to hold the resolve results. + * @attention It is the user's responsibility to either destroy the resulting streaminfo objects or + * to pass them back to the LSL during during creation of an inlet. + * + * @attention The stream_info's returned by the resolver are only short versions that do not include + * the lsl_get_desc() field (which can be arbitrarily big). To obtain the full stream information + * you need to call lsl_get_info() on the inlet after you have created one. + * @param buffer_elements The user-provided buffer length. + * @param prop The streaminfo property that should have a specific value (`"name"`, `"type"`, + * `"source_id"`, or, e.g., `"desc/manufaturer"` if present). + * @param value The string value that the property should have (e.g., "EEG" as the type). + * @param minimum Return at least this number of streams. + * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout). + * If the timeout expires, less than the desired number of streams (possibly none) will be returned. + * @return The number of results written into the buffer (never more than the provided # of slots) + * or a negative number if an error has occurred (values corresponding to #lsl_error_code_t). + */ +extern LIBLSL_C_API int32_t lsl_resolve_byprop(lsl_streaminfo *buffer, uint32_t buffer_elements, const char *prop, const char *value, int32_t minimum, double timeout); + +/** + * Resolve all streams that match a given predicate. + * + * Advanced query that allows to impose more conditions on the retrieved streams; + * the given string is an [XPath 1.0 predicate](http://en.wikipedia.org/w/index.php?title=XPath_1.0) + * for the `` node (omitting the surrounding []'s) + * @param[out] buffer A user-allocated buffer to hold the resolve results. + * @attention It is the user's responsibility to either destroy the resulting streaminfo objects or + * to pass them back to the LSL during during creation of an inlet. + * + * @attention The stream_info's returned by the resolver are only short versions that do not include + * the lsl_get_desc() field (which can be arbitrarily big). To obtain the full stream information + * you need to call lsl_get_info() on the inlet after you have created one. + * @param buffer_elements The user-provided buffer length. + * @param pred The predicate string, e.g. + * `name='BioSemi'` or `type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32` + * @param minimum Return at least this number of streams. + * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout). + * If the timeout expires, less than the desired number of streams (possibly none) + * will be returned. + * @return The number of results written into the buffer (never more than the provided # of slots) + * or a negative number if an error has occurred (values corresponding to lsl_error_code_t). + */ +extern LIBLSL_C_API int32_t lsl_resolve_bypred(lsl_streaminfo *buffer, uint32_t buffer_elements, const char *pred, int32_t minimum, double timeout); + +/// @} diff --git a/Plugins/LSL/include/lsl/resolver.h.meta b/Plugins/LSL/include/lsl/resolver.h.meta new file mode 100644 index 0000000..ddab476 --- /dev/null +++ b/Plugins/LSL/include/lsl/resolver.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 1150bda128e3aa14695f6559cc49350f +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl/streaminfo.h b/Plugins/LSL/include/lsl/streaminfo.h new file mode 100644 index 0000000..2ecfff0 --- /dev/null +++ b/Plugins/LSL/include/lsl/streaminfo.h @@ -0,0 +1,196 @@ +#pragma once +#include "common.h" +#include "types.h" + +/// @file streaminfo.h Stream info functions + +/** @defgroup streaminfo The lsl_streaminfo object + * + * The #lsl_streaminfo object keeps a stream's meta data and connection settings. + * @{ + */ + +/** + * Construct a new streaminfo object. + * + * Core stream information is specified here. Any remaining meta-data can be added later. + * @param name Name of the stream.
+ * Describes the device (or product series) that this stream makes available + * (for use by programs, experimenters or data analysts). Cannot be empty. + * @param type Content type of the stream. Please see https://github.com/sccn/xdf/wiki/Meta-Data (or + * web search for: XDF meta-data) for pre-defined content-type names, but you can also make up your + * own. The content type is the preferred way to find streams (as opposed to searching by name). + * @param channel_count Number of channels per sample. + * This stays constant for the lifetime of the stream. + * @param nominal_srate The sampling rate (in Hz) as advertised by the + * datasource, if regular (otherwise set to #LSL_IRREGULAR_RATE). + * @param channel_format Format/type of each channel.
+ * If your channels have different formats, consider supplying multiple streams + * or use the largest type that can hold them all (such as #cft_double64). + * + * A good default is #cft_float32. + * @param source_id Unique identifier of the source or device, if available (e.g. a serial number). + * Allows recipients to recover from failure even after the serving app or device crashes. + * May in some cases also be constructed from device settings. + * @return A newly created streaminfo handle or NULL in the event that an error occurred. + */ +extern LIBLSL_C_API lsl_streaminfo lsl_create_streaminfo(const char *name, const char *type, int32_t channel_count, double nominal_srate, lsl_channel_format_t channel_format, const char *source_id); + +/// Destroy a previously created streaminfo object. +extern LIBLSL_C_API void lsl_destroy_streaminfo(lsl_streaminfo info); + +/// Copy an existing streaminfo object (rarely used). +extern LIBLSL_C_API lsl_streaminfo lsl_copy_streaminfo(lsl_streaminfo info); + +/** + * Name of the stream. + * + * This is a human-readable name. + * For streams offered by device modules, it refers to the type of device or product series that is + * generating the data of the stream. If the source is an application, the name may be a more + * generic or specific identifier. Multiple streams with the same name can coexist, though + * potentially at the cost of ambiguity (for the recording app or experimenter). + * @return An immutable library-owned pointer to the string value. @sa lsl_destroy_string() + */ +extern LIBLSL_C_API const char *lsl_get_name(lsl_streaminfo info); + +/** + * Content type of the stream. + * + * The content type is a short string such as "EEG", "Gaze" which describes the content carried by + * the channel (if known). If a stream contains mixed content this value need not be assigned but + * may instead be stored in the description of channel types. To be useful to applications and + * automated processing systems using the recommended content types is preferred. Content types + * usually follow those pre-defined in the [wiki](https://github.com/sccn/xdf/wiki/Meta-Data) (or + * web search for: XDF meta-data). + * @return An immutable library-owned pointer to the string value. @sa lsl_destroy_string() + */ +extern LIBLSL_C_API const char *lsl_get_type(lsl_streaminfo info); + +/** +* Number of channels of the stream. +* A stream has at least one channels; the channel count stays constant for all samples. +*/ +extern LIBLSL_C_API int32_t lsl_get_channel_count(lsl_streaminfo info); + +/** + * Sampling rate of the stream, according to the source (in Hz). + * + * If a stream is irregularly sampled, this should be set to #LSL_IRREGULAR_RATE. + * + * Note that no data will be lost even if this sampling rate is incorrect or if a device has + * temporary hiccups, since all samples will be recorded anyway (except for those dropped by the + * device itself). However, when the recording is imported into an application, a good importer may + * correct such errors more accurately if the advertised sampling rate was close to the specs of the + * device. + */ +extern LIBLSL_C_API double lsl_get_nominal_srate(lsl_streaminfo info); + +/** + * Channel format of the stream. + * All channels in a stream have the same format. + * However, a device might offer multiple time-synched streams each with its own format. + */ +extern LIBLSL_C_API lsl_channel_format_t lsl_get_channel_format(lsl_streaminfo info); + +/** + * Unique identifier of the stream's source, if available. + * + * The unique source (or device) identifier is an optional piece of information that, if available, + * allows that endpoints (such as the recording program) can re-acquire a stream automatically once + * it is back online. + * @return An immutable library-owned pointer to the string value. @sa lsl_destroy_string() + */ +extern LIBLSL_C_API const char *lsl_get_source_id(lsl_streaminfo info); + +/** +* Protocol version used to deliver the stream. +*/ +extern LIBLSL_C_API int32_t lsl_get_version(lsl_streaminfo info); + +/** +* Creation time stamp of the stream. +* +* This is the time stamp when the stream was first created +* (as determined via local_clock() on the providing machine). +*/ +extern LIBLSL_C_API double lsl_get_created_at(lsl_streaminfo info); + +/** + * Unique ID of the stream outlet (once assigned). + * + * This is a unique identifier of the stream outlet, and is guaranteed to be different + * across multiple instantiations of the same outlet (e.g., after a re-start). + * @return An immutable library-owned pointer to the string value. @sa lsl_destroy_string() + */ +extern LIBLSL_C_API const char *lsl_get_uid(lsl_streaminfo info); + +/** + * Session ID for the given stream. + * + * The session id is an optional human-assigned identifier of the recording session. + * While it is rarely used, it can be used to prevent concurrent recording activitites + * on the same sub-network (e.g., in multiple experiment areas) from seeing each other's streams + * (assigned via a configuration file by the experimenter, see Network Connectivity on the LSL + * wiki). + * @return An immutable library-owned pointer to the string value. @sa lsl_destroy_string() + */ +extern LIBLSL_C_API const char *lsl_get_session_id(lsl_streaminfo info); + +/// Hostname of the providing machine (once bound to an outlet). Modification is not permitted. +extern LIBLSL_C_API const char *lsl_get_hostname(lsl_streaminfo info); + +/** +* Extended description of the stream. +* +* It is highly recommended that at least the channel labels are described here. +* See code examples on the LSL wiki. Other information, such as amplifier settings, +* measurement units if deviating from defaults, setup information, subject information, etc., +* can be specified here, as well. Meta-data recommendations follow the XDF file format project +* (github.com/sccn/xdf/wiki/Meta-Data or web search for: XDF meta-data). +* +* @attention if you use a stream content type for which meta-data recommendations exist, please +* try to lay out your meta-data in agreement with these recommendations for compatibility with other applications. +*/ +extern LIBLSL_C_API lsl_xml_ptr lsl_get_desc(lsl_streaminfo info); + +/** + * Retrieve the entire streaminfo in XML format. + * + * This yields an XML document (in string form) whose top-level element is ``. The info + * element contains one element for each field of the streaminfo class, including: + * + * - the core elements ``, ``, ``, + * ``, `` + * - the misc elements ``, ``, ``, ``, + * ``, ``, ``, ``, ``, + * `` + * - the extended description element `` with user-defined sub-elements. + * @return A pointer to a copy of the XML text or NULL in the event that an error occurred. + * @note It is the user's responsibility to deallocate this string when it is no longer needed. + */ +extern LIBLSL_C_API char *lsl_get_xml(lsl_streaminfo info); + +/// Number of bytes occupied by a channel (0 for string-typed channels). +extern LIBLSL_C_API int32_t lsl_get_channel_bytes(lsl_streaminfo info); + +/// Number of bytes occupied by a sample (0 for string-typed channels). +extern LIBLSL_C_API int32_t lsl_get_sample_bytes(lsl_streaminfo info); + +/** + * Tries to match the stream info XML element @p info against an + * XPath query. + * + * Example query strings: + * @code + * channel_count>5 and type='EEG' + * type='TestStream' or contains(name,'Brain') + * name='ExampleStream' + * @endcode + */ +extern LIBLSL_C_API int32_t lsl_stream_info_matches_query(lsl_streaminfo info, const char *query); + +/// Create a streaminfo object from an XML representation +extern LIBLSL_C_API lsl_streaminfo lsl_streaminfo_from_xml(const char *xml); + +/// @} diff --git a/Plugins/LSL/include/lsl/streaminfo.h.meta b/Plugins/LSL/include/lsl/streaminfo.h.meta new file mode 100644 index 0000000..9cb1a14 --- /dev/null +++ b/Plugins/LSL/include/lsl/streaminfo.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 852b56ff673638c4388cdc82204e6564 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl/types.h b/Plugins/LSL/include/lsl/types.h new file mode 100644 index 0000000..95b9c27 --- /dev/null +++ b/Plugins/LSL/include/lsl/types.h @@ -0,0 +1,60 @@ +#ifndef LSL_TYPES +#define LSL_TYPES + +/** + * @class lsl_streaminfo + * Handle to a stream info object. + * + * Stores the declaration of a data stream. + * Represents the following information: + * + * - stream data format (number of channels, channel format) + * - core information (stream name, content type, sampling rate) + * - optional meta-data about the stream content (channel labels, measurement units, etc.) + * + * Whenever a program wants to provide a new stream on the lab network it will typically first + * create an lsl_streaminfo to describe its properties and then construct an #lsl_outlet with it to + * create the stream on the network. Other parties who discover/resolve the outlet on the network + * can query the stream info; it is also written to disk when recording the stream (playing a + * similar role as a file header). + */ +typedef struct lsl_streaminfo_struct_ *lsl_streaminfo; + +/** + * @class lsl_outlet + * A stream outlet handle. + * Outlets are used to make streaming data (and the meta-data) available on the lab network. + */ +typedef struct lsl_outlet_struct_ *lsl_outlet; + +/** + * @class lsl_inlet + * A stream inlet handle. + * Inlets are used to receive streaming data (and meta-data) from the lab network. + */ +typedef struct lsl_inlet_struct_ *lsl_inlet; + +/** + * @class lsl_xml_ptr + * A lightweight XML element tree handle; models the description of a streaminfo object. + * XML elements behave like advanced pointers into memory that is owned by some respective + * streaminfo. + * Has a name and can have multiple named children or have text content as value; + * attributes are omitted. + * @note The interface is modeled after a subset of pugixml's node type and is compatible with it. + * Type-casts between pugi::xml_node_struct* and #lsl_xml_ptr are permitted (in both directions) + * since the types are binary compatible. + * @sa [pugixml documentation](https://pugixml.org/docs/manual.html#access). + */ +typedef struct lsl_xml_ptr_struct_ *lsl_xml_ptr; + +/** + * @class lsl_continuous_resolver + * + * Handle to a convenience object that resolves streams continuously in the background throughout + * its lifetime and which can be queried at any time for the set of streams that are currently + * visible on the network. + */ +typedef struct lsl_continuous_resolver_ *lsl_continuous_resolver; + +#endif // LSL_TYPES diff --git a/Plugins/LSL/include/lsl/types.h.meta b/Plugins/LSL/include/lsl/types.h.meta new file mode 100644 index 0000000..403df69 --- /dev/null +++ b/Plugins/LSL/include/lsl/types.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 493c5f1d573cd4148878442d3f78f621 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl/xml.h b/Plugins/LSL/include/lsl/xml.h new file mode 100644 index 0000000..2ab7cea --- /dev/null +++ b/Plugins/LSL/include/lsl/xml.h @@ -0,0 +1,103 @@ +#pragma once +#include "common.h" +#include "types.h" + +/// @file inlet.h XML functions + +/** @defgroup xml_ptr The lsl_xml_ptr object + * @{ + */ + +// XML Tree Navigation + +/** Get the first child of the element. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_first_child(lsl_xml_ptr e); + +/** Get the last child of the element. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_last_child(lsl_xml_ptr e); + +/** Get the next sibling in the children list of the parent node. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_next_sibling(lsl_xml_ptr e); + +/** Get the previous sibling in the children list of the parent node. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_previous_sibling(lsl_xml_ptr e); + +/** Get the parent node. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_parent(lsl_xml_ptr e); + + +// XML Tree Navigation by Name + +/** Get a child with a specified name. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_child(lsl_xml_ptr e, const char *name); + +/** Get the next sibling with the specified name. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_next_sibling_n(lsl_xml_ptr e, const char *name); + +/** Get the previous sibling with the specified name. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_previous_sibling_n(lsl_xml_ptr e, const char *name); + + +// Content Queries + +/** Whether this node is empty. */ +extern LIBLSL_C_API int32_t lsl_empty(lsl_xml_ptr e); + +/** Whether this is a text body (instead of an XML element). True both for plain char data and CData. */ +extern LIBLSL_C_API int32_t lsl_is_text(lsl_xml_ptr e); + +/** Name of the element. */ +extern LIBLSL_C_API const char *lsl_name(lsl_xml_ptr e); + +/** Value of the element. */ +extern LIBLSL_C_API const char *lsl_value(lsl_xml_ptr e); + +/** Get child value (value of the first child that is text). */ +extern LIBLSL_C_API const char *lsl_child_value(lsl_xml_ptr e); + +/** Get child value of a child with a specified name. */ +extern LIBLSL_C_API const char *lsl_child_value_n(lsl_xml_ptr e, const char *name); + + +// Data Modification + +/// Append a child node with a given name, which has a (nameless) plain-text child with the given text value. +extern LIBLSL_C_API lsl_xml_ptr lsl_append_child_value(lsl_xml_ptr e, const char *name, const char *value); + +/// Prepend a child node with a given name, which has a (nameless) plain-text child with the given text value. +extern LIBLSL_C_API lsl_xml_ptr lsl_prepend_child_value(lsl_xml_ptr e, const char *name, const char *value); + +/// Set the text value of the (nameless) plain-text child of a named child node. +extern LIBLSL_C_API int32_t lsl_set_child_value(lsl_xml_ptr e, const char *name, const char *value); + +/** +* Set the element's name. +* @return 0 if the node is empty (or if out of memory). +*/ +extern LIBLSL_C_API int32_t lsl_set_name(lsl_xml_ptr e, const char *rhs); + +/** +* Set the element's value. +* @return 0 if the node is empty (or if out of memory). +*/ +extern LIBLSL_C_API int32_t lsl_set_value(lsl_xml_ptr e, const char *rhs); + +/** Append a child element with the specified name. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_append_child(lsl_xml_ptr e, const char *name); + +/** Prepend a child element with the specified name. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_prepend_child(lsl_xml_ptr e, const char *name); + +/** Append a copy of the specified element as a child. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_append_copy(lsl_xml_ptr e, lsl_xml_ptr e2); + +/** Prepend a child element with the specified name. */ +extern LIBLSL_C_API lsl_xml_ptr lsl_prepend_copy(lsl_xml_ptr e, lsl_xml_ptr e2); + +/** Remove a child element with the specified name. */ +extern LIBLSL_C_API void lsl_remove_child_n(lsl_xml_ptr e, const char *name); + +/** Remove a specified child element. */ +extern LIBLSL_C_API void lsl_remove_child(lsl_xml_ptr e, lsl_xml_ptr e2); + +/// @} diff --git a/Plugins/LSL/include/lsl/xml.h.meta b/Plugins/LSL/include/lsl/xml.h.meta new file mode 100644 index 0000000..3cc77c6 --- /dev/null +++ b/Plugins/LSL/include/lsl/xml.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 2b311ac1bc1688446addb205f3881cb2 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl_c.h b/Plugins/LSL/include/lsl_c.h new file mode 100644 index 0000000..0a6d2e9 --- /dev/null +++ b/Plugins/LSL/include/lsl_c.h @@ -0,0 +1,36 @@ +#ifndef LSL_C_H +#define LSL_C_H + +/** @file lsl_c.h LSL C API for the lab streaming layer + * + * The lab streaming layer provides a set of functions to make instrument data accessible + * in real time within a lab network. From there, streams can be picked up by recording programs, + * viewing programs or custom experiment applications that access data streams in real time. + * + * The API covers two areas: + * - The "push API" allows to create stream outlets and to push data (regular or irregular + * measurement time series, event data, coded audio/video frames, etc.) into them. + * - The "pull API" allows to create stream inlets and read time-synched experiment data from them + * (for recording, viewing or experiment control). + * + * To use this library you need to link to the liblsl library that comes with + * this header. Under Visual Studio the library is linked in automatically. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "lsl/common.h" +#include "lsl/inlet.h" +#include "lsl/outlet.h" +#include "lsl/resolver.h" +#include "lsl/streaminfo.h" +#include "lsl/types.h" +#include "lsl/xml.h" + +#ifdef __cplusplus +} /* end extern "C" */ +#endif + +#endif diff --git a/Plugins/LSL/include/lsl_c.h.meta b/Plugins/LSL/include/lsl_c.h.meta new file mode 100644 index 0000000..072c0e9 --- /dev/null +++ b/Plugins/LSL/include/lsl_c.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: f511fe2f12ddd2b4ba64b034bcf8aaac +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/include/lsl_cpp.h b/Plugins/LSL/include/lsl_cpp.h new file mode 100644 index 0000000..72d5881 --- /dev/null +++ b/Plugins/LSL/include/lsl_cpp.h @@ -0,0 +1,1721 @@ +#ifndef LSL_CPP_H +#define LSL_CPP_H + +/** + * @file lsl_cpp.h + * + * C++ API for the lab streaming layer. + * + * The lab streaming layer provides a set of functions to make instrument data accessible + * in real time within a lab network. From there, streams can be picked up by recording programs, + * viewing programs or custom experiment applications that access data streams in real time. + * + * The API covers two areas: + * - The "push API" allows to create stream outlets and to push data (regular or irregular + * measurement time series, event data, coded audio/video frames, etc.) into them. + * - The "pull API" allows to create stream inlets and read time-synched experiment data from them + * (for recording, viewing or experiment control). + * + * To use this library you need to link to the shared library (lsl) that comes with + * this header. Under Visual Studio the library is linked in automatically. + */ + +#include +#include +#include +#include + +extern "C" { +#include "lsl_c.h" +} + +namespace lsl { +/// Assert that no error happened; throw appropriate exception otherwise +int32_t check_error(int32_t ec); + +/// Constant to indicate that a stream has variable sampling rate. +const double IRREGULAR_RATE = 0.0; + +/** + * Constant to indicate that a sample has the next successive time stamp. + * + * This is an optional optimization to transmit less data per sample. + * The stamp is then deduced from the preceding one according to the stream's sampling rate + * (in the case of an irregular rate, the same time stamp as before will is assumed). + */ +const double DEDUCED_TIMESTAMP = -1.0; + +/** + * A very large time duration (> 1 year) for timeout values. + * + * Note that significantly larger numbers can cause the timeout to be invalid on some operating + * systems (e.g., 32-bit UNIX). + */ +const double FOREVER = 32000000.0; + +/// Data format of a channel (each transmitted sample holds an array of channels). +enum channel_format_t { + /** For up to 24-bit precision measurements in the appropriate physical unit (e.g., microvolts). + Integers from -16777216 to 16777216 are represented accurately.*/ + cf_float32 = 1, + /// For universal numeric data as long as permitted by network & disk budget. + /// The largest representable integer is 53-bit. + cf_double64 = 2, + /// For variable-length ASCII strings or data blobs, such as video frames, complex event + /// descriptions, etc. + cf_string = 3, + /// For high-rate digitized formats that require 32-bit precision. + /// Depends critically on meta-data to represent meaningful units. + /// Useful for application event codes or other coded data. + cf_int32 = 4, + /// For very high rate signals (40Khz+) or consumer-grade audio (for professional audio float is + /// recommended). + cf_int16 = 5, + /// For binary signals or other coded data. Not recommended for encoding string data. + cf_int8 = 6, + /// For now only for future compatibility. Support for this type is not yet exposed in all + /// languages. Also, some builds of liblsl will not be able to send or receive data of this + /// type. + cf_int64 = 7, + /// Can not be transmitted. + cf_undefined = 0 +}; + +/// Post-processing options for stream inlets. +enum processing_options_t { + /// No automatic post-processing; return the ground-truth time stamps for manual post-processing + /// (this is the default behavior of the inlet). + post_none = 0, + /// Perform automatic clock synchronization; equivalent to manually adding the time_correction() + /// value to the received time stamps. + post_clocksync = 1, + /// Remove jitter from time stamps. This will apply a smoothing algorithm to the received time + /// stamps; the smoothing needs to see a minimum number of samples (30-120 seconds worst-case) + /// until the remaining jitter is consistently below 1ms. + post_dejitter = 2, + /// Force the time-stamps to be monotonically ascending (only makes sense if timestamps are + /// dejittered). + post_monotonize = 4, + /// Post-processing is thread-safe (same inlet can be read from by multiple threads); uses + /// somewhat more CPU. + post_threadsafe = 8, + /// The combination of all possible post-processing options. + post_ALL = 1 | 2 | 4 | 8 +}; + +/** + * Protocol version. + * + * The major version is `protocol_version() / 100`; + * The minor version is `protocol_version() % 100`; + * Clients with different minor versions are protocol-compatible with each other + * while clients with different major versions will refuse to work together. + */ +inline int32_t protocol_version() { return lsl_protocol_version(); } + +/// @copydoc ::lsl_library_version() +inline int32_t library_version() { return lsl_library_version(); } + +/** + * Get a string containing library information. + * + * The format of the string shouldn't be used for anything important except giving a a debugging + * person a good idea which exact library version is used. */ +inline const char *library_info() { return lsl_library_info(); } + +/** + * Obtain a local system time stamp in seconds. + * + * The resolution is better than a millisecond. + * This reading can be used to assign time stamps to samples as they are being acquired. + * If the "age" of a sample is known at a particular time (e.g., from USB transmission + * delays), it can be used as an offset to local_clock() to obtain a better estimate of + * when a sample was actually captured. See stream_outlet::push_sample() for a use case. + */ +inline double local_clock() { return lsl_local_clock(); } + + +/// @section Stream Declaration + +class xml_element; + +/** + * The stream_info object stores the declaration of a data stream. + * + * Represents the following information: + * a) stream data format (number of channels, channel format) + * b) core information (stream name, content type, sampling rate) + * c) optional meta-data about the stream content (channel labels, measurement units, etc.) + * + * Whenever a program wants to provide a new stream on the lab network it will typically first + * create a stream_info to describe its properties and then construct a stream_outlet with it to + * create the stream on the network. Recipients who discover the outlet can query the stream_info; + * it is also written to disk when recording the stream (playing a similar role as a file header). + */ +class stream_info { +public: + /** + * Construct a new stream_info object. + * + * Core stream information is specified here. Any remaining meta-data can be added later. + * @param name Name of the stream. Describes the device (or product series) that this stream + * makes available (for use by programs, experimenters or data analysts). Cannot be empty. + * @param type Content type of the stream. Please see https://github.com/sccn/xdf/wiki/Meta-Data + * (or web search for: XDF meta-data) for pre-defined content-type names, but you can also make + * up your own. The content type is the preferred way to find streams (as opposed to searching + * by name). + * @param channel_count Number of channels per sample. This stays constant for the lifetime of + * the stream. + * @param nominal_srate The sampling rate (in Hz) as advertised by the data source, if regular + * (otherwise set to IRREGULAR_RATE). + * @param channel_format Format/type of each channel. If your channels have different formats, + * consider supplying multiple streams or use the largest type that can hold them all (such as + * cf_double64). + * @param source_id Unique identifier of the device or source of the data, if available (such as + * the serial number). This is critical for system robustness since it allows recipients to + * recover from failure even after the serving app, device or computer crashes (just by finding + * a stream with the same source id on the network again). Therefore, it is highly recommended + * to always try to provide whatever information can uniquely identify the data source itself. + */ + stream_info(const std::string &name, const std::string &type, int32_t channel_count = 1, + double nominal_srate = IRREGULAR_RATE, channel_format_t channel_format = cf_float32, + const std::string &source_id = std::string()) + : obj(lsl_create_streaminfo((name.c_str()), (type.c_str()), channel_count, nominal_srate, + (lsl_channel_format_t)channel_format, (source_id.c_str())), &lsl_destroy_streaminfo) { + if (obj == nullptr) throw std::invalid_argument(lsl_last_error()); + } + + /// Default contructor. + stream_info(): stream_info("untitled", "", 0, 0, cf_undefined, ""){} + + /// Copy constructor. Only increments the reference count! @see clone() + stream_info(const stream_info &) noexcept = default; + stream_info(lsl_streaminfo handle) : obj(handle, &lsl_destroy_streaminfo) {} + + /// Clones a streaminfo object. + stream_info clone() { return stream_info(lsl_copy_streaminfo(obj.get())); } + + + // ======================== + // === Core Information === + // ======================== + // (these fields are assigned at construction) + + /** + * Name of the stream. + * + * This is a human-readable name. For streams offered by device modules, it refers to the type + * of device or product series that is generating the data of the stream. If the source is an + * application, the name may be a more generic or specific identifier. Multiple streams with the + * same name can coexist, though potentially at the cost of ambiguity (for the recording app or + * experimenter). + */ + std::string name() const { return lsl_get_name(obj.get()); } + + /** + * Content type of the stream. + * + * The content type is a short string such as "EEG", "Gaze" which describes the content carried + * by the channel (if known). If a stream contains mixed content this value need not be assigned + * but may instead be stored in the description of channel types. To be useful to applications + * and automated processing systems using the recommended content types is preferred. Content + * types usually follow those pre-defined in https://github.com/sccn/xdf/wiki/Meta-Data (or web + * search for: XDF meta-data). + */ + std::string type() const { return lsl_get_type(obj.get()); } + + /** + * Number of channels of the stream. + * + * A stream has at least one channel; the channel count stays constant for all samples. + */ + int32_t channel_count() const { return lsl_get_channel_count(obj.get()); } + + /** + * Sampling rate of the stream, according to the source (in Hz). + * + * If a stream is irregularly sampled, this should be set to IRREGULAR_RATE. + * + * Note that no data will be lost even if this sampling rate is incorrect or if a device has + * temporary hiccups, since all samples will be recorded anyway (except for those dropped by the + * device itself). However, when the recording is imported into an application, a good importer + * may correct such errors more accurately if the advertised sampling rate was close to the + * specs of the device. + */ + double nominal_srate() const { return lsl_get_nominal_srate(obj.get()); } + + /** + * Channel format of the stream. + * + * All channels in a stream have the same format. However, a device might offer multiple + * time-synched streams each with its own format. + */ + channel_format_t channel_format() const { + return static_cast(lsl_get_channel_format(obj.get())); + } + + /** + * Unique identifier of the stream's source, if available. + * + * The unique source (or device) identifier is an optional piece of information that, if + * available, allows that endpoints (such as the recording program) can re-acquire a stream + * automatically once it is back online. + */ + std::string source_id() const { return lsl_get_source_id(obj.get()); } + + + // ====================================== + // === Additional Hosting Information === + // ====================================== + // (these fields are implicitly assigned once bound to an outlet/inlet) + + /// Protocol version used to deliver the stream. + int32_t version() const { return lsl_get_version(obj.get()); } + + /** + * Creation time stamp of the stream. + * + * This is the time stamp when the stream was first created + * (as determined via #lsl::local_clock() on the providing machine). + */ + double created_at() const { return lsl_get_created_at(obj.get()); } + + /** + * Unique ID of the stream outlet instance (once assigned). + * + * This is a unique identifier of the stream outlet, and is guaranteed to be different + * across multiple instantiations of the same outlet (e.g., after a re-start). + */ + std::string uid() const { return lsl_get_uid(obj.get()); } + + /** + * Session ID for the given stream. + * + * The session id is an optional human-assigned identifier of the recording session. + * While it is rarely used, it can be used to prevent concurrent recording activitites + * on the same sub-network (e.g., in multiple experiment areas) from seeing each other's streams + * (assigned via a configuration file by the experimenter, see Network Connectivity in the LSL + * wiki). + */ + std::string session_id() const { return lsl_get_session_id(obj.get()); } + + /// Hostname of the providing machine. + std::string hostname() const { return lsl_get_hostname(obj.get()); } + + + // ======================== + // === Data Description === + // ======================== + + /** + * Extended description of the stream. + * + * It is highly recommended that at least the channel labels are described here. + * See code examples on the LSL wiki. Other information, such as amplifier settings, + * measurement units if deviating from defaults, setup information, subject information, etc., + * can be specified here, as well. Meta-data recommendations follow the XDF file format project + * (github.com/sccn/xdf/wiki/Meta-Data or web search for: XDF meta-data). + * + * Important: if you use a stream content type for which meta-data recommendations exist, please + * try to lay out your meta-data in agreement with these recommendations for compatibility with + * other applications. + */ + xml_element desc(); + + /// lsl_stream_info_matches_query + bool matches_query(const char *query) const { + return lsl_stream_info_matches_query(obj.get(), query); + } + + + // =============================== + // === Miscellaneous Functions === + // =============================== + + /** Retrieve the entire streaminfo in XML format. + * This yields an XML document (in string form) whose top-level element is ``. The info + * element contains one element for each field of the streaminfo class, including: + * + * - the core elements ``, ``, ``, + * ``, `` + * - the misc elements ``, ``, ``, ``, + * ``, ``, ``, ``, ``, + * `` + * - the extended description element `` with user-defined sub-elements. + */ + std::string as_xml() const { + char *tmp = lsl_get_xml(obj.get()); + std::string result(tmp); + lsl_destroy_string(tmp); + return result; + } + + /// Number of bytes occupied by a channel (0 for string-typed channels). + int32_t channel_bytes() const { return lsl_get_channel_bytes(obj.get()); } + + /// Number of bytes occupied by a sample (0 for string-typed channels). + int32_t sample_bytes() const { return lsl_get_sample_bytes(obj.get()); } + + /// Get the implementation handle. + std::shared_ptr handle() const { return obj; } + + /// Assignment operator. + stream_info &operator=(const stream_info &rhs) { + if (this != &rhs) obj = stream_info(rhs).handle(); + return *this; + } + + stream_info(stream_info &&rhs) noexcept = default; + + stream_info &operator=(stream_info &&rhs) noexcept = default; + + /// Utility function to create a stream_info from an XML representation + static stream_info from_xml(const std::string &xml) { + return stream_info(lsl_streaminfo_from_xml(xml.c_str())); + } + +private: + std::shared_ptr obj; +}; + + +// ======================= +// ==== Stream Outlet ==== +// ======================= + +/** A stream outlet. + * Outlets are used to make streaming data (and the meta-data) available on the lab network. + */ +class stream_outlet { +public: + /** Establish a new stream outlet. This makes the stream discoverable. + * @param info The stream information to use for creating this stream. Stays constant over the + * lifetime of the outlet. + * @param chunk_size Optionally the desired chunk granularity (in samples) for transmission. If + * unspecified, each push operation yields one chunk. Inlets can override this setting. + * @param max_buffered Optionally the maximum amount of data to buffer (in seconds if there is a + * nominal sampling rate, otherwise x100 in samples). The default is 6 minutes of data. + */ + stream_outlet(const stream_info &info, int32_t chunk_size = 0, int32_t max_buffered = 360, + lsl_transport_options_t flags = transp_default) + : channel_count(info.channel_count()), sample_rate(info.nominal_srate()), + obj(lsl_create_outlet_ex(info.handle().get(), chunk_size, max_buffered, flags), + &lsl_destroy_outlet) {} + + // ======================================== + // === Pushing a sample into the outlet === + // ======================================== + + /** Push a C array of values as a sample into the outlet. + * Each entry in the array corresponds to one channel. + * The function handles type checking & conversion. + * @param data An array of values to push (one per channel). + * @param timestamp Optionally the capture time of the sample, in agreement with + * lsl::local_clock(); if omitted, the current time is used. + * @param pushthrough Whether to push the sample through to the receivers instead of + * buffering it with subsequent samples. + * Note that the chunk_size, if specified at outlet construction, takes precedence over the + * pushthrough flag. + */ + template + void push_sample(const T data[N], double timestamp = 0.0, bool pushthrough = true) { + check_numchan(N); + push_sample(&data[0], timestamp, pushthrough); + } + + /** Push a std vector of values as a sample into the outlet. + * Each entry in the vector corresponds to one channel. The function handles type checking & + * conversion. + * @param data A vector of values to push (one for each channel). + * @param timestamp Optionally the capture time of the sample, in agreement with local_clock(); + * if omitted, the current time is used. + * @param pushthrough Whether to push the sample through to the receivers instead of buffering + * it with subsequent samples. Note that the chunk_size, if specified at outlet construction, + * takes precedence over the pushthrough flag. + */ + template + void push_sample( + const std::vector &data, double timestamp = 0.0, bool pushthrough = true) { + check_numchan(data.size()); + push_sample(data.data(), timestamp, pushthrough); + } + + /** Push a pointer to some values as a sample into the outlet. + * This is a lower-level function for cases where data is available in some buffer. + * Handles type checking & conversion. + * @param data A pointer to values to push. The number of values pointed to must not be less + * than the number of channels in the sample. + * @param timestamp Optionally the capture time of the sample, in agreement with local_clock(); + * if omitted, the current time is used. + * @param pushthrough Whether to push the sample through to the receivers instead of buffering + * it with subsequent samples. Note that the chunk_size, if specified at outlet construction, + * takes precedence over the pushthrough flag. + */ + void push_sample(const float *data, double timestamp = 0.0, bool pushthrough = true) { + lsl_push_sample_ftp(obj.get(), (data), timestamp, pushthrough); + } + void push_sample(const double *data, double timestamp = 0.0, bool pushthrough = true) { + lsl_push_sample_dtp(obj.get(), (data), timestamp, pushthrough); + } + void push_sample(const int64_t *data, double timestamp = 0.0, bool pushthrough = true) { + lsl_push_sample_ltp(obj.get(), (data), timestamp, pushthrough); + } + void push_sample(const int32_t *data, double timestamp = 0.0, bool pushthrough = true) { + lsl_push_sample_itp(obj.get(), (data), timestamp, pushthrough); + } + void push_sample(const int16_t *data, double timestamp = 0.0, bool pushthrough = true) { + lsl_push_sample_stp(obj.get(), (data), timestamp, pushthrough); + } + void push_sample(const char *data, double timestamp = 0.0, bool pushthrough = true) { + lsl_push_sample_ctp(obj.get(), (data), timestamp, pushthrough); + } + void push_sample(const std::string *data, double timestamp = 0.0, bool pushthrough = true) { + std::vector lengths(channel_count); + std::vector pointers(channel_count); + for (int32_t k = 0; k < channel_count; k++) { + pointers[k] = data[k].c_str(); + lengths[k] = (uint32_t)data[k].size(); + } + lsl_push_sample_buftp(obj.get(), pointers.data(), lengths.data(), timestamp, pushthrough); + } + + /** Push a packed C struct (of numeric data) as one sample into the outlet (search for + * [`#``pragma pack`](https://stackoverflow.com/a/3318475/73299) for information on packing + * structs appropriately).
+ * Overall size checking but no type checking or conversion are done.
+ * Can not be used forvariable-size / string-formatted data. + * @param sample The sample struct to push. + * @param timestamp Optionally the capture time of the sample, in agreement with + * local_clock(); if omitted, the current time is used. + * @param pushthrough Whether to push the sample through to the receivers instead of + * buffering it with subsequent samples. Note that the chunk_size, if specified at outlet + * construction, takes precedence over the pushthrough flag. + */ + template + void push_numeric_struct(const T &sample, double timestamp = 0.0, bool pushthrough = true) { + if (info().sample_bytes() != sizeof(T)) + throw std::runtime_error( + "Provided object size does not match the stream's sample size."); + push_numeric_raw((void *)&sample, timestamp, pushthrough); + } + + /** Push a pointer to raw numeric data as one sample into the outlet. + * This is the lowest-level function; performs no checking whatsoever. Cannot be used for + * variable-size / string-formatted channels. + * @param sample A pointer to the raw sample data to push. + * @param timestamp Optionally the capture time of the sample, in agreement with local_clock(); + * if omitted, the current time is used. + * @param pushthrough Whether to push the sample through to the receivers instead of buffering + * it with subsequent samples. Note that the chunk_size, if specified at outlet construction, + * takes precedence over the pushthrough flag. + */ + void push_numeric_raw(const void *sample, double timestamp = 0.0, bool pushthrough = true) { + lsl_push_sample_vtp(obj.get(), (sample), timestamp, pushthrough); + } + + + // =================================================== + // === Pushing an chunk of samples into the outlet === + // =================================================== + + /** Push a chunk of samples (batched into an STL vector) into the outlet. + * @param samples A vector of samples in some supported format (each sample can be a data + * pointer, data array, or std vector of data). + * @param timestamp Optionally the capture time of the most recent sample, in agreement with + * local_clock(); if omitted, the current time is used. The time stamps of other samples are + * automatically derived according to the sampling rate of the stream. + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + */ + template + void push_chunk( + const std::vector &samples, double timestamp = 0.0, bool pushthrough = true) { + if (!samples.empty()) { + if (timestamp == 0.0) timestamp = local_clock(); + if (sample_rate != IRREGULAR_RATE) + timestamp = timestamp - (samples.size() - 1) / sample_rate; + push_sample(samples[0], timestamp, pushthrough && samples.size() == 1); + for (std::size_t k = 1; k < samples.size(); k++) + push_sample(samples[k], DEDUCED_TIMESTAMP, pushthrough && k == samples.size() - 1); + } + } + + /** Push a chunk of samples (batched into an STL vector) into the outlet. + * Allows to specify a separate time stamp for each sample (for irregular-rate streams). + * @param samples A vector of samples in some supported format (each sample can be a data + * pointer, data array, or std vector of data). + * @param timestamps A vector of capture times for each sample, in agreement with local_clock(). + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + */ + template + void push_chunk(const std::vector &samples, const std::vector ×tamps, + bool pushthrough = true) { + for (unsigned k = 0; k < samples.size() - 1; k++) + push_sample(samples[k], timestamps[k], false); + if (!samples.empty()) push_sample(samples.back(), timestamps.back(), pushthrough); + } + + /** Push a chunk of numeric data as C-style structs (batched into an STL vector) into the + * outlet. This performs some size checking but no type checking. Can not be used for + * variable-size / string-formatted data. + * @param samples A vector of samples, as C structs. + * @param timestamp Optionally the capture time of the sample, in agreement with local_clock(); + * if omitted, the current time is used. + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + */ + template + void push_chunk_numeric_structs( + const std::vector &samples, double timestamp = 0.0, bool pushthrough = true) { + if (!samples.empty()) { + if (timestamp == 0.0) timestamp = local_clock(); + if (sample_rate != IRREGULAR_RATE) + timestamp = timestamp - (samples.size() - 1) / sample_rate; + push_numeric_struct(samples[0], timestamp, pushthrough && samples.size() == 1); + for (std::size_t k = 1; k < samples.size(); k++) + push_numeric_struct( + samples[k], DEDUCED_TIMESTAMP, pushthrough && k == samples.size() - 1); + } + } + + /** Push a chunk of numeric data from C-style structs (batched into an STL vector), into the + * outlet. This performs some size checking but no type checking. Can not be used for + * variable-size / string-formatted data. + * @param samples A vector of samples, as C structs. + * @param timestamps A vector of capture times for each sample, in agreement with local_clock(). + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + */ + template + void push_chunk_numeric_structs(const std::vector &samples, + const std::vector ×tamps, bool pushthrough = true) { + for (unsigned k = 0; k < samples.size() - 1; k++) + push_numeric_struct(samples[k], timestamps[k], false); + if (!samples.empty()) push_numeric_struct(samples.back(), timestamps.back(), pushthrough); + } + + /** Push a chunk of multiplexed data into the outlet. + * @name Push functions + * @param buffer A buffer of channel values holding the data for zero or more successive samples + * to send. + * @param timestamp Optionally the capture time of the most recent sample, in agreement with + * local_clock(); if omitted, the current time is used. The time stamps of other samples are + * automatically derived according to the sampling rate of the stream. + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + */ + template + void push_chunk_multiplexed( + const std::vector &buffer, double timestamp = 0.0, bool pushthrough = true) { + if (!buffer.empty()) + push_chunk_multiplexed( + buffer.data(), static_cast(buffer.size()), timestamp, pushthrough); + } + + /** Push a chunk of multiplexed data into the outlet. One timestamp per sample is provided. + * Allows to specify a separate time stamp for each sample (for irregular-rate streams). + * @param buffer A buffer of channel values holding the data for zero or more successive samples + * to send. + * @param timestamps A buffer of timestamp values holding time stamps for each sample in the + * data buffer. + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + */ + template + void push_chunk_multiplexed(const std::vector &buffer, + const std::vector ×tamps, bool pushthrough = true) { + if (!buffer.empty() && !timestamps.empty()) + push_chunk_multiplexed( + buffer.data(), static_cast(buffer.size()), timestamps.data(), pushthrough); + } + + /** Push a chunk of multiplexed samples into the outlet. Single timestamp provided. + * @warning The provided buffer size is measured in channel values (e.g., floats), not samples. + * @param buffer A buffer of channel values holding the data for zero or more successive samples + * to send. + * @param buffer_elements The number of channel values (of type T) in the buffer. Must be a + * multiple of the channel count. + * @param timestamp Optionally the capture time of the most recent sample, in agreement with + * local_clock(); if omitted, the current time is used. The time stamps of other samples are + * automatically derived based on the sampling rate of the stream. + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the stream_outlet() constructur parameter @p chunk_size, + * if specified at outlet construction, takes precedence over the pushthrough flag. + */ + void push_chunk_multiplexed(const float *buffer, std::size_t buffer_elements, + double timestamp = 0.0, bool pushthrough = true) { + lsl_push_chunk_ftp(obj.get(), buffer, static_cast(buffer_elements), timestamp, pushthrough); + } + void push_chunk_multiplexed(const double *buffer, std::size_t buffer_elements, + double timestamp = 0.0, bool pushthrough = true) { + lsl_push_chunk_dtp(obj.get(), buffer, static_cast(buffer_elements), timestamp, pushthrough); + } + void push_chunk_multiplexed(const int64_t *buffer, std::size_t buffer_elements, + double timestamp = 0.0, bool pushthrough = true) { + lsl_push_chunk_ltp(obj.get(), buffer, static_cast(buffer_elements), timestamp, pushthrough); + } + void push_chunk_multiplexed(const int32_t *buffer, std::size_t buffer_elements, + double timestamp = 0.0, bool pushthrough = true) { + lsl_push_chunk_itp(obj.get(), buffer, static_cast(buffer_elements), timestamp, pushthrough); + } + void push_chunk_multiplexed(const int16_t *buffer, std::size_t buffer_elements, + double timestamp = 0.0, bool pushthrough = true) { + lsl_push_chunk_stp(obj.get(), buffer, static_cast(buffer_elements), timestamp, pushthrough); + } + void push_chunk_multiplexed(const char *buffer, std::size_t buffer_elements, + double timestamp = 0.0, bool pushthrough = true) { + lsl_push_chunk_ctp(obj.get(), buffer, static_cast(buffer_elements), timestamp, pushthrough); + } + void push_chunk_multiplexed(const std::string *buffer, std::size_t buffer_elements, + double timestamp = 0.0, bool pushthrough = true) { + if (buffer_elements) { + std::vector lengths(buffer_elements); + std::vector pointers(buffer_elements); + for (std::size_t k = 0; k < buffer_elements; k++) { + pointers[k] = buffer[k].c_str(); + lengths[k] = (uint32_t)buffer[k].size(); + } + lsl_push_chunk_buftp(obj.get(), pointers.data(), lengths.data(), + static_cast(buffer_elements), timestamp, pushthrough); + } + } + + /** Push a chunk of multiplexed samples into the outlet. One timestamp per sample is provided. + * @warning Note that the provided buffer size is measured in channel values (e.g., floats) + * rather than in samples. + * @param data_buffer A buffer of channel values holding the data for zero or more successive + * samples to send. + * @param timestamp_buffer A buffer of timestamp values holding time stamps for each sample in + * the data buffer. + * @param data_buffer_elements The number of data values (of type T) in the data buffer. Must be + * a multiple of the channel count. + * @param pushthrough Whether to push the chunk through to the receivers instead of buffering it + * with subsequent samples. Note that the chunk_size, if specified at outlet construction, takes + * precedence over the pushthrough flag. + */ + void push_chunk_multiplexed(const float *data_buffer, const double *timestamp_buffer, + std::size_t data_buffer_elements, bool pushthrough = true) { + lsl_push_chunk_ftnp(obj.get(), data_buffer, static_cast(data_buffer_elements), + (timestamp_buffer), pushthrough); + } + void push_chunk_multiplexed(const double *data_buffer, const double *timestamp_buffer, + std::size_t data_buffer_elements, bool pushthrough = true) { + lsl_push_chunk_dtnp(obj.get(), data_buffer, static_cast(data_buffer_elements), + (timestamp_buffer), pushthrough); + } + void push_chunk_multiplexed(const int64_t *data_buffer, const double *timestamp_buffer, + std::size_t data_buffer_elements, bool pushthrough = true) { + lsl_push_chunk_ltnp(obj.get(), data_buffer, static_cast(data_buffer_elements), + (timestamp_buffer), pushthrough); + } + void push_chunk_multiplexed(const int32_t *data_buffer, const double *timestamp_buffer, + std::size_t data_buffer_elements, bool pushthrough = true) { + lsl_push_chunk_itnp(obj.get(), data_buffer, static_cast(data_buffer_elements), + (timestamp_buffer), pushthrough); + } + void push_chunk_multiplexed(const int16_t *data_buffer, const double *timestamp_buffer, + std::size_t data_buffer_elements, bool pushthrough = true) { + lsl_push_chunk_stnp(obj.get(), data_buffer, static_cast(data_buffer_elements), + (timestamp_buffer), pushthrough); + } + void push_chunk_multiplexed(const char *data_buffer, const double *timestamp_buffer, + std::size_t data_buffer_elements, bool pushthrough = true) { + lsl_push_chunk_ctnp(obj.get(), data_buffer, static_cast(data_buffer_elements), + (timestamp_buffer), pushthrough); + } + + void push_chunk_multiplexed(const std::string *data_buffer, const double *timestamp_buffer, + std::size_t data_buffer_elements, bool pushthrough = true) { + if (data_buffer_elements) { + std::vector lengths(data_buffer_elements); + std::vector pointers(data_buffer_elements); + for (std::size_t k = 0; k < data_buffer_elements; k++) { + pointers[k] = data_buffer[k].c_str(); + lengths[k] = (uint32_t)data_buffer[k].size(); + } + lsl_push_chunk_buftnp(obj.get(), pointers.data(), lengths.data(), + static_cast(data_buffer_elements), timestamp_buffer, pushthrough); + } + } + + + // =============================== + // === Miscellaneous Functions === + // =============================== + + /** Check whether consumers are currently registered. + * While it does not hurt, there is technically no reason to push samples if there is no + * consumer. + */ + bool have_consumers() { return lsl_have_consumers(obj.get()) != 0; } + + /** Wait until some consumer shows up (without wasting resources). + * @return True if the wait was successful, false if the timeout expired. + */ + bool wait_for_consumers(double timeout) { return lsl_wait_for_consumers(obj.get(), timeout) != 0; } + + /** Retrieve the stream info provided by this outlet. + * This is what was used to create the stream (and also has the Additional Network Information + * fields assigned). + */ + stream_info info() const { return stream_info(lsl_get_info(obj.get())); } + + /// Return a shared pointer to pass to C-API functions that aren't wrapped yet + /// + /// Example: @code lsl_push_chunk_buft(outlet.handle().get(), data, …); @endcode + std::shared_ptr handle() { return obj; } + + /** Destructor. + * The stream will no longer be discoverable after destruction and all paired inlets will stop + * delivering data. + */ + ~stream_outlet() = default; + + /// stream_outlet move constructor + stream_outlet(stream_outlet &&res) noexcept = default; + + stream_outlet &operator=(stream_outlet &&rhs) noexcept = default; + + +private: + // The outlet is a non-copyable object. + stream_outlet(const stream_outlet &rhs); + stream_outlet &operator=(const stream_outlet &rhs); + + /// Check whether a given data length matches the number of channels; throw if not + void check_numchan(std::size_t N) const { + if (N != static_cast(channel_count)) + throw std::runtime_error("Provided element count (" + std::to_string(N) + + ") does not match the stream's channel count (" + + std::to_string(channel_count) + '.'); + } + + int32_t channel_count; + double sample_rate; + std::shared_ptr obj; +}; + + +// =========================== +// ==== Resolve Functions ==== +// =========================== + +/** Resolve all streams on the network. + * This function returns all currently available streams from any outlet on the network. + * The network is usually the subnet specified at the local router, but may also include + * a multicast group of machines (given that the network supports it), or list of hostnames. + * These details may optionally be customized by the experimenter in a configuration file + * (see Network Connectivity in the LSL wiki). + * This is the default mechanism used by the browsing programs and the recording program. + * @param wait_time The waiting time for the operation, in seconds, to search for streams. + * If this is too short (<0.5s) only a subset (or none) of the outlets that are present on the + * network may be returned. + * @return A vector of stream info objects (excluding their desc field), any of which can + * subsequently be used to open an inlet. The full info can be retrieve from the inlet. + */ +inline std::vector resolve_streams(double wait_time = 1.0) { + lsl_streaminfo buffer[1024]; + int nres = check_error(lsl_resolve_all(buffer, sizeof(buffer), wait_time)); + return std::vector(&buffer[0], &buffer[nres]); +} + +/** Resolve all streams with a specific value for a given property. + * If the goal is to resolve a specific stream, this method is preferred over resolving all streams + * and then selecting the desired one. + * @param prop The stream_info property that should have a specific value (e.g., "name", "type", + * "source_id", or "desc/manufaturer"). + * @param value The string value that the property should have (e.g., "EEG" as the type property). + * @param minimum Return at least this number of streams. + * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout). + * If the timeout expires, less than the desired number of streams (possibly none) + * will be returned. + * @return A vector of matching stream info objects (excluding their meta-data), any of + * which can subsequently be used to open an inlet. + */ +inline std::vector resolve_stream(const std::string &prop, const std::string &value, + int32_t minimum = 1, double timeout = FOREVER) { + lsl_streaminfo buffer[1024]; + int nres = check_error( + lsl_resolve_byprop(buffer, sizeof(buffer), prop.c_str(), value.c_str(), minimum, timeout)); + return std::vector(&buffer[0], &buffer[nres]); +} + +/** Resolve all streams that match a given predicate. + * + * Advanced query that allows to impose more conditions on the retrieved streams; the given + * string is an [XPath 1.0](http://en.wikipedia.org/w/index.php?title=XPath_1.0) predicate for + * the `` node (omitting the surrounding []'s) + * @param pred The predicate string, e.g. `name='BioSemi'` or + * `type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32` + * @param minimum Return at least this number of streams. + * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout). + * If the timeout expires, less than the desired number of streams (possibly + * none) will be returned. + * @return A vector of matching stream info objects (excluding their meta-data), any of + * which can subsequently be used to open an inlet. + */ +inline std::vector resolve_stream( + const std::string &pred, int32_t minimum = 1, double timeout = FOREVER) { + lsl_streaminfo buffer[1024]; + int nres = + check_error(lsl_resolve_bypred(buffer, sizeof(buffer), pred.c_str(), minimum, timeout)); + return std::vector(&buffer[0], &buffer[nres]); +} + + +// ====================== +// ==== Stream Inlet ==== +// ====================== + +/** A stream inlet. + * Inlets are used to receive streaming data (and meta-data) from the lab network. + */ +class stream_inlet { +public: + /** + * Construct a new stream inlet from a resolved stream info. + * @param info A resolved stream info object (as coming from one of the resolver functions). + * Note: The stream_inlet may also be constructed with a fully-specified stream_info, if the + * desired channel format and count is already known up-front, but this is strongly discouraged + * and should only ever be done if there is no time to resolve the stream up-front (e.g., due + * to limitations in the client program). + * @param max_buflen Optionally the maximum amount of data to buffer (in seconds if there is a + * nominal sampling rate, otherwise x100 in samples). Recording applications want to use a + * fairly large buffer size here, while real-time applications would only buffer as much as + * they need to perform their next calculation. + * @param max_chunklen Optionally the maximum size, in samples, at which chunks are transmitted + * (the default corresponds to the chunk sizes used by the sender). + * Recording applications can use a generous size here (leaving it to the network how to pack + * things), while real-time applications may want a finer (perhaps 1-sample) granularity. + * If left unspecified (=0), the sender determines the chunk granularity. + * @param recover Try to silently recover lost streams that are recoverable (=those that that + * have a source_id set). + * In all other cases (recover is false or the stream is not recoverable) functions may throw a + * lsl::lost_error if the stream's source is lost (e.g., due to an app or computer crash). + */ + stream_inlet(const stream_info &info, int32_t max_buflen = 360, int32_t max_chunklen = 0, + bool recover = true, lsl_transport_options_t flags = transp_default) + : channel_count(info.channel_count()), + obj(lsl_create_inlet_ex(info.handle().get(), max_buflen, max_chunklen, recover, flags), + &lsl_destroy_inlet) {} + + /// Return a shared pointer to pass to C-API functions that aren't wrapped yet + /// + /// Example: @code lsl_pull_sample_buf(inlet.handle().get(), buf, …); @endcode + std::shared_ptr handle() { return obj; } + + /// Move constructor for stream_inlet + stream_inlet(stream_inlet &&rhs) noexcept = default; + stream_inlet &operator=(stream_inlet &&rhs) noexcept= default; + + + /** Retrieve the complete information of the given stream, including the extended description. + * Can be invoked at any time of the stream's lifetime. + * @param timeout Timeout of the operation (default: no timeout). + * @throws timeout_error (if the timeout expires), or lost_error (if the stream source has been + * lost). + */ + stream_info info(double timeout = FOREVER) { + int32_t ec = 0; + lsl_streaminfo res = lsl_get_fullinfo(obj.get(), timeout, &ec); + check_error(ec); + return stream_info(res); + } + + /** Subscribe to the data stream. + * All samples pushed in at the other end from this moment onwards will be queued and + * eventually be delivered in response to pull_sample() or pull_chunk() calls. + * Pulling a sample without some preceding open_stream() is permitted (the stream will then be + * opened implicitly). + * @param timeout Optional timeout of the operation (default: no timeout). + * @throws timeout_error (if the timeout expires), or lost_error (if the stream source has been + * lost). + */ + void open_stream(double timeout = FOREVER) { + int32_t ec = 0; + lsl_open_stream(obj.get(), timeout, &ec); + check_error(ec); + } + + /** Drop the current data stream. + * + * All samples that are still buffered or in flight will be dropped and transmission + * and buffering of data for this inlet will be stopped. If an application stops being + * interested in data from a source (temporarily or not) but keeps the outlet alive, + * it should call close_stream() to not waste unnecessary system and network + * resources. + */ + void close_stream() { lsl_close_stream(obj.get()); } + + /** Retrieve an estimated time correction offset for the given stream. + * + * The first call to this function takes several milliseconds until a reliable first estimate + * is obtained. Subsequent calls are instantaneous (and rely on periodic background updates). + * On a well-behaved network, the precision of these estimates should be below 1 ms + * (empirically it is within +/-0.2 ms). + * + * To get a measure of whether the network is well-behaved, use the extended version + * time_correction(double*,double*,double) and check uncertainty (i.e. the round-trip-time). + * + * 0.2 ms is typical of wired networks. 2 ms is typical of wireless networks. + * The number can be much higher on poor networks. + * + * @param timeout Timeout to acquire the first time-correction estimate (default: no timeout). + * @return The time correction estimate. This is the number that needs to be added to a time + * stamp that was remotely generated via lsl_local_clock() to map it into the local clock + * domain of this machine. + * @throws #lsl::timeout_error (if the timeout expires), or #lsl::lost_error (if the stream + * source has been lost). + */ + + double time_correction(double timeout = FOREVER) { + int32_t ec = 0; + double res = lsl_time_correction(obj.get(), timeout, &ec); + check_error(ec); + return res; + } + /** @copydoc time_correction(double) + * @param remote_time The current time of the remote computer that was used to generate this + * time_correction. If desired, the client can fit time_correction vs remote_time to improve + * the real-time time_correction further. + * @param uncertainty The maximum uncertainty of the given time correction. + */ + double time_correction(double *remote_time, double *uncertainty, double timeout = FOREVER) { + int32_t ec = 0; + double res = lsl_time_correction_ex(obj.get(), remote_time, uncertainty, timeout, &ec); + check_error(ec); + return res; + } + + /** Set post-processing flags to use. + * + * By default, the inlet performs NO post-processing and returns the ground-truth time + * stamps, which can then be manually synchronized using .time_correction(), and then + * smoothed/dejittered if desired.
+ * This function allows automating these two and possibly more operations.
+ * @warning When you enable this, you will no longer receive or be able to recover the original + * time stamps. + * @param flags An integer that is the result of bitwise OR'ing one or more options from + * processing_options_t together (e.g., `post_clocksync|post_dejitter`); the default is to + * enable all options. + */ + void set_postprocessing(uint32_t flags = post_ALL) { + check_error(lsl_set_postprocessing(obj.get(), flags)); + } + + // ======================================= + // === Pulling a sample from the inlet === + // ======================================= + + /** Pull a sample from the inlet and read it into an array of values. + * Handles type checking & conversion. + * @param sample An array to hold the resulting values. + * @param timeout The timeout for this operation, if any. Use 0.0 to make the function + * non-blocking. + * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was + * available. To remap this time stamp to the local clock, add the value returned by + * .time_correction() to it. + * @throws lost_error (if the stream source has been lost). + */ + template double pull_sample(T sample[N], double timeout = FOREVER) { + return pull_sample(&sample[0], N, timeout); + } + + /** Pull a sample from the inlet and read it into a std vector of values. + * Handles type checking & conversion and allocates the necessary memory in the vector if + * necessary. + * @param sample An STL vector to hold the resulting values. + * @param timeout The timeout for this operation, if any. Use 0.0 to make the function + * non-blocking. + * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was + * available. To remap this time stamp to the local clock, add the value returned by + * .time_correction() to it. + * @throws lost_error (if the stream source has been lost). + */ + double pull_sample(std::vector &sample, double timeout = FOREVER) { + sample.resize(channel_count); + return pull_sample(&sample[0], (int32_t)sample.size(), timeout); + } + double pull_sample(std::vector &sample, double timeout = FOREVER) { + sample.resize(channel_count); + return pull_sample(&sample[0], (int32_t)sample.size(), timeout); + } + double pull_sample(std::vector &sample, double timeout = FOREVER) { + sample.resize(channel_count); + return pull_sample(&sample[0], (int32_t)sample.size(), timeout); + } + double pull_sample(std::vector &sample, double timeout = FOREVER) { + sample.resize(channel_count); + return pull_sample(&sample[0], (int32_t)sample.size(), timeout); + } + double pull_sample(std::vector &sample, double timeout = FOREVER) { + sample.resize(channel_count); + return pull_sample(&sample[0], (int32_t)sample.size(), timeout); + } + double pull_sample(std::vector &sample, double timeout = FOREVER) { + sample.resize(channel_count); + return pull_sample(&sample[0], (int32_t)sample.size(), timeout); + } + double pull_sample(std::vector &sample, double timeout = FOREVER) { + sample.resize(channel_count); + return pull_sample(&sample[0], (int32_t)sample.size(), timeout); + } + + /** Pull a sample from the inlet and read it into a pointer to values. + * Handles type checking & conversion. + * @param buffer A pointer to hold the resulting values. + * @param buffer_elements The number of samples allocated in the buffer. Note: it is the + * responsibility of the user to allocate enough memory. + * @param timeout The timeout for this operation, if any. Use 0.0 to make the function + * non-blocking. + * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was + * available. To remap this time stamp to the local clock, add the value returned by + * .time_correction() to it. + * @throws lost_error (if the stream source has been lost). + */ + double pull_sample(float *buffer, int32_t buffer_elements, double timeout = FOREVER) { + int32_t ec = 0; + double res = lsl_pull_sample_f(obj.get(), buffer, buffer_elements, timeout, &ec); + check_error(ec); + return res; + } + double pull_sample(double *buffer, int32_t buffer_elements, double timeout = FOREVER) { + int32_t ec = 0; + double res = lsl_pull_sample_d(obj.get(), buffer, buffer_elements, timeout, &ec); + check_error(ec); + return res; + } + double pull_sample(int64_t *buffer, int32_t buffer_elements, double timeout = FOREVER) { + int32_t ec = 0; + double res = lsl_pull_sample_l(obj.get(), buffer, buffer_elements, timeout, &ec); + check_error(ec); + return res; + } + double pull_sample(int32_t *buffer, int32_t buffer_elements, double timeout = FOREVER) { + int32_t ec = 0; + double res = lsl_pull_sample_i(obj.get(), buffer, buffer_elements, timeout, &ec); + check_error(ec); + return res; + } + double pull_sample(int16_t *buffer, int32_t buffer_elements, double timeout = FOREVER) { + int32_t ec = 0; + double res = lsl_pull_sample_s(obj.get(), buffer, buffer_elements, timeout, &ec); + check_error(ec); + return res; + } + double pull_sample(char *buffer, int32_t buffer_elements, double timeout = FOREVER) { + int32_t ec = 0; + double res = lsl_pull_sample_c(obj.get(), buffer, buffer_elements, timeout, &ec); + check_error(ec); + return res; + } + double pull_sample(std::string *buffer, int32_t buffer_elements, double timeout = FOREVER) { + int32_t ec = 0; + if (buffer_elements) { + std::vector result_strings(buffer_elements); + std::vector result_lengths(buffer_elements); + double res = lsl_pull_sample_buf( + obj.get(), result_strings.data(), result_lengths.data(), buffer_elements, timeout, &ec); + check_error(ec); + for (int32_t k = 0; k < buffer_elements; k++) { + buffer[k].assign(result_strings[k], result_lengths[k]); + lsl_destroy_string(result_strings[k]); + } + return res; + } else + throw std::runtime_error( + "Provided element count does not match the stream's channel count."); + } + + /** + * Pull a sample from the inlet and read it into a custom C-style struct. + * + * Overall size checking but no type checking or conversion are done. + * Do not use for variable-size/string-formatted streams. + * @param sample The raw sample object to hold the data (packed C-style struct). + * Search for [`#``pragma pack`](https://stackoverflow.com/a/3318475/73299) for information + * on how to pack structs correctly. + * @param timeout The timeout for this operation, if any. Use 0.0 to make the function + * non-blocking. + * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was + * available. To remap this time stamp to the local clock, add the value returned by + * .time_correction() to it. + * @throws lost_error (if the stream source has been lost). + */ + template double pull_numeric_struct(T &sample, double timeout = FOREVER) { + return pull_numeric_raw((void *)&sample, sizeof(T), timeout); + } + + /** + * Pull a sample from the inlet and read it into a pointer to raw data. + * + * No type checking or conversions are done (not recommended!).
+ * Do not use for variable-size/string-formatted streams. + * @param sample A pointer to hold the resulting raw sample data. + * @param buffer_bytes The number of bytes allocated in the buffer.
+ * Note: it is the responsibility of the user to allocate enough memory. + * @param timeout The timeout for this operation, if any. Use 0.0 to make the function + * non-blocking. + * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was + * available. To remap this time stamp to the local clock, add the value returned by + * .time_correction() to it. + * @throws lost_error (if the stream source has been lost). + */ + double pull_numeric_raw(void *sample, int32_t buffer_bytes, double timeout = FOREVER) { + int32_t ec = 0; + double res = lsl_pull_sample_v(obj.get(), sample, buffer_bytes, timeout, &ec); + check_error(ec); + return res; + } + + + // ================================================= + // === Pulling a chunk of samples from the inlet === + // ================================================= + + /** + * Pull a chunk of samples from the inlet. + * + * This is the most complete version, returning both the data and a timestamp for each sample. + * @param chunk A vector of vectors to hold the samples. + * @param timestamps A vector to hold the time stamps. + * @return True if some data was obtained. + * @throws lost_error (if the stream source has been lost). + */ + template + bool pull_chunk(std::vector> &chunk, std::vector ×tamps) { + std::vector sample; + chunk.clear(); + timestamps.clear(); + while (double ts = pull_sample(sample, 0.0)) { + chunk.push_back(sample); + timestamps.push_back(ts); + } + return !chunk.empty(); + } + + /** + * Pull a chunk of samples from the inlet. + * + * This version returns only the most recent sample's time stamp. + * @param chunk A vector of vectors to hold the samples. + * @return The time when the most recent sample was captured + * on the remote machine, or 0.0 if no new sample was available. + * @throws lost_error (if the stream source has been lost) + */ + template double pull_chunk(std::vector> &chunk) { + double timestamp = 0.0; + std::vector sample; + chunk.clear(); + while (double ts = pull_sample(sample, 0.0)) { + chunk.push_back(sample); + timestamp = ts; + } + return timestamp; + } + + /** + * Pull a chunk of samples from the inlet. + * + * This function does not return time stamps for the samples. Invoked as: mychunk = + * pull_chunk(); + * @return A vector of vectors containing the obtained samples; may be empty. + * @throws lost_error (if the stream source has been lost) + */ + template std::vector> pull_chunk() { + std::vector> result; + std::vector sample; + while (pull_sample(sample, 0.0)) result.push_back(sample); + return result; + } + + /** + * Pull a chunk of data from the inlet into a pre-allocated buffer. + * + * This is a high-performance function that performs no memory allocations + * (useful for very high data rates or on low-powered devices). + * @warning The provided buffer size is measured in channel values (e.g., floats), not samples. + * @param data_buffer A pointer to a buffer of data values where the results shall be stored. + * @param timestamp_buffer A pointer to a buffer of timestamp values where time stamps shall be + * stored. If this is NULL, no time stamps will be returned. + * @param data_buffer_elements The size of the data buffer, in channel data elements (of type + * T). Must be a multiple of the stream's channel count. + * @param timestamp_buffer_elements The size of the timestamp buffer. If a timestamp buffer is + * provided then this must correspond to the same number of samples as data_buffer_elements. + * @param timeout The timeout for this operation, if any. When the timeout expires, the function + * may return before the entire buffer is filled. The default value of 0.0 will retrieve only + * data available for immediate pickup. + * @return data_elements_written Number of channel data elements written to the data buffer. + * @throws lost_error (if the stream source has been lost). + */ + std::size_t pull_chunk_multiplexed(float *data_buffer, double *timestamp_buffer, + std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements, + double timeout = 0.0) { + int32_t ec = 0; + std::size_t res = lsl_pull_chunk_f(obj.get(), data_buffer, timestamp_buffer, + (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout, + &ec); + check_error(ec); + return res; + } + std::size_t pull_chunk_multiplexed(double *data_buffer, double *timestamp_buffer, + std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements, + double timeout = 0.0) { + int32_t ec = 0; + std::size_t res = lsl_pull_chunk_d(obj.get(), data_buffer, timestamp_buffer, + (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout, + &ec); + check_error(ec); + return res; + } + std::size_t pull_chunk_multiplexed(int64_t *data_buffer, double *timestamp_buffer, + std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements, + double timeout = 0.0) { + int32_t ec = 0; + std::size_t res = lsl_pull_chunk_l(obj.get(), data_buffer, timestamp_buffer, + (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout, + &ec); + check_error(ec); + return res; + } + std::size_t pull_chunk_multiplexed(int32_t *data_buffer, double *timestamp_buffer, + std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements, + double timeout = 0.0) { + int32_t ec = 0; + std::size_t res = lsl_pull_chunk_i(obj.get(), data_buffer, timestamp_buffer, + (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout, + &ec); + check_error(ec); + return res; + } + std::size_t pull_chunk_multiplexed(int16_t *data_buffer, double *timestamp_buffer, + std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements, + double timeout = 0.0) { + int32_t ec = 0; + std::size_t res = lsl_pull_chunk_s(obj.get(), data_buffer, timestamp_buffer, + (unsigned long)data_buffer_elements, (unsigned long)timestamp_buffer_elements, timeout, + &ec); + check_error(ec); + return res; + } + std::size_t pull_chunk_multiplexed(char *data_buffer, double *timestamp_buffer, + std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements, + double timeout = 0.0) { + int32_t ec = 0; + std::size_t res = lsl_pull_chunk_c(obj.get(), data_buffer, timestamp_buffer, + static_cast(data_buffer_elements), static_cast(timestamp_buffer_elements), timeout, + &ec); + check_error(ec); + return res; + } + std::size_t pull_chunk_multiplexed(std::string *data_buffer, double *timestamp_buffer, + std::size_t data_buffer_elements, std::size_t timestamp_buffer_elements, + double timeout = 0.0) { + int32_t ec = 0; + if (data_buffer_elements) { + std::vector result_strings(data_buffer_elements); + std::vector result_lengths(data_buffer_elements); + std::size_t num = lsl_pull_chunk_buf(obj.get(), result_strings.data(), result_lengths.data(), + timestamp_buffer, static_cast(data_buffer_elements), + static_cast(timestamp_buffer_elements), timeout, &ec); + check_error(ec); + for (std::size_t k = 0; k < num; k++) { + data_buffer[k].assign(result_strings[k], result_lengths[k]); + lsl_destroy_string(result_strings[k]); + } + return num; + }; + return 0; + } + + /** + * Pull a multiplexed chunk of samples and optionally the sample timestamps from the inlet. + * + * @param chunk A vector to hold the multiplexed (Sample 1 Channel 1, + * S1C2, S2C1, S2C2, S3C1, S3C2, ...) samples + * @param timestamps A vector to hold the timestamps or nullptr + * @param timeout Time to wait for the first sample. The default value of 0.0 will not wait + * for data to arrive, pulling only samples already received. + * @param append (True:) Append data or (false:) clear them first + * @return True if some data was obtained. + * @throws lost_error (if the stream source has been lost). + */ + template + bool pull_chunk_multiplexed(std::vector &chunk, std::vector *timestamps = nullptr, + double timeout = 0.0, bool append = false) { + if (!append) { + chunk.clear(); + if (timestamps) timestamps->clear(); + } + std::vector sample; + double ts; + if ((ts = pull_sample(sample, timeout)) == 0.0) return false; + chunk.insert(chunk.end(), sample.begin(), sample.end()); + if (timestamps) timestamps->push_back(ts); + const auto target = samples_available(); + chunk.reserve(chunk.size() + target * this->channel_count); + if (timestamps) timestamps->reserve(timestamps->size() + target); + while ((ts = pull_sample(sample, 0.0)) != 0.0) { +#if LSL_CPP11 + chunk.insert(chunk.end(), std::make_move_iterator(sample.begin()), + std::make_move_iterator(sample.end())); +#else + chunk.insert(chunk.end(), sample.begin(), sample.end()); +#endif + if (timestamps) timestamps->push_back(ts); + } + return true; + } + + /** + * Pull a chunk of samples from the inlet. + * + * This is the most complete version, returning both the data and a timestamp for each sample. + * @param chunk A vector of C-style structs to hold the samples. + * @param timestamps A vector to hold the time stamps. + * @return True if some data was obtained. + * @throws lost_error (if the stream source has been lost) + */ + template + bool pull_chunk_numeric_structs(std::vector &chunk, std::vector ×tamps) { + T sample; + chunk.clear(); + timestamps.clear(); + while (double ts = pull_numeric_struct(sample, 0.0)) { + chunk.push_back(sample); + timestamps.push_back(ts); + } + return !chunk.empty(); + } + + /** + * Pull a chunk of samples from the inlet. + * + * This version returns only the most recent sample's time stamp. + * @param chunk A vector of C-style structs to hold the samples. + * @return The time when the most recent sample was captured + * on the remote machine, or 0.0 if no new sample was available. + * @throws lost_error (if the stream source has been lost) + */ + template double pull_chunk_numeric_structs(std::vector &chunk) { + double timestamp = 0.0; + T sample; + chunk.clear(); + while (double ts = pull_numeric_struct(sample, 0.0)) { + chunk.push_back(sample); + timestamp = ts; + } + return timestamp; + } + + /** + * Pull a chunk of samples from the inlet. + * + * This function does not return time stamps. Invoked as: mychunk = pull_chunk(); + * @return A vector of C-style structs containing the obtained samples; may be empty. + * @throws lost_error (if the stream source has been lost) + */ + template std::vector pull_chunk_numeric_structs() { + std::vector result; + T sample; + while (pull_numeric_struct(sample, 0.0)) result.push_back(sample); + return result; + } + + /** + * Query whether samples are currently available for immediate pickup. + * + * Note that it is not a good idea to use samples_available() to determine whether + * a pull_*() call would block: to be sure, set the pull timeout to 0.0 or an acceptably + * low value. If the underlying implementation supports it, the value will be the number of + * samples available (otherwise it will be 1 or 0). + */ + std::size_t samples_available() { return lsl_samples_available(obj.get()); } + + /// Drop all queued not-yet pulled samples, return the nr of dropped samples + uint32_t flush() noexcept { return lsl_inlet_flush(obj.get()); } + + /** + * Query whether the clock was potentially reset since the last call to was_clock_reset(). + * + * This is a rarely-used function that is only useful to applications that combine multiple + * time_correction values to estimate precise clock drift; it allows to tolerate cases where the + * source machine was hot-swapped or restarted in between two measurements. + */ + bool was_clock_reset() { return lsl_was_clock_reset(obj.get()) != 0; } + + /** + * Override the half-time (forget factor) of the time-stamp smoothing. + * + * The default is 90 seconds unless a different value is set in the config file. + * Using a longer window will yield lower jitter in the time stamps, but longer + * windows will have trouble tracking changes in the clock rate (usually due to + * temperature changes); the default is able to track changes up to 10 + * degrees C per minute sufficiently well. + */ + void smoothing_halftime(float value) { check_error(lsl_smoothing_halftime(obj.get(), value)); } + + int get_channel_count() const { return channel_count; } + +private: + // The inlet is a non-copyable object. + stream_inlet(const stream_inlet &rhs); + stream_inlet &operator=(const stream_inlet &rhs); + + int32_t channel_count; + std::shared_ptr obj; +}; + + +// ===================== +// ==== XML Element ==== +// ===================== + +/** + * A lightweight XML element tree; models the .desc() field of stream_info. + * + * Has a name and can have multiple named children or have text content as value; attributes are + * omitted. Insider note: The interface is modeled after a subset of pugixml's node type and is + * compatible with it. See also + * http://pugixml.googlecode.com/svn/tags/latest/docs/manual/access.html for additional + * documentation. + */ +class xml_element { +public: + /// Constructor. + xml_element(lsl_xml_ptr obj = 0) : obj(obj) {} + + + // === Tree Navigation === + + /// Get the first child of the element. + xml_element first_child() const { return lsl_first_child(obj); } + + /// Get the last child of the element. + xml_element last_child() const { return lsl_last_child(obj); } + + /// Get the next sibling in the children list of the parent node. + xml_element next_sibling() const { return lsl_next_sibling(obj); } + + /// Get the previous sibling in the children list of the parent node. + xml_element previous_sibling() const { return lsl_previous_sibling(obj); } + + /// Get the parent node. + xml_element parent() const { return lsl_parent(obj); } + + + // === Tree Navigation by Name === + + /// Get a child with a specified name. + xml_element child(const std::string &name) const { return lsl_child(obj, (name.c_str())); } + + /// Get the next sibling with the specified name. + xml_element next_sibling(const std::string &name) const { + return lsl_next_sibling_n(obj, (name.c_str())); + } + + /// Get the previous sibling with the specified name. + xml_element previous_sibling(const std::string &name) const { + return lsl_previous_sibling_n(obj, (name.c_str())); + } + + + // === Content Queries === + + /// Whether this node is empty. + bool empty() const { return lsl_empty(obj) != 0; } + + /// Is this a text body (instead of an XML element)? True both for plain char data and CData. + bool is_text() const { return lsl_is_text(obj) != 0; } + + /// Name of the element. + const char *name() const { return lsl_name(obj); } + + /// Value of the element. + const char *value() const { return lsl_value(obj); } + + /// Get child value (value of the first child that is text). + const char *child_value() const { return lsl_child_value(obj); } + + /// Get child value of a child with a specified name. + const char *child_value(const std::string &name) const { + return lsl_child_value_n(obj, (name.c_str())); + } + + + // === Modification === + + /// Append a child node with a given name, which has a (nameless) plain-text child with the + /// given text value. + xml_element append_child_value(const std::string &name, const std::string &value) { + return lsl_append_child_value(obj, (name.c_str()), (value.c_str())); + } + + /// Prepend a child node with a given name, which has a (nameless) plain-text child with the + /// given text value. + xml_element prepend_child_value(const std::string &name, const std::string &value) { + return lsl_prepend_child_value(obj, (name.c_str()), (value.c_str())); + } + + /// Set the text value of the (nameless) plain-text child of a named child node. + bool set_child_value(const std::string &name, const std::string &value) { + return lsl_set_child_value(obj, (name.c_str()), (value.c_str())) != 0; + } + + /** + * Set the element's name. + * @return False if the node is empty (or if out of memory). + */ + bool set_name(const std::string &rhs) { return lsl_set_name(obj, rhs.c_str()) != 0; } + + /** + * Set the element's value. + * @return False if the node is empty (or if out of memory). + */ + bool set_value(const std::string &rhs) { return lsl_set_value(obj, rhs.c_str()) != 0; } + + /// Append a child element with the specified name. + xml_element append_child(const std::string &name) { + return lsl_append_child(obj, name.c_str()); + } + + /// Prepend a child element with the specified name. + xml_element prepend_child(const std::string &name) { + return lsl_prepend_child(obj, (name.c_str())); + } + + /// Append a copy of the specified element as a child. + xml_element append_copy(const xml_element &e) { return lsl_append_copy(obj, e.obj); } + + /// Prepend a child element with the specified name. + xml_element prepend_copy(const xml_element &e) { return lsl_prepend_copy(obj, e.obj); } + + /// Remove a child element with the specified name. + void remove_child(const std::string &name) { lsl_remove_child_n(obj, (name.c_str())); } + + /// Remove a specified child element. + void remove_child(const xml_element &e) { lsl_remove_child(obj, e.obj); } + +private: + lsl_xml_ptr obj; +}; + +inline xml_element stream_info::desc() { return lsl_get_desc(obj.get()); } + + +// ============================= +// ==== Continuous Resolver ==== +// ============================= + +/** + * A convenience class that resolves streams continuously in the background throughout + * its lifetime and which can be queried at any time for the set of streams that are currently + * visible on the network. + */ +class continuous_resolver { +public: + /** + * Construct a new continuous_resolver that resolves all streams on the network. + * + * This is analogous to the functionality offered by the free function resolve_streams(). + * @param forget_after When a stream is no longer visible on the network (e.g., because it was + * shut down), this is the time in seconds after which it is no longer reported by the resolver. + */ + continuous_resolver(double forget_after = 5.0) + : obj(lsl_create_continuous_resolver(forget_after), &lsl_destroy_continuous_resolver) {} + + /** + * Construct a new continuous_resolver that resolves all streams with a specific value for a + * given property. + * + * This is analogous to the functionality provided by the free function resolve_stream(prop,value). + * @param prop The stream_info property that should have a specific value (e.g., "name", "type", + * "source_id", or "desc/manufaturer"). + * @param value The string value that the property should have (e.g., "EEG" as the type + * property). + * @param forget_after When a stream is no longer visible on the network (e.g., because it was + * shut down), this is the time in seconds after which it is no longer reported by the resolver. + */ + continuous_resolver( + const std::string &prop, const std::string &value, double forget_after = 5.0) + : obj(lsl_create_continuous_resolver_byprop((prop.c_str()), (value.c_str()), forget_after), + &lsl_destroy_continuous_resolver) {} + + /** + * Construct a new continuous_resolver that resolves all streams that match a given XPath 1.0 + * predicate. + * + * This is analogous to the functionality provided by the free function resolve_stream(pred). + * @param pred The predicate string, e.g. + * `name='BioSemi'` or + * `type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32` + * @param forget_after When a stream is no longer visible on the network (e.g., because it was + * shut down), this is the time in seconds after which it is no longer reported by the resolver. + */ + continuous_resolver(const std::string &pred, double forget_after = 5.0) + : obj(lsl_create_continuous_resolver_bypred((pred.c_str()), forget_after), &lsl_destroy_continuous_resolver) {} + + /** + * Obtain the set of currently present streams on the network (i.e. resolve result). + * @return A vector of matching stream info objects (excluding their meta-data), any of + * which can subsequently be used to open an inlet. + */ + std::vector results() { + lsl_streaminfo buffer[1024]; + return std::vector( + buffer, buffer + check_error(lsl_resolver_results(obj.get(), buffer, sizeof(buffer)))); + } + + /// Move constructor for stream_inlet + continuous_resolver(continuous_resolver &&rhs) noexcept = default; + continuous_resolver &operator=(continuous_resolver &&rhs) noexcept = default; + +private: + std::unique_ptr obj; +}; + + +// =============================== +// ==== Exception Definitions ==== +// =============================== + +/// Exception class that indicates that a stream inlet's source has been irrecoverably lost. +class lost_error : public std::runtime_error { +public: + explicit lost_error(const std::string &msg) : std::runtime_error(msg) {} +}; + + +/// Exception class that indicates that an operation failed due to a timeout. +class timeout_error : public std::runtime_error { +public: + explicit timeout_error(const std::string &msg) : std::runtime_error(msg) {} +}; + +/// Check error codes returned from the C interface and translate into appropriate exceptions. +inline int32_t check_error(int32_t ec) { + if (ec < 0) { + switch (ec) { + case lsl_timeout_error: throw timeout_error("The operation has timed out."); + case lsl_lost_error: + throw timeout_error( + "The stream has been lost; to continue reading, you need to re-resolve it."); + case lsl_argument_error: + throw std::invalid_argument("An argument was incorrectly specified."); + case lsl_internal_error: throw std::runtime_error("An internal error has occurred."); + default: throw std::runtime_error("An unknown error has occurred."); + } + } + return ec; +} + +} // namespace lsl + +#endif // LSL_CPP_H diff --git a/Plugins/LSL/include/lsl_cpp.h.meta b/Plugins/LSL/include/lsl_cpp.h.meta new file mode 100644 index 0000000..3924e42 --- /dev/null +++ b/Plugins/LSL/include/lsl_cpp.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 1de9b24c7af7a6c4284f2bd3a3712ed1 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/linux.meta b/Plugins/LSL/linux.meta new file mode 100644 index 0000000..27d91b9 --- /dev/null +++ b/Plugins/LSL/linux.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ec5fe2a92675ab047a8a72d8d7b9df7e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/linux/liblsl.so b/Plugins/LSL/linux/liblsl.so new file mode 100644 index 0000000..62aa68b Binary files /dev/null and b/Plugins/LSL/linux/liblsl.so differ diff --git a/Plugins/LSL/linux/liblsl.so.1.15.2 b/Plugins/LSL/linux/liblsl.so.1.15.2 new file mode 100644 index 0000000..62aa68b Binary files /dev/null and b/Plugins/LSL/linux/liblsl.so.1.15.2 differ diff --git a/Plugins/LSL/linux/liblsl.so.1.15.2.meta b/Plugins/LSL/linux/liblsl.so.1.15.2.meta new file mode 100644 index 0000000..b66769b --- /dev/null +++ b/Plugins/LSL/linux/liblsl.so.1.15.2.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4a6186398b90a394cb5e26d60fd7150c +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/linux/liblsl.so.2 b/Plugins/LSL/linux/liblsl.so.2 new file mode 100644 index 0000000..62aa68b Binary files /dev/null and b/Plugins/LSL/linux/liblsl.so.2 differ diff --git a/Plugins/LSL/linux/liblsl.so.2.meta b/Plugins/LSL/linux/liblsl.so.2.meta new file mode 100644 index 0000000..14d0782 --- /dev/null +++ b/Plugins/LSL/linux/liblsl.so.2.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7e3a1296118fd8548a93eb6d83181a88 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/linux/liblsl.so.meta b/Plugins/LSL/linux/liblsl.so.meta new file mode 100644 index 0000000..8de59ff --- /dev/null +++ b/Plugins/LSL/linux/liblsl.so.meta @@ -0,0 +1,63 @@ +fileFormatVersion: 2 +guid: a83361f9e806b1e45b520ee093e8cc21 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 0 + Exclude Win64: 0 + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: Linux + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: x86 + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: x86_64 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/macOS.meta b/Plugins/LSL/macOS.meta new file mode 100644 index 0000000..4901eb7 --- /dev/null +++ b/Plugins/LSL/macOS.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8bf491d67b7ba8b4b9a6c0612c0b61d8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/macOS/liblsl.1.15.2.dylib b/Plugins/LSL/macOS/liblsl.1.15.2.dylib new file mode 100644 index 0000000..c46887c Binary files /dev/null and b/Plugins/LSL/macOS/liblsl.1.15.2.dylib differ diff --git a/Plugins/LSL/macOS/liblsl.1.15.2.dylib.meta b/Plugins/LSL/macOS/liblsl.1.15.2.dylib.meta new file mode 100644 index 0000000..36efba6 --- /dev/null +++ b/Plugins/LSL/macOS/liblsl.1.15.2.dylib.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 40e5b84d5b3826a4289a216db3c64108 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/macOS/liblsl.2.dylib b/Plugins/LSL/macOS/liblsl.2.dylib new file mode 100644 index 0000000..c46887c Binary files /dev/null and b/Plugins/LSL/macOS/liblsl.2.dylib differ diff --git a/Plugins/LSL/macOS/liblsl.2.dylib.meta b/Plugins/LSL/macOS/liblsl.2.dylib.meta new file mode 100644 index 0000000..3e62ff5 --- /dev/null +++ b/Plugins/LSL/macOS/liblsl.2.dylib.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: c48dfea47ee98044eb5972816c4dec7e +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/LSL/macOS/liblsl.dylib b/Plugins/LSL/macOS/liblsl.dylib new file mode 100644 index 0000000..c46887c Binary files /dev/null and b/Plugins/LSL/macOS/liblsl.dylib differ diff --git a/Plugins/LSL/macOS/liblsl.dylib.meta b/Plugins/LSL/macOS/liblsl.dylib.meta new file mode 100644 index 0000000..9387a1d --- /dev/null +++ b/Plugins/LSL/macOS/liblsl.dylib.meta @@ -0,0 +1,63 @@ +fileFormatVersion: 2 +guid: 741fe9cda1aa4f44c971e9b3734c00de +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 0 + Exclude Win: 1 + Exclude Win64: 1 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: OSX + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: x86_64 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/liblsl32.dll b/Plugins/liblsl32.dll deleted file mode 100644 index e9832a0..0000000 Binary files a/Plugins/liblsl32.dll and /dev/null differ diff --git a/Plugins/liblsl32.so b/Plugins/liblsl32.so deleted file mode 100644 index d7f28f3..0000000 Binary files a/Plugins/liblsl32.so and /dev/null differ diff --git a/Plugins/liblsl64.bundle b/Plugins/liblsl64.bundle deleted file mode 100644 index 15eb8a4..0000000 Binary files a/Plugins/liblsl64.bundle and /dev/null differ diff --git a/Plugins/liblsl64.dll b/Plugins/liblsl64.dll deleted file mode 100644 index fa27df9..0000000 Binary files a/Plugins/liblsl64.dll and /dev/null differ diff --git a/Plugins/liblsl64.so b/Plugins/liblsl64.so deleted file mode 100644 index bf25b01..0000000 Binary files a/Plugins/liblsl64.so and /dev/null differ diff --git a/Plugins/liblslAndroid.so b/Plugins/liblslAndroid.so deleted file mode 100644 index 3639038..0000000 Binary files a/Plugins/liblslAndroid.so and /dev/null differ diff --git a/README.md b/README.md index 318406f..7caff44 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,68 @@ -LSL4Unity is no longer in active development. The recommended way to use LSL in unity is to follow the [Unity instructions in the liblsl-Csharp project](https://github.com/labstreaminglayer/liblsl-Csharp/blob/master/README-Unity.md). However, LSL4Unity still has some very useful examples of how to use LSL in Unity effectively. - # LSL4Unity -A integration approach of the LabStreamingLayer Framework for Unity3D providing the following features. +LSL4Unity was originally created by @xfleckx several years ago. That version has been [archived](https://github.com/labstreaminglayer/LSL4Unity/releases/tag/archive). + +LSL4Unity is reborn as a [Unity Custom Package](https://docs.unity3d.com/Manual/CustomPackages.html). + +The package comprises: + +* [liblsl-Csharp](https://github.com/labstreaminglayer/liblsl-Csharp) as a [Unity Native plug-in](https://docs.unity3d.com/Manual/NativePlugins.html). + * Has LSL.cs and shared object files for various platforms. +* General assets to facilitate using liblsl in Unity. * Simple Editor Integration to lookup LSL streams. -* Provides a ready to use Marker stream implementation. -* Basic implementations and examples for LSL inlets and outlets. -* Build hooks to copy correct platform library to the build directory +* Samples to show basic functionality, including continuous inlets, outlets, and event outlets. + +## Adding to your project + +### Option 1 - From the Editor + +Open the Package Manager Window, click on the `+` dropdown, and [choose `Add package from git URL...`](https://docs.unity3d.com/Manual/upm-ui-giturl.html). Enter the followingURL: + +`https://github.com/labstreaminglayer/LSL4Unity.git` + +### Option 2 - Modify Project Package Manifest + +This option is preferred if this package will be a dependency of another package. + +Edit `/Packages/manifest.json` and [add the following to your dependencies section](https://docs.unity3d.com/2020.3/Documentation/Manual/upm-git.html): + +`"com.LSL.LSL4Unity": "https://github.com/labstreaminglayer/LSL4Unity.git"` + +### (Future) Option 3 - Using OpenUPM + +TODO - https://openupm.com/docs/ + +## Using LSL4Unity + +The easiest way is to use the Package Manager window, select the LSL4Unity package, and choose to Import one or more of the Samples. + +The samples appear in `Assets/labstreaminglayer for Unity/1.16.0/{sample name}`. Open the sample's scene. + +### Simple Inlet Scale Object + +This scene uses LSL.cs only, and not any of the Utilitis or helpers that come with LSL4Unity. Thus it demonstrates the minimum required steps to resolve, open, and pull data from an LSL Inlet in Unity. + +You will need a separate process running an LSL outlet with at least 3 float channels. In an active Python environment with [`pylsl`](https://github.com/labstreaminglayer/liblsl-Python) installed, run `python -m pylsl.examples.SendDataAdvanced`. + +The cylinder will update its scale according to the data coming in from the found stream. + +### Simple Physics Event Outlet + +This scene uses LSL.cs only, and shows the minimal amount of code to setup a Markers stream and send events. -See the [Project Wiki](https://github.com/xfleckx/LSL4Unity/wiki) to get more details and installation instructions. -Also, see the [Tips](https://github.com/xfleckx/LSL4Unity/wiki/Tips-for-using-LSL4Unity)! +A sphere oscillates back and forth. Whenever it enters or exits the collider of a nearby cube, an event is transmitted. -**LSL ships a C# wrapper for the LSL lib - why should I use an additional wrapper?** +Note that this sample is designed to send out physics events (collisions) and thus the events are timestamped when the collision is detected in code. -Good question - LSL4Unity tries to provide an enhanced user experience within Unity. -It is intented to solve several issues, -* instable framerates results in irregular sampling intervalls -* plattform dependent compilation +If you wanted to instead timestamp stimulus events then it would be better to send out the Marker on `WaitForEndOfFrame`. There is an example of this in the Complex Sample scene. -when using an Game Engine - in this case Unity - as a data provider within your experiments. +### Complex Outlet Inlet Event -We also try to provide an easy start with predefined implementations which supports a integration into the EEGLAB, BCILAB and MoBILAB ecosystem. **Far from finished :X** - -# Compatibility info -Currently LSL ~~works only with x64 builds~~ might work x64 and x86 builds of Unity3D projects! -I got the whole thing running on both platforms under Windows. - -Linux and MacOS X Support seems to be working at least in the editor but more testing is necessary. -Contributions are welcome! Just try to build the example scene on your platform and report potential errors as issues! +A capsule continuously streams its pose over an outlet. Occassionally (every 2 seconds by default), the position is reset and new velocities are applied to the capsule. -# Dependencies -In the current Version, the Asset package ships a sligthly modified version of the C# LSL API and the plugin binaries. -The LabStreaming Layer is original created by SCCN und could be found at . +A cube has its pose set (+ a static offset) by the values coming in from an inlet, the very same stream that the capsule is sending out. -It's highly recommended to read the section about the [Time Synchronization](https://labstreaminglayer.readthedocs.io/info/time_synchronization.html) before building your own experiments! +Thus the cube should move the same as the capsule, except delayed by the capsule outlet -> cube inlet LSL transmission. +A plane changes its colours occassionally (every ~3.4 seconds). The colour change events also stream out a marker string of the new colour. +The marker is sent out using WaitForEndOfFrame, so its timestamp should be as close as possible to the actual colour change on-screen. diff --git a/README.md.meta b/README.md.meta index c74fce8..dee68a3 100644 --- a/README.md.meta +++ b/README.md.meta @@ -1,4 +1,7 @@ fileFormatVersion: 2 -guid: 6094b3ec094a0d44c8728785d4185122 -DefaultImporter: +guid: baaf897b0028fc34ba6291047482ee11 +TextScriptImporter: + externalObjects: {} userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime.meta b/Runtime.meta new file mode 100644 index 0000000..252844a --- /dev/null +++ b/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 063d0dbc7431b4242b85abbcf4820303 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/LSL.cs b/Runtime/LSL.cs new file mode 100644 index 0000000..910965b --- /dev/null +++ b/Runtime/LSL.cs @@ -0,0 +1,1203 @@ +using System; +using System.Runtime.InteropServices; + +namespace LSL +{ + /// + /// C# API for the lab streaming layer. + /// + /// The lab streaming layer provides a set of functions to make instrument data accessible + /// in real time within a lab network. From there, streams can be picked up by recording programs, + /// viewing programs or custom experiment applications that access data streams in real time. + /// + /// The API covers two areas: + /// - The "push API" allows to create stream outlets and to push data (regular or irregular measurement + /// time series, event data, coded audio/video frames, etc.) into them. + /// - The "pull API" allows to create stream inlets and read time-synched experiment data from them + /// (for recording, viewing or experiment control). + /// + /// + + public abstract class LSLObject : SafeHandle + { + public IntPtr obj { get => handle; } + public LSLObject(IntPtr obj) : base(IntPtr.Zero, true) + { +#if LSL_PRINT_OBJECT_LIFETIMES + System.Console.Out.WriteLine($"Created object {obj:X}"); +#endif + if (obj == IntPtr.Zero) throw new InternalException("Error creating object"); + this.SetHandle(obj); + } + + public override bool IsInvalid => handle == IntPtr.Zero; + + /// + /// To be implemented in inheriting classes: the liblsl function to destroy the internal object + /// + protected abstract void DestroyLSLObject(IntPtr obj); + + protected override bool ReleaseHandle() + { +#if LSL_PRINT_OBJECT_LIFETIMES + System.Console.Out.WriteLine($"Destroying object {handle:X}"); +#endif + DestroyLSLObject(handle); + return true; + } + } + + /// + /// Static functions implemented in liblsl + /// + public static class LSL + { + /// + /// Helper method to dispose a StreamInfo[] array + /// + /// Array to be disposed + public static void DisposeArray(this StreamInfo[] array) + { + foreach (var si in array) si.Dispose(); + } + + /// Constant to indicate that a stream has variable sampling rate. + public const double IRREGULAR_RATE = 0.0; + + /** + * Constant to indicate that a sample has the next successive time stamp. + * This is an optional optimization to transmit less data per sample. + * The stamp is then deduced from the preceding one according to the stream's sampling rate + * (in the case of an irregular rate, the same time stamp as before will is assumed). + */ + public const double DEDUCED_TIMESTAMP = -1.0; + + /** + A very large time duration (> 1 year) for timeout values. + Note that significantly larger numbers can cause the timeout to be invalid on some operating systems (e.g., 32-bit UNIX). + */ + public const double FOREVER = 32000000.0; + + /** + * Protocol version. + * The major version is protocol_version() / 100; + * The minor version is protocol_version() % 100; + * Clients with different minor versions are protocol-compatible with each other + * while clients with different major versions will refuse to work together. + */ + public static int protocol_version() { return dll.lsl_protocol_version(); } + + /** + * Version of the liblsl library. + * The major version is library_version() / 100; + * The minor version is library_version() % 100; + */ + public static int library_version() { return dll.lsl_library_version(); } + + /** + * Obtain a local system time stamp in seconds. The resolution is better than a millisecond. + * This reading can be used to assign time stamps to samples as they are being acquired. + * If the "age" of a sample is known at a particular time (e.g., from USB transmission + * delays), it can be used as an offset to local_clock() to obtain a better estimate of + * when a sample was actually captured. See stream_outlet::push_sample() for a use case. + */ + public static double local_clock() { return dll.lsl_local_clock(); } + + // ========================== + // === Stream Declaration === + // ========================== + + /** + * The stream_info object stores the declaration of a data stream. + * Represents the following information: + * a) stream data format (#channels, channel format) + * b) core information (stream name, content type, sampling rate) + * c) optional meta-data about the stream content (channel labels, measurement units, etc.) + * + * Whenever a program wants to provide a new stream on the lab network it will typically first + * create a stream_info to describe its properties and then construct a stream_outlet with it to create + * the stream on the network. Recipients who discover the outlet can query the stream_info; it is also + * written to disk when recording the stream (playing a similar role as a file header). + */ + + // =========================== + // ==== Resolve Functions ==== + // =========================== + + /** + * Resolve all streams on the network. + * This function returns all currently available streams from any outlet on the network. + * The network is usually the subnet specified at the local router, but may also include + * a multicast group of machines (given that the network supports it), or list of hostnames. + * These details may optionally be customized by the experimenter in a configuration file + * (see Network Connectivity in the LSL wiki). + * This is the default mechanism used by the browsing programs and the recording program. + * @param wait_time The waiting time for the operation, in seconds, to search for streams. + * Warning: If this is too short (less than 0.5s) only a subset (or none) of the + * outlets that are present on the network may be returned. + * @return An array of stream info objects (excluding their desc field), any of which can + * subsequently be used to open an inlet. The full info can be retrieve from the inlet. + */ + public static StreamInfo[] resolve_streams(double wait_time = 1.0) + { + IntPtr[] buf = new IntPtr[1024]; int num = dll.lsl_resolve_all(buf, (uint)buf.Length, wait_time); + StreamInfo[] res = new StreamInfo[num]; + for (int k = 0; k < num; k++) + res[k] = new StreamInfo(buf[k]); + return res; + } + + /** + * Resolve all streams with a specific value for a given property. + * If the goal is to resolve a specific stream, this method is preferred over resolving all streams and then selecting the desired one. + * @param prop The stream_info property that should have a specific value (e.g., "name", "type", "source_id", or "desc/manufaturer"). + * @param value The string value that the property should have (e.g., "EEG" as the type property). + * @param minimum Optionally return at least this number of streams. + * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout). + * If the timeout expires, less than the desired number of streams (possibly none) will be returned. + * @return An array of matching stream info objects (excluding their meta-data), any of + * which can subsequently be used to open an inlet. + */ + public static StreamInfo[] resolve_stream(string prop, string value, int minimum = 1, double timeout = LSL.FOREVER) + { + IntPtr[] buf = new IntPtr[1024]; int num = dll.lsl_resolve_byprop(buf, (uint)buf.Length, prop, value, minimum, timeout); + StreamInfo[] res = new StreamInfo[num]; + for (int k = 0; k < num; k++) + res[k] = new StreamInfo(buf[k]); + return res; + } + + /** + * Resolve all streams that match a given predicate. + * Advanced query that allows to impose more conditions on the retrieved streams; the given string is an XPath 1.0 + * predicate for the node (omitting the surrounding []'s), see also http://en.wikipedia.org/w/index.php?title=XPath_1.0&oldid=474981951. + * @param pred The predicate string, e.g. "name='BioSemi'" or "type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32" + * @param minimum Return at least this number of streams. + * @param timeout Optionally a timeout of the operation, in seconds (default: no timeout). + * If the timeout expires, less than the desired number of streams (possibly none) will be returned. + * @return An array of matching stream info objects (excluding their meta-data), any of + * which can subsequently be used to open an inlet. + */ + public static StreamInfo[] resolve_stream(string pred, int minimum = 1, double timeout = LSL.FOREVER) + { + IntPtr[] buf = new IntPtr[1024]; int num = dll.lsl_resolve_bypred(buf, (uint)buf.Length, pred, minimum, timeout); + StreamInfo[] res = new StreamInfo[num]; + for (int k = 0; k < num; k++) + res[k] = new StreamInfo(buf[k]); + return res; + } + + /// Check an error condition and throw an exception if appropriate. + public static void check_error(int ec) + { + if (ec < 0) + switch (ec) + { + case -1: throw new TimeoutException("The operation failed due to a timeout."); + case -2: throw new LostException("The stream has been lost."); + case -3: throw new ArgumentException("An argument was incorrectly specified (e.g., wrong format or wrong length)."); + case -4: throw new InternalException("An internal internal error has occurred."); + default: throw new Exception("An unknown error has occurred."); + } + } + } + + /// Data format of a channel (each transmitted sample holds an array of channels). + public enum channel_format_t : int + { + cf_float32 = 1, // For up to 24-bit precision measurements in the appropriate physical unit + // (e.g., microvolts). Integers from -16777216 to 16777216 are represented accurately. + cf_double64 = 2, // For universal numeric data as long as permitted by network & disk budget. + // The largest representable integer is 53-bit. + cf_string = 3, // For variable-length ASCII strings or data blobs, such as video frames, + // complex event descriptions, etc. + cf_int32 = 4, // For high-rate digitized formats that require 32-bit precision. Depends critically on + // meta-data to represent meaningful units. Useful for application event codes or other coded data. + cf_int16 = 5, // For very high rate signals (40Khz+) or consumer-grade audio + // (for professional audio float is recommended). + cf_int8 = 6, // For binary signals or other coded data. + // Not recommended for encoding string data. + cf_int64 = 7, // For now only for future compatibility. Support for this type is not yet exposed in all languages. + // Also, some builds of liblsl will not be able to send or receive data of this type. + cf_undefined = 0 // Can not be transmitted. + }; + + /** + * Post-processing options for stream inlets. + */ + public enum processing_options_t : int + { + proc_none = 0, // No automatic post-processing; return the ground-truth time stamps for manual + // post-processing. This is the default behavior of the inlet. + + proc_clocksync = 1, // Perform automatic clock synchronization; equivalent to manually adding + // the time_correction() value to the received time stamps. + + proc_dejitter = 2, // Remove jitter from time stamps. + // This will apply a smoothing algorithm to the received time stamps; + // the smoothing needs to see a minimum number of samples (30-120 seconds worst-case) + // until the remaining jitter is consistently below 1ms. + + proc_monotonize = 4, // Force the time-stamps to be monotonically ascending. + // Only makes sense if timestamps are dejittered. + + proc_threadsafe = 8, // Post-processing is thread-safe (same inlet can be read from by multiple threads); + // uses somewhat more CPU. + + proc_ALL = 1 | 2 | 4 | 8 // The combination of all possible post-processing options. + }; + + public class StreamInfo : LSLObject + { + /** + * Construct a new StreamInfo object. + * Core stream information is specified here. Any remaining meta-data can be added later. + * @param name Name of the stream. Describes the device (or product series) that this stream makes available + * (for use by programs, experimenters or data analysts). Cannot be empty. + * @param type Content type of the stream. Please see https://github.com/sccn/xdf/wiki/Meta-Data (or web search for: + * XDF meta-data) for pre-defined content-type names, but you can also make up your own. + * The content type is the preferred way to find streams (as opposed to searching by name). + * @param channel_count Number of channels per sample. This stays constant for the lifetime of the stream. + * @param nominal_srate The sampling rate (in Hz) as advertised by the data source, if regular (otherwise set to IRREGULAR_RATE). + * @param channel_format Format/type of each channel. If your channels have different formats, consider supplying + * multiple streams or use the largest type that can hold them all (such as cf_double64). + * @param source_id Unique identifier of the device or source of the data, if available (such as the serial number). + * This is critical for system robustness since it allows recipients to recover from failure even after the + * serving app, device or computer crashes (just by finding a stream with the same source id on the network again). + * Therefore, it is highly recommended to always try to provide whatever information can uniquely identify the data source itself. + */ + public StreamInfo(string name, string type, int channel_count = 1, double nominal_srate = LSL.IRREGULAR_RATE, channel_format_t channel_format = channel_format_t.cf_float32, string source_id = "") + : base(dll.lsl_create_streaminfo(name, type, channel_count, nominal_srate, channel_format, source_id)) { } + public StreamInfo(IntPtr handle) : base(handle) { } + + protected override void DestroyLSLObject(IntPtr obj) { dll.lsl_destroy_streaminfo(obj); } + + // ======================== + // === Core Information === + // ======================== + // (these fields are assigned at construction) + + /** + * Name of the stream. + * This is a human-readable name. For streams offered by device modules, it refers to the type of device or product series + * that is generating the data of the stream. If the source is an application, the name may be a more generic or specific identifier. + * Multiple streams with the same name can coexist, though potentially at the cost of ambiguity (for the recording app or experimenter). + */ + public string name() { return Marshal.PtrToStringAnsi(dll.lsl_get_name(obj)); } + + + /** + * Content type of the stream. + * The content type is a short string such as "EEG", "Gaze" which describes the content carried by the channel (if known). + * If a stream contains mixed content this value need not be assigned but may instead be stored in the description of channel types. + * To be useful to applications and automated processing systems using the recommended content types is preferred. + * Content types usually follow those pre-defined in https://github.com/sccn/xdf/wiki/Meta-Data (or web search for: XDF meta-data). + */ + public string type() { return Marshal.PtrToStringAnsi(dll.lsl_get_type(obj)); } + + /** + * Number of channels of the stream. + * A stream has at least one channel; the channel count stays constant for all samples. + */ + public int channel_count() { return dll.lsl_get_channel_count(obj); } + + /** + * Sampling rate of the stream, according to the source (in Hz). + * If a stream is irregularly sampled, this should be set to IRREGULAR_RATE. + * + * Note that no data will be lost even if this sampling rate is incorrect or if a device has temporary + * hiccups, since all samples will be recorded anyway (except for those dropped by the device itself). However, + * when the recording is imported into an application, a good importer may correct such errors more accurately + * if the advertised sampling rate was close to the specs of the device. + */ + public double nominal_srate() { return dll.lsl_get_nominal_srate(obj); } + + /** + * Channel format of the stream. + * All channels in a stream have the same format. However, a device might offer multiple time-synched streams + * each with its own format. + */ + public channel_format_t channel_format() { return dll.lsl_get_channel_format(obj); } + + /** + * Unique identifier of the stream's source, if available. + * The unique source (or device) identifier is an optional piece of information that, if available, allows that + * endpoints (such as the recording program) can re-acquire a stream automatically once it is back online. + */ + public string source_id() { return Marshal.PtrToStringAnsi(dll.lsl_get_source_id(obj)); } + + + // ====================================== + // === Additional Hosting Information === + // ====================================== + // (these fields are implicitly assigned once bound to an outlet/inlet) + + /** + * Protocol version used to deliver the stream. + */ + public int version() { return dll.lsl_get_version(obj); } + + /** + * Creation time stamp of the stream. + * This is the time stamp when the stream was first created + * (as determined via local_clock() on the providing machine). + */ + public double created_at() { return dll.lsl_get_created_at(obj); } + + /** + * Unique ID of the stream outlet instance (once assigned). + * This is a unique identifier of the stream outlet, and is guaranteed to be different + * across multiple instantiations of the same outlet (e.g., after a re-start). + */ + public string uid() { return Marshal.PtrToStringAnsi(dll.lsl_get_uid(obj)); } + + /** + * Session ID for the given stream. + * The session id is an optional human-assigned identifier of the recording session. + * While it is rarely used, it can be used to prevent concurrent recording activitites + * on the same sub-network (e.g., in multiple experiment areas) from seeing each other's streams + * (assigned via a configuration file by the experimenter, see Network Connectivity in the LSL wiki). + */ + public string session_id() { return Marshal.PtrToStringAnsi(dll.lsl_get_session_id(obj)); } + + /** + * Hostname of the providing machine. + */ + public string hostname() { return Marshal.PtrToStringAnsi(dll.lsl_get_hostname(obj)); } + + + // ======================== + // === Data Description === + // ======================== + + /** + * Extended description of the stream. + * It is highly recommended that at least the channel labels are described here. + * See code examples on the LSL wiki. Other information, such as amplifier settings, + * measurement units if deviating from defaults, setup information, subject information, etc., + * can be specified here, as well. Meta-data recommendations follow the XDF file format project + * (github.com/sccn/xdf/wiki/Meta-Data or web search for: XDF meta-data). + * + * Important: if you use a stream content type for which meta-data recommendations exist, please + * try to lay out your meta-data in agreement with these recommendations for compatibility with other applications. + */ + public XMLElement desc() { return new XMLElement(dll.lsl_get_desc(obj)); } + + /** + * Retrieve the entire stream_info in XML format. + * This yields an XML document (in string form) whose top-level element is . The info element contains + * one element for each field of the stream_info class, including: + * a) the core elements , , , , , + * b) the misc elements , , , , , , , , , + * c) the extended description element with user-defined sub-elements. + */ + public string as_xml() + { + IntPtr pXml = dll.lsl_get_xml(obj); + string strXml = Marshal.PtrToStringAnsi(pXml); + dll.lsl_destroy_string(pXml); + return strXml; + } + } + + + // ======================= + // ==== Stream Outlet ==== + // ======================= + + /** + * A stream outlet. + * Outlets are used to make streaming data (and the meta-data) available on the lab network. + */ + public class StreamOutlet : LSLObject + { + /** + * Establish a new stream outlet. This makes the stream discoverable. + * @param info The stream information to use for creating this stream. Stays constant over the lifetime of the outlet. + * @param chunk_size Optionally the desired chunk granularity (in samples) for transmission. If unspecified, + * each push operation yields one chunk. Inlets can override this setting. + * @param max_buffered Optionally the maximum amount of data to buffer (in seconds if there is a nominal + * sampling rate, otherwise x100 in samples). The default is 6 minutes of data. + */ + public StreamOutlet(StreamInfo info, int chunk_size = 0, int max_buffered = 360) + : base(dll.lsl_create_outlet(info.DangerousGetHandle(), chunk_size, max_buffered)) { } + + protected override void DestroyLSLObject(IntPtr obj) + { + dll.lsl_destroy_outlet(obj); + } + + // ======================================== + // === Pushing a sample into the outlet === + // ======================================== + + /** + * Push an array of values as a sample into the outlet. + * Each entry in the vector corresponds to one channel. + * @param data An array of values to push (one for each channel). + * @param timestamp Optionally the capture time of the sample, in agreement with local_clock(); if omitted, the current time is used. + * @param pushthrough Optionally whether to push the sample through to the receivers instead of buffering it with subsequent samples. + * Note that the chunk_size, if specified at outlet construction, takes precedence over the pushthrough flag. + */ + public void push_sample(float[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_ftp(obj, data, timestamp, pushthrough ? 1 : 0); } + public void push_sample(double[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_dtp(obj, data, timestamp, pushthrough ? 1 : 0); } + public void push_sample(int[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_itp(obj, data, timestamp, pushthrough ? 1 : 0); } + public void push_sample(short[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_stp(obj, data, timestamp, pushthrough ? 1 : 0); } + public void push_sample(char[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_ctp(obj, data, timestamp, pushthrough ? 1 : 0); } + public void push_sample(string[] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_sample_strtp(obj, data, timestamp, pushthrough ? 1 : 0); } + + + // =================================================== + // === Pushing an chunk of samples into the outlet === + // =================================================== + + /** + * Push a chunk of samples into the outlet. Single timestamp provided. + * @param data A rectangular array of values for multiple samples. + * @param timestamp Optionally the capture time of the most recent sample, in agreement with local_clock(); if omitted, the current time is used. + * The time stamps of other samples are automatically derived based on the sampling rate of the stream. + * @param pushthrough Optionally whether to push the chunk through to the receivers instead of buffering it with subsequent samples. + * Note that the chunk_size, if specified at outlet construction, takes precedence over the pushthrough flag. + */ + public void push_chunk(float[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_ftp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } + public void push_chunk(double[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_dtp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } + public void push_chunk(int[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_itp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } + public void push_chunk(short[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_stp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } + public void push_chunk(char[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_ctp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } + public void push_chunk(string[,] data, double timestamp = 0.0, bool pushthrough = true) { dll.lsl_push_chunk_strtp(obj, data, (uint)data.Length, timestamp, pushthrough ? 1 : 0); } + + /** + * Push a chunk of multiplexed samples into the outlet. One timestamp per sample is provided. + * @param data A rectangular array of values for multiple samples. + * @param timestamps An array of timestamp values holding time stamps for each sample in the data buffer. + * @param pushthrough Optionally whether to push the chunk through to the receivers instead of buffering it with subsequent samples. + * Note that the chunk_size, if specified at outlet construction, takes precedence over the pushthrough flag. + */ + public void push_chunk(float[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_ftnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } + public void push_chunk(double[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_dtnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } + public void push_chunk(int[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_itnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } + public void push_chunk(short[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_stnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } + public void push_chunk(char[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_ctnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } + public void push_chunk(string[,] data, double[] timestamps, bool pushthrough = true) { dll.lsl_push_chunk_strtnp(obj, data, (uint)data.Length, timestamps, pushthrough ? 1 : 0); } + + + // =============================== + // === Miscellaneous Functions === + // =============================== + + /** + * Check whether consumers are currently registered. + * While it does not hurt, there is technically no reason to push samples if there is no consumer. + */ + public bool have_consumers() { return dll.lsl_have_consumers(obj) > 0; } + + /** + * Wait until some consumer shows up (without wasting resources). + * @return True if the wait was successful, false if the timeout expired. + */ + public bool wait_for_consumers(double timeout = LSL.FOREVER) { return dll.lsl_wait_for_consumers(obj, timeout) > 0; } + + /** + * Retrieve the stream info provided by this outlet. + * This is what was used to create the stream (and also has the Additional Network Information fields assigned). + */ + public StreamInfo info() { return new StreamInfo(dll.lsl_get_info(obj)); } + } + + + // ====================== + // ==== Stream Inlet ==== + // ====================== + + /** + * A stream inlet. + * Inlets are used to receive streaming data (and meta-data) from the lab network. + */ + public class StreamInlet : LSLObject + { + /** + * Construct a new stream inlet from a resolved stream info. + * @param info A resolved stream info object (as coming from one of the resolver functions). + * Note: the stream_inlet may also be constructed with a fully-specified stream_info, + * if the desired channel format and count is already known up-front, but this is + * strongly discouraged and should only ever be done if there is no time to resolve the + * stream up-front (e.g., due to limitations in the client program). + * @param max_buflen Optionally the maximum amount of data to buffer (in seconds if there is a nominal + * sampling rate, otherwise x100 in samples). Recording applications want to use a fairly + * large buffer size here, while real-time applications would only buffer as much as + * they need to perform their next calculation. + * @param max_chunklen Optionally the maximum size, in samples, at which chunks are transmitted + * (the default corresponds to the chunk sizes used by the sender). + * Recording applications can use a generous size here (leaving it to the network how + * to pack things), while real-time applications may want a finer (perhaps 1-sample) granularity. + If left unspecified (=0), the sender determines the chunk granularity. + * @param recover Try to silently recover lost streams that are recoverable (=those that that have a source_id set). + * In all other cases (recover is false or the stream is not recoverable) functions may throw a + * LostException if the stream's source is lost (e.g., due to an app or computer crash). + */ + public StreamInlet(StreamInfo info, int max_buflen = 360, int max_chunklen = 0, bool recover = true, processing_options_t postproc_flags = processing_options_t.proc_none) + : base(dll.lsl_create_inlet(info.DangerousGetHandle(), max_buflen, max_chunklen, recover ? 1 : 0)) + { + dll.lsl_set_postprocessing(obj, postproc_flags); + } + + protected override void DestroyLSLObject(IntPtr obj) + { + dll.lsl_destroy_inlet(obj); + } + + /** + * Retrieve the complete information of the given stream, including the extended description. + * Can be invoked at any time of the stream's lifetime. + * @param timeout Timeout of the operation (default: no timeout). + * @throws TimeoutException (if the timeout expires), or LostException (if the stream source has been lost). + */ + public StreamInfo info(double timeout = LSL.FOREVER) { int ec = 0; IntPtr res = dll.lsl_get_fullinfo(obj, timeout, ref ec); LSL.check_error(ec); return new StreamInfo(res); } + + /** + * Subscribe to the data stream. + * All samples pushed in at the other end from this moment onwards will be queued and + * eventually be delivered in response to pull_sample() or pull_chunk() calls. + * Pulling a sample without some preceding open_stream is permitted (the stream will then be opened implicitly). + * @param timeout Optional timeout of the operation (default: no timeout). + * @throws TimeoutException (if the timeout expires), or LostException (if the stream source has been lost). + */ + public void open_stream(double timeout = LSL.FOREVER) { int ec = 0; dll.lsl_open_stream(obj, timeout, ref ec); LSL.check_error(ec); } + + /** + * Drop the current data stream. + * All samples that are still buffered or in flight will be dropped and transmission + * and buffering of data for this inlet will be stopped. If an application stops being + * interested in data from a source (temporarily or not) but keeps the outlet alive, + * it should call close_stream() to not waste unnecessary system and network + * resources. + */ + public void close_stream() { dll.lsl_close_stream(obj); } + + /** + * Retrieve an estimated time correction offset for the given stream. + * The first call to this function takes several miliseconds until a reliable first estimate is obtained. + * Subsequent calls are instantaneous (and rely on periodic background updates). + * The precision of these estimates should be below 1 ms (empirically within +/-0.2 ms). + * @timeout Timeout to acquire the first time-correction estimate (default: no timeout). + * @return The time correction estimate. This is the number that needs to be added to a time stamp + * that was remotely generated via lsl_local_clock() to map it into the local clock domain of this machine. + * @throws TimeoutException (if the timeout expires), or LostException (if the stream source has been lost). + */ + public double time_correction(double timeout = LSL.FOREVER) { int ec = 0; double res = dll.lsl_time_correction(obj, timeout, ref ec); LSL.check_error(ec); return res; } + + // ======================================= + // === Pulling a sample from the inlet === + // ======================================= + + /** + * Pull a sample from the inlet and read it into an array of values. + * Handles type checking & conversion. + * @param sample An array to hold the resulting values. + * @param timeout The timeout for this operation, if any. Use 0.0 to make the function non-blocking. + * @return The capture time of the sample on the remote machine, or 0.0 if no new sample was available. + * To remap this time stamp to the local clock, add the value returned by .time_correction() to it. + * @throws LostException (if the stream source has been lost). + */ + public double pull_sample(float[] sample, double timeout = LSL.FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_f(obj, sample, sample.Length, timeout, ref ec); LSL.check_error(ec); return res; } + public double pull_sample(double[] sample, double timeout = LSL.FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_d(obj, sample, sample.Length, timeout, ref ec); LSL.check_error(ec); return res; } + public double pull_sample(int[] sample, double timeout = LSL.FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_i(obj, sample, sample.Length, timeout, ref ec); LSL.check_error(ec); return res; } + public double pull_sample(short[] sample, double timeout = LSL.FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_s(obj, sample, sample.Length, timeout, ref ec); LSL.check_error(ec); return res; } + public double pull_sample(char[] sample, double timeout = LSL.FOREVER) { int ec = 0; double res = dll.lsl_pull_sample_c(obj, sample, sample.Length, timeout, ref ec); LSL.check_error(ec); return res; } + public double pull_sample(string[] sample, double timeout = LSL.FOREVER) + { + int ec = 0; + IntPtr[] tmp = new IntPtr[sample.Length]; + double res = dll.lsl_pull_sample_str(obj, tmp, tmp.Length, timeout, ref ec); LSL.check_error(ec); + try + { + for (int k = 0; k < tmp.Length; k++) + sample[k] = Marshal.PtrToStringAnsi(tmp[k]); + } + finally + { + for (int k = 0; k < tmp.Length; k++) + dll.lsl_destroy_string(tmp[k]); + } + return res; + } + + + // ================================================= + // === Pulling a chunk of samples from the inlet === + // ================================================= + + /** + * Pull a chunk of data from the inlet. + * @param data_buffer A pre-allocated buffer where the channel data shall be stored. + * @param timestamp_buffer A pre-allocated buffer where time stamps shall be stored. + * @param timeout Optionally the timeout for this operation, if any. When the timeout expires, the function + * may return before the entire buffer is filled. The default value of 0.0 will retrieve only + * data available for immediate pickup. + * @return samples_written Number of samples written to the data and timestamp buffers. + * @throws LostException (if the stream source has been lost). + */ + public int pull_chunk(float[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_f(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); LSL.check_error(ec); return (int)res / data_buffer.GetLength(1); } + public int pull_chunk(double[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_d(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); LSL.check_error(ec); return (int)res / data_buffer.GetLength(1); } + public int pull_chunk(int[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_i(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); LSL.check_error(ec); return (int)res / data_buffer.GetLength(1); } + public int pull_chunk(short[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_s(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); LSL.check_error(ec); return (int)res / data_buffer.GetLength(1); } + public int pull_chunk(char[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) { int ec = 0; uint res = dll.lsl_pull_chunk_c(obj, data_buffer, timestamp_buffer, (uint)data_buffer.Length, (uint)timestamp_buffer.Length, timeout, ref ec); LSL.check_error(ec); return (int)res / data_buffer.GetLength(1); } + public int pull_chunk(string[,] data_buffer, double[] timestamp_buffer, double timeout = 0.0) + { + int ec = 0; + IntPtr[,] tmp = new IntPtr[data_buffer.GetLength(0), data_buffer.GetLength(1)]; + uint res = dll.lsl_pull_chunk_str(obj, tmp, timestamp_buffer, (uint)tmp.Length, (uint)timestamp_buffer.Length, timeout, ref ec); + LSL.check_error(ec); + try + { + for (int s = 0; s < tmp.GetLength(0); s++) + for (int c = 0; c < tmp.GetLength(1); c++) + data_buffer[s, c] = Marshal.PtrToStringAnsi(tmp[s, c]); + } + finally + { + for (int s = 0; s < tmp.GetLength(0); s++) + for (int c = 0; c < tmp.GetLength(1); c++) + dll.lsl_destroy_string(tmp[s, c]); + } + return (int)res / data_buffer.GetLength(1); + } + + /** + * Query whether samples are currently available for immediate pickup. + * Note that it is not a good idea to use samples_available() to determine whether + * a pull_*() call would block: to be sure, set the pull timeout to 0.0 or an acceptably + * low value. If the underlying implementation supports it, the value will be the number of + * samples available (otherwise it will be 1 or 0). + */ + public int samples_available() { return (int)dll.lsl_samples_available(obj); } + + /** + * Query whether the clock was potentially reset since the last call to was_clock_reset(). + * This is a rarely-used function that is only useful to applications that combine multiple time_correction + * values to estimate precise clock drift; it allows to tolerate cases where the source machine was + * hot-swapped or restarted in between two measurements. + */ + public bool was_clock_reset() { return (int)dll.lsl_was_clock_reset(obj) != 0; } + } + + + // ===================== + // ==== XML Element ==== + // ===================== + + /** + * A lightweight XML element tree; models the .desc() field of stream_info. + * Has a name and can have multiple named children or have text content as value; attributes are omitted. + * Insider note: The interface is modeled after a subset of pugixml's node type and is compatible with it. + * See also http://pugixml.googlecode.com/svn/tags/latest/docs/manual/access.html for additional documentation. + */ + public struct XMLElement + { + public XMLElement(IntPtr handle) { obj = handle; } + + // === Tree Navigation === + + /// Get the first child of the element. + public XMLElement first_child() { return new XMLElement(dll.lsl_first_child(obj)); } + + /// Get the last child of the element. + public XMLElement last_child() { return new XMLElement(dll.lsl_last_child(obj)); } + + /// Get the next sibling in the children list of the parent node. + public XMLElement next_sibling() { return new XMLElement(dll.lsl_next_sibling(obj)); } + + /// Get the previous sibling in the children list of the parent node. + public XMLElement previous_sibling() { return new XMLElement(dll.lsl_previous_sibling(obj)); } + + /// Get the parent node. + public XMLElement parent() { return new XMLElement(dll.lsl_parent(obj)); } + + + // === Tree Navigation by Name === + + /// Get a child with a specified name. + public XMLElement child(string name) { return new XMLElement(dll.lsl_child(obj, name)); } + + /// Get the next sibling with the specified name. + public XMLElement next_sibling(string name) { return new XMLElement(dll.lsl_next_sibling_n(obj, name)); } + + /// Get the previous sibling with the specified name. + public XMLElement previous_sibling(string name) { return new XMLElement(dll.lsl_previous_sibling_n(obj, name)); } + + + // === Content Queries === + + /// Whether this node is empty. + public bool empty() { return dll.lsl_empty(obj) != 0; } + + /// Whether this is a text body (instead of an XML element). True both for plain char data and CData. + public bool is_text() { return dll.lsl_is_text(obj) != 0; } + + /// Name of the element. + public string name() { return Marshal.PtrToStringAnsi(dll.lsl_name(obj)); } + + /// Value of the element. + public string value() { return Marshal.PtrToStringAnsi(dll.lsl_value(obj)); } + + /// Get child value (value of the first child that is text). + public string child_value() { return Marshal.PtrToStringAnsi(dll.lsl_child_value(obj)); } + + /// Get child value of a child with a specified name. + public string child_value(string name) { return Marshal.PtrToStringAnsi(dll.lsl_child_value_n(obj, name)); } + + + // === Modification === + + /** + * Append a child node with a given name, which has a (nameless) plain-text child with the given text value. + */ + public XMLElement append_child_value(string name, string value) { return new XMLElement(dll.lsl_append_child_value(obj, name, value)); } + + /** + * Prepend a child node with a given name, which has a (nameless) plain-text child with the given text value. + */ + public XMLElement prepend_child_value(string name, string value) { return new XMLElement(dll.lsl_prepend_child_value(obj, name, value)); } + + /** + * Set the text value of the (nameless) plain-text child of a named child node. + */ + public bool set_child_value(string name, string value) { return dll.lsl_set_child_value(obj, name, value) != 0; } + + /** + * Set the element's name. + * @return False if the node is empty. + */ + public bool set_name(string rhs) { return dll.lsl_set_name(obj, rhs) != 0; } + + /** + * Set the element's value. + * @return False if the node is empty. + */ + public bool set_value(string rhs) { return dll.lsl_set_value(obj, rhs) != 0; } + + /// Append a child element with the specified name. + public XMLElement append_child(string name) { return new XMLElement(dll.lsl_append_child(obj, name)); } + + /// Prepend a child element with the specified name. + public XMLElement prepend_child(string name) { return new XMLElement(dll.lsl_prepend_child(obj, name)); } + + /// Append a copy of the specified element as a child. + public XMLElement append_copy(XMLElement e) { return new XMLElement(dll.lsl_append_copy(obj, e.obj)); } + + /// Prepend a child element with the specified name. + public XMLElement prepend_copy(XMLElement e) { return new XMLElement(dll.lsl_prepend_copy(obj, e.obj)); } + + /// Remove a child element with the specified name. + public void remove_child(string name) { dll.lsl_remove_child_n(obj, name); } + + /// Remove a specified child element. + public void remove_child(XMLElement e) { dll.lsl_remove_child(obj, e.obj); } + + readonly IntPtr obj; + } + + + // =========================== + // === Continuous Resolver === + // =========================== + + /** + * A convenience class that resolves streams continuously in the background throughout + * its lifetime and which can be queried at any time for the set of streams that are currently + * visible on the network. + */ + + public class ContinuousResolver : LSLObject + { + /** + * Construct a new continuous_resolver that resolves all streams on the network. + * This is analogous to the functionality offered by the free function resolve_streams(). + * @param forget_after When a stream is no longer visible on the network (e.g., because it was shut down), + * this is the time in seconds after which it is no longer reported by the resolver. + */ + public ContinuousResolver(double forget_after = 5.0) + : base(dll.lsl_create_continuous_resolver(forget_after)) { } + + /** + * Construct a new continuous_resolver that resolves all streams with a specific value for a given property. + * This is analogous to the functionality provided by the free function resolve_stream(prop,value). + * @param prop The stream_info property that should have a specific value (e.g., "name", "type", "source_id", or "desc/manufaturer"). + * @param value The string value that the property should have (e.g., "EEG" as the type property). + * @param forget_after When a stream is no longer visible on the network (e.g., because it was shut down), + * this is the time in seconds after which it is no longer reported by the resolver. + */ + public ContinuousResolver(string prop, string value, double forget_after = 5.0) + : base(dll.lsl_create_continuous_resolver_byprop(prop, value, forget_after)) { } + + /** + * Construct a new continuous_resolver that resolves all streams that match a given XPath 1.0 predicate. + * This is analogous to the functionality provided by the free function resolve_stream(pred). + * @param pred The predicate string, e.g. "name='BioSemi'" or "type='EEG' and starts-with(name,'BioSemi') and count(info/desc/channel)=32" + * @param forget_after When a stream is no longer visible on the network (e.g., because it was shut down), + * this is the time in seconds after which it is no longer reported by the resolver. + */ + public ContinuousResolver(string pred, double forget_after = 5.0) + : base(dll.lsl_create_continuous_resolver_bypred(pred, forget_after)) { } + + + /** + * Obtain the set of currently present streams on the network (i.e. resolve result). + * @return An array of matching stream info objects (excluding their meta-data), any of + * which can subsequently be used to open an inlet. + */ + public StreamInfo[] results() + { + IntPtr[] buf = new IntPtr[1024]; + int num = dll.lsl_resolver_results(obj, buf, (uint)buf.Length); + StreamInfo[] res = new StreamInfo[num]; + for (int k = 0; k < num; k++) + res[k] = new StreamInfo(buf[k]); + return res; + } + + protected override void DestroyLSLObject(IntPtr obj) + { + dll.lsl_destroy_continuous_resolver(obj); + } + } + + #region Exception Types + + /** + * Exception class that indicates that a stream inlet's source has been irrecoverably lost. + */ + public class LostException : System.Exception + { + public LostException(string message = "", System.Exception inner = null) { } + protected LostException(System.Runtime.Serialization.SerializationInfo info, + System.Runtime.Serialization.StreamingContext context) + { } + } + + /** + * Exception class that indicates that an internal error has occurred inside liblsl. + */ + public class InternalException : System.Exception + { + public InternalException(string message = "", System.Exception inner = null) { } + protected InternalException(System.Runtime.Serialization.SerializationInfo info, + System.Runtime.Serialization.StreamingContext context) + { } + } + #endregion + + + + #region Internal: C library function definitions + + class dll + { + // Name of the binary to include -- replace this if the native library has a differentname + const string libname = "lsl"; + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_protocol_version(); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_library_version(); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_local_clock(); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_create_streaminfo(string name, string type, int channel_count, double nominal_srate, channel_format_t channel_format, string source_id); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_destroy_streaminfo(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_name(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_type(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_get_channel_count(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_get_nominal_srate(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern channel_format_t lsl_get_channel_format(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_source_id(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_get_version(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_get_created_at(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_uid(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_session_id(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_hostname(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_desc(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_xml(IntPtr info); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_create_outlet(IntPtr info, int chunk_size, int max_buffered); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern void lsl_destroy_outlet(IntPtr obj); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_sample_ftp(IntPtr obj, float[] data, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_sample_dtp(IntPtr obj, double[] data, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_sample_itp(IntPtr obj, int[] data, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_sample_stp(IntPtr obj, short[] data, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_sample_ctp(IntPtr obj, char[] data, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_sample_strtp(IntPtr obj, string[] data, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_sample_buftp(IntPtr obj, char[][] data, uint[] lengths, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_ftp(IntPtr obj, float[,] data, uint data_elements, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_ftnp(IntPtr obj, float[,] data, uint data_elements, double[] timestamps, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_dtp(IntPtr obj, double[,] data, uint data_elements, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_dtnp(IntPtr obj, double[,] data, uint data_elements, double[] timestamps, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_itp(IntPtr obj, int[,] data, uint data_elements, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_itnp(IntPtr obj, int[,] data, uint data_elements, double[] timestamps, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_stp(IntPtr obj, short[,] data, uint data_elements, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_stnp(IntPtr obj, short[,] data, uint data_elements, double[] timestamps, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_ctp(IntPtr obj, char[,] data, uint data_elements, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_ctnp(IntPtr obj, char[,] data, uint data_elements, double[] timestamps, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_strtp(IntPtr obj, string[,] data, uint data_elements, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_strtnp(IntPtr obj, string[,] data, uint data_elements, double[] timestamps, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_buftp(IntPtr obj, char[][] data, uint[] lengths, uint data_elements, double timestamp, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_push_chunk_buftnp(IntPtr obj, char[][] data, uint[] lengths, uint data_elements, double[] timestamps, int pushthrough); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_have_consumers(IntPtr obj); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_wait_for_consumers(IntPtr obj, double timeout); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_info(IntPtr obj); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_resolve_all(IntPtr[] buffer, uint buffer_elements, double wait_time); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_resolve_byprop(IntPtr[] buffer, uint buffer_elements, string prop, string value, int minimum, double wait_time); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_resolve_bypred(IntPtr[] buffer, uint buffer_elements, string pred, int minimum, double wait_time); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_create_inlet(IntPtr info, int max_buflen, int max_chunklen, int recover); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern void lsl_destroy_inlet(IntPtr obj); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_get_fullinfo(IntPtr obj, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern void lsl_open_stream(IntPtr obj, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern void lsl_close_stream(IntPtr obj); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_time_correction(IntPtr obj, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_set_postprocessing(IntPtr obj, processing_options_t flags); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_pull_sample_f(IntPtr obj, float[] buffer, int buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_pull_sample_d(IntPtr obj, double[] buffer, int buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_pull_sample_i(IntPtr obj, int[] buffer, int buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_pull_sample_s(IntPtr obj, short[] buffer, int buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_pull_sample_c(IntPtr obj, char[] buffer, int buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_pull_sample_str(IntPtr obj, IntPtr[] buffer, int buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern double lsl_pull_sample_buf(IntPtr obj, char[][] buffer, uint[] buffer_lengths, int buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern void lsl_destroy_string(IntPtr str); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern uint lsl_pull_chunk_f(IntPtr obj, float[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern uint lsl_pull_chunk_d(IntPtr obj, double[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern uint lsl_pull_chunk_i(IntPtr obj, int[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern uint lsl_pull_chunk_s(IntPtr obj, short[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern uint lsl_pull_chunk_c(IntPtr obj, char[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern uint lsl_pull_chunk_str(IntPtr obj, IntPtr[,] data_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern uint lsl_pull_chunk_buf(IntPtr obj, char[][,] data_buffer, uint[,] lengths_buffer, double[] timestamp_buffer, uint data_buffer_elements, uint timestamp_buffer_elements, double timeout, ref int ec); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern uint lsl_samples_available(IntPtr obj); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern uint lsl_was_clock_reset(IntPtr obj); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_first_child(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_last_child(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_next_sibling(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_previous_sibling(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_parent(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_child(IntPtr e, string name); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_next_sibling_n(IntPtr e, string name); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_previous_sibling_n(IntPtr e, string name); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_empty(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_is_text(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_name(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_value(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_child_value(IntPtr e); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_child_value_n(IntPtr e, string name); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_append_child_value(IntPtr e, string name, string value); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_prepend_child_value(IntPtr e, string name, string value); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_set_child_value(IntPtr e, string name, string value); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_set_name(IntPtr e, string rhs); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_set_value(IntPtr e, string rhs); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_append_child(IntPtr e, string name); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_prepend_child(IntPtr e, string name); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_append_copy(IntPtr e, IntPtr e2); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_prepend_copy(IntPtr e, IntPtr e2); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern void lsl_remove_child_n(IntPtr e, string name); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern void lsl_remove_child(IntPtr e, IntPtr e2); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_create_continuous_resolver(double forget_after); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_create_continuous_resolver_byprop(string prop, string value, double forget_after); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern IntPtr lsl_create_continuous_resolver_bypred(string pred, double forget_after); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern int lsl_resolver_results(IntPtr obj, IntPtr[] buffer, uint buffer_elements); + + [DllImport(libname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)] + public static extern void lsl_destroy_continuous_resolver(IntPtr obj); + } + #endregion +} diff --git a/Demos/LSLTransformDemoOutlet.cs.meta b/Runtime/LSL.cs.meta similarity index 69% rename from Demos/LSLTransformDemoOutlet.cs.meta rename to Runtime/LSL.cs.meta index 079e20a..982d8a3 100644 --- a/Demos/LSLTransformDemoOutlet.cs.meta +++ b/Runtime/LSL.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 357857a4b3c756d4aa4c765f4b02f577 -timeCreated: 1470250104 -licenseType: Free +guid: 4c4a19b91c426324ca04220f97d0cafb MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Prefabs.meta b/Runtime/Prefabs.meta similarity index 57% rename from Prefabs.meta rename to Runtime/Prefabs.meta index a422197..8c23aa5 100644 --- a/Prefabs.meta +++ b/Runtime/Prefabs.meta @@ -1,9 +1,8 @@ fileFormatVersion: 2 -guid: 31a281ad43a12d844bfc5160e3b4e4ea +guid: c7c7651e0bea3c342ae71c3ae8bad962 folderAsset: yes -timeCreated: 1469088811 -licenseType: Free DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/Prefabs/LabStreamingLayer.prefab b/Runtime/Prefabs/LabStreamingLayer.prefab similarity index 100% rename from Prefabs/LabStreamingLayer.prefab rename to Runtime/Prefabs/LabStreamingLayer.prefab diff --git a/Prefabs/LabStreamingLayer.prefab.meta b/Runtime/Prefabs/LabStreamingLayer.prefab.meta similarity index 100% rename from Prefabs/LabStreamingLayer.prefab.meta rename to Runtime/Prefabs/LabStreamingLayer.prefab.meta diff --git a/Runtime/Scripts.meta b/Runtime/Scripts.meta new file mode 100644 index 0000000..7522728 --- /dev/null +++ b/Runtime/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 57a1041cf4fc37f4a9ef28e33087e191 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Scripts/BaseInlet.cs b/Runtime/Scripts/BaseInlet.cs new file mode 100644 index 0000000..b0c2db6 --- /dev/null +++ b/Runtime/Scripts/BaseInlet.cs @@ -0,0 +1,221 @@ +using LSL; +using System; +using System.Linq; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Events; + +namespace LSL4Unity.Utils +{ + public abstract class ABaseInlet : MonoBehaviour + { + public string StreamName; + + public string StreamType; + + // Set this to true to only pass the last sample in a chunk to Process. + public bool ProcessLastInChunkOnly = false; + + // Duration, in seconds, of buffer passed to pull_chunk. This must be > than average frame interval. + double maxChunkDuration = 0.2; + + // Hook in frame lifecycle in which to pull data. + public MomentForSampling moment; + + protected StreamInlet inlet; + public Resolver resolver; + protected double[] timestamp_buffer; + protected TData[,] data_buffer; + protected TData[] single_sample; + protected List ChannelNames = new List(); + public virtual int ChannelCount { get { return ChannelNames.Count; } } + + protected virtual void Start() + { + registerAndLookUpStream(); + } + + /// + /// Call this method when your inlet implementation got created at runtime + /// + protected virtual void registerAndLookUpStream() + { + resolver = FindObjectOfType(); + if (resolver == null) + { + resolver = gameObject.AddComponent(); + } + + // Check already-present streams. + if (resolver.knownStreams.Any(isTheExpected)) + { + var stream = resolver.knownStreams.First(isTheExpected); + AStreamIsFound(stream); + } + + // Register callbacks for new streams or lost streams. + resolver.OnStreamFound += AStreamIsFound; + resolver.OnStreamLost += AStreamGotLost; + } + + /// + /// Callback method for the Resolver gets called each time the resolver found a stream + /// + /// + public virtual void AStreamIsFound(StreamInfo stream_info) + { + if (!isTheExpected(stream_info)) + return; + + Debug.Log(string.Format("LSL Stream {0} found for {1}", stream_info.name(), name)); + + inlet = new StreamInlet(stream_info); + int buf_samples = (int)Mathf.Ceil((float)(inlet.info().nominal_srate() * maxChunkDuration)); + int nChannels = inlet.info().channel_count(); + + timestamp_buffer = new double[buf_samples]; + data_buffer = new TData[buf_samples, nChannels]; + single_sample = new TData[nChannels]; + + XMLElement channels = inlet.info().desc().child("channels"); + if (!channels.empty()) + { + + XMLElement chan = channels.first_child(); + while (!chan.empty()) + { + // Read chan + ChannelNames.Add(chan.child_value("label")); + chan = chan.next_sibling(); + } + } + // Pad with empty strings to make ChannelNames length == nChannels. + for (int chan_ix = ChannelNames.Count; chan_ix < nChannels; chan_ix++) + { + ChannelNames.Add("Chan" + chan_ix); + } + + OnStreamAvailable(); + } + + /// + /// Callback method for the Resolver gets called each time the resolver misses a stream within its cache + /// + /// + public virtual void AStreamGotLost(StreamInfo stream_info) + { + if (!isTheExpected(stream_info)) + return; + + Debug.Log(string.Format("LSL Stream {0} Lost for {1}", stream_info.name(), name)); + + OnStreamLost(); + } + + protected virtual bool isTheExpected(StreamInfo stream_info) + { + bool predicate = StreamName == "" || StreamName.Equals(stream_info.name()); + predicate &= StreamType == "" || StreamType.Equals(stream_info.type()); + + return predicate; + } + + // Must override for each data type because LSL can't handle Generics. + protected abstract void pullChunk(); + + protected abstract void Process(TData[] newSample, double timestamp); + + protected void ProcessChunk(int n_samples) + { + if (n_samples == 0) + return; + for (int sample_ix = ProcessLastInChunkOnly ? n_samples-1 : 0; sample_ix < n_samples; sample_ix++) + { + for (int chan_ix = 0; chan_ix < ChannelCount; chan_ix++) + { + single_sample[chan_ix] = data_buffer[sample_ix, chan_ix]; + } + Process(single_sample, timestamp_buffer[sample_ix]); + } + } + + protected virtual void OnStreamAvailable() + { + // base implementation may not decide what happens when the stream gets available + throw new NotImplementedException("Please override this method in a derived class!"); + } + + protected virtual void OnStreamLost() + { + // base implementation may not decide what happens when the stream gets lost + throw new NotImplementedException("Please override this method in a derived class!"); + } + + protected void FixedUpdate() + { + if (moment == MomentForSampling.FixedUpdate && inlet != null) + pullChunk(); + } + + protected void Update() + { + if (moment == MomentForSampling.Update && inlet != null) + pullChunk(); + } + + protected void LateUpdate() + { + if (moment == MomentForSampling.LateUpdate && inlet != null) + pullChunk(); + } + } + + public abstract class AFloatInlet : ABaseInlet + { + protected override void pullChunk() + { + ProcessChunk(inlet.pull_chunk(data_buffer, timestamp_buffer)); + } + } + + public abstract class ADoubleInlet : ABaseInlet + { + protected override void pullChunk() + { + ProcessChunk(inlet.pull_chunk(data_buffer, timestamp_buffer)); + } + } + + public abstract class AIntInlet : ABaseInlet + { + protected override void pullChunk() + { + ProcessChunk(inlet.pull_chunk(data_buffer, timestamp_buffer)); + } + } + + public abstract class ACharInlet : ABaseInlet + { + protected override void pullChunk() + { + ProcessChunk(inlet.pull_chunk(data_buffer, timestamp_buffer)); + } + } + + public abstract class InletAStringInlet : ABaseInlet + { + protected override void pullChunk() + { + ProcessChunk(inlet.pull_chunk(data_buffer, timestamp_buffer)); + } + } + + public abstract class AShortInlet : ABaseInlet + { + protected override void pullChunk() + { + ProcessChunk(inlet.pull_chunk(data_buffer, timestamp_buffer)); + } + } + +} diff --git a/Scripts/BaseInlet.cs.meta b/Runtime/Scripts/BaseInlet.cs.meta similarity index 100% rename from Scripts/BaseInlet.cs.meta rename to Runtime/Scripts/BaseInlet.cs.meta diff --git a/Runtime/Scripts/BaseOutlet.cs b/Runtime/Scripts/BaseOutlet.cs new file mode 100644 index 0000000..e001532 --- /dev/null +++ b/Runtime/Scripts/BaseOutlet.cs @@ -0,0 +1,176 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using LSL; + +namespace LSL4Unity.Utils +{ + public abstract class ABaseOutlet : MonoBehaviour + { + public string StreamName; + public string StreamType; + public MomentForSampling moment; + public bool IrregularRate = false; + + public abstract List ChannelNames { get; } + public virtual int ChannelCount { get { return ChannelNames.Count; } } + public abstract channel_format_t Format { get; } + + protected StreamOutlet outlet; + protected TData[] sample; + private TimeSync timeSync; + + // Add an XML element for each channel. The automatic version adds only channel labels. Override to add unit, location, etc. + protected virtual void FillChannelsHeader(XMLElement channels) + { + foreach (var chanName in ChannelNames) + { + XMLElement chan = channels.append_child("channel"); + chan.append_child_value("label", chanName); + } + } + + protected virtual void Start() + { + // TODO: Check StreamName, StreamType, and moment are not null. + + timeSync = gameObject.GetComponent(); + sample = new TData[ChannelCount]; + + var hash = new Hash128(); + hash.Append(StreamName); + hash.Append(StreamType); + hash.Append(moment.ToString()); + hash.Append(gameObject.GetInstanceID()); + ExtendHash(hash); + + double dataRate = IrregularRate ? LSL.LSL.IRREGULAR_RATE : LSLCommon.GetSamplingRateFor(moment); + StreamInfo streamInfo = new StreamInfo(StreamName, StreamType, ChannelCount, dataRate, Format, hash.ToString()); + + // Build XML header. See xdf wiki for recommendations: https://github.com/sccn/xdf/wiki/Meta-Data + XMLElement acq_el = streamInfo.desc().append_child("acquisition"); + acq_el.append_child_value("manufacturer", "LSL4Unity"); + XMLElement channels = streamInfo.desc().append_child("channels"); + FillChannelsHeader(channels); + + outlet = new StreamOutlet(streamInfo); + } + + // Override to extend hash + protected virtual void ExtendHash(Hash128 hash) { } + + protected abstract bool BuildSample(); + protected abstract void pushSample(double timestamp = 0); + + // Update is called once per frame + void FixedUpdate() + { + if (moment == MomentForSampling.FixedUpdate && outlet != null) + { + if (BuildSample()) + pushSample((timeSync != null) ? timeSync.FixedUpdateTimeStamp : 0.0); + } + } + + void Update() + { + if (outlet != null) + { + if (BuildSample()) + { + if (moment == MomentForSampling.Update) + { + pushSample((timeSync != null) ? timeSync.UpdateTimeStamp : 0.0); + } + else if (moment == MomentForSampling.EndOfFrame) + { + // Send as close to render-time as possible. Use this to log stimulus events. + StartCoroutine(PushAfterRendered()); + } + } + } + } + + void LateUpdate() + { + if (moment == MomentForSampling.LateUpdate && outlet != null) + { + if (BuildSample()) + pushSample((timeSync != null) ? timeSync.LateUpdateTimeStamp : 0.0); + } + } + + IEnumerator PushAfterRendered() + { + yield return new WaitForEndOfFrame(); + pushSample(); + yield return null; + } + } + + public abstract class AFloatOutlet : ABaseOutlet + { + public override channel_format_t Format { get { return channel_format_t.cf_float32; } } + protected override void pushSample(double timestamp = 0) + { + if (outlet == null) + return; + outlet.push_sample(sample, timestamp); + } + } + + public abstract class ADoubleOutlet : ABaseOutlet + { + public override channel_format_t Format { get { return channel_format_t.cf_double64; } } + protected override void pushSample(double timestamp = 0) + { + if (outlet == null) + return; + outlet.push_sample(sample, timestamp); + } + } + + public abstract class AIntOutlet : ABaseOutlet + { + public override channel_format_t Format { get { return channel_format_t.cf_int32; } } + protected override void pushSample(double timestamp = 0) + { + if (outlet == null) + return; + outlet.push_sample(sample, timestamp); + } + } + + public abstract class ACharOutlet : ABaseOutlet + { + public override channel_format_t Format { get { return channel_format_t.cf_int8; } } + protected override void pushSample(double timestamp = 0) + { + if (outlet == null) + return; + outlet.push_sample(sample, timestamp); + } + } + + public abstract class AStringOutlet : ABaseOutlet + { + public override channel_format_t Format { get { return channel_format_t.cf_string; } } + protected override void pushSample(double timestamp = 0) + { + if (outlet == null) + return; + outlet.push_sample(sample, timestamp); + } + } + + public abstract class AShortOutlet : ABaseOutlet + { + public override channel_format_t Format { get { return channel_format_t.cf_int16; } } + protected override void pushSample(double timestamp = 0) + { + if (outlet == null) + return; + outlet.push_sample(sample, timestamp); + } + } +} \ No newline at end of file diff --git a/Demos/RandomMarker.cs.meta b/Runtime/Scripts/BaseOutlet.cs.meta similarity index 69% rename from Demos/RandomMarker.cs.meta rename to Runtime/Scripts/BaseOutlet.cs.meta index 405b13a..2220547 100644 --- a/Demos/RandomMarker.cs.meta +++ b/Runtime/Scripts/BaseOutlet.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 04edb71db3ae93943b11404c7012e4e8 -timeCreated: 1471591971 -licenseType: Free +guid: 2672a379c04bb57429944a700c350f3e MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Scripts/LSLCommon.cs b/Runtime/Scripts/Common.cs similarity index 93% rename from Scripts/LSLCommon.cs rename to Runtime/Scripts/Common.cs index 044cf29..b0700da 100644 --- a/Scripts/LSLCommon.cs +++ b/Runtime/Scripts/Common.cs @@ -2,9 +2,11 @@ using System; using System.Collections; -namespace Assets.LSL4Unity.Scripts.Common +namespace LSL4Unity.Utils { - public static class LSLUtils + public enum MomentForSampling { Update, FixedUpdate, LateUpdate, EndOfFrame } + + public static class LSLCommon { private const int DEFAULT_PLATTFORM_SPECIFIC_FRAMERATE = -1; /// @@ -49,5 +51,4 @@ public struct ChannelDefinition public string unit; public string type; } - } diff --git a/Demos/CubeRotation.cs.meta b/Runtime/Scripts/Common.cs.meta similarity index 69% rename from Demos/CubeRotation.cs.meta rename to Runtime/Scripts/Common.cs.meta index 22ed545..f85781c 100644 --- a/Demos/CubeRotation.cs.meta +++ b/Runtime/Scripts/Common.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 89ccfd963e304fe4c89df7f836670980 -timeCreated: 1470245128 -licenseType: Free +guid: f525467d5cfd0cd49b85e249302526c0 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Runtime/Scripts/Resolver.cs b/Runtime/Scripts/Resolver.cs new file mode 100644 index 0000000..56ea691 --- /dev/null +++ b/Runtime/Scripts/Resolver.cs @@ -0,0 +1,103 @@ +/// +/// Copy-Pasted the base Resolver class from the LSL4Unity toolbox to correct +/// for a few bugs in the code. +/// +/// +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using System.Linq; +using LSL; + + +namespace LSL4Unity.Utils +{ + /// + /// Encapsulates the lookup logic for LSL streams with an event based appraoch + /// your custom stream inlet implementations could be subscribed to the OnStreamFound + /// + public class Resolver : MonoBehaviour + { + public List knownStreams = new List(); + // public List knownStreams = new List; + + public float forgetStreamAfter = 1.0f; + + private ContinuousResolver resolver; + + public delegate void StreamFound(StreamInfo streamInfo); // Declare callback signature when stream found. + public StreamFound OnStreamFound; // delegate instance to hold callbacks. + + public delegate void StreamLost(StreamInfo streamInfo); + public StreamLost OnStreamLost; + + public bool Resolve + { + get { return (OnStreamFound != null || OnStreamLost != null); } + set { } + } + + public void Start() + { + resolver = new ContinuousResolver(forgetStreamAfter); + StartCoroutine(resolveContinuously()); + } + + public bool IsStreamAvailable(out StreamInfo info, string streamName = "", string streamType = "", string hostName = "") + { + var result = knownStreams.Where(i => + + (streamName == "" || i.name().Equals(streamName)) && + (streamType == "" || i.type().Equals(streamType)) && + (hostName == "" || i.type().Equals(hostName)) + ); + + if (result.Any()) + { + info = result.First(); + return true; + } + else + { + info = null; + return false; + } + } + + private IEnumerator resolveContinuously() + { + // We don't bother checking the resolver unless we have any registered callbacks. + // This gives other objects time to setup and register before streams go into knownStreams! + while (Resolve) + { + var results = resolver.results(); + + foreach (var item in knownStreams) + { + if (!results.Any(r => r.name().Equals(item.name()))) + { + OnStreamLost?.Invoke(item); + } + } + + // remove lost streams from cache + knownStreams.RemoveAll(s => !results.Any(r => r.name().Equals(s.name()))); + + // add new found streams to the cache + foreach (var item in results) + { + if (!knownStreams.Any(s => s.name() == item.name() )) + { + Debug.Log(string.Format("Found new Stream {0}", item.name())); + // var newStreamInfo = new StreamInfoWrapper(item); + knownStreams.Add(item); // newStreamInfo); + OnStreamFound?.Invoke(item); // newStreamInfo); + } + } + + yield return new WaitForSecondsRealtime(0.1f); + } + yield return null; + } + } +} diff --git a/Scripts/Resolver.cs.meta b/Runtime/Scripts/Resolver.cs.meta similarity index 84% rename from Scripts/Resolver.cs.meta rename to Runtime/Scripts/Resolver.cs.meta index a5944ef..2970b72 100644 --- a/Scripts/Resolver.cs.meta +++ b/Runtime/Scripts/Resolver.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 guid: 4bc033cd2cffec7459d6fa31ad6a961b -timeCreated: 1482337355 -licenseType: Free MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Scripts/ScriptOrder.cs b/Runtime/Scripts/ScriptOrder.cs similarity index 85% rename from Scripts/ScriptOrder.cs rename to Runtime/Scripts/ScriptOrder.cs index bbf757a..8db445e 100644 --- a/Scripts/ScriptOrder.cs +++ b/Runtime/Scripts/ScriptOrder.cs @@ -2,11 +2,11 @@ using System; -namespace Assets.LSL4Unity +namespace LSL4Unity { /// /// This attribute is used to define specific script execution orders when necessary! - /// Example: LSLTimeSync -> should be called at the beginning of each frame before other scripts use it's properties. + /// Example: LSLTimeSync -> should be called at the beginning of each frame before other scripts use its properties. /// Original from Unity forum: https://forum.unity3d.com/threads/script-execution-order-manipulation.130805/ /// public class ScriptOrder : Attribute diff --git a/Scripts/ScriptOrder.cs.meta b/Runtime/Scripts/ScriptOrder.cs.meta similarity index 84% rename from Scripts/ScriptOrder.cs.meta rename to Runtime/Scripts/ScriptOrder.cs.meta index 6b9b6dc..df7c325 100644 --- a/Scripts/ScriptOrder.cs.meta +++ b/Runtime/Scripts/ScriptOrder.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 guid: 8e57d8143f1290c418f0aac8a1534531 -timeCreated: 1475325030 -licenseType: Free MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Runtime/Scripts/StreamInfo.cs b/Runtime/Scripts/StreamInfo.cs new file mode 100644 index 0000000..a52b6d3 --- /dev/null +++ b/Runtime/Scripts/StreamInfo.cs @@ -0,0 +1,106 @@ +using System; +using UnityEngine.Events; +using LSL; + + +namespace LSL4Unity.Utils +{ + [Serializable] + public class LSLStreamInfoWrapper + { + public string Name; + + public string Type; + + private StreamInfo item; + private readonly string streamUID; + + private readonly int channelCount; + private readonly string sessionId; + private readonly string sourceID; + private readonly double dataRate; + private readonly string hostName; + private readonly int streamVersion; + + public LSLStreamInfoWrapper(StreamInfo streamInfo) + { + this.item = streamInfo; + Name = item.name(); + Type = item.type(); + channelCount = item.channel_count(); + streamUID = item.uid(); + sessionId = item.session_id(); + sourceID = item.source_id(); + dataRate = item.nominal_srate(); + hostName = item.hostname(); + streamVersion = item.version(); + } + + public StreamInfo Item + { + get + { + return item; + } + } + + public string StreamUID + { + get + { + return streamUID; + } + } + + public int ChannelCount + { + get + { + return channelCount; + } + } + + public string SessionId + { + get + { + return sessionId; + } + } + + public string SourceID + { + get + { + return sourceID; + } + } + + public string HostName + { + get + { + return hostName; + } + } + + public double DataRate + { + get + { + return dataRate; + } + } + + public int StreamVersion + { + get + { + return streamVersion; + } + } + } + + [Serializable] + public class StreamEvent : UnityEvent { } +} diff --git a/Demos/StreamInfo.cs.meta b/Runtime/Scripts/StreamInfo.cs.meta similarity index 69% rename from Demos/StreamInfo.cs.meta rename to Runtime/Scripts/StreamInfo.cs.meta index ef145f0..8758939 100644 --- a/Demos/StreamInfo.cs.meta +++ b/Runtime/Scripts/StreamInfo.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: 1a5f5978f3c997a4e83f46f049b25b66 -timeCreated: 1470246118 -licenseType: Free +guid: 02e187b7f8685d349b45ee20019e1dc4 MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 diff --git a/Scripts/LSLTimeSync.cs b/Runtime/Scripts/TimeSync.cs similarity index 75% rename from Scripts/LSLTimeSync.cs rename to Runtime/Scripts/TimeSync.cs index b370268..755ec83 100644 --- a/Scripts/LSLTimeSync.cs +++ b/Runtime/Scripts/TimeSync.cs @@ -1,6 +1,7 @@ using UnityEngine; -namespace Assets.LSL4Unity.Scripts + +namespace LSL4Unity.Utils { /// /// This singleton should provide an dedicated timestamp for each update call or fixed update LSL sample! @@ -8,10 +9,10 @@ namespace Assets.LSL4Unity.Scripts /// Important! Make sure that the script is called before the default execution order! /// [ScriptOrder( -1000 )] - public class LSLTimeSync : MonoBehaviour + public class TimeSync : MonoBehaviour { - private static LSLTimeSync instance; - public static LSLTimeSync Instance + private static TimeSync instance; + public static TimeSync Instance { get { @@ -45,22 +46,22 @@ public double LateUpdateTimeStamp void Awake() { - LSLTimeSync.instance = this; + TimeSync.instance = this; } void FixedUpdate() { - fixedUpdateTimeStamp = LSL.liblsl.local_clock(); + fixedUpdateTimeStamp = LSL.LSL.local_clock(); } void Update() { - updateTimeStamp = LSL.liblsl.local_clock(); + updateTimeStamp = LSL.LSL.local_clock(); } void LateUpdate() { - lateUpdateTimeStamp = LSL.liblsl.local_clock(); + lateUpdateTimeStamp = LSL.LSL.local_clock(); } } } \ No newline at end of file diff --git a/Scripts/LSLTimeSync.cs.meta b/Runtime/Scripts/TimeSync.cs.meta similarity index 69% rename from Scripts/LSLTimeSync.cs.meta rename to Runtime/Scripts/TimeSync.cs.meta index 420d574..c2922e3 100644 --- a/Scripts/LSLTimeSync.cs.meta +++ b/Runtime/Scripts/TimeSync.cs.meta @@ -1,8 +1,7 @@ fileFormatVersion: 2 -guid: c8977e0332010724a8f646c07c062447 -timeCreated: 1475325093 -licenseType: Free +guid: 873d45d18db8f14409781ddee1823d2f MonoImporter: + externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: -1000 diff --git a/Runtime/labstreaminglayer.LSL4Unity.Runtime.asmdef b/Runtime/labstreaminglayer.LSL4Unity.Runtime.asmdef new file mode 100644 index 0000000..985875a --- /dev/null +++ b/Runtime/labstreaminglayer.LSL4Unity.Runtime.asmdef @@ -0,0 +1,14 @@ +{ + "name": "labstreaminglayer.LSL4Unity.Runtime", + "rootNamespace": "", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Runtime/labstreaminglayer.LSL4Unity.Runtime.asmdef.meta b/Runtime/labstreaminglayer.LSL4Unity.Runtime.asmdef.meta new file mode 100644 index 0000000..43b9fce --- /dev/null +++ b/Runtime/labstreaminglayer.LSL4Unity.Runtime.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: e280ff789d4407a47998ba70fab1034b +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/ComplexOutletInletEvent/ChangePlaneColour.cs b/Samples~/ComplexOutletInletEvent/ChangePlaneColour.cs new file mode 100644 index 0000000..1123bef --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/ChangePlaneColour.cs @@ -0,0 +1,54 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using LSL4Unity.Utils; + +namespace LSL4Unity.Samples.Complex +{ + public class ChangePlaneColour : AStringOutlet + { + public float ResetInterval = 3.4f; + private float elapsed_time = 0.0f; + private Material mat; + + public override List ChannelNames + { + get + { + List chanNames = new List{ "Event" }; + return chanNames; + } + } + + public void Reset() + { + StreamName = "Unity.MatColour"; + StreamType = "Markers"; + moment = MomentForSampling.EndOfFrame; + IrregularRate = true; + } + + protected override void Start() + { + base.Start(); + Renderer rend = GetComponent(); + mat = rend.material; + } + + // Update is called once per frame + protected override bool BuildSample() + { + // Called by Update because our moment is EndOfFrame. + elapsed_time += Time.deltaTime; + if (elapsed_time >= ResetInterval) + { + mat.color = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f)); + sample[0] = mat.color.ToString(); + + elapsed_time = 0.0f; + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/Samples~/ComplexOutletInletEvent/ChangePlaneColour.cs.meta b/Samples~/ComplexOutletInletEvent/ChangePlaneColour.cs.meta new file mode 100644 index 0000000..c9b7736 --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/ChangePlaneColour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0ee235854d9e2dc4989aaaf553020e36 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/ComplexOutletInletEvent/PlaneColour.mat b/Samples~/ComplexOutletInletEvent/PlaneColour.mat new file mode 100644 index 0000000..56c6ac6 --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/PlaneColour.mat @@ -0,0 +1,78 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: PlaneColour + m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _BumpMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailAlbedoMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailMask: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailNormalMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _EmissionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MetallicGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _OcclusionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _ParallaxMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _GlossMapScale: 1 + - _Glossiness: 0.5 + - _GlossyReflections: 1 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 1, g: 0, b: 0, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} + m_BuildTextureStacks: [] diff --git a/Samples~/ComplexOutletInletEvent/PlaneColour.mat.meta b/Samples~/ComplexOutletInletEvent/PlaneColour.mat.meta new file mode 100644 index 0000000..fbfe708 --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/PlaneColour.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f32786651daeee14e8d1298fb1691523 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/ComplexOutletInletEvent/PoseInlet.cs b/Samples~/ComplexOutletInletEvent/PoseInlet.cs new file mode 100644 index 0000000..58ffd00 --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/PoseInlet.cs @@ -0,0 +1,43 @@ +using UnityEngine; +using LSL4Unity.Utils; + +namespace LSL4Unity.Samples.Complex +{ + public class PoseInlet : AFloatInlet + { + public Vector3 Offset = new Vector3(1.0f, 1.0f, 0.0f); + private PoseFormat _transformFormat = PoseFormat.PosQuat7D; + public PoseFormat TransformFormat { get { return _transformFormat; } } + + void Reset() + { + StreamName = "Unity.Pose"; + } + + protected override void OnStreamAvailable() + { + if (ChannelCount == 7) + _transformFormat = PoseFormat.PosQuat7D; + else if (ChannelCount == 6) + _transformFormat = PoseFormat.PosEul6D; + else if (ChannelCount == 12) + _transformFormat = PoseFormat.Transform12D; + } + + protected override void Process(float[] newSample, double timestamp) + { + if (TransformFormat == PoseFormat.Transform12D) + { + gameObject.transform.position = new Vector3(newSample[3], newSample[7], newSample[11]); + // TODO: Update the matrix instead. + } + else + { + gameObject.transform.position = new Vector3(newSample[0], newSample[1], newSample[2]); + if (TransformFormat == PoseFormat.PosQuat7D) + gameObject.transform.rotation = new Quaternion(newSample[3], newSample[4], newSample[5], newSample[6]); + } + gameObject.transform.position += Offset; + } + } +} \ No newline at end of file diff --git a/Samples~/ComplexOutletInletEvent/PoseInlet.cs.meta b/Samples~/ComplexOutletInletEvent/PoseInlet.cs.meta new file mode 100644 index 0000000..7eaf1e3 --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/PoseInlet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b255e671a1902f742b43c8fc878b6152 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/ComplexOutletInletEvent/PoseOutlet.cs b/Samples~/ComplexOutletInletEvent/PoseOutlet.cs new file mode 100644 index 0000000..f4a3ccf --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/PoseOutlet.cs @@ -0,0 +1,98 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using LSL; +using LSL4Unity.Utils; + +namespace LSL4Unity.Samples.Complex +{ + public enum PoseFormat { PosEul6D, PosQuat7D, Transform12D } + + public class PoseOutlet : AFloatOutlet + { + public PoseFormat transformFormat = PoseFormat.PosQuat7D; + + public void Reset() + { + StreamName = "Unity.Pose"; + StreamType = "Unity.Transform"; + moment = MomentForSampling.FixedUpdate; + } + + public override List ChannelNames + { + get + { + List chanNames = new List(); + if ((transformFormat == PoseFormat.PosEul6D) || (transformFormat == PoseFormat.PosQuat7D)) + { + chanNames.AddRange(new string[] { "PosX", "PosY", "PosZ" }); + + if (transformFormat == PoseFormat.PosEul6D) + { + chanNames.AddRange(new string[] { "Pitch", "Yaw", "Roll" }); + } + else + { + chanNames.AddRange(new string[] { "RotX", "RotY", "RotZ", "RotW" }); + } + } + else if (transformFormat == PoseFormat.Transform12D) + { + var pose = gameObject.transform.localToWorldMatrix; + for (int row_ix = 0; row_ix < 3; row_ix++) + { + for (int col_ix = 0; col_ix < 4; col_ix++) + { + chanNames.Add(string.Format("{0},{1}", row_ix, col_ix)); + } + } + } + return chanNames; + } + } + + protected override void ExtendHash(Hash128 hash) + { + hash.Append(transformFormat.ToString()); + } + + protected override bool BuildSample() + { + if ((transformFormat == PoseFormat.PosEul6D) || (transformFormat == PoseFormat.PosQuat7D)) { + var position = gameObject.transform.position; + sample[0] = position.x; + sample[1] = position.y; + sample[2] = position.z; + + if (transformFormat == PoseFormat.PosEul6D) + { + var rotation = gameObject.transform.eulerAngles; + sample[3] = rotation.x; + sample[4] = rotation.y; + sample[5] = rotation.z; + } + else + { + var rotation = gameObject.transform.rotation; + sample[3] = rotation.x; + sample[4] = rotation.y; + sample[5] = rotation.z; + sample[6] = rotation.w; + } + } + else if (transformFormat == PoseFormat.Transform12D) + { + var pose = gameObject.transform.localToWorldMatrix; + for (int row_ix = 0; row_ix < 3; row_ix++) + { + for (int col_ix = 0; col_ix < 4; col_ix++) + { + sample[col_ix + 4 * row_ix] = pose[row_ix, col_ix]; + } + } + } + return true; + } + } +} \ No newline at end of file diff --git a/Samples~/ComplexOutletInletEvent/PoseOutlet.cs.meta b/Samples~/ComplexOutletInletEvent/PoseOutlet.cs.meta new file mode 100644 index 0000000..3d1068f --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/PoseOutlet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6024fc8798a90dc4e863536785d04693 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/ComplexOutletInletEvent/RandomTransform.cs b/Samples~/ComplexOutletInletEvent/RandomTransform.cs new file mode 100644 index 0000000..ac46d47 --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/RandomTransform.cs @@ -0,0 +1,37 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace LSL4Unity.Samples.Complex +{ + public class RandomTransform : MonoBehaviour + { + public float ResetInterval = 2.0f; + private float elapsed_time = 0.0f; + public Rigidbody rb; + private Vector3 start_position; + + // Start is called before the first frame update + void Start() + { + rb = gameObject.AddComponent(); + rb.useGravity = false; + // rb.isKinematic = true; + Vector3 p = gameObject.transform.position; + start_position = new Vector3(p.x, p.y, p.z); + } + + // Update is called once per frame + void Update() + { + elapsed_time += Time.deltaTime; + if (elapsed_time >= ResetInterval) + { + gameObject.transform.position = start_position; + rb.velocity = new Vector3(Random.Range(-2.0f, 2.0f), Random.Range(-2.0f, 2.0f), Random.Range(-2.0f, 2.0f)); + rb.angularVelocity = new Vector3(Random.Range(-6.0f, 6.0f), Random.Range(-6.0f, 6.0f), Random.Range(-6.0f, 6.0f)); + elapsed_time = 0.0f; + } + } + } +} \ No newline at end of file diff --git a/Samples~/ComplexOutletInletEvent/RandomTransform.cs.meta b/Samples~/ComplexOutletInletEvent/RandomTransform.cs.meta new file mode 100644 index 0000000..7b9dfbb --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/RandomTransform.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 51c0279ef5303b948b7a0e6241550384 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/ComplexOutletInletEvent/UtilsTransformOutlet.unity b/Samples~/ComplexOutletInletEvent/UtilsTransformOutlet.unity new file mode 100644 index 0000000..11c6caf --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/UtilsTransformOutlet.unity @@ -0,0 +1,671 @@ +%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: 705507994} + m_IndirectSpecularColor: {r: 0.44657898, g: 0.4964133, b: 0.5748178, 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: 0 + 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: 0} + m_LightingSettings: {fileID: 0} +--- !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!1 &705507993 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 705507995} + - component: {fileID: 705507994} + 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 &705507994 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 705507993} + m_Enabled: 1 + serializedVersion: 10 + m_Type: 1 + m_Shape: 0 + m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_InnerSpotAngle: 21.80208 + 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_CullingMatrixOverride: + e00: 1 + e01: 0 + e02: 0 + e03: 0 + e10: 0 + e11: 1 + e12: 0 + e13: 0 + e20: 0 + e21: 0 + e22: 1 + e23: 0 + e30: 0 + e31: 0 + e32: 0 + e33: 1 + m_UseCullingMatrixOverride: 0 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingLayerMask: 1 + m_Lightmapping: 1 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0} + m_UseBoundingSphereOverride: 0 + m_UseViewFrustumForShadowCasterCull: 1 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &705507995 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 705507993} + 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 &900133042 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 900133046} + - component: {fileID: 900133045} + - component: {fileID: 900133044} + - component: {fileID: 900133043} + - component: {fileID: 900133047} + m_Layer: 0 + m_Name: Plane + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!64 &900133043 +MeshCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 900133042} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + serializedVersion: 4 + m_Convex: 0 + m_CookingOptions: 30 + m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} +--- !u!23 &900133044 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 900133042} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + 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: f32786651daeee14e8d1298fb1691523, 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!33 &900133045 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 900133042} + m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &900133046 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 900133042} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: -5, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &900133047 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 900133042} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 0ee235854d9e2dc4989aaaf553020e36, type: 3} + m_Name: + m_EditorClassIdentifier: + StreamName: Unity.MatColour + StreamType: Markers + moment: 3 + IrregularRate: 1 + ResetInterval: 3.4 +--- !u!1 &963194225 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 963194228} + - component: {fileID: 963194227} + - component: {fileID: 963194226} + 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 &963194226 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 963194225} + m_Enabled: 1 +--- !u!20 &963194227 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 963194225} + 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_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: -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 &963194228 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 963194225} + 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} +--- !u!1 &977530796 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 977530801} + - component: {fileID: 977530800} + - component: {fileID: 977530799} + - component: {fileID: 977530798} + - component: {fileID: 977530797} + m_Layer: 0 + m_Name: Cube + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &977530797 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 977530796} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: b255e671a1902f742b43c8fc878b6152, type: 3} + m_Name: + m_EditorClassIdentifier: + StreamName: Unity.Pose + StreamType: + ProcessLastInChunkOnly: 1 + moment: 0 + resolver: {fileID: 0} + Offset: {x: 1, y: 1, z: 0} +--- !u!65 &977530798 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 977530796} + 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 &977530799 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 977530796} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + 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: 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!33 &977530800 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 977530796} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &977530801 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 977530796} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: -0.114909604, y: 0.5046388, z: -2.2564588} + 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 &1081904551 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1081904555} + - component: {fileID: 1081904554} + - component: {fileID: 1081904553} + - component: {fileID: 1081904552} + - component: {fileID: 1081904556} + - component: {fileID: 1081904558} + - component: {fileID: 1081904557} + m_Layer: 0 + m_Name: Capsule + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!136 &1081904552 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081904551} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0, y: 0, z: 0} +--- !u!23 &1081904553 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081904551} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + 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: 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!33 &1081904554 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081904551} + m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1081904555 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081904551} + 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 &1081904556 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081904551} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 6024fc8798a90dc4e863536785d04693, type: 3} + m_Name: + m_EditorClassIdentifier: + StreamName: Unity.Pose + StreamType: Unity.Transform + moment: 1 + IrregularRate: 0 + transformFormat: 1 +--- !u!114 &1081904557 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081904551} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 873d45d18db8f14409781ddee1823d2f, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!114 &1081904558 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1081904551} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 51c0279ef5303b948b7a0e6241550384, type: 3} + m_Name: + m_EditorClassIdentifier: + ResetInterval: 2 + rb: {fileID: 0} diff --git a/Samples~/ComplexOutletInletEvent/UtilsTransformOutlet.unity.meta b/Samples~/ComplexOutletInletEvent/UtilsTransformOutlet.unity.meta new file mode 100644 index 0000000..ba3f565 --- /dev/null +++ b/Samples~/ComplexOutletInletEvent/UtilsTransformOutlet.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 606b5cee8ce09654687c023a7d163a0b +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/SimpleInletScaleObject/DisplayFPS.cs b/Samples~/SimpleInletScaleObject/DisplayFPS.cs new file mode 100644 index 0000000..75472cb --- /dev/null +++ b/Samples~/SimpleInletScaleObject/DisplayFPS.cs @@ -0,0 +1,26 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; + +namespace LSL4Unity.Samples.SimpleInlet +{ + // You probably don't need this namespace. We do it to avoid contaminating the global namespace of your project. + public class DisplayFPS : MonoBehaviour + { + private Text m_Text; + + // Start is called before the first frame update + void Start() + { + m_Text = GetComponent(); + InvokeRepeating(nameof(GetFPS), 1, 1); + } + + void GetFPS() + { + float fps = (int)(1f / Time.unscaledDeltaTime); + m_Text.text = "FPS: " + fps; + } + } +} diff --git a/Samples~/SimpleInletScaleObject/DisplayFPS.cs.meta b/Samples~/SimpleInletScaleObject/DisplayFPS.cs.meta new file mode 100644 index 0000000..99be53b --- /dev/null +++ b/Samples~/SimpleInletScaleObject/DisplayFPS.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 45fa31e365edd4e4ab48f22aece16e64 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/SimpleInletScaleObject/ExpandingCylinderSimple.unity b/Samples~/SimpleInletScaleObject/ExpandingCylinderSimple.unity new file mode 100644 index 0000000..02acf67 --- /dev/null +++ b/Samples~/SimpleInletScaleObject/ExpandingCylinderSimple.unity @@ -0,0 +1,669 @@ +%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: 705507994} + m_IndirectSpecularColor: {r: 0.44657898, g: 0.4964133, b: 0.5748178, 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: 0 + 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: 0} + m_LightingSettings: {fileID: 0} +--- !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!1 &120617522 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 120617525} + - component: {fileID: 120617524} + - component: {fileID: 120617523} + m_Layer: 0 + m_Name: EventSystem + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &120617523 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 120617522} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 4f231c4fb786f3946a6b90b886c48677, type: 3} + m_Name: + m_EditorClassIdentifier: + m_HorizontalAxis: Horizontal + m_VerticalAxis: Vertical + m_SubmitButton: Submit + m_CancelButton: Cancel + m_InputActionsPerSecond: 10 + m_RepeatDelay: 0.5 + m_ForceModuleActive: 0 +--- !u!114 &120617524 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 120617522} + 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 &120617525 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 120617522} + 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: 4 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &220959412 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 220959413} + - component: {fileID: 220959415} + - component: {fileID: 220959414} + - component: {fileID: 220959416} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &220959413 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 220959412} + 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: 1993425945} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0.5, y: 0.5} + m_AnchorMax: {x: 0.5, y: 0.5} + m_AnchoredPosition: {x: -867, y: -351} + m_SizeDelta: {x: 160, y: 30} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &220959414 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 220959412} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 14 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 10 + m_MaxSize: 40 + m_Alignment: 0 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: 'FPS: ' +--- !u!222 &220959415 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 220959412} + m_CullTransparentMesh: 1 +--- !u!114 &220959416 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 220959412} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 45fa31e365edd4e4ab48f22aece16e64, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &705507993 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 705507995} + - component: {fileID: 705507994} + 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 &705507994 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 705507993} + m_Enabled: 1 + serializedVersion: 10 + m_Type: 1 + m_Shape: 0 + m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_InnerSpotAngle: 21.80208 + 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_CullingMatrixOverride: + e00: 1 + e01: 0 + e02: 0 + e03: 0 + e10: 0 + e11: 1 + e12: 0 + e13: 0 + e20: 0 + e21: 0 + e22: 1 + e23: 0 + e30: 0 + e31: 0 + e32: 0 + e33: 1 + m_UseCullingMatrixOverride: 0 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingLayerMask: 1 + m_Lightmapping: 1 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0} + m_UseBoundingSphereOverride: 0 + m_UseViewFrustumForShadowCasterCull: 1 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &705507995 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 705507993} + 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 &963194225 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 963194228} + - component: {fileID: 963194227} + - component: {fileID: 963194226} + 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 &963194226 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 963194225} + m_Enabled: 1 +--- !u!20 &963194227 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 963194225} + 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_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: -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 &963194228 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 963194225} + 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} +--- !u!1 &1993425941 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1993425945} + - component: {fileID: 1993425944} + - component: {fileID: 1993425943} + - component: {fileID: 1993425942} + m_Layer: 5 + m_Name: Canvas + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1993425942 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1993425941} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: dc42784cf147c0c48a680349fa168899, type: 3} + m_Name: + m_EditorClassIdentifier: + m_IgnoreReversedGraphics: 1 + m_BlockingObjects: 0 + m_BlockingMask: + serializedVersion: 2 + m_Bits: 4294967295 +--- !u!114 &1993425943 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1993425941} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 0cd44c1031e13a943bb63640046fad76, type: 3} + m_Name: + m_EditorClassIdentifier: + m_UiScaleMode: 0 + m_ReferencePixelsPerUnit: 100 + m_ScaleFactor: 1 + m_ReferenceResolution: {x: 800, y: 600} + m_ScreenMatchMode: 0 + m_MatchWidthOrHeight: 0 + m_PhysicalUnit: 3 + m_FallbackScreenDPI: 96 + m_DefaultSpriteDPI: 96 + m_DynamicPixelsPerUnit: 1 + m_PresetInfoIsWorld: 0 +--- !u!223 &1993425944 +Canvas: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1993425941} + m_Enabled: 1 + serializedVersion: 3 + m_RenderMode: 0 + m_Camera: {fileID: 0} + m_PlaneDistance: 100 + m_PixelPerfect: 0 + m_ReceivesEvents: 1 + m_OverrideSorting: 0 + m_OverridePixelPerfect: 0 + m_SortingBucketNormalizedSize: 0 + m_AdditionalShaderChannelsFlag: 0 + m_SortingLayerID: 0 + m_SortingOrder: 0 + m_TargetDisplay: 0 +--- !u!224 &1993425945 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1993425941} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 0, y: 0, z: 0} + m_Children: + - {fileID: 220959413} + m_Father: {fileID: 0} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0, y: 0} +--- !u!1 &2124754312 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2124754316} + - component: {fileID: 2124754315} + - component: {fileID: 2124754314} + - component: {fileID: 2124754313} + - component: {fileID: 2124754317} + m_Layer: 0 + m_Name: Cylinder + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!136 &2124754313 +CapsuleCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2124754312} + m_Material: {fileID: 0} + m_IsTrigger: 0 + m_Enabled: 1 + m_Radius: 0.5000001 + m_Height: 2 + m_Direction: 1 + m_Center: {x: 0.000000059604645, y: 0, z: -0.00000008940697} +--- !u!23 &2124754314 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2124754312} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + 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: 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!33 &2124754315 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2124754312} + m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &2124754316 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2124754312} + 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 &2124754317 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2124754312} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: a1fc6991df701014e992fe08bf552d93, type: 3} + m_Name: + m_EditorClassIdentifier: + StreamName: LSLExampleAmp diff --git a/Samples~/SimpleInletScaleObject/ExpandingCylinderSimple.unity.meta b/Samples~/SimpleInletScaleObject/ExpandingCylinderSimple.unity.meta new file mode 100644 index 0000000..2d64eb4 --- /dev/null +++ b/Samples~/SimpleInletScaleObject/ExpandingCylinderSimple.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 8aebd75e0361ad343a939bae7958e314 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/SimpleInletScaleObject/SimpleInletScaleObject.cs b/Samples~/SimpleInletScaleObject/SimpleInletScaleObject.cs new file mode 100644 index 0000000..8c27fa4 --- /dev/null +++ b/Samples~/SimpleInletScaleObject/SimpleInletScaleObject.cs @@ -0,0 +1,90 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using LSL; + +namespace LSL4Unity.Samples.SimpleInlet +{ + // You probably don't need this namespace. We do it to avoid contaminating the global namespace of your project. + public class SimpleInletScaleObject : MonoBehaviour + { + /* + * This example shows the minimal code required to get an LSL inlet running + * without leveraging any of the helper scripts that come with the LSL package. + * This behaviour uses LSL.cs only. There is little-to-no error checking. + * See Resolver.cs and BaseInlet.cs for helper behaviours to make your implementation + * simpler and more robust. + */ + + // We need to find the stream somehow. You must provide a StreamName in editor or before this object is Started. + public string StreamName; + ContinuousResolver resolver; + + double max_chunk_duration = 0.2; // Duration, in seconds, of buffer passed to pull_chunk. This must be > than average frame interval. + + // We need to keep track of the inlet once it is resolved. + private StreamInlet inlet; + + // We need buffers to pass to LSL when pulling data. + private float[,] data_buffer; // Note it's a 2D Array, not array of arrays. Each element has to be indexed specifically, no frames/columns. + private double[] timestamp_buffer; + + void Start() + { + if (!StreamName.Equals("")) + resolver = new ContinuousResolver("name", StreamName); + else + { + Debug.LogError("Object must specify a name for resolver to lookup a stream."); + this.enabled = false; + return; + } + StartCoroutine(ResolveExpectedStream()); + } + + IEnumerator ResolveExpectedStream() + { + + var results = resolver.results(); + while (results.Length == 0) + { + yield return new WaitForSeconds(.1f); + results = resolver.results(); + } + + inlet = new StreamInlet(results[0]); + + // Prepare pull_chunk buffer + int buf_samples = (int)Mathf.Ceil((float)(inlet.info().nominal_srate() * max_chunk_duration)); + // Debug.Log("Allocating buffers to receive " + buf_samples + " samples."); + int n_channels = inlet.info().channel_count(); + data_buffer = new float[buf_samples, n_channels]; + timestamp_buffer = new double[buf_samples]; + } + + // Update is called once per frame + void Update() + { + if (inlet != null) + { + int samples_returned = inlet.pull_chunk(data_buffer, timestamp_buffer); + // Debug.Log("Samples returned: " + samples_returned); + if (samples_returned > 0) + { + // There are many things you can do with the incoming chunk to make it more palatable for Unity. + // Note that if you are going to do significant processing and feature extraction on your signal, + // it makes much more sense to do that in an external process then have that process output its + // result to yet another stream that you capture in Unity. + // Most of the time we only care about the latest sample to get a visual representation of the latest + // state, so that's what we do here: take the last sample only and use it to udpate the object scale. + float x = data_buffer[samples_returned - 1, 0]; + float y = data_buffer[samples_returned - 1, 1]; + float z = data_buffer[samples_returned - 1, 2]; + var new_scale = new Vector3(x, y, z); + // Debug.Log("Setting cylinder scale to " + new_scale); + gameObject.transform.localScale = new_scale; + } + } + } + } +} \ No newline at end of file diff --git a/Samples~/SimpleInletScaleObject/SimpleInletScaleObject.cs.meta b/Samples~/SimpleInletScaleObject/SimpleInletScaleObject.cs.meta new file mode 100644 index 0000000..a380505 --- /dev/null +++ b/Samples~/SimpleInletScaleObject/SimpleInletScaleObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a1fc6991df701014e992fe08bf552d93 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/SimplePhysicsEventOutlet/OscillatingSphere.cs b/Samples~/SimplePhysicsEventOutlet/OscillatingSphere.cs new file mode 100644 index 0000000..5cbba29 --- /dev/null +++ b/Samples~/SimplePhysicsEventOutlet/OscillatingSphere.cs @@ -0,0 +1,14 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace LSL4Unity.Samples.SimplePhysicsEvent +{ + public class OscillatingSphere : MonoBehaviour + { + void Update() + { + gameObject.transform.position = new Vector3(Mathf.Sin(Time.time), 0, 0); + } + } +} \ No newline at end of file diff --git a/Samples~/SimplePhysicsEventOutlet/OscillatingSphere.cs.meta b/Samples~/SimplePhysicsEventOutlet/OscillatingSphere.cs.meta new file mode 100644 index 0000000..2fd4192 --- /dev/null +++ b/Samples~/SimplePhysicsEventOutlet/OscillatingSphere.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 32db551a17bc81142ba263ac3b4accc8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/SimplePhysicsEventOutlet/SimpleEventOutlet.unity b/Samples~/SimplePhysicsEventOutlet/SimpleEventOutlet.unity new file mode 100644 index 0000000..8ec58f8 --- /dev/null +++ b/Samples~/SimplePhysicsEventOutlet/SimpleEventOutlet.unity @@ -0,0 +1,534 @@ +%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.44657898, g: 0.4964133, b: 0.5748178, 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: 0 + 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: 512 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 1 + m_PVRDenoiserTypeIndirect: 1 + m_PVRDenoiserTypeAO: 1 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 1 + 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: 0} + m_LightingSettings: {fileID: 0} +--- !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!1 &181527231 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 181527236} + - component: {fileID: 181527235} + - component: {fileID: 181527234} + - component: {fileID: 181527233} + - component: {fileID: 181527232} + - component: {fileID: 181527237} + m_Layer: 0 + m_Name: Sphere + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &181527232 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 181527231} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 32db551a17bc81142ba263ac3b4accc8, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!135 &181527233 +SphereCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 181527231} + m_Material: {fileID: 0} + m_IsTrigger: 1 + m_Enabled: 1 + serializedVersion: 2 + m_Radius: 0.5 + m_Center: {x: 0, y: 0, z: 0} +--- !u!23 &181527234 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 181527231} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + 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: 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!33 &181527235 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 181527231} + m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &181527236 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 181527231} + 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!54 &181527237 +Rigidbody: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 181527231} + serializedVersion: 2 + m_Mass: 1 + m_Drag: 0 + m_AngularDrag: 0.05 + m_UseGravity: 0 + m_IsKinematic: 1 + m_Interpolate: 0 + m_Constraints: 0 + m_CollisionDetection: 0 +--- !u!1 &580728745 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 580728747} + - component: {fileID: 580728746} + 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 &580728746 +Light: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 580728745} + m_Enabled: 1 + serializedVersion: 10 + m_Type: 1 + m_Shape: 0 + m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} + m_Intensity: 1 + m_Range: 10 + m_SpotAngle: 30 + m_InnerSpotAngle: 21.80208 + 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_CullingMatrixOverride: + e00: 1 + e01: 0 + e02: 0 + e03: 0 + e10: 0 + e11: 1 + e12: 0 + e13: 0 + e20: 0 + e21: 0 + e22: 1 + e23: 0 + e30: 0 + e31: 0 + e32: 0 + e33: 1 + m_UseCullingMatrixOverride: 0 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingLayerMask: 1 + m_Lightmapping: 4 + m_LightShadowCasterMode: 0 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ColorTemperature: 6570 + m_UseColorTemperature: 0 + m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0} + m_UseBoundingSphereOverride: 0 + m_UseViewFrustumForShadowCasterCull: 1 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &580728747 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 580728745} + 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 &702756399 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 702756402} + - component: {fileID: 702756401} + - component: {fileID: 702756400} + 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 &702756400 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 702756399} + m_Enabled: 1 +--- !u!20 &702756401 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 702756399} + 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_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: -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 &702756402 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 702756399} + 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} +--- !u!1 &1025417351 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1025417355} + - component: {fileID: 1025417354} + - component: {fileID: 1025417353} + - component: {fileID: 1025417352} + - component: {fileID: 1025417356} + m_Layer: 0 + m_Name: Cube + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!65 &1025417352 +BoxCollider: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1025417351} + m_Material: {fileID: 0} + m_IsTrigger: 1 + m_Enabled: 1 + serializedVersion: 2 + m_Size: {x: 1, y: 1, z: 1} + m_Center: {x: 0, y: 0, z: 0} +--- !u!23 &1025417353 +MeshRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1025417351} + m_Enabled: 1 + m_CastShadows: 1 + m_ReceiveShadows: 1 + m_DynamicOccludee: 1 + 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: 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!33 &1025417354 +MeshFilter: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1025417351} + m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!4 &1025417355 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1025417351} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 1.8, 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!114 &1025417356 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1025417351} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 4147dd2d667c1824cbe4531fbba7302c, type: 3} + m_Name: + m_EditorClassIdentifier: diff --git a/Samples~/SimplePhysicsEventOutlet/SimpleEventOutlet.unity.meta b/Samples~/SimplePhysicsEventOutlet/SimpleEventOutlet.unity.meta new file mode 100644 index 0000000..a7b2fad --- /dev/null +++ b/Samples~/SimplePhysicsEventOutlet/SimpleEventOutlet.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 74dca66aeb40d5545a57643dba350a33 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/SimplePhysicsEventOutlet/SimpleOutletTriggerEvent.cs b/Samples~/SimplePhysicsEventOutlet/SimpleOutletTriggerEvent.cs new file mode 100644 index 0000000..2c53ef5 --- /dev/null +++ b/Samples~/SimplePhysicsEventOutlet/SimpleOutletTriggerEvent.cs @@ -0,0 +1,57 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using LSL; + +namespace LSL4Unity.Samples.SimplePhysicsEvent +{ + public class SimpleOutletTriggerEvent : MonoBehaviour + { + /* + * This is a simple example of an LSL Outlet to stream out irregular events occurring in Unity. + * This uses only LSL.cs and is intentionally simple. For a more robust version, see another sample. + * + * We stream out the trigger event during OnTriggerEnter which is, in our opinion, the closest + * time to when the trigger actually occurs (i.e., independent of its rendering). + * A simple way to print the events is with pylsl: `python -m pylsl.examples.ReceiveStringMarkers` + * + * If you are instead trying to log a stimulus event then there are better options. Please see the + * LSL4Unity SimpleStimulusEvent Sample for such a design. + */ + string StreamName = "LSL4Unity.Samples.SimpleCollisionEvent"; + string StreamType = "Markers"; + private StreamOutlet outlet; + private string[] sample = {""}; + + void Start() + { + var hash = new Hash128(); + hash.Append(StreamName); + hash.Append(StreamType); + hash.Append(gameObject.GetInstanceID()); + StreamInfo streamInfo = new StreamInfo(StreamName, StreamType, 1, LSL.LSL.IRREGULAR_RATE, + channel_format_t.cf_string, hash.ToString()); + outlet = new StreamOutlet(streamInfo); + } + + private void OnTriggerEnter(Collider other) + { + if (outlet != null) + { + sample[0] = "TriggerEnter " + gameObject.GetInstanceID(); + // Debug.Log(sample[0]); + outlet.push_sample(sample); + } + } + + private void OnTriggerExit(Collider other) + { + if (outlet != null) + { + sample[0] = "TriggerExit " + gameObject.GetInstanceID(); + // Debug.Log(sample[0]); + outlet.push_sample(sample); + } + } + } +} \ No newline at end of file diff --git a/Samples~/SimplePhysicsEventOutlet/SimpleOutletTriggerEvent.cs.meta b/Samples~/SimplePhysicsEventOutlet/SimpleOutletTriggerEvent.cs.meta new file mode 100644 index 0000000..c9cee85 --- /dev/null +++ b/Samples~/SimplePhysicsEventOutlet/SimpleOutletTriggerEvent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4147dd2d667c1824cbe4531fbba7302c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts.meta b/Scripts.meta deleted file mode 100644 index 9d89325..0000000 --- a/Scripts.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 74b45236cbe97874484d1d60f2915b56 -folderAsset: yes -DefaultImporter: - userData: diff --git a/Scripts/AInlet.cs b/Scripts/AInlet.cs deleted file mode 100644 index 0f335ab..0000000 --- a/Scripts/AInlet.cs +++ /dev/null @@ -1,718 +0,0 @@ -using UnityEngine; -using System.Collections; -using LSL; -using System; -using System.Linq; - -/// -/// DO NOT CHANGE CLASSES WITHIN THESE NAMESPACE -/// -/// These namespace provides basic implementations to quick start with simple stream inlets. -/// -/// These implementation supporting just the simplest use case. -/// Getting all samples available in at the moment of the update call (Update/FixedUpdate). -/// Samples won't get cached or queue. -/// -namespace Assets.LSL4Unity.Scripts.AbstractInlets -{ - public abstract class AFloatInlet : MonoBehaviour - { - public enum UpdateMoment { FixedUpdate, Update } - - public UpdateMoment moment; - - public string StreamName; - - public string StreamType; - - liblsl.StreamInfo[] results; - liblsl.StreamInlet inlet; - liblsl.ContinuousResolver resolver; - - private int expectedChannels = 0; - - float[] sample; - - void Start() - { - var expectedStreamHasAName = !StreamName.Equals(""); - var expectedStreamHasAType = !StreamType.Equals(""); - - if (!expectedStreamHasAName && !expectedStreamHasAType) - { - Debug.LogError("Inlet has to specify a name or a type before it is able to lookup a stream."); - this.enabled = false; - return; - } - - if (expectedStreamHasAName) - { - Debug.Log("Creating LSL resolver for stream " + StreamName); - - resolver = new liblsl.ContinuousResolver("name", StreamName); - } - else if (expectedStreamHasAType) - { - Debug.Log("Creating LSL resolver for stream with type " + StreamType); - resolver = new liblsl.ContinuousResolver("type ", StreamType); - } - - StartCoroutine(ResolveExpectedStream()); - - AdditionalStart(); - } - /// - /// Override this method in the subclass to specify what should happen during Start(). - /// - protected virtual void AdditionalStart() - { - //By default, do nothing. - } - - IEnumerator ResolveExpectedStream() - { - var results = resolver.results(); - - yield return new WaitUntil(() => results.Length > 0); - - Debug.Log(string.Format("Resolving Stream: {0}", StreamName)); - - inlet = new liblsl.StreamInlet(results[0]); - - expectedChannels = inlet.info().channel_count(); - - yield return null; - } - - protected void pullSamples() - { - sample = new float[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch(ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - - /// - /// Override this method in the subclass to specify what should happen when samples are available. - /// - /// - protected abstract void Process(float[] newSample, double timeStamp); - - void FixedUpdate() - { - if (moment == UpdateMoment.FixedUpdate && inlet != null) - pullSamples(); - } - - void Update() - { - if (moment == UpdateMoment.Update && inlet != null) - pullSamples(); - } - } - - public abstract class ADoubleInlet : MonoBehaviour - { - public enum UpdateMoment { FixedUpdate, Update } - - public UpdateMoment moment; - - public string StreamName; - - public string StreamType; - - liblsl.StreamInfo[] results; - liblsl.StreamInlet inlet; - liblsl.ContinuousResolver resolver; - - private int expectedChannels = 0; - - double[] sample; - - void Start() - { - var expectedStreamHasAName = !StreamName.Equals(""); - var expectedStreamHasAType = !StreamType.Equals(""); - - if (!expectedStreamHasAName && !expectedStreamHasAType) - { - Debug.LogError("Inlet has to specify a name or a type before it is able to lookup a stream."); - this.enabled = false; - return; - } - - if (expectedStreamHasAName) - { - Debug.Log("Creating LSL resolver for stream " + StreamName); - - resolver = new liblsl.ContinuousResolver("name", StreamName); - } - else if (expectedStreamHasAType) - { - Debug.Log("Creating LSL resolver for stream with type " + StreamType); - resolver = new liblsl.ContinuousResolver("type", StreamType); - } - - StartCoroutine(ResolveExpectedStream()); - - AdditionalStart(); - } - /// - /// Override this method in the subclass to specify what should happen during Start(). - /// - protected virtual void AdditionalStart() - { - //By default, do nothing. - } - - IEnumerator ResolveExpectedStream() - { - var results = resolver.results(); - - while(inlet == null) { - - yield return new WaitUntil(() => results.Length > 0); - - inlet = new liblsl.StreamInlet(GetStreamInfoFrom(results)); - - expectedChannels = inlet.info().channel_count(); - } - - yield return null; - } - - private liblsl.StreamInfo GetStreamInfoFrom(liblsl.StreamInfo[] results) - { - var targetInfo = results.Where(r => r.name().Equals(StreamName)).First(); - return targetInfo; - } - - protected void pullSamples() - { - sample = new double[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - - /// - /// Override this method in the subclass to specify what should happen when samples are available. - /// - /// - protected abstract void Process(double[] newSample, double timeStamp); - - void FixedUpdate() - { - if (moment == UpdateMoment.FixedUpdate && inlet != null) - pullSamples(); - } - - void Update() - { - if (moment == UpdateMoment.Update && inlet != null) - pullSamples(); - } - } - - public abstract class ACharInlet : MonoBehaviour - { - public enum UpdateMoment { FixedUpdate, Update } - - public UpdateMoment moment; - - public string StreamName; - - public string StreamType; - - liblsl.StreamInfo[] results; - liblsl.StreamInlet inlet; - liblsl.ContinuousResolver resolver; - - private int expectedChannels = 0; - - char[] sample; - - void Start() - { - var expectedStreamHasAName = !StreamName.Equals(""); - var expectedStreamHasAType = !StreamType.Equals(""); - - if (!expectedStreamHasAName && !expectedStreamHasAType) - { - Debug.LogError("Inlet has to specify a name or a type before it is able to lookup a stream."); - this.enabled = false; - return; - } - - if (expectedStreamHasAName) - { - Debug.Log("Creating LSL resolver for stream " + StreamName); - - resolver = new liblsl.ContinuousResolver("name", StreamName); - } - else if (expectedStreamHasAType) - { - Debug.Log("Creating LSL resolver for stream with type " + StreamType); - resolver = new liblsl.ContinuousResolver("type", StreamType); - } - - StartCoroutine(ResolveExpectedStream()); - - AdditionalStart(); - } - /// - /// Override this method in the subclass to specify what should happen during Start(). - /// - protected virtual void AdditionalStart() - { - //By default, do nothing. - } - - - IEnumerator ResolveExpectedStream() - { - var results = resolver.results(); - - yield return new WaitUntil(() => results.Length > 0); - - inlet = new liblsl.StreamInlet(results[0]); - - expectedChannels = inlet.info().channel_count(); - - yield return null; - } - - protected void pullSamples() - { - sample = new char[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - - /// - /// Override this method in the subclass to specify what should happen when samples are available. - /// - /// - protected abstract void Process(char[] newSample, double timeStamp); - - void FixedUpdate() - { - if (moment == UpdateMoment.FixedUpdate && inlet != null) - pullSamples(); - } - - void Update() - { - if (moment == UpdateMoment.Update && inlet != null) - pullSamples(); - } - } - - public abstract class AShortInlet : MonoBehaviour - { - public enum UpdateMoment { FixedUpdate, Update } - - public UpdateMoment moment; - - public string StreamName; - - public string StreamType; - - liblsl.StreamInfo[] results; - liblsl.StreamInlet inlet; - liblsl.ContinuousResolver resolver; - - private int expectedChannels = 0; - - short[] sample; - - void Start() - { - var expectedStreamHasAName = !StreamName.Equals(""); - var expectedStreamHasAType = !StreamType.Equals(""); - - if (!expectedStreamHasAName && !expectedStreamHasAType) - { - Debug.LogError("Inlet has to specify a name or a type before it is able to lookup a stream."); - this.enabled = false; - return; - } - - if (expectedStreamHasAName) - { - Debug.Log("Creating LSL resolver for stream " + StreamName); - - resolver = new liblsl.ContinuousResolver("name", StreamName); - } - else if (expectedStreamHasAType) - { - Debug.Log("Creating LSL resolver for stream with type " + StreamType); - resolver = new liblsl.ContinuousResolver("type", StreamType); - } - - StartCoroutine(ResolveExpectedStream()); - - AdditionalStart(); - } - /// - /// Override this method in the subclass to specify what should happen during Start(). - /// - protected virtual void AdditionalStart() - { - //By default, do nothing. - } - - IEnumerator ResolveExpectedStream() - { - var results = resolver.results(); - - yield return new WaitUntil(() => results.Length > 0); - - inlet = new liblsl.StreamInlet(results[0]); - - expectedChannels = inlet.info().channel_count(); - - yield return null; - } - - protected void pullSamples() - { - sample = new short[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - - /// - /// Override this method in the subclass to specify what should happen when samples are available. - /// - /// - protected abstract void Process(short[] newSample, double timeStamp); - - void FixedUpdate() - { - if (moment == UpdateMoment.FixedUpdate && inlet != null) - pullSamples(); - } - - void Update() - { - if (moment == UpdateMoment.Update && inlet != null) - pullSamples(); - } - } - - public abstract class AIntInlet : MonoBehaviour - { - public enum UpdateMoment { FixedUpdate, Update } - - public UpdateMoment moment; - - public string StreamName; - - public string StreamType; - - liblsl.StreamInfo[] results; - liblsl.StreamInlet inlet; - liblsl.ContinuousResolver resolver; - - private int expectedChannels = 0; - - int[] sample; - - void Start() - { - var expectedStreamHasAName = !StreamName.Equals(""); - var expectedStreamHasAType = !StreamType.Equals(""); - - if (!expectedStreamHasAName && !expectedStreamHasAType) - { - Debug.LogError("Inlet has to specify a name or a type before it is able to lookup a stream."); - this.enabled = false; - return; - } - - if (expectedStreamHasAName) - { - Debug.Log("Creating LSL resolver for stream " + StreamName); - - resolver = new liblsl.ContinuousResolver("name", StreamName); - } - else if (expectedStreamHasAType) - { - Debug.Log("Creating LSL resolver for stream with type " + StreamType); - resolver = new liblsl.ContinuousResolver("type", StreamType); - } - - StartCoroutine(ResolveExpectedStream()); - - AdditionalStart(); - } - /// - /// Override this method in the subclass to specify what should happen during Start(). - /// - protected virtual void AdditionalStart() - { - //By default, do nothing. - } - - IEnumerator ResolveExpectedStream() - { - var results = resolver.results(); - - yield return new WaitUntil(() => results.Length > 0); - - inlet = new liblsl.StreamInlet(results[0]); - - expectedChannels = inlet.info().channel_count(); - - yield return null; - } - - protected void pullSamples() - { - sample = new int[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - - /// - /// Override this method in the subclass to specify what should happen when samples are available. - /// - /// - protected abstract void Process(int[] newSample, double timeStamp); - - void FixedUpdate() - { - if (moment == UpdateMoment.FixedUpdate && inlet != null) - pullSamples(); - } - - void Update() - { - if (moment == UpdateMoment.Update && inlet != null) - pullSamples(); - } - } - - public abstract class AStringInlet : MonoBehaviour - { - public enum UpdateMoment { FixedUpdate, Update } - - public UpdateMoment moment; - - public string StreamName; - - public string StreamType; - - liblsl.StreamInfo[] results; - liblsl.StreamInlet inlet; - liblsl.ContinuousResolver resolver; - - private int expectedChannels = 0; - - string[] sample; - - void Start() - { - var expectedStreamHasAName = !StreamName.Equals(""); - var expectedStreamHasAType = !StreamType.Equals(""); - - if (!expectedStreamHasAName && !expectedStreamHasAType) - { - Debug.LogError("Inlet has to specify a name or a type before it is able to lookup a stream."); - this.enabled = false; - return; - } - - if (expectedStreamHasAName) - { - Debug.Log("Creating LSL resolver for stream " + StreamName); - - resolver = new liblsl.ContinuousResolver("name", StreamName); - } - else if (expectedStreamHasAType) - { - Debug.Log("Creating LSL resolver for stream with type " + StreamType); - resolver = new liblsl.ContinuousResolver("type", StreamType); - } - - StartCoroutine(ResolveExpectedStream()); - - AdditionalStart(); - } - /// - /// Override this method in the subclass to specify what should happen during Start(). - /// - protected virtual void AdditionalStart() - { - //By default, do nothing. - } - - IEnumerator ResolveExpectedStream() - { - var results = resolver.results(); - - yield return new WaitUntil(() => results.Length > 0); - - inlet = new liblsl.StreamInlet(results[0]); - - expectedChannels = inlet.info().channel_count(); - - yield return null; - } - - protected void pullSamples() - { - sample = new string[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - - /// - /// Override this method in the subclass to specify what should happen when samples are available. - /// - /// - protected abstract void Process(string[] newSample, double timeStamp); - - void FixedUpdate() - { - if (moment == UpdateMoment.FixedUpdate && inlet != null) - pullSamples(); - } - - void Update() - { - if (moment == UpdateMoment.Update && inlet != null) - pullSamples(); - } - } -} \ No newline at end of file diff --git a/Scripts/AInlet.cs.meta b/Scripts/AInlet.cs.meta deleted file mode 100644 index dd27035..0000000 --- a/Scripts/AInlet.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: e4dbfc4bac1d43d4c85a008a0e3f3aad -timeCreated: 1469171488 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Scripts/BaseInlet.cs b/Scripts/BaseInlet.cs deleted file mode 100644 index a88ade3..0000000 --- a/Scripts/BaseInlet.cs +++ /dev/null @@ -1,310 +0,0 @@ -using LSL; -using System; -using System.Linq; -using UnityEngine; -using UnityEngine.Events; - -namespace Assets.LSL4Unity.Scripts.AbstractInlets -{ - public abstract class ABaseInlet : MonoBehaviour - { - public string StreamName; - - public string StreamType; - - protected liblsl.StreamInlet inlet; - - protected int expectedChannels; - - protected Resolver resolver; - - /// - /// Call this method when your inlet implementation got created at runtime - /// - protected virtual void registerAndLookUpStream() - { - resolver = FindObjectOfType(); - - resolver.onStreamFound.AddListener(new UnityAction(AStreamIsFound)); - - resolver.onStreamLost.AddListener(new UnityAction(AStreamGotLost)); - - if (resolver.knownStreams.Any(isTheExpected)) - { - var stream = resolver.knownStreams.First(isTheExpected); - AStreamIsFound(stream); - } - } - - /// - /// Callback method for the Resolver gets called each time the resolver found a stream - /// - /// - public virtual void AStreamIsFound(LSLStreamInfoWrapper stream) - { - if (!isTheExpected(stream)) - return; - - Debug.Log(string.Format("LSL Stream {0} found for {1}", stream.Name, name)); - - inlet = new LSL.liblsl.StreamInlet(stream.Item); - expectedChannels = stream.ChannelCount; - - OnStreamAvailable(); - } - - /// - /// Callback method for the Resolver gets called each time the resolver misses a stream within its cache - /// - /// - public virtual void AStreamGotLost(LSLStreamInfoWrapper stream) - { - if (!isTheExpected(stream)) - return; - - Debug.Log(string.Format("LSL Stream {0} Lost for {1}", stream.Name, name)); - - OnStreamLost(); - } - - protected virtual bool isTheExpected(LSLStreamInfoWrapper stream) - { - bool predicate = StreamName.Equals(stream.Name); - predicate &= StreamType.Equals(stream.Type); - - return predicate; - } - - protected abstract void pullSamples(); - - protected virtual void OnStreamAvailable() - { - // base implementation may not decide what happens when the stream gets available - throw new NotImplementedException("Please override this method in a derived class!"); - } - - protected virtual void OnStreamLost() - { - // base implementation may not decide what happens when the stream gets lost - throw new NotImplementedException("Please override this method in a derived class!"); - } - } - - public abstract class InletFloatSamples : ABaseInlet - { - protected abstract void Process(float[] newSample, double timeStamp); - - protected float[] sample; - - protected override void pullSamples() - { - sample = new float[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - } - - public abstract class InletDoubleSamples : ABaseInlet - { - protected abstract void Process(double[] newSample, double timeStamp); - - protected double[] sample; - - protected override void pullSamples() - { - sample = new double[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - } - - public abstract class InletIntSamples : ABaseInlet - { - protected abstract void Process(int[] newSample, double timeStamp); - - protected int[] sample; - - protected override void pullSamples() - { - sample = new int[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - } - - public abstract class InletCharSamples : ABaseInlet - { - protected abstract void Process(char[] newSample, double timeStamp); - - protected char[] sample; - - protected override void pullSamples() - { - sample = new char[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - } - - public abstract class InletStringSamples : ABaseInlet - { - protected abstract void Process(String[] newSample, double timeStamp); - - protected String[] sample; - - protected override void pullSamples() - { - sample = new String[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - } - - public abstract class InletShortSamples : ABaseInlet - { - protected abstract void Process(short[] newSample, double timeStamp); - - protected short[] sample; - - protected override void pullSamples() - { - sample = new short[expectedChannels]; - - try - { - double lastTimeStamp = inlet.pull_sample(sample, 0.0f); - - if (lastTimeStamp != 0.0) - { - // do not miss the first one found - Process(sample, lastTimeStamp); - // pull as long samples are available - while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) - { - Process(sample, lastTimeStamp); - } - - } - } - catch (ArgumentException aex) - { - Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); - this.enabled = false; - Debug.LogException(aex, this); - } - - } - } - - -} diff --git a/Scripts/Examples/DemoInletForFloatSamples.cs b/Scripts/Examples/DemoInletForFloatSamples.cs deleted file mode 100644 index 623f84f..0000000 --- a/Scripts/Examples/DemoInletForFloatSamples.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System.Collections; -using UnityEngine; -using Assets.LSL4Unity.Scripts.AbstractInlets; - -namespace Assets.LSL4Unity.Scripts.Examples { - - /// - /// Example that works with the Resolver component. - /// This script waits for the resolver to resolve a Stream which matches the Name and Type. - /// See the base class for more details. - /// - /// The specific implementation should only deal with the moment when the samples need to be pulled - /// and how they should processed in your game logic - /// - /// - public class DemoInletForFloatSamples : InletFloatSamples - { - public Transform targetTransform; - - public bool useX; - public bool useY; - public bool useZ; - - private bool pullSamplesContinuously = false; - - - void Start() - { - // [optional] call this only, if your gameobject hosting this component - // got instantiated during runtime - - // registerAndLookUpStream(); - } - - protected override bool isTheExpected(LSLStreamInfoWrapper stream) - { - // the base implementation just checks for stream name and type - var predicate = base.isTheExpected(stream); - // add a more specific description for your stream here specifying hostname etc. - //predicate &= stream.HostName.Equals("Expected Hostname"); - return predicate; - } - - /// - /// Override this method to implement whatever should happen with the samples... - /// IMPORTANT: Avoid heavy processing logic within this method, update a state and use - /// coroutines for more complexe processing tasks to distribute processing time over - /// several frames - /// - /// - /// - protected override void Process(float[] newSample, double timeStamp) - { - //Assuming that a sample contains at least 3 values for x,y,z - float x = useX ? newSample[0] : 1; - float y = useY ? newSample[1] : 1; - float z = useZ ? newSample[2] : 1; - - // we map the data to the scale factors - var targetScale = new Vector3(x, y, z); - - // apply the rotation to the target transform - targetTransform.localScale = targetScale; - } - - protected override void OnStreamAvailable() - { - pullSamplesContinuously = true; - } - - protected override void OnStreamLost() - { - pullSamplesContinuously = false; - } - - private void Update() - { - if(pullSamplesContinuously) - pullSamples(); - } - } -} \ No newline at end of file diff --git a/Scripts/Examples/DemoInletForFloatSamples.cs.meta b/Scripts/Examples/DemoInletForFloatSamples.cs.meta deleted file mode 100644 index 4d89483..0000000 --- a/Scripts/Examples/DemoInletForFloatSamples.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 5ba4ed7276e95054fb35c620c2207e28 -timeCreated: 1482351815 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Scripts/Examples/ExampleFloatInlet.cs b/Scripts/Examples/ExampleFloatInlet.cs deleted file mode 100644 index 3a128f6..0000000 --- a/Scripts/Examples/ExampleFloatInlet.cs +++ /dev/null @@ -1,25 +0,0 @@ -using UnityEngine; -using System; -using System.Linq; -using Assets.LSL4Unity.Scripts.AbstractInlets; - -namespace Assets.LSL4Unity.Scripts.Examples -{ - /// - /// Just an example implementation for a Inlet recieving float values - /// - public class ExampleFloatInlet : AFloatInlet - { - public string lastSample = String.Empty; - - protected override void Process(float[] newSample, double timeStamp) - { - // just as an example, make a string out of all channel values of this sample - lastSample = string.Join(" ", newSample.Select(c => c.ToString()).ToArray()); - - Debug.Log( - string.Format("Got {0} samples at {1}", newSample.Length, timeStamp) - ); - } - } -} \ No newline at end of file diff --git a/Scripts/Examples/ExampleFloatInlet.cs.meta b/Scripts/Examples/ExampleFloatInlet.cs.meta deleted file mode 100644 index 135effe..0000000 --- a/Scripts/Examples/ExampleFloatInlet.cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 1da38a6a9335e8e48af8b17d9c369265 -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: diff --git a/Scripts/Examples/ScaleMapping.cs b/Scripts/Examples/ScaleMapping.cs deleted file mode 100644 index e30e2f9..0000000 --- a/Scripts/Examples/ScaleMapping.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Assets.LSL4Unity.Scripts.AbstractInlets; -using UnityEngine; - -public class ScaleMapping : AFloatInlet -{ - public Transform targetTransform; - - public bool useX ; - public bool useY ; - public bool useZ ; - - protected override void Process(float[] newSample, double timeStamp) - { - //Assuming that a sample contains at least 3 values for x,y,z - float x = useX ? newSample[0] : 1; - float y = useY ? newSample[1] : 1; - float z = useZ ? newSample[2] : 1; - - // we map the data to the scale factors - var targetScale = new Vector3(x, y, z); - - // apply the rotation to the target transform - targetTransform.localScale = targetScale; - } -} diff --git a/Scripts/Examples/ScaleMapping.cs.meta b/Scripts/Examples/ScaleMapping.cs.meta deleted file mode 100644 index 6797511..0000000 --- a/Scripts/Examples/ScaleMapping.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 87163fb44bc059c4d99f26b875930ecf -timeCreated: 1469177646 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Scripts/Examples/TransformMapping.cs b/Scripts/Examples/TransformMapping.cs deleted file mode 100644 index 899dbda..0000000 --- a/Scripts/Examples/TransformMapping.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Assets.LSL4Unity.Scripts.AbstractInlets; -using UnityEngine; - -public class TransformMapping : AFloatInlet -{ - public Transform targetTransform; - - protected override void Process(float[] newSample, double timeStamp) - { - //Assuming that a sample contains at least 3 values for x,y,z - float x = newSample[0]; - float y = newSample[1]; - float z = newSample[2]; - - // we map the coordinates to a rotation - var targetRotation = Quaternion.Euler(x, y, z); - - // apply the rotation to the target transform - targetTransform.rotation = targetRotation; - } -} diff --git a/Scripts/Examples/TransformMapping.cs.meta b/Scripts/Examples/TransformMapping.cs.meta deleted file mode 100644 index 512fc59..0000000 --- a/Scripts/Examples/TransformMapping.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 1fcdacf901118b647b6fb2f179ca702c -timeCreated: 1469177646 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Scripts/LSLCommon.cs.meta b/Scripts/LSLCommon.cs.meta deleted file mode 100644 index bd2ad59..0000000 --- a/Scripts/LSLCommon.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 22778c42f56c0ad41b381ce95aeb188d -timeCreated: 1474311115 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Scripts/LSLMarkerStream.cs b/Scripts/LSLMarkerStream.cs deleted file mode 100644 index 0e7ab8e..0000000 --- a/Scripts/LSLMarkerStream.cs +++ /dev/null @@ -1,74 +0,0 @@ -using UnityEngine; -using System.Collections; -using LSL; - -namespace Assets.LSL4Unity.Scripts -{ - [HelpURL("https://github.com/xfleckx/LSL4Unity/wiki#using-a-marker-stream")] - public class LSLMarkerStream : MonoBehaviour - { - private const string unique_source_id = "D3F83BB699EB49AB94A9FA44B88882AB"; - - public string lslStreamName = "Unity_"; - public string lslStreamType = "LSL_Marker_Strings"; - - private liblsl.StreamInfo lslStreamInfo; - private liblsl.StreamOutlet lslOutlet; - private int lslChannelCount = 1; - - //Assuming that markers are never send in regular intervalls - private double nominal_srate = liblsl.IRREGULAR_RATE; - - private const liblsl.channel_format_t lslChannelFormat = liblsl.channel_format_t.cf_string; - - private string[] sample; - - void Awake() - { - sample = new string[lslChannelCount]; - - lslStreamInfo = new liblsl.StreamInfo( - lslStreamName, - lslStreamType, - lslChannelCount, - nominal_srate, - lslChannelFormat, - unique_source_id); - - lslOutlet = new liblsl.StreamOutlet(lslStreamInfo); - } - - public void Write(string marker) - { - sample[0] = marker; - lslOutlet.push_sample(sample); - } - - public void Write(string marker, double customTimeStamp) - { - sample[0] = marker; - lslOutlet.push_sample(sample, customTimeStamp); - } - - public void Write(string marker, float customTimeStamp) - { - sample[0] = marker; - lslOutlet.push_sample(sample, customTimeStamp); - } - - public void WriteBeforeFrameIsDisplayed(string marker) - { - StartCoroutine(WriteMarkerAfterImageIsRendered(marker)); - } - - IEnumerator WriteMarkerAfterImageIsRendered(string pendingMarker) - { - yield return new WaitForEndOfFrame(); - - Write(pendingMarker); - - yield return null; - } - - } -} \ No newline at end of file diff --git a/Scripts/LSLMarkerStream.cs.meta b/Scripts/LSLMarkerStream.cs.meta deleted file mode 100644 index bb8da19..0000000 --- a/Scripts/LSLMarkerStream.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 42f6a5f2a177ae14badbe859d5c565d2 -timeCreated: 1432219043 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Scripts/LSLOutlet.cs b/Scripts/LSLOutlet.cs deleted file mode 100644 index 9c870f9..0000000 --- a/Scripts/LSLOutlet.cs +++ /dev/null @@ -1,52 +0,0 @@ -using UnityEngine; -using System.Collections; -using LSL; -using System.Diagnostics; - -namespace Assets.LSL4Unity.Scripts -{ - public enum MomentForSampling { Update, FixedUpdate, LateUpdate } - - - public class LSLOutlet : MonoBehaviour - { - private liblsl.StreamOutlet outlet; - private liblsl.StreamInfo streamInfo; - private float[] currentSample; - - public string StreamName = "Unity.ExampleStream"; - public string StreamType = "Unity.FixedUpdateTime"; - public int ChannelCount = 1; - - Stopwatch watch; - - // Use this for initialization - void Start() - { - watch = new Stopwatch(); - - watch.Start(); - - currentSample = new float[ChannelCount]; - - streamInfo = new liblsl.StreamInfo(StreamName, StreamType, ChannelCount, Time.fixedDeltaTime * 1000); - - outlet = new liblsl.StreamOutlet(streamInfo); - } - - public void FixedUpdate() - { - if (watch == null) - return; - - watch.Stop(); - - currentSample[0] = watch.ElapsedMilliseconds; - - watch.Reset(); - watch.Start(); - - outlet.push_sample(currentSample); - } - } -} \ No newline at end of file diff --git a/Scripts/LSLOutlet.cs.meta b/Scripts/LSLOutlet.cs.meta deleted file mode 100644 index 15ca8d2..0000000 --- a/Scripts/LSLOutlet.cs.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: cc7c6d8f5d4acb546a2da215dd3df12a -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: diff --git a/Scripts/LSLTransformOutlet.cs b/Scripts/LSLTransformOutlet.cs deleted file mode 100644 index 6d917ce..0000000 --- a/Scripts/LSLTransformOutlet.cs +++ /dev/null @@ -1,174 +0,0 @@ -using UnityEngine; -using LSL; -using System.Collections.Generic; -using Assets.LSL4Unity.Scripts.Common; - -namespace Assets.LSL4Unity.Scripts -{ - /// - /// An reusable example of an outlet which provides the orientation and world position of an entity of an Unity Scene to LSL - /// - public class LSLTransformOutlet : MonoBehaviour - { - private const string unique_source_id_suffix = "63CE5B03731944F6AC30DBB04B451A94"; - - private string unique_source_id; - - private liblsl.StreamOutlet outlet; - private liblsl.StreamInfo streamInfo; - - private int channelCount = 0; - - /// - /// Use a array to reduce allocation costs - /// and reuse it for each sampling call - /// - private float[] currentSample; - - public Transform sampleSource; - - public string StreamName = "BeMoBI.Unity.Orientation."; - public string StreamType = "Unity.Quaternion"; - - public bool StreamRotationAsQuaternion = true; - public bool StreamRotationAsEuler = true; - public bool StreamPosition = true; - - /// - /// Due to an instable framerate we assume a irregular data rate. - /// - private const double dataRate = liblsl.IRREGULAR_RATE; - - void Awake() - { - // assigning a unique source id as a combination of a the instance ID for the case that - // multiple LSLTransformOutlet are used and a guid identifing the script itself. - unique_source_id = string.Format("{0}_{1}", GetInstanceID(), unique_source_id_suffix); - } - - void Start() - { - var channelDefinitions = SetupChannels(); - - channelCount = channelDefinitions.Count; - - // initialize the array once - currentSample = new float[channelCount]; - - streamInfo = new liblsl.StreamInfo(StreamName, StreamType, channelCount, dataRate, liblsl.channel_format_t.cf_float32, unique_source_id); - - // it's not possible to create a XMLElement before and append it. - liblsl.XMLElement chns = streamInfo.desc().append_child("channels"); - // so this workaround has been introduced. - foreach (var def in channelDefinitions) - { - chns.append_child("channel") - .append_child_value("label", def.label) - .append_child_value("unit", def.unit) - .append_child_value("type", def.type); - } - - outlet = new liblsl.StreamOutlet(streamInfo); - } - - /// - /// Sampling on Late Update to make sure the transform recieved all updates - /// - void LateUpdate() - { - if (outlet == null) - return; - - sample(); - } - - private void sample() - { - int offset = -1; - - if (StreamRotationAsQuaternion) - { - var rotation = sampleSource.rotation; - - currentSample[++offset] = rotation.x; - currentSample[++offset] = rotation.y; - currentSample[++offset] = rotation.z; - currentSample[++offset] = rotation.w; - } - if (StreamRotationAsEuler) - { - var rotation = sampleSource.rotation.eulerAngles; - - currentSample[++offset] = rotation.x; - currentSample[++offset] = rotation.y; - currentSample[++offset] = rotation.z; - } - if (StreamPosition) - { - var position = sampleSource.position; - - currentSample[++offset] = position.x; - currentSample[++offset] = position.y; - currentSample[++offset] = position.z; - } - - outlet.push_sample(currentSample, liblsl.local_clock()); - } - - - #region workaround for channel creation - - private ICollection SetupChannels() - { - var list = new List(); - - if (StreamRotationAsQuaternion) - { - string[] quatlabels = { "x", "y", "z", "w" }; - - foreach (var item in quatlabels) - { - var definition = new ChannelDefinition(); - definition.label = item; - definition.unit = "unit quaternion"; - definition.type = "quaternion component"; - list.Add(definition); - } - } - - if (StreamRotationAsEuler) - { - string[] eulerLabels = { "x", "y", "z" }; - - foreach (var item in eulerLabels) - { - var definition = new ChannelDefinition(); - definition.label = item; - definition.unit = "degree"; - definition.type = "axis angle"; - list.Add(definition); - } - } - - - if (StreamPosition) - { - string[] eulerLabels = { "x", "y", "z" }; - - foreach (var item in eulerLabels) - { - var definition = new ChannelDefinition(); - definition.label = item; - definition.unit = "meter"; - definition.type = "position in world space"; - list.Add(definition); - } - } - - return list; - } - - #endregion - - } -} \ No newline at end of file diff --git a/Scripts/LSLTransformOutlet.cs.meta b/Scripts/LSLTransformOutlet.cs.meta deleted file mode 100644 index 4a039fe..0000000 --- a/Scripts/LSLTransformOutlet.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: 01c23d6a1fd35524fbcfcb4c996f6439 -timeCreated: 1453471087 -licenseType: Free -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Scripts/Resolver.cs b/Scripts/Resolver.cs deleted file mode 100644 index 03524d6..0000000 --- a/Scripts/Resolver.cs +++ /dev/null @@ -1,200 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using System.Linq; -using LSL; -using UnityEngine.Events; -using UnityEngine.EventSystems; - -namespace Assets.LSL4Unity.Scripts -{ - /// - /// Encapsulates the lookup logic for LSL streams with an event based appraoch - /// your custom stream inlet implementations could be subscribed to the On - /// - public class Resolver : MonoBehaviour, IEventSystemHandler - { - - public List knownStreams; - - public float forgetStreamAfter = 1.0f; - - private liblsl.ContinuousResolver resolver; - - private bool resolve = true; - - public StreamEvent onStreamFound = new StreamEvent(); - - public StreamEvent onStreamLost = new StreamEvent(); - - // Use this for initialization - void Start() - { - - resolver = new liblsl.ContinuousResolver(forgetStreamAfter); - - StartCoroutine(resolveContinuously()); - } - - public bool IsStreamAvailable(out LSLStreamInfoWrapper info, string streamName = "", string streamType = "", string hostName = "") - { - var result = knownStreams.Where(i => - - (streamName == "" || i.Name.Equals(streamName)) && - (streamType == "" || i.Type.Equals(streamType)) && - (hostName == "" || i.Type.Equals(hostName)) - ); - - if (result.Any()) - { - info = result.First(); - return true; - } - else - { - info = null; - return false; - } - } - - private IEnumerator resolveContinuously() - { - while (resolve) - { - var results = resolver.results(); - - foreach (var item in knownStreams) - { - if (!results.Any(r => r.name().Equals(item.Name))) - { - if (onStreamLost.GetPersistentEventCount() > 0) - onStreamLost.Invoke(item); - } - } - - // remove lost streams from cache - knownStreams.RemoveAll(s => !results.Any(r => r.name().Equals(s.Name))); - - // add new found streams to the cache - foreach (var item in results) - { - if (!knownStreams.Any(s => s.Name == item.name() && s.Type == item.type())) - { - - Debug.Log(string.Format("Found new Stream {0}", item.name())); - - var newStreamInfo = new LSLStreamInfoWrapper(item); - knownStreams.Add(newStreamInfo); - - if (onStreamFound.GetPersistentEventCount() > 0) - onStreamFound.Invoke(newStreamInfo); - } - } - - yield return new WaitForSecondsRealtime(0.1f); - } - yield return null; - } - } - - [Serializable] - public class LSLStreamInfoWrapper - { - public string Name; - - public string Type; - - private liblsl.StreamInfo item; - private readonly string streamUID; - - private readonly int channelCount; - private readonly string sessionId; - private readonly string sourceID; - private readonly double dataRate; - private readonly string hostName; - private readonly int streamVersion; - - public LSLStreamInfoWrapper(liblsl.StreamInfo item) - { - this.item = item; - Name = item.name(); - Type = item.type(); - channelCount = item.channel_count(); - streamUID = item.uid(); - sessionId = item.session_id(); - sourceID = item.source_id(); - dataRate = item.nominal_srate(); - hostName = item.hostname(); - streamVersion = item.version(); - } - - public liblsl.StreamInfo Item - { - get - { - return item; - } - } - - public string StreamUID - { - get - { - return streamUID; - } - } - - public int ChannelCount - { - get - { - return channelCount; - } - } - - public string SessionId - { - get - { - return sessionId; - } - } - - public string SourceID - { - get - { - return sourceID; - } - } - - public string HostName - { - get - { - return hostName; - } - } - - public double DataRate - { - get - { - return dataRate; - } - } - - public int StreamVersion - { - get - { - return streamVersion; - } - } - } - - [Serializable] - public class StreamEvent : UnityEvent { } -} - diff --git a/package.json b/package.json new file mode 100644 index 0000000..03c0f3b --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "com.labstreaminglayer.lsl4unity", + "version": "1.16.0", + "description": "labstreaminglayer for Unity", + "displayName": "labstreaminglayer for Unity", + "unity": "2020.3", + "author": { + "name": "Chadwick Boulay", + "email": "chadwick.boulay@gmail.com" + }, + "documentationUrl": "https://github.com/labstreaminglayer/LSL4Unity", + "samples": [ + { + "displayName": "SimpleInletScaleObject", + "description": "Use an LSL Inlet's data to scale a GameObject - Simple", + "path": "Samples~/SimpleInletScaleObject" + }, + { + "displayName": "SimplePhysicsEventOutlet", + "description": "Stream trigger events over an LSL Outlet.", + "path": "Samples~/SimplePhysicsEventOutlet" + }, + { + "displayName": "ComplexOutletInletEvent", + "description": "Randomly moving capsule streams out its pose, while a cube sets its pose from a stream, and a flashing pane streams out its colour-change events.", + "path": "Samples~/ComplexOutletInletEvent" + } + ] +} diff --git a/package.json.meta b/package.json.meta new file mode 100644 index 0000000..7de00c7 --- /dev/null +++ b/package.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 666bf36249ec0cc4e92e51cab3f48e2d +PackageManifestImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: