text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
#if MLA_INPUT_TESTS using NUnit.Framework; using Unity.MLAgents.Actuators; using Unity.MLAgents.Extensions.Input; using UnityEngine; using UnityEngine.InputSystem; namespace Unity.MLAgents.Extensions.Tests.Runtime.Input { public class DoubleInputActionAdaptorTests : InputTestFixture { DoubleInputActionAdaptor m_Adaptor; InputDevice m_Device; InputControl<double> m_Control; InputAction m_Action; public override void Setup() { base.Setup(); const string kLayout = @" { ""name"" : ""TestDevice"", ""extend"" : ""HID"", ""controls"" : [ { ""name"" : ""button"", ""layout"" : ""Double"" } ] }"; InputSystem.RegisterLayout(kLayout); m_Device = InputSystem.AddDevice("TestDevice"); m_Control = (InputControl<double>)m_Device["button"]; m_Action = new InputAction("action", InputActionType.Value, "/TestDevice/button", null, null, "double"); m_Action.Enable(); m_Adaptor = new DoubleInputActionAdaptor(); } public override void TearDown() { base.TearDown(); m_Adaptor = null; } [Test] public void TestGenerateActionSpec() { var actionSpec = m_Adaptor.GetActionSpecForInputAction(new InputAction()); Assert.IsTrue(actionSpec.NumContinuousActions == 1); } [Test] public void TestQueueEvent() { var actionBuffers = new ActionBuffers(new ActionSegment<float>(new[] { 1f }), ActionSegment<int>.Empty); var context = new InputActuatorEventContext(1, m_Device); using (context.GetEventForFrame(out var eventPtr)) { m_Adaptor.WriteToInputEventForAction(eventPtr, m_Action, m_Control, new ActionSpec(), actionBuffers); } InputSystem.Update(); Assert.IsTrue(Mathf.Approximately(1f, (float)m_Action.ReadValue<double>())); } [Test] public void TestWriteToHeuristic() { var actionBuffers = new ActionBuffers(new ActionSegment<float>(new[] { 1f }), ActionSegment<int>.Empty); var context = new InputActuatorEventContext(1, m_Device); using (context.GetEventForFrame(out var eventPtr)) { m_Adaptor.WriteToInputEventForAction(eventPtr, m_Action, m_Control, new ActionSpec(), actionBuffers); } InputSystem.Update(); var buffer = new ActionBuffers(new ActionSegment<float>(new[] { 1f }), ActionSegment<int>.Empty); m_Adaptor.WriteToHeuristic(m_Action, buffer); Assert.IsTrue(Mathf.Approximately(buffer.ContinuousActions[0], 1f)); } } } #endif // MLA_INPUT_TESTS
ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Input/Adaptors/DoubleInputActionAdaptorTests.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Input/Adaptors/DoubleInputActionAdaptorTests.cs", "repo_id": "ml-agents", "token_count": 1378 }
1,862
using NUnit.Framework; namespace Unity.MLAgents.Extensions.Tests { internal class RuntimeExampleTest { [Test] public void RuntimeTestMath() { Assert.AreEqual(2, 1 + 1); } } }
ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/RuntimeExampleTest.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/RuntimeExampleTest.cs", "repo_id": "ml-agents", "token_count": 114 }
1,863
fileFormatVersion: 2 guid: 8b8b560acc80a4ddab0239d0535d5324 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Sensors/RigidBodySensorTests.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents.extensions/Tests/Runtime/Sensors/RigidBodySensorTests.cs.meta", "repo_id": "ml-agents", "token_count": 94 }
1,864
using UnityEngine; using UnityEditor; namespace Unity.MLAgents.Editor { /* This code is meant to modify the behavior of the inspector on Agent Components. */ [CustomEditor(typeof(Agent), true)] [CanEditMultipleObjects] internal class AgentEditor : UnityEditor.Editor { public override void OnInspectorGUI() { var serializedAgent = serializedObject; serializedAgent.Update(); var maxSteps = serializedAgent.FindProperty("MaxStep"); EditorGUILayout.PropertyField( maxSteps, new GUIContent("Max Step", "The per-agent maximum number of steps.") ); serializedAgent.ApplyModifiedProperties(); EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); base.OnInspectorGUI(); } } }
ml-agents/com.unity.ml-agents/Editor/AgentEditor.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Editor/AgentEditor.cs", "repo_id": "ml-agents", "token_count": 366 }
1,865
using UnityEditor; using UnityEngine; using Unity.MLAgents.Sensors; namespace Unity.MLAgents.Editor { [CustomEditor(typeof(GridSensorComponent), editorForChildClasses: true)] [CanEditMultipleObjects] internal class GridSensorComponentEditor : UnityEditor.Editor { public override void OnInspectorGUI() { #if !MLA_UNITY_PHYSICS_MODULE EditorGUILayout.HelpBox("The Physics Module is not currently present. " + "Please add it to your project in order to use the GridSensor APIs in the " + $"{nameof(GridSensorComponent)}", MessageType.Warning); #endif var so = serializedObject; so.Update(); // Drawing the GridSensorComponent EditorGUI.BeginChangeCheck(); EditorGUI.BeginDisabledGroup(!EditorUtilities.CanUpdateModelProperties()); { // These fields affect the sensor order or observation size, // So can't be changed at runtime. EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_SensorName)), true); EditorGUILayout.LabelField("Grid Settings", EditorStyles.boldLabel); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_CellScale)), true); // We only supports 2D GridSensor now so lock gridSize.y to 1 var gridSize = so.FindProperty(nameof(GridSensorComponent.m_GridSize)); var gridSize2d = new Vector3Int(gridSize.vector3IntValue.x, 1, gridSize.vector3IntValue.z); var newGridSize = EditorGUILayout.Vector3IntField("Grid Size", gridSize2d); gridSize.vector3IntValue = new Vector3Int(newGridSize.x, 1, newGridSize.z); } EditorGUI.EndDisabledGroup(); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_AgentGameObject)), true); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_RotateWithAgent)), true); EditorGUI.BeginDisabledGroup(!EditorUtilities.CanUpdateModelProperties()); { // detectable tags var detectableTags = so.FindProperty(nameof(GridSensorComponent.m_DetectableTags)); var newSize = EditorGUILayout.IntField("Detectable Tags", detectableTags.arraySize); if (newSize != detectableTags.arraySize) { detectableTags.arraySize = newSize; } EditorGUI.indentLevel++; for (var i = 0; i < detectableTags.arraySize; i++) { var objectTag = detectableTags.GetArrayElementAtIndex(i); EditorGUILayout.PropertyField(objectTag, new GUIContent("Tag " + i), true); } EditorGUI.indentLevel--; } EditorGUI.EndDisabledGroup(); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_ColliderMask)), true); EditorGUILayout.LabelField("Sensor Settings", EditorStyles.boldLabel); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_ObservationStacks)), true); EditorGUI.EndDisabledGroup(); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_CompressionType)), true); EditorGUI.BeginDisabledGroup(!EditorUtilities.CanUpdateModelProperties()); { EditorGUILayout.LabelField("Collider and Buffer", EditorStyles.boldLabel); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_InitialColliderBufferSize)), true); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_MaxColliderBufferSize)), true); } EditorGUI.EndDisabledGroup(); EditorGUILayout.LabelField("Debug Gizmo", EditorStyles.boldLabel); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_ShowGizmos)), true); EditorGUILayout.PropertyField(so.FindProperty(nameof(GridSensorComponent.m_GizmoYOffset)), true); // detectable objects var debugColors = so.FindProperty(nameof(GridSensorComponent.m_DebugColors)); var detectableObjectSize = so.FindProperty(nameof(GridSensorComponent.m_DetectableTags)).arraySize; if (detectableObjectSize != debugColors.arraySize) { debugColors.arraySize = detectableObjectSize; } EditorGUILayout.LabelField("Debug Colors"); EditorGUI.indentLevel++; for (var i = 0; i < debugColors.arraySize; i++) { var debugColor = debugColors.GetArrayElementAtIndex(i); EditorGUILayout.PropertyField(debugColor, new GUIContent("Tag " + i + " Color"), true); } EditorGUI.indentLevel--; var requireSensorUpdate = EditorGUI.EndChangeCheck(); so.ApplyModifiedProperties(); if (requireSensorUpdate) { UpdateSensor(); } } void UpdateSensor() { var sensorComponent = serializedObject.targetObject as GridSensorComponent; sensorComponent?.UpdateSensor(); } } }
ml-agents/com.unity.ml-agents/Editor/GridSensorComponentEditor.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Editor/GridSensorComponentEditor.cs", "repo_id": "ml-agents", "token_count": 2360 }
1,866
fileFormatVersion: 2 guid: e44343d7e31b04d47bd5f7329c918ffe folderAsset: yes timeCreated: 1521839636 licenseType: Free DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer.meta", "repo_id": "ml-agents", "token_count": 83 }
1,867
fileFormatVersion: 2 guid: b1fc0029fee784d9cb9854f8912bfd07 timeCreated: 1503613254 licenseType: Free MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Runtime/Academy.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Academy.cs.meta", "repo_id": "ml-agents", "token_count": 99 }
1,868
namespace Unity.MLAgents.Actuators { /// <summary> /// Identifiers for "built in" actuator types. /// These are only used for analytics, and should not be used for any runtime decisions. /// /// NOTE: Do not renumber these, since the values are used for analytics. Renaming is allowed though. /// </summary> public enum BuiltInActuatorType { /// <summary> /// Default Sensor type if it cannot be determined. /// </summary> Unknown = 0, /// <summary> /// VectorActuator used by the Agent /// </summary> AgentVectorActuator = 1, /// <summary> /// Corresponds to <see cref="VectorActuator"/> /// </summary> VectorActuator = 2, /// <summary> /// Corresponds to the Match3Actuator in com.unity.ml-agents.extensions. /// </summary> Match3Actuator = 3, /// <summary> /// Corresponds to the InputActionActuator in com.unity.ml-agents.extensions. /// </summary> InputActionActuator = 4, } /// <summary> /// Interface for actuators that are provided as part of ML-Agents. /// User-implemented actuators don't need to use this interface. /// </summary> internal interface IBuiltInActuator { /// <summary> /// Return the corresponding BuiltInActuatorType for the actuator. /// </summary> /// <returns>A BuiltInActuatorType corresponding to the actuator.</returns> BuiltInActuatorType GetBuiltInActuatorType(); } }
ml-agents/com.unity.ml-agents/Runtime/Actuators/IBuiltInActuator.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Actuators/IBuiltInActuator.cs", "repo_id": "ml-agents", "token_count": 612 }
1,869
fileFormatVersion: 2 guid: ac4c40c2394d481ebf602caa600a32f3 timeCreated: 1604359787
ml-agents/com.unity.ml-agents/Runtime/Analytics/InferenceAnalytics.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Analytics/InferenceAnalytics.cs.meta", "repo_id": "ml-agents", "token_count": 39 }
1,870
fileFormatVersion: 2 guid: 57a3dc12d3b88408688bb490b65a838e timeCreated: 1523046536 licenseType: Free MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Runtime/Communicator/RpcCommunicator.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Communicator/RpcCommunicator.cs.meta", "repo_id": "ml-agents", "token_count": 107 }
1,871
using System; using System.Collections.Generic; using Unity.MLAgents.SideChannels; namespace Unity.MLAgents { /// <summary> /// A container for the Environment Parameters that may be modified during training. /// The keys for those parameters are defined in the trainer configurations and the /// the values are generated from the training process in features such as Curriculum Learning /// and Environment Parameter Randomization. /// /// One current assumption for all the environment parameters is that they are of type float. /// </summary> public sealed class EnvironmentParameters { /// <summary> /// The side channel that is used to receive the new parameter values. /// </summary> readonly EnvironmentParametersChannel m_Channel; /// <summary> /// Constructor. /// </summary> internal EnvironmentParameters() { m_Channel = new EnvironmentParametersChannel(); SideChannelManager.RegisterSideChannel(m_Channel); } /// <summary> /// Returns the parameter value for the specified key. Returns the default value provided /// if this parameter key does not have a value. Only returns a parameter value if it is /// of type float. /// </summary> /// <param name="key">The parameter key</param> /// <param name="defaultValue">Default value for this parameter.</param> /// <returns></returns> public float GetWithDefault(string key, float defaultValue) { return m_Channel.GetWithDefault(key, defaultValue); } /// <summary> /// Registers a callback action for the provided parameter key. Will overwrite any /// existing action for that parameter. The callback will be called whenever the parameter /// receives a value from the training process. /// </summary> /// <param name="key">The parameter key</param> /// <param name="action">The callback action</param> public void RegisterCallback(string key, Action<float> action) { m_Channel.RegisterCallback(key, action); } /// <summary> /// Returns a list of all the parameter keys that have received values. /// </summary> /// <returns>List of parameter keys.</returns> public IList<string> Keys() { return m_Channel.ListParameters(); } internal void Dispose() { SideChannelManager.UnregisterSideChannel(m_Channel); } } }
ml-agents/com.unity.ml-agents/Runtime/EnvironmentParameters.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/EnvironmentParameters.cs", "repo_id": "ml-agents", "token_count": 924 }
1,872
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: mlagents_envs/communicator_objects/capabilities.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Unity.MLAgents.CommunicatorObjects { /// <summary>Holder for reflection information generated from mlagents_envs/communicator_objects/capabilities.proto</summary> internal static partial class CapabilitiesReflection { #region Descriptor /// <summary>File descriptor for mlagents_envs/communicator_objects/capabilities.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CapabilitiesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjVtbGFnZW50c19lbnZzL2NvbW11bmljYXRvcl9vYmplY3RzL2NhcGFiaWxp", "dGllcy5wcm90bxIUY29tbXVuaWNhdG9yX29iamVjdHMi7AEKGFVuaXR5UkxD", "YXBhYmlsaXRpZXNQcm90bxIaChJiYXNlUkxDYXBhYmlsaXRpZXMYASABKAgS", "IwobY29uY2F0ZW5hdGVkUG5nT2JzZXJ2YXRpb25zGAIgASgIEiAKGGNvbXBy", "ZXNzZWRDaGFubmVsTWFwcGluZxgDIAEoCBIVCg1oeWJyaWRBY3Rpb25zGAQg", "ASgIEhkKEXRyYWluaW5nQW5hbHl0aWNzGAUgASgIEiEKGXZhcmlhYmxlTGVu", "Z3RoT2JzZXJ2YXRpb24YBiABKAgSGAoQbXVsdGlBZ2VudEdyb3VwcxgHIAEo", "CEIlqgIiVW5pdHkuTUxBZ2VudHMuQ29tbXVuaWNhdG9yT2JqZWN0c2IGcHJv", "dG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Unity.MLAgents.CommunicatorObjects.UnityRLCapabilitiesProto), global::Unity.MLAgents.CommunicatorObjects.UnityRLCapabilitiesProto.Parser, new[]{ "BaseRLCapabilities", "ConcatenatedPngObservations", "CompressedChannelMapping", "HybridActions", "TrainingAnalytics", "VariableLengthObservation", "MultiAgentGroups" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// /// A Capabilities message that will communicate both C# and Python /// what features are available to both. /// </summary> internal sealed partial class UnityRLCapabilitiesProto : pb::IMessage<UnityRLCapabilitiesProto> { private static readonly pb::MessageParser<UnityRLCapabilitiesProto> _parser = new pb::MessageParser<UnityRLCapabilitiesProto>(() => new UnityRLCapabilitiesProto()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UnityRLCapabilitiesProto> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Unity.MLAgents.CommunicatorObjects.CapabilitiesReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UnityRLCapabilitiesProto() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UnityRLCapabilitiesProto(UnityRLCapabilitiesProto other) : this() { baseRLCapabilities_ = other.baseRLCapabilities_; concatenatedPngObservations_ = other.concatenatedPngObservations_; compressedChannelMapping_ = other.compressedChannelMapping_; hybridActions_ = other.hybridActions_; trainingAnalytics_ = other.trainingAnalytics_; variableLengthObservation_ = other.variableLengthObservation_; multiAgentGroups_ = other.multiAgentGroups_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UnityRLCapabilitiesProto Clone() { return new UnityRLCapabilitiesProto(this); } /// <summary>Field number for the "baseRLCapabilities" field.</summary> public const int BaseRLCapabilitiesFieldNumber = 1; private bool baseRLCapabilities_; /// <summary> /// These are the 1.0 capabilities. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool BaseRLCapabilities { get { return baseRLCapabilities_; } set { baseRLCapabilities_ = value; } } /// <summary>Field number for the "concatenatedPngObservations" field.</summary> public const int ConcatenatedPngObservationsFieldNumber = 2; private bool concatenatedPngObservations_; /// <summary> /// concatenated PNG files for compressed visual observations with >3 channels. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool ConcatenatedPngObservations { get { return concatenatedPngObservations_; } set { concatenatedPngObservations_ = value; } } /// <summary>Field number for the "compressedChannelMapping" field.</summary> public const int CompressedChannelMappingFieldNumber = 3; private bool compressedChannelMapping_; /// <summary> /// compression mapping for stacking compressed observations. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool CompressedChannelMapping { get { return compressedChannelMapping_; } set { compressedChannelMapping_ = value; } } /// <summary>Field number for the "hybridActions" field.</summary> public const int HybridActionsFieldNumber = 4; private bool hybridActions_; /// <summary> /// support for hybrid action spaces (discrete + continuous) /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool HybridActions { get { return hybridActions_; } set { hybridActions_ = value; } } /// <summary>Field number for the "trainingAnalytics" field.</summary> public const int TrainingAnalyticsFieldNumber = 5; private bool trainingAnalytics_; /// <summary> /// support for training analytics /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool TrainingAnalytics { get { return trainingAnalytics_; } set { trainingAnalytics_ = value; } } /// <summary>Field number for the "variableLengthObservation" field.</summary> public const int VariableLengthObservationFieldNumber = 6; private bool variableLengthObservation_; /// <summary> /// Support for variable length observations of rank 2 /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool VariableLengthObservation { get { return variableLengthObservation_; } set { variableLengthObservation_ = value; } } /// <summary>Field number for the "multiAgentGroups" field.</summary> public const int MultiAgentGroupsFieldNumber = 7; private bool multiAgentGroups_; /// <summary> /// Support for multi agent groups and group rewards /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool MultiAgentGroups { get { return multiAgentGroups_; } set { multiAgentGroups_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UnityRLCapabilitiesProto); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UnityRLCapabilitiesProto other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (BaseRLCapabilities != other.BaseRLCapabilities) return false; if (ConcatenatedPngObservations != other.ConcatenatedPngObservations) return false; if (CompressedChannelMapping != other.CompressedChannelMapping) return false; if (HybridActions != other.HybridActions) return false; if (TrainingAnalytics != other.TrainingAnalytics) return false; if (VariableLengthObservation != other.VariableLengthObservation) return false; if (MultiAgentGroups != other.MultiAgentGroups) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (BaseRLCapabilities != false) hash ^= BaseRLCapabilities.GetHashCode(); if (ConcatenatedPngObservations != false) hash ^= ConcatenatedPngObservations.GetHashCode(); if (CompressedChannelMapping != false) hash ^= CompressedChannelMapping.GetHashCode(); if (HybridActions != false) hash ^= HybridActions.GetHashCode(); if (TrainingAnalytics != false) hash ^= TrainingAnalytics.GetHashCode(); if (VariableLengthObservation != false) hash ^= VariableLengthObservation.GetHashCode(); if (MultiAgentGroups != false) hash ^= MultiAgentGroups.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (BaseRLCapabilities != false) { output.WriteRawTag(8); output.WriteBool(BaseRLCapabilities); } if (ConcatenatedPngObservations != false) { output.WriteRawTag(16); output.WriteBool(ConcatenatedPngObservations); } if (CompressedChannelMapping != false) { output.WriteRawTag(24); output.WriteBool(CompressedChannelMapping); } if (HybridActions != false) { output.WriteRawTag(32); output.WriteBool(HybridActions); } if (TrainingAnalytics != false) { output.WriteRawTag(40); output.WriteBool(TrainingAnalytics); } if (VariableLengthObservation != false) { output.WriteRawTag(48); output.WriteBool(VariableLengthObservation); } if (MultiAgentGroups != false) { output.WriteRawTag(56); output.WriteBool(MultiAgentGroups); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (BaseRLCapabilities != false) { size += 1 + 1; } if (ConcatenatedPngObservations != false) { size += 1 + 1; } if (CompressedChannelMapping != false) { size += 1 + 1; } if (HybridActions != false) { size += 1 + 1; } if (TrainingAnalytics != false) { size += 1 + 1; } if (VariableLengthObservation != false) { size += 1 + 1; } if (MultiAgentGroups != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UnityRLCapabilitiesProto other) { if (other == null) { return; } if (other.BaseRLCapabilities != false) { BaseRLCapabilities = other.BaseRLCapabilities; } if (other.ConcatenatedPngObservations != false) { ConcatenatedPngObservations = other.ConcatenatedPngObservations; } if (other.CompressedChannelMapping != false) { CompressedChannelMapping = other.CompressedChannelMapping; } if (other.HybridActions != false) { HybridActions = other.HybridActions; } if (other.TrainingAnalytics != false) { TrainingAnalytics = other.TrainingAnalytics; } if (other.VariableLengthObservation != false) { VariableLengthObservation = other.VariableLengthObservation; } if (other.MultiAgentGroups != false) { MultiAgentGroups = other.MultiAgentGroups; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { BaseRLCapabilities = input.ReadBool(); break; } case 16: { ConcatenatedPngObservations = input.ReadBool(); break; } case 24: { CompressedChannelMapping = input.ReadBool(); break; } case 32: { HybridActions = input.ReadBool(); break; } case 40: { TrainingAnalytics = input.ReadBool(); break; } case 48: { VariableLengthObservation = input.ReadBool(); break; } case 56: { MultiAgentGroups = input.ReadBool(); break; } } } } } #endregion } #endregion Designer generated code
ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/Capabilities.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/Capabilities.cs", "repo_id": "ml-agents", "token_count": 5548 }
1,873
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: mlagents_envs/communicator_objects/training_analytics.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Unity.MLAgents.CommunicatorObjects { /// <summary>Holder for reflection information generated from mlagents_envs/communicator_objects/training_analytics.proto</summary> internal static partial class TrainingAnalyticsReflection { #region Descriptor /// <summary>File descriptor for mlagents_envs/communicator_objects/training_analytics.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TrainingAnalyticsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjttbGFnZW50c19lbnZzL2NvbW11bmljYXRvcl9vYmplY3RzL3RyYWluaW5n", "X2FuYWx5dGljcy5wcm90bxIUY29tbXVuaWNhdG9yX29iamVjdHMi7gEKHlRy", "YWluaW5nRW52aXJvbm1lbnRJbml0aWFsaXplZBIYChBtbGFnZW50c192ZXJz", "aW9uGAEgASgJEh0KFW1sYWdlbnRzX2VudnNfdmVyc2lvbhgCIAEoCRIWCg5w", "eXRob25fdmVyc2lvbhgDIAEoCRIVCg10b3JjaF92ZXJzaW9uGAQgASgJEhkK", "EXRvcmNoX2RldmljZV90eXBlGAUgASgJEhAKCG51bV9lbnZzGAYgASgFEiIK", "Gm51bV9lbnZpcm9ubWVudF9wYXJhbWV0ZXJzGAcgASgFEhMKC3J1bl9vcHRp", "b25zGAggASgJIr0DChtUcmFpbmluZ0JlaGF2aW9ySW5pdGlhbGl6ZWQSFQoN", "YmVoYXZpb3JfbmFtZRgBIAEoCRIUCgx0cmFpbmVyX3R5cGUYAiABKAkSIAoY", "ZXh0cmluc2ljX3Jld2FyZF9lbmFibGVkGAMgASgIEhsKE2dhaWxfcmV3YXJk", "X2VuYWJsZWQYBCABKAgSIAoYY3VyaW9zaXR5X3Jld2FyZF9lbmFibGVkGAUg", "ASgIEhoKEnJuZF9yZXdhcmRfZW5hYmxlZBgGIAEoCBIiChpiZWhhdmlvcmFs", "X2Nsb25pbmdfZW5hYmxlZBgHIAEoCBIZChFyZWN1cnJlbnRfZW5hYmxlZBgI", "IAEoCBIWCg52aXN1YWxfZW5jb2RlchgJIAEoCRIaChJudW1fbmV0d29ya19s", "YXllcnMYCiABKAUSIAoYbnVtX25ldHdvcmtfaGlkZGVuX3VuaXRzGAsgASgF", "EhgKEHRyYWluZXJfdGhyZWFkZWQYDCABKAgSGQoRc2VsZl9wbGF5X2VuYWJs", "ZWQYDSABKAgSGgoSY3VycmljdWx1bV9lbmFibGVkGA4gASgIEg4KBmNvbmZp", "ZxgPIAEoCUIlqgIiVW5pdHkuTUxBZ2VudHMuQ29tbXVuaWNhdG9yT2JqZWN0", "c2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Unity.MLAgents.CommunicatorObjects.TrainingEnvironmentInitialized), global::Unity.MLAgents.CommunicatorObjects.TrainingEnvironmentInitialized.Parser, new[]{ "MlagentsVersion", "MlagentsEnvsVersion", "PythonVersion", "TorchVersion", "TorchDeviceType", "NumEnvs", "NumEnvironmentParameters", "RunOptions" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Unity.MLAgents.CommunicatorObjects.TrainingBehaviorInitialized), global::Unity.MLAgents.CommunicatorObjects.TrainingBehaviorInitialized.Parser, new[]{ "BehaviorName", "TrainerType", "ExtrinsicRewardEnabled", "GailRewardEnabled", "CuriosityRewardEnabled", "RndRewardEnabled", "BehavioralCloningEnabled", "RecurrentEnabled", "VisualEncoder", "NumNetworkLayers", "NumNetworkHiddenUnits", "TrainerThreaded", "SelfPlayEnabled", "CurriculumEnabled", "Config" }, null, null, null) })); } #endregion } #region Messages internal sealed partial class TrainingEnvironmentInitialized : pb::IMessage<TrainingEnvironmentInitialized> { private static readonly pb::MessageParser<TrainingEnvironmentInitialized> _parser = new pb::MessageParser<TrainingEnvironmentInitialized>(() => new TrainingEnvironmentInitialized()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TrainingEnvironmentInitialized> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Unity.MLAgents.CommunicatorObjects.TrainingAnalyticsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrainingEnvironmentInitialized() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrainingEnvironmentInitialized(TrainingEnvironmentInitialized other) : this() { mlagentsVersion_ = other.mlagentsVersion_; mlagentsEnvsVersion_ = other.mlagentsEnvsVersion_; pythonVersion_ = other.pythonVersion_; torchVersion_ = other.torchVersion_; torchDeviceType_ = other.torchDeviceType_; numEnvs_ = other.numEnvs_; numEnvironmentParameters_ = other.numEnvironmentParameters_; runOptions_ = other.runOptions_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrainingEnvironmentInitialized Clone() { return new TrainingEnvironmentInitialized(this); } /// <summary>Field number for the "mlagents_version" field.</summary> public const int MlagentsVersionFieldNumber = 1; private string mlagentsVersion_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MlagentsVersion { get { return mlagentsVersion_; } set { mlagentsVersion_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "mlagents_envs_version" field.</summary> public const int MlagentsEnvsVersionFieldNumber = 2; private string mlagentsEnvsVersion_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MlagentsEnvsVersion { get { return mlagentsEnvsVersion_; } set { mlagentsEnvsVersion_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "python_version" field.</summary> public const int PythonVersionFieldNumber = 3; private string pythonVersion_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PythonVersion { get { return pythonVersion_; } set { pythonVersion_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "torch_version" field.</summary> public const int TorchVersionFieldNumber = 4; private string torchVersion_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TorchVersion { get { return torchVersion_; } set { torchVersion_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "torch_device_type" field.</summary> public const int TorchDeviceTypeFieldNumber = 5; private string torchDeviceType_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TorchDeviceType { get { return torchDeviceType_; } set { torchDeviceType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "num_envs" field.</summary> public const int NumEnvsFieldNumber = 6; private int numEnvs_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NumEnvs { get { return numEnvs_; } set { numEnvs_ = value; } } /// <summary>Field number for the "num_environment_parameters" field.</summary> public const int NumEnvironmentParametersFieldNumber = 7; private int numEnvironmentParameters_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NumEnvironmentParameters { get { return numEnvironmentParameters_; } set { numEnvironmentParameters_ = value; } } /// <summary>Field number for the "run_options" field.</summary> public const int RunOptionsFieldNumber = 8; private string runOptions_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string RunOptions { get { return runOptions_; } set { runOptions_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TrainingEnvironmentInitialized); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TrainingEnvironmentInitialized other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (MlagentsVersion != other.MlagentsVersion) return false; if (MlagentsEnvsVersion != other.MlagentsEnvsVersion) return false; if (PythonVersion != other.PythonVersion) return false; if (TorchVersion != other.TorchVersion) return false; if (TorchDeviceType != other.TorchDeviceType) return false; if (NumEnvs != other.NumEnvs) return false; if (NumEnvironmentParameters != other.NumEnvironmentParameters) return false; if (RunOptions != other.RunOptions) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (MlagentsVersion.Length != 0) hash ^= MlagentsVersion.GetHashCode(); if (MlagentsEnvsVersion.Length != 0) hash ^= MlagentsEnvsVersion.GetHashCode(); if (PythonVersion.Length != 0) hash ^= PythonVersion.GetHashCode(); if (TorchVersion.Length != 0) hash ^= TorchVersion.GetHashCode(); if (TorchDeviceType.Length != 0) hash ^= TorchDeviceType.GetHashCode(); if (NumEnvs != 0) hash ^= NumEnvs.GetHashCode(); if (NumEnvironmentParameters != 0) hash ^= NumEnvironmentParameters.GetHashCode(); if (RunOptions.Length != 0) hash ^= RunOptions.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (MlagentsVersion.Length != 0) { output.WriteRawTag(10); output.WriteString(MlagentsVersion); } if (MlagentsEnvsVersion.Length != 0) { output.WriteRawTag(18); output.WriteString(MlagentsEnvsVersion); } if (PythonVersion.Length != 0) { output.WriteRawTag(26); output.WriteString(PythonVersion); } if (TorchVersion.Length != 0) { output.WriteRawTag(34); output.WriteString(TorchVersion); } if (TorchDeviceType.Length != 0) { output.WriteRawTag(42); output.WriteString(TorchDeviceType); } if (NumEnvs != 0) { output.WriteRawTag(48); output.WriteInt32(NumEnvs); } if (NumEnvironmentParameters != 0) { output.WriteRawTag(56); output.WriteInt32(NumEnvironmentParameters); } if (RunOptions.Length != 0) { output.WriteRawTag(66); output.WriteString(RunOptions); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (MlagentsVersion.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MlagentsVersion); } if (MlagentsEnvsVersion.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MlagentsEnvsVersion); } if (PythonVersion.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PythonVersion); } if (TorchVersion.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TorchVersion); } if (TorchDeviceType.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TorchDeviceType); } if (NumEnvs != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumEnvs); } if (NumEnvironmentParameters != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumEnvironmentParameters); } if (RunOptions.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(RunOptions); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TrainingEnvironmentInitialized other) { if (other == null) { return; } if (other.MlagentsVersion.Length != 0) { MlagentsVersion = other.MlagentsVersion; } if (other.MlagentsEnvsVersion.Length != 0) { MlagentsEnvsVersion = other.MlagentsEnvsVersion; } if (other.PythonVersion.Length != 0) { PythonVersion = other.PythonVersion; } if (other.TorchVersion.Length != 0) { TorchVersion = other.TorchVersion; } if (other.TorchDeviceType.Length != 0) { TorchDeviceType = other.TorchDeviceType; } if (other.NumEnvs != 0) { NumEnvs = other.NumEnvs; } if (other.NumEnvironmentParameters != 0) { NumEnvironmentParameters = other.NumEnvironmentParameters; } if (other.RunOptions.Length != 0) { RunOptions = other.RunOptions; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { MlagentsVersion = input.ReadString(); break; } case 18: { MlagentsEnvsVersion = input.ReadString(); break; } case 26: { PythonVersion = input.ReadString(); break; } case 34: { TorchVersion = input.ReadString(); break; } case 42: { TorchDeviceType = input.ReadString(); break; } case 48: { NumEnvs = input.ReadInt32(); break; } case 56: { NumEnvironmentParameters = input.ReadInt32(); break; } case 66: { RunOptions = input.ReadString(); break; } } } } } internal sealed partial class TrainingBehaviorInitialized : pb::IMessage<TrainingBehaviorInitialized> { private static readonly pb::MessageParser<TrainingBehaviorInitialized> _parser = new pb::MessageParser<TrainingBehaviorInitialized>(() => new TrainingBehaviorInitialized()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TrainingBehaviorInitialized> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Unity.MLAgents.CommunicatorObjects.TrainingAnalyticsReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrainingBehaviorInitialized() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrainingBehaviorInitialized(TrainingBehaviorInitialized other) : this() { behaviorName_ = other.behaviorName_; trainerType_ = other.trainerType_; extrinsicRewardEnabled_ = other.extrinsicRewardEnabled_; gailRewardEnabled_ = other.gailRewardEnabled_; curiosityRewardEnabled_ = other.curiosityRewardEnabled_; rndRewardEnabled_ = other.rndRewardEnabled_; behavioralCloningEnabled_ = other.behavioralCloningEnabled_; recurrentEnabled_ = other.recurrentEnabled_; visualEncoder_ = other.visualEncoder_; numNetworkLayers_ = other.numNetworkLayers_; numNetworkHiddenUnits_ = other.numNetworkHiddenUnits_; trainerThreaded_ = other.trainerThreaded_; selfPlayEnabled_ = other.selfPlayEnabled_; curriculumEnabled_ = other.curriculumEnabled_; config_ = other.config_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrainingBehaviorInitialized Clone() { return new TrainingBehaviorInitialized(this); } /// <summary>Field number for the "behavior_name" field.</summary> public const int BehaviorNameFieldNumber = 1; private string behaviorName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BehaviorName { get { return behaviorName_; } set { behaviorName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "trainer_type" field.</summary> public const int TrainerTypeFieldNumber = 2; private string trainerType_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TrainerType { get { return trainerType_; } set { trainerType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "extrinsic_reward_enabled" field.</summary> public const int ExtrinsicRewardEnabledFieldNumber = 3; private bool extrinsicRewardEnabled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool ExtrinsicRewardEnabled { get { return extrinsicRewardEnabled_; } set { extrinsicRewardEnabled_ = value; } } /// <summary>Field number for the "gail_reward_enabled" field.</summary> public const int GailRewardEnabledFieldNumber = 4; private bool gailRewardEnabled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool GailRewardEnabled { get { return gailRewardEnabled_; } set { gailRewardEnabled_ = value; } } /// <summary>Field number for the "curiosity_reward_enabled" field.</summary> public const int CuriosityRewardEnabledFieldNumber = 5; private bool curiosityRewardEnabled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool CuriosityRewardEnabled { get { return curiosityRewardEnabled_; } set { curiosityRewardEnabled_ = value; } } /// <summary>Field number for the "rnd_reward_enabled" field.</summary> public const int RndRewardEnabledFieldNumber = 6; private bool rndRewardEnabled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool RndRewardEnabled { get { return rndRewardEnabled_; } set { rndRewardEnabled_ = value; } } /// <summary>Field number for the "behavioral_cloning_enabled" field.</summary> public const int BehavioralCloningEnabledFieldNumber = 7; private bool behavioralCloningEnabled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool BehavioralCloningEnabled { get { return behavioralCloningEnabled_; } set { behavioralCloningEnabled_ = value; } } /// <summary>Field number for the "recurrent_enabled" field.</summary> public const int RecurrentEnabledFieldNumber = 8; private bool recurrentEnabled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool RecurrentEnabled { get { return recurrentEnabled_; } set { recurrentEnabled_ = value; } } /// <summary>Field number for the "visual_encoder" field.</summary> public const int VisualEncoderFieldNumber = 9; private string visualEncoder_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string VisualEncoder { get { return visualEncoder_; } set { visualEncoder_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "num_network_layers" field.</summary> public const int NumNetworkLayersFieldNumber = 10; private int numNetworkLayers_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NumNetworkLayers { get { return numNetworkLayers_; } set { numNetworkLayers_ = value; } } /// <summary>Field number for the "num_network_hidden_units" field.</summary> public const int NumNetworkHiddenUnitsFieldNumber = 11; private int numNetworkHiddenUnits_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NumNetworkHiddenUnits { get { return numNetworkHiddenUnits_; } set { numNetworkHiddenUnits_ = value; } } /// <summary>Field number for the "trainer_threaded" field.</summary> public const int TrainerThreadedFieldNumber = 12; private bool trainerThreaded_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool TrainerThreaded { get { return trainerThreaded_; } set { trainerThreaded_ = value; } } /// <summary>Field number for the "self_play_enabled" field.</summary> public const int SelfPlayEnabledFieldNumber = 13; private bool selfPlayEnabled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool SelfPlayEnabled { get { return selfPlayEnabled_; } set { selfPlayEnabled_ = value; } } /// <summary>Field number for the "curriculum_enabled" field.</summary> public const int CurriculumEnabledFieldNumber = 14; private bool curriculumEnabled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool CurriculumEnabled { get { return curriculumEnabled_; } set { curriculumEnabled_ = value; } } /// <summary>Field number for the "config" field.</summary> public const int ConfigFieldNumber = 15; private string config_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Config { get { return config_; } set { config_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TrainingBehaviorInitialized); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TrainingBehaviorInitialized other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (BehaviorName != other.BehaviorName) return false; if (TrainerType != other.TrainerType) return false; if (ExtrinsicRewardEnabled != other.ExtrinsicRewardEnabled) return false; if (GailRewardEnabled != other.GailRewardEnabled) return false; if (CuriosityRewardEnabled != other.CuriosityRewardEnabled) return false; if (RndRewardEnabled != other.RndRewardEnabled) return false; if (BehavioralCloningEnabled != other.BehavioralCloningEnabled) return false; if (RecurrentEnabled != other.RecurrentEnabled) return false; if (VisualEncoder != other.VisualEncoder) return false; if (NumNetworkLayers != other.NumNetworkLayers) return false; if (NumNetworkHiddenUnits != other.NumNetworkHiddenUnits) return false; if (TrainerThreaded != other.TrainerThreaded) return false; if (SelfPlayEnabled != other.SelfPlayEnabled) return false; if (CurriculumEnabled != other.CurriculumEnabled) return false; if (Config != other.Config) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (BehaviorName.Length != 0) hash ^= BehaviorName.GetHashCode(); if (TrainerType.Length != 0) hash ^= TrainerType.GetHashCode(); if (ExtrinsicRewardEnabled != false) hash ^= ExtrinsicRewardEnabled.GetHashCode(); if (GailRewardEnabled != false) hash ^= GailRewardEnabled.GetHashCode(); if (CuriosityRewardEnabled != false) hash ^= CuriosityRewardEnabled.GetHashCode(); if (RndRewardEnabled != false) hash ^= RndRewardEnabled.GetHashCode(); if (BehavioralCloningEnabled != false) hash ^= BehavioralCloningEnabled.GetHashCode(); if (RecurrentEnabled != false) hash ^= RecurrentEnabled.GetHashCode(); if (VisualEncoder.Length != 0) hash ^= VisualEncoder.GetHashCode(); if (NumNetworkLayers != 0) hash ^= NumNetworkLayers.GetHashCode(); if (NumNetworkHiddenUnits != 0) hash ^= NumNetworkHiddenUnits.GetHashCode(); if (TrainerThreaded != false) hash ^= TrainerThreaded.GetHashCode(); if (SelfPlayEnabled != false) hash ^= SelfPlayEnabled.GetHashCode(); if (CurriculumEnabled != false) hash ^= CurriculumEnabled.GetHashCode(); if (Config.Length != 0) hash ^= Config.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (BehaviorName.Length != 0) { output.WriteRawTag(10); output.WriteString(BehaviorName); } if (TrainerType.Length != 0) { output.WriteRawTag(18); output.WriteString(TrainerType); } if (ExtrinsicRewardEnabled != false) { output.WriteRawTag(24); output.WriteBool(ExtrinsicRewardEnabled); } if (GailRewardEnabled != false) { output.WriteRawTag(32); output.WriteBool(GailRewardEnabled); } if (CuriosityRewardEnabled != false) { output.WriteRawTag(40); output.WriteBool(CuriosityRewardEnabled); } if (RndRewardEnabled != false) { output.WriteRawTag(48); output.WriteBool(RndRewardEnabled); } if (BehavioralCloningEnabled != false) { output.WriteRawTag(56); output.WriteBool(BehavioralCloningEnabled); } if (RecurrentEnabled != false) { output.WriteRawTag(64); output.WriteBool(RecurrentEnabled); } if (VisualEncoder.Length != 0) { output.WriteRawTag(74); output.WriteString(VisualEncoder); } if (NumNetworkLayers != 0) { output.WriteRawTag(80); output.WriteInt32(NumNetworkLayers); } if (NumNetworkHiddenUnits != 0) { output.WriteRawTag(88); output.WriteInt32(NumNetworkHiddenUnits); } if (TrainerThreaded != false) { output.WriteRawTag(96); output.WriteBool(TrainerThreaded); } if (SelfPlayEnabled != false) { output.WriteRawTag(104); output.WriteBool(SelfPlayEnabled); } if (CurriculumEnabled != false) { output.WriteRawTag(112); output.WriteBool(CurriculumEnabled); } if (Config.Length != 0) { output.WriteRawTag(122); output.WriteString(Config); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (BehaviorName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BehaviorName); } if (TrainerType.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TrainerType); } if (ExtrinsicRewardEnabled != false) { size += 1 + 1; } if (GailRewardEnabled != false) { size += 1 + 1; } if (CuriosityRewardEnabled != false) { size += 1 + 1; } if (RndRewardEnabled != false) { size += 1 + 1; } if (BehavioralCloningEnabled != false) { size += 1 + 1; } if (RecurrentEnabled != false) { size += 1 + 1; } if (VisualEncoder.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(VisualEncoder); } if (NumNetworkLayers != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumNetworkLayers); } if (NumNetworkHiddenUnits != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumNetworkHiddenUnits); } if (TrainerThreaded != false) { size += 1 + 1; } if (SelfPlayEnabled != false) { size += 1 + 1; } if (CurriculumEnabled != false) { size += 1 + 1; } if (Config.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Config); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TrainingBehaviorInitialized other) { if (other == null) { return; } if (other.BehaviorName.Length != 0) { BehaviorName = other.BehaviorName; } if (other.TrainerType.Length != 0) { TrainerType = other.TrainerType; } if (other.ExtrinsicRewardEnabled != false) { ExtrinsicRewardEnabled = other.ExtrinsicRewardEnabled; } if (other.GailRewardEnabled != false) { GailRewardEnabled = other.GailRewardEnabled; } if (other.CuriosityRewardEnabled != false) { CuriosityRewardEnabled = other.CuriosityRewardEnabled; } if (other.RndRewardEnabled != false) { RndRewardEnabled = other.RndRewardEnabled; } if (other.BehavioralCloningEnabled != false) { BehavioralCloningEnabled = other.BehavioralCloningEnabled; } if (other.RecurrentEnabled != false) { RecurrentEnabled = other.RecurrentEnabled; } if (other.VisualEncoder.Length != 0) { VisualEncoder = other.VisualEncoder; } if (other.NumNetworkLayers != 0) { NumNetworkLayers = other.NumNetworkLayers; } if (other.NumNetworkHiddenUnits != 0) { NumNetworkHiddenUnits = other.NumNetworkHiddenUnits; } if (other.TrainerThreaded != false) { TrainerThreaded = other.TrainerThreaded; } if (other.SelfPlayEnabled != false) { SelfPlayEnabled = other.SelfPlayEnabled; } if (other.CurriculumEnabled != false) { CurriculumEnabled = other.CurriculumEnabled; } if (other.Config.Length != 0) { Config = other.Config; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { BehaviorName = input.ReadString(); break; } case 18: { TrainerType = input.ReadString(); break; } case 24: { ExtrinsicRewardEnabled = input.ReadBool(); break; } case 32: { GailRewardEnabled = input.ReadBool(); break; } case 40: { CuriosityRewardEnabled = input.ReadBool(); break; } case 48: { RndRewardEnabled = input.ReadBool(); break; } case 56: { BehavioralCloningEnabled = input.ReadBool(); break; } case 64: { RecurrentEnabled = input.ReadBool(); break; } case 74: { VisualEncoder = input.ReadString(); break; } case 80: { NumNetworkLayers = input.ReadInt32(); break; } case 88: { NumNetworkHiddenUnits = input.ReadInt32(); break; } case 96: { TrainerThreaded = input.ReadBool(); break; } case 104: { SelfPlayEnabled = input.ReadBool(); break; } case 112: { CurriculumEnabled = input.ReadBool(); break; } case 122: { Config = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/TrainingAnalytics.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/TrainingAnalytics.cs", "repo_id": "ml-agents", "token_count": 13855 }
1,874
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: mlagents_envs/communicator_objects/unity_to_external.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Unity.MLAgents.CommunicatorObjects { /// <summary>Holder for reflection information generated from mlagents_envs/communicator_objects/unity_to_external.proto</summary> public static partial class UnityToExternalReflection { #region Descriptor /// <summary>File descriptor for mlagents_envs/communicator_objects/unity_to_external.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UnityToExternalReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjptbGFnZW50c19lbnZzL2NvbW11bmljYXRvcl9vYmplY3RzL3VuaXR5X3Rv", "X2V4dGVybmFsLnByb3RvEhRjb21tdW5pY2F0b3Jfb2JqZWN0cxo2bWxhZ2Vu", "dHNfZW52cy9jb21tdW5pY2F0b3Jfb2JqZWN0cy91bml0eV9tZXNzYWdlLnBy", "b3RvMnYKFFVuaXR5VG9FeHRlcm5hbFByb3RvEl4KCEV4Y2hhbmdlEicuY29t", "bXVuaWNhdG9yX29iamVjdHMuVW5pdHlNZXNzYWdlUHJvdG8aJy5jb21tdW5p", "Y2F0b3Jfb2JqZWN0cy5Vbml0eU1lc3NhZ2VQcm90byIAQiWqAiJVbml0eS5N", "TEFnZW50cy5Db21tdW5pY2F0b3JPYmplY3RzYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Unity.MLAgents.CommunicatorObjects.UnityMessageReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null)); } #endregion } } #endregion Designer generated code
ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/UnityToExternal.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/UnityToExternal.cs", "repo_id": "ml-agents", "token_count": 889 }
1,875
namespace Unity.MLAgents.Inference.Utils { /// <summary> /// Multinomial - Draws samples from a multinomial distribution given a (potentially unscaled) /// cumulative mass function (CMF). This means that the CMF need not "end" with probability /// mass of 1.0. For instance: [0.1, 0.2, 0.5] is a valid (unscaled). What is important is /// that it is a cumulative function, not a probability function. In other words, /// entry[i] = P(x \le i), NOT P(i - 1 \le x \lt i). /// (\le stands for less than or equal to while \lt is strictly less than). /// </summary> internal class Multinomial { readonly System.Random m_Random; /// <summary> /// Constructor. /// </summary> /// <param name="seed"> /// Seed for the random number generator used in the sampling process. /// </param> public Multinomial(int seed) { m_Random = new System.Random(seed); } /// <summary> /// Samples from the Multinomial distribution defined by the provided cumulative /// mass function. /// </summary> /// <param name="cmf"> /// Cumulative mass function, which may be unscaled. The entries in this array need /// to be monotonic (always increasing). If the CMF is scaled, then the last entry in /// the array will be 1.0. /// </param> /// <param name="branchSize">The number of possible branches, i.e. the effective size of the cmf array.</param> /// <returns>A sampled index from the CMF ranging from 0 to branchSize-1.</returns> public int Sample(float[] cmf, int branchSize) { var p = (float)m_Random.NextDouble() * cmf[branchSize - 1]; var cls = 0; while (cmf[cls] < p) { ++cls; } return cls; } /// <summary> /// Samples from the Multinomial distribution defined by the provided cumulative /// mass function. /// </summary> /// <returns>A sampled index from the CMF ranging from 0 to cmf.Length-1.</returns> public int Sample(float[] cmf) { return Sample(cmf, cmf.Length); } } }
ml-agents/com.unity.ml-agents/Runtime/Inference/Utils/Multinomial.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Inference/Utils/Multinomial.cs", "repo_id": "ml-agents", "token_count": 931 }
1,876
using System; using Unity.MLAgents.Sensors; using UnityEngine; using UnityEngine.Serialization; namespace Unity.MLAgents.Integrations.Match3 { /// <summary> /// Sensor component for a Match3 game. /// </summary> [AddComponentMenu("ML Agents/Match 3 Sensor", (int)MenuGroup.Sensors)] public class Match3SensorComponent : SensorComponent, IDisposable { [HideInInspector, SerializeField, FormerlySerializedAs("SensorName")] string m_SensorName = "Match3 Sensor"; /// <summary> /// Name of the generated Match3Sensor object. /// Note that changing this at runtime does not affect how the Agent sorts the sensors. /// </summary> public string SensorName { get => m_SensorName; set => m_SensorName = value; } [HideInInspector, SerializeField, FormerlySerializedAs("ObservationType")] Match3ObservationType m_ObservationType = Match3ObservationType.Vector; /// <summary> /// Type of observation to generate. /// </summary> public Match3ObservationType ObservationType { get => m_ObservationType; set => m_ObservationType = value; } private ISensor[] m_Sensors; /// <inheritdoc/> public override ISensor[] CreateSensors() { // Clean up any existing sensors Dispose(); var board = GetComponent<AbstractBoard>(); if (!board) { return Array.Empty<ISensor>(); } var cellSensor = Match3Sensor.CellTypeSensor(board, m_ObservationType, m_SensorName + " (cells)"); // This can be null if BoardSize.NumSpecialTypes is 0 var specialSensor = Match3Sensor.SpecialTypeSensor(board, m_ObservationType, m_SensorName + " (special)"); m_Sensors = specialSensor != null ? new ISensor[] { cellSensor, specialSensor } : new ISensor[] { cellSensor }; return m_Sensors; } /// <summary> /// Clean up the sensors created by CreateSensors(). /// </summary> public void Dispose() { if (m_Sensors != null) { for (var i = 0; i < m_Sensors.Length; i++) { ((Match3Sensor)m_Sensors[i]).Dispose(); } m_Sensors = null; } } } }
ml-agents/com.unity.ml-agents/Runtime/Integrations/Match3/Match3SensorComponent.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Integrations/Match3/Match3SensorComponent.cs", "repo_id": "ml-agents", "token_count": 1132 }
1,877
fileFormatVersion: 2 guid: 8a55e3cea7fd643109e42f5f4c9a1425 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Runtime/Policies/HeuristicPolicy.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Policies/HeuristicPolicy.cs.meta", "repo_id": "ml-agents", "token_count": 97 }
1,878
using System; namespace Unity.MLAgents.Sensors { /// <summary> /// A Sensor that allows to observe a variable number of entities. /// </summary> public class BufferSensor : ISensor, IBuiltInSensor { private string m_Name; private int m_MaxNumObs; private int m_ObsSize; float[] m_ObservationBuffer; int m_CurrentNumObservables; ObservationSpec m_ObservationSpec; /// <summary> /// Creates the BufferSensor. /// </summary> /// <param name="maxNumberObs">The maximum number of observations to be appended to this BufferSensor.</param> /// <param name="obsSize">The size of each observation appended to the BufferSensor.</param> /// <param name="name">The name of the sensor.</param> public BufferSensor(int maxNumberObs, int obsSize, string name) { m_Name = name; m_MaxNumObs = maxNumberObs; m_ObsSize = obsSize; m_ObservationBuffer = new float[m_ObsSize * m_MaxNumObs]; m_CurrentNumObservables = 0; m_ObservationSpec = ObservationSpec.VariableLength(m_MaxNumObs, m_ObsSize); } /// <inheritdoc/> public ObservationSpec GetObservationSpec() { return m_ObservationSpec; } /// <summary> /// Appends an observation to the buffer. If the buffer is full (maximum number /// of observation is reached) the observation will be ignored. the length of /// the provided observation array must be equal to the observation size of /// the buffer sensor. /// </summary> /// <param name="obs"> The float array observation</param> public void AppendObservation(float[] obs) { if (obs.Length != m_ObsSize) { throw new UnityAgentsException( "The BufferSensor was expecting an observation of size " + $"{m_ObsSize} but received {obs.Length} observations instead." ); } if (m_CurrentNumObservables >= m_MaxNumObs) { return; } for (int i = 0; i < obs.Length; i++) { m_ObservationBuffer[m_CurrentNumObservables * m_ObsSize + i] = obs[i]; } m_CurrentNumObservables++; } /// <inheritdoc/> public int Write(ObservationWriter writer) { // for (int i = 0; i < m_ObsSize * m_MaxNumObs; i++) // { // writer[i] = m_ObservationBuffer[i]; // } for (int i = 0; i < m_MaxNumObs; i++) { for (int j = 0; j < m_ObsSize; j++) { writer[i, j] = m_ObservationBuffer[i * m_ObsSize + j]; } } return m_ObsSize * m_MaxNumObs; } /// <inheritdoc/> public virtual byte[] GetCompressedObservation() { return null; } /// <inheritdoc/> public void Update() { Reset(); } /// <inheritdoc/> public void Reset() { m_CurrentNumObservables = 0; Array.Clear(m_ObservationBuffer, 0, m_ObservationBuffer.Length); } /// <inheritdoc/> public CompressionSpec GetCompressionSpec() { return CompressionSpec.Default(); } /// <inheritdoc/> public string GetName() { return m_Name; } /// <inheritdoc/> public BuiltInSensorType GetBuiltInSensorType() { return BuiltInSensorType.BufferSensor; } } }
ml-agents/com.unity.ml-agents/Runtime/Sensors/BufferSensor.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/BufferSensor.cs", "repo_id": "ml-agents", "token_count": 1832 }
1,879
using System; using UnityEngine; namespace Unity.MLAgents.Sensors { /// <summary> /// An interface for GridSensor perception that defines the grid cells and collider detecting strategies. /// </summary> internal interface IGridPerception { bool RotateWithAgent { get; set; } LayerMask ColliderMask { get; set; } /// <summary>Converts the index of the cell to the 3D point (y is zero) relative to grid center</summary> /// <returns>Vector3 of the position of the center of the cell relative to grid center</returns> /// <param name="cellIndex">The index of the cell</param> Vector3 GetCellLocalPosition(int cellIndex); /// <summary> /// Converts the index of the cell to the 3D point (y is zero) in world space /// based on the result from GetCellLocalPosition() /// </summary> /// <returns>Vector3 of the position of the center of the cell in world space</returns> /// <param name="cellIndex">The index of the cell</param> Vector3 GetCellGlobalPosition(int cellIndex); Quaternion GetGridRotation(); /// <summary> /// Perceive the latest grid status. Detect colliders for each cell, parse the collider arrays, /// then trigger registered sensors to encode and update with the new grid status. /// </summary> void Perceive(); /// <summary> /// Same as Perceive(), but only load data for debug gizmo. /// </summary> void UpdateGizmo(); /// <summary> /// Register a sensor to this GridPerception to receive the grid perception results. /// When the GridPerception perceive a new observation, registered sensors will be triggered /// to encode the new observation and update its data. /// </summary> void RegisterSensor(GridSensorBase sensor); /// <summary> /// Register an internal debug sensor. /// Debug sensors will only be triggered when drawing debug gizmos. /// </summary> void RegisterDebugSensor(GridSensorBase debugSensor); } }
ml-agents/com.unity.ml-agents/Runtime/Sensors/IGridPerception.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/IGridPerception.cs", "repo_id": "ml-agents", "token_count": 812 }
1,880
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Serialization; namespace Unity.MLAgents.Sensors { /// <summary> /// A base class to support sensor components for raycast-based sensors. /// </summary> public abstract class RayPerceptionSensorComponentBase : SensorComponent { [HideInInspector, SerializeField, FormerlySerializedAs("sensorName")] string m_SensorName = "RayPerceptionSensor"; /// <summary> /// The name of the Sensor that this component wraps. /// Note that changing this at runtime does not affect how the Agent sorts the sensors. /// </summary> public string SensorName { get { return m_SensorName; } set { m_SensorName = value; } } [SerializeField, FormerlySerializedAs("detectableTags")] [Tooltip("List of tags in the scene to compare against.")] List<string> m_DetectableTags; /// <summary> /// List of tags in the scene to compare against. /// Note that this should not be changed at runtime. /// </summary> public List<string> DetectableTags { get { return m_DetectableTags; } set { m_DetectableTags = value; } } [HideInInspector, SerializeField, FormerlySerializedAs("raysPerDirection")] [Range(0, 50)] [Tooltip("Number of rays to the left and right of center.")] int m_RaysPerDirection = 3; /// <summary> /// Number of rays to the left and right of center. /// Note that this should not be changed at runtime. /// </summary> public int RaysPerDirection { get { return m_RaysPerDirection; } // Note: can't change at runtime set { m_RaysPerDirection = value; } } [HideInInspector, SerializeField, FormerlySerializedAs("maxRayDegrees")] [Range(0, 180)] [Tooltip("Cone size for rays. Using 90 degrees will cast rays to the left and right. " + "Greater than 90 degrees will go backwards.")] float m_MaxRayDegrees = 70; /// <summary> /// Cone size for rays. Using 90 degrees will cast rays to the left and right. /// Greater than 90 degrees will go backwards. /// </summary> public float MaxRayDegrees { get => m_MaxRayDegrees; set { m_MaxRayDegrees = value; UpdateSensor(); } } [HideInInspector, SerializeField, FormerlySerializedAs("sphereCastRadius")] [Range(0f, 10f)] [Tooltip("Radius of sphere to cast. Set to zero for raycasts.")] float m_SphereCastRadius = 0.5f; /// <summary> /// Radius of sphere to cast. Set to zero for raycasts. /// </summary> public float SphereCastRadius { get => m_SphereCastRadius; set { m_SphereCastRadius = value; UpdateSensor(); } } [HideInInspector, SerializeField, FormerlySerializedAs("rayLength")] [Range(1, 1000)] [Tooltip("Length of the rays to cast.")] float m_RayLength = 20f; /// <summary> /// Length of the rays to cast. /// </summary> public float RayLength { get => m_RayLength; set { m_RayLength = value; UpdateSensor(); } } // The value of the default layers. const int k_PhysicsDefaultLayers = -5; [HideInInspector, SerializeField, FormerlySerializedAs("rayLayerMask")] [Tooltip("Controls which layers the rays can hit.")] LayerMask m_RayLayerMask = k_PhysicsDefaultLayers; /// <summary> /// Controls which layers the rays can hit. /// </summary> public LayerMask RayLayerMask { get => m_RayLayerMask; set { m_RayLayerMask = value; UpdateSensor(); } } [HideInInspector, SerializeField, FormerlySerializedAs("observationStacks")] [Range(1, 50)] [Tooltip("Number of raycast results that will be stacked before being fed to the neural network.")] int m_ObservationStacks = 1; /// <summary> /// Whether to stack previous observations. Using 1 means no previous observations. /// Note that changing this after the sensor is created has no effect. /// </summary> public int ObservationStacks { get { return m_ObservationStacks; } set { m_ObservationStacks = value; } } [HideInInspector, SerializeField] [Tooltip("Disable to provide the rays in left to right order. Warning: Alternating order will be deprecated, disable it to ensure compatibility with future versions of ML-Agents.")] public bool m_AlternatingRayOrder = true; /// <summary> /// Determines how the rays are ordered. By default the ordering is as follows: middle ray is first; /// then alternates outward adding rays to the left and right. If set to false, then the rays are /// ordered from left to right (viewed from above) which is more amenable to processing with /// conv nets. /// This property will be deprecated with the next major version update and the left to right ordering /// will be used thereafter. /// </summary> public bool AlternatingRayOrder { get { return m_AlternatingRayOrder; } set { m_AlternatingRayOrder = value; } } [HideInInspector, SerializeField] [Tooltip("Enable to use batched raycasts and the jobs system.")] public bool m_UseBatchedRaycasts = false; /// <summary> /// Determines whether to use batched raycasts and the jobs system. Default = false. /// </summary> public bool UseBatchedRaycasts { get { return m_UseBatchedRaycasts; } set { m_UseBatchedRaycasts = value; } } /// <summary> /// Color to code a ray that hits another object. /// </summary> [HideInInspector] [SerializeField] [Header("Debug Gizmos", order = 999)] internal Color rayHitColor = Color.red; /// <summary> /// Color to code a ray that avoid or misses all other objects. /// </summary> [HideInInspector] [SerializeField] internal Color rayMissColor = Color.white; [NonSerialized] RayPerceptionSensor m_RaySensor; /// <summary> /// Get the RayPerceptionSensor that was created. /// </summary> public RayPerceptionSensor RaySensor { get => m_RaySensor; } /// <summary> /// Returns the <see cref="RayPerceptionCastType"/> for the associated raycast sensor. /// </summary> /// <returns></returns> public abstract RayPerceptionCastType GetCastType(); /// <summary> /// Returns the amount that the ray start is offset up or down by. /// </summary> /// <returns></returns> public virtual float GetStartVerticalOffset() { return 0f; } /// <summary> /// Returns the amount that the ray end is offset up or down by. /// </summary> /// <returns></returns> public virtual float GetEndVerticalOffset() { return 0f; } /// <summary> /// Returns an initialized raycast sensor. /// </summary> /// <returns></returns> public override ISensor[] CreateSensors() { var rayPerceptionInput = GetRayPerceptionInput(); m_RaySensor = new RayPerceptionSensor(m_SensorName, rayPerceptionInput); if (ObservationStacks != 1) { var stackingSensor = new StackingSensor(m_RaySensor, ObservationStacks); return new ISensor[] { stackingSensor }; } return new ISensor[] { m_RaySensor }; } /// <summary> /// Returns the specific ray angles given the number of rays per direction and the /// cone size for the rays. /// </summary> /// <param name="raysPerDirection">Number of rays to the left and right of center.</param> /// <param name="maxRayDegrees"> /// Cone size for rays. Using 90 degrees will cast rays to the left and right. /// Greater than 90 degrees will go backwards. /// Orders the rays starting with the centermost and alternating to the left and right. /// Should be deprecated with a future major version release (doing so will break existing /// models). /// </param> /// <returns></returns> internal static float[] GetRayAnglesAlternating(int raysPerDirection, float maxRayDegrees) { // Example: // { 90, 90 - delta, 90 + delta, 90 - 2*delta, 90 + 2*delta } var anglesOut = new float[2 * raysPerDirection + 1]; var delta = maxRayDegrees / raysPerDirection; anglesOut[0] = 90f; for (var i = 0; i < raysPerDirection; i++) { anglesOut[2 * i + 1] = 90 - (i + 1) * delta; anglesOut[2 * i + 2] = 90 + (i + 1) * delta; } return anglesOut; } /// <summary> /// Returns the specific ray angles given the number of rays per direction and the /// cone size for the rays. /// </summary> /// <param name="raysPerDirection">Number of rays to the left and right of center.</param> /// <param name="maxRayDegrees"> /// Cone size for rays. Using 90 degrees will cast rays to the left and right. /// Greater than 90 degrees will go backwards. /// Orders the rays from the left-most to the right-most which makes using a convolution /// in the model easier. /// </param> /// <returns></returns> internal static float[] GetRayAngles(int raysPerDirection, float maxRayDegrees) { // Example: // { 90 - 3*delta, 90 - 2*delta, ..., 90, 90 + delta, ..., 90 + 3*delta } var anglesOut = new float[2 * raysPerDirection + 1]; var delta = maxRayDegrees / raysPerDirection; for (var i = 0; i < 2 * raysPerDirection + 1; i++) { anglesOut[i] = 90 + (i - raysPerDirection) * delta; } return anglesOut; } /// <summary> /// Get the RayPerceptionInput that is used by the <see cref="RayPerceptionSensor"/>. /// </summary> /// <returns></returns> public RayPerceptionInput GetRayPerceptionInput() { var rayAngles = m_AlternatingRayOrder ? GetRayAnglesAlternating(RaysPerDirection, MaxRayDegrees) : GetRayAngles(RaysPerDirection, MaxRayDegrees); var rayPerceptionInput = new RayPerceptionInput(); rayPerceptionInput.RayLength = RayLength; rayPerceptionInput.DetectableTags = DetectableTags; rayPerceptionInput.Angles = rayAngles; rayPerceptionInput.StartOffset = GetStartVerticalOffset(); rayPerceptionInput.EndOffset = GetEndVerticalOffset(); rayPerceptionInput.CastRadius = SphereCastRadius; rayPerceptionInput.Transform = transform; rayPerceptionInput.CastType = GetCastType(); rayPerceptionInput.LayerMask = RayLayerMask; rayPerceptionInput.UseBatchedRaycasts = UseBatchedRaycasts; return rayPerceptionInput; } internal void UpdateSensor() { if (m_RaySensor != null) { var rayInput = GetRayPerceptionInput(); m_RaySensor.SetRayPerceptionInput(rayInput); } } internal int SensorObservationAge() { if (m_RaySensor != null) { return Time.frameCount - m_RaySensor.DebugLastFrameCount; } return 0; } void OnDrawGizmosSelected() { if (m_RaySensor?.RayPerceptionOutput?.RayOutputs != null) { // If we have cached debug info from the sensor, draw that. // Draw "old" observations in a lighter color. // Since the agent may not step every frame, this helps de-emphasize "stale" hit information. var alpha = Mathf.Pow(.5f, SensorObservationAge()); foreach (var rayInfo in m_RaySensor.RayPerceptionOutput.RayOutputs) { DrawRaycastGizmos(rayInfo, alpha); } } else { var rayInput = GetRayPerceptionInput(); // We don't actually need the tags here, since they don't affect the display of the rays. // Additionally, the user might be in the middle of typing the tag name when this is called, // and there's no way to turn off the "Tag ... is not defined" error logs. // So just don't use any tags here. rayInput.DetectableTags = null; if (m_UseBatchedRaycasts && rayInput.CastType == RayPerceptionCastType.Cast3D) { // TODO add call to PerceiveBatchedRays() var rayOutputs = new RayPerceptionOutput.RayOutput[rayInput.Angles.Count]; RayPerceptionSensor.PerceiveBatchedRays(ref rayOutputs, rayInput); for (var rayIndex = 0; rayIndex < rayInput.Angles.Count; rayIndex++) { DrawRaycastGizmos(rayOutputs[rayIndex]); } } else { for (var rayIndex = 0; rayIndex < rayInput.Angles.Count; rayIndex++) { var rayOutput = RayPerceptionSensor.PerceiveSingleRay(rayInput, rayIndex); DrawRaycastGizmos(rayOutput); } } } } /// <summary> /// Draw the debug information from the sensor (if available). /// </summary> void DrawRaycastGizmos(RayPerceptionOutput.RayOutput rayOutput, float alpha = 1.0f) { var startPositionWorld = rayOutput.StartPositionWorld; var endPositionWorld = rayOutput.EndPositionWorld; var rayDirection = endPositionWorld - startPositionWorld; rayDirection *= rayOutput.HitFraction; // hit fraction ^2 will shift "far" hits closer to the hit color var lerpT = rayOutput.HitFraction * rayOutput.HitFraction; var color = Color.Lerp(rayHitColor, rayMissColor, lerpT); color.a *= alpha; Gizmos.color = color; Gizmos.DrawRay(startPositionWorld, rayDirection); // Draw the hit point as a sphere. If using rays to cast (0 radius), use a small sphere. if (rayOutput.HasHit) { var hitRadius = Mathf.Max(rayOutput.ScaledCastRadius, .05f); Gizmos.DrawWireSphere(startPositionWorld + rayDirection, hitRadius); } } } }
ml-agents/com.unity.ml-agents/Runtime/Sensors/RayPerceptionSensorComponentBase.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/RayPerceptionSensorComponentBase.cs", "repo_id": "ml-agents", "token_count": 6771 }
1,881
fileFormatVersion: 2 guid: 8b7a6e88d47d4438ad67e1862566462c timeCreated: 1572299581
ml-agents/com.unity.ml-agents/Runtime/Sensors/StackingSensor.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/StackingSensor.cs.meta", "repo_id": "ml-agents", "token_count": 40 }
1,882
using System.Collections.Generic; using System; namespace Unity.MLAgents.SideChannels { /// <summary> /// Side channel for managing raw bytes of data. It is up to the clients of this side channel /// to interpret the messages. /// </summary> public class RawBytesChannel : SideChannel { List<byte[]> m_MessagesReceived = new List<byte[]>(); /// <summary> /// RawBytesChannel provides a way to exchange raw byte arrays between Unity and Python. /// </summary> /// <param name="channelId"> The identifier for the RawBytesChannel. Must be /// the same on Python and Unity.</param> public RawBytesChannel(Guid channelId) { ChannelId = channelId; } /// <inheritdoc/> protected override void OnMessageReceived(IncomingMessage msg) { m_MessagesReceived.Add(msg.GetRawBytes()); } /// <summary> /// Sends the byte array message to the Python side channel. The message will be sent /// alongside the simulation step. /// </summary> /// <param name="data"> The byte array of data to send to Python.</param> public void SendRawBytes(byte[] data) { using (var msg = new OutgoingMessage()) { msg.SetRawBytes(data); QueueMessageToSend(msg); } } /// <summary> /// Gets the messages that were sent by python since the last call to /// GetAndClearReceivedMessages. /// </summary> /// <returns> a list of byte array messages that Python has sent.</returns> public IList<byte[]> GetAndClearReceivedMessages() { var result = new List<byte[]>(); result.AddRange(m_MessagesReceived); m_MessagesReceived.Clear(); return result; } /// <summary> /// Gets the messages that were sent by python since the last call to /// GetAndClearReceivedMessages. Note that the messages received will not /// be cleared with a call to GetReceivedMessages. /// </summary> /// <returns> a list of byte array messages that Python has sent.</returns> public IList<byte[]> GetReceivedMessages() { var result = new List<byte[]>(); result.AddRange(m_MessagesReceived); return result; } } }
ml-agents/com.unity.ml-agents/Runtime/SideChannels/RawBytesChannel.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/SideChannels/RawBytesChannel.cs", "repo_id": "ml-agents", "token_count": 1011 }
1,883
{ "name": "Unity.ML-Agents", "rootNamespace": "", "references": [ "Unity.ML-Agents.CommunicatorObjects", "Unity.Mathematics", "Unity.Sentis" ], "includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": false, "overrideReferences": true, "precompiledReferences": [ "System.IO.Abstractions.dll", "Grpc.Core.dll", "Google.Protobuf_Packed.dll" ], "autoReferenced": true, "defineConstraints": [], "versionDefines": [ { "name": "com.unity.modules.unityanalytics", "expression": "1.0.0", "define": "MLA_UNITY_ANALYTICS_MODULE" }, { "name": "com.unity.modules.physics", "expression": "1.0.0", "define": "MLA_UNITY_PHYSICS_MODULE" }, { "name": "com.unity.modules.physics2d", "expression": "1.0.0", "define": "MLA_UNITY_PHYSICS2D_MODULE" } ], "noEngineReferences": false }
ml-agents/com.unity.ml-agents/Runtime/Unity.ML-Agents.asmdef/0
{ "file_path": "ml-agents/com.unity.ml-agents/Runtime/Unity.ML-Agents.asmdef", "repo_id": "ml-agents", "token_count": 547 }
1,884
fileFormatVersion: 2 guid: c7e705f7d549e43c6be18ae809cd6f54 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Tests/Editor/Actuators.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Actuators.meta", "repo_id": "ml-agents", "token_count": 70 }
1,885
using System; using System.Collections.Generic; using NUnit.Framework; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; using Unity.MLAgents.Analytics; using Unity.MLAgents.Policies; using UnityEditor; namespace Unity.MLAgents.Tests.Analytics { [TestFixture] public class TrainingAnalyticsTests { [TestCase("foo?team=42", ExpectedResult = "foo")] [TestCase("foo", ExpectedResult = "foo")] [TestCase("foo?bar?team=1337", ExpectedResult = "foo?bar")] public string TestParseBehaviorName(string fullyQualifiedBehaviorName) { return TrainingAnalytics.ParseBehaviorName(fullyQualifiedBehaviorName); } [Test] public void TestRemotePolicyEvent() { var behaviorName = "testBehavior"; var sensor1 = new Test3DSensor("SensorA", 21, 20, 3); var sensor2 = new Test3DSensor("SensorB", 20, 22, 3); var sensors = new List<ISensor> { sensor1, sensor2 }; var actionSpec = ActionSpec.MakeContinuous(2); var vectorActuator = new VectorActuator(null, actionSpec, "test'"); var actuators = new IActuator[] { vectorActuator }; var remotePolicyEvent = TrainingAnalytics.GetEventForRemotePolicy(behaviorName, sensors, actionSpec, actuators); // The behavior name should be hashed, not pass-through. Assert.AreNotEqual(behaviorName, remotePolicyEvent.BehaviorName); Assert.AreEqual(2, remotePolicyEvent.ObservationSpecs.Count); Assert.AreEqual(3, remotePolicyEvent.ObservationSpecs[0].DimensionInfos.Length); Assert.AreEqual(20, remotePolicyEvent.ObservationSpecs[0].DimensionInfos[1].Size); Assert.AreEqual(0, remotePolicyEvent.ObservationSpecs[0].ObservationType); Assert.AreEqual("None", remotePolicyEvent.ObservationSpecs[0].CompressionType); Assert.AreEqual(Test3DSensor.k_BuiltInSensorType, remotePolicyEvent.ObservationSpecs[0].BuiltInSensorType); Assert.AreEqual(2, remotePolicyEvent.ActionSpec.NumContinuousActions); Assert.AreEqual(0, remotePolicyEvent.ActionSpec.NumDiscreteActions); Assert.AreEqual(2, remotePolicyEvent.ActuatorInfos[0].NumContinuousActions); Assert.AreEqual(0, remotePolicyEvent.ActuatorInfos[0].NumDiscreteActions); } [Test] public void TestRemotePolicy() { if (Academy.IsInitialized) { Academy.Instance.Dispose(); } using (new AnalyticsUtils.DisableAnalyticsSending()) { var actionSpec = ActionSpec.MakeContinuous(3); var policy = new RemotePolicy(actionSpec, Array.Empty<IActuator>(), "TestBehavior?team=42"); policy.RequestDecision(new AgentInfo(), new List<ISensor>()); } Academy.Instance.Dispose(); } [TestCase("a name we expect to hash", ExpectedResult = "d084a8b6da6a6a1c097cdc9ffea95e1546da4647352113ed77cbe7b4192e6d73")] [TestCase("another_name", ExpectedResult = "0b74613c872e79aba11e06eda3538f2b646eb2b459e75087829ea500bd703d0b")] [TestCase("0b74613c872e79aba11e06eda3538f2b646eb2b459e75087829ea500bd703d0b", ExpectedResult = "0b74613c872e79aba11e06eda3538f2b646eb2b459e75087829ea500bd703d0b")] public string TestTrainingBehaviorInitialized(string stringToMaybeHash) { var tbiEvent = new TrainingBehaviorInitializedEvent(); tbiEvent.BehaviorName = stringToMaybeHash; tbiEvent.Config = "{}"; var sanitizedEvent = TrainingAnalytics.SanitizeTrainingBehaviorInitializedEvent(tbiEvent); return sanitizedEvent.BehaviorName; } [Test] public void TestEnableAnalytics() { #if UNITY_EDITOR && MLA_UNITY_ANALYTICS_MODULE Assert.IsTrue(EditorAnalytics.enabled == TrainingAnalytics.EnableAnalytics()); #else Assert.IsFalse(TrainingAnalytics.EnableAnalytics()); #endif } } }
ml-agents/com.unity.ml-agents/Tests/Editor/Analytics/TrainingAnalyticsTest.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Analytics/TrainingAnalyticsTest.cs", "repo_id": "ml-agents", "token_count": 1794 }
1,886
fileFormatVersion: 2 guid: 7b8fc3bc69d3a4cd9a66ad334f944fb2 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/Tests/Editor/Inference.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Inference.meta", "repo_id": "ml-agents", "token_count": 72 }
1,887
fileFormatVersion: 2 guid: 77b0212dde404f7c8ce9aac13bd550b8 timeCreated: 1601332716
ml-agents/com.unity.ml-agents/Tests/Editor/Integrations/Match3.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Integrations/Match3.meta", "repo_id": "ml-agents", "token_count": 41 }
1,888
fileFormatVersion: 2 guid: 27ff1979bd5e4b8ebeb4d98f414a5090 timeCreated: 1615863866
ml-agents/com.unity.ml-agents/Tests/Editor/ObservationSpecTests.cs.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/ObservationSpecTests.cs.meta", "repo_id": "ml-agents", "token_count": 41 }
1,889
using NUnit.Framework; using UnityEngine; using UnityEditor; using Unity.MLAgents.Policies; namespace Unity.MLAgents.Tests { [TestFixture] public class TestSerialization { const string k_oldPrefabPath = "Packages/com.unity.ml-agents/Tests/Editor/TestModels/old_serialized_agent.prefab"; const int k_numVecObs = 212; const int k_numContinuousActions = 39; [Test] public void TestDeserialization() { var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(k_oldPrefabPath); var agent = GameObject.Instantiate(prefab); var bp = agent.GetComponent<BehaviorParameters>(); Assert.AreEqual(bp.BrainParameters.ActionSpec.NumContinuousActions, k_numContinuousActions); Assert.AreEqual(bp.BrainParameters.VectorObservationSize, k_numVecObs); } } }
ml-agents/com.unity.ml-agents/Tests/Editor/Serialization/TestLoadOldPrefab.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Serialization/TestLoadOldPrefab.cs", "repo_id": "ml-agents", "token_count": 366 }
1,890
using System; using System.Linq; using System.Text; using NUnit.Framework; using Google.Protobuf; using Unity.MLAgents.Analytics; using Unity.MLAgents.SideChannels; using Unity.MLAgents.CommunicatorObjects; namespace Unity.MLAgents.Tests { /// <summary> /// These tests send messages through the event handling code. /// There's no output to test, so just make sure there are no exceptions /// (and get the code coverage above the minimum). /// </summary> public class TrainingAnalyticsSideChannelTests { [Test] public void TestTrainingEnvironmentReceived() { var anyMsg = Google.Protobuf.WellKnownTypes.Any.Pack(new TrainingEnvironmentInitialized()); var anyMsgBytes = anyMsg.ToByteArray(); var sideChannel = new TrainingAnalyticsSideChannel(); using (new AnalyticsUtils.DisableAnalyticsSending()) { sideChannel.ProcessMessage(anyMsgBytes); } } [Test] public void TestTrainingBehaviorReceived() { var anyMsg = Google.Protobuf.WellKnownTypes.Any.Pack(new TrainingBehaviorInitialized()); var anyMsgBytes = anyMsg.ToByteArray(); var sideChannel = new TrainingAnalyticsSideChannel(); using (new AnalyticsUtils.DisableAnalyticsSending()) { sideChannel.ProcessMessage(anyMsgBytes); } } [Test] public void TestInvalidProtobufMessage() { // Test an invalid (non-protobuf) message. This should silently ignore the data. var badBytes = Encoding.ASCII.GetBytes("Lorem ipsum"); var sideChannel = new TrainingAnalyticsSideChannel(); using (new AnalyticsUtils.DisableAnalyticsSending()) { sideChannel.ProcessMessage(badBytes); } // Test an almost-valid message. This should silently ignore the data. var anyMsg = Google.Protobuf.WellKnownTypes.Any.Pack(new TrainingBehaviorInitialized()); var anyMsgBytes = anyMsg.ToByteArray(); var truncatedMessage = new ArraySegment<byte>(anyMsgBytes, 0, anyMsgBytes.Length - 1).ToArray(); using (new AnalyticsUtils.DisableAnalyticsSending()) { sideChannel.ProcessMessage(truncatedMessage); } } } }
ml-agents/com.unity.ml-agents/Tests/Editor/TrainingAnalyticsSideChannelTests.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/TrainingAnalyticsSideChannelTests.cs", "repo_id": "ml-agents", "token_count": 998 }
1,891
using System; using NUnit.Framework; using UnityEngine; using Unity.MLAgents.Sensors; namespace Unity.MLAgents.Tests { [TestFixture] public class CameraSensorTest { [Test] public void TestCameraSensor() { foreach (var grayscale in new[] { true, false }) { foreach (SensorCompressionType compression in Enum.GetValues(typeof(SensorCompressionType))) { var width = 24; var height = 16; var camera = Camera.main; var c = new GameObject(); if (ReferenceEquals(null, camera)) { camera = c.AddComponent<Camera>(); } var sensor = new CameraSensor(camera, width, height, grayscale, "TestCameraSensor", compression); var obsWriter = new ObservationWriter(); var obs = sensor.GetObservationProto(obsWriter); Assert.AreEqual((int)compression, (int)obs.CompressionType); var expectedShape = new[] { grayscale ? 1 : 3, height, width }; Assert.AreEqual(expectedShape, obs.Shape); UnityEngine.Object.DestroyImmediate(c); } } } [Test] public void TestObservationType() { var width = 24; var height = 16; var camera = Camera.main; var sensor = new CameraSensor(camera, width, height, true, "TestCameraSensor", SensorCompressionType.None); var spec = sensor.GetObservationSpec(); Assert.AreEqual((int)spec.ObservationType, (int)ObservationType.Default); sensor = new CameraSensor(camera, width, height, true, "TestCameraSensor", SensorCompressionType.None, ObservationType.Default); spec = sensor.GetObservationSpec(); Assert.AreEqual((int)spec.ObservationType, (int)ObservationType.Default); sensor = new CameraSensor(camera, width, height, true, "TestCameraSensor", SensorCompressionType.None, ObservationType.GoalSignal); spec = sensor.GetObservationSpec(); Assert.AreEqual((int)spec.ObservationType, (int)ObservationType.GoalSignal); } } }
ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/CameraSensorTest.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/CameraSensorTest.cs", "repo_id": "ml-agents", "token_count": 1104 }
1,892
using System; using NUnit.Framework; using UnityEngine; using Unity.MLAgents.Sensors; namespace Unity.MLAgents.Tests { [TestFixture] public class RenderTextureSensorComponentTest { [Test] public void TestRenderTextureSensorComponent() { foreach (var grayscale in new[] { true, false }) { foreach (SensorCompressionType compression in Enum.GetValues(typeof(SensorCompressionType))) { var width = 24; var height = 16; var texture = new RenderTexture(width, height, 0); var agentGameObj = new GameObject("agent"); var renderTexComponent = agentGameObj.AddComponent<RenderTextureSensorComponent>(); renderTexComponent.RenderTexture = texture; renderTexComponent.Grayscale = grayscale; renderTexComponent.CompressionType = compression; var expectedShape = new InplaceArray<int>(grayscale ? 1 : 3, height, width); var sensor = renderTexComponent.CreateSensors()[0]; Assert.AreEqual(expectedShape, sensor.GetObservationSpec().Shape); Assert.AreEqual(typeof(RenderTextureSensor), sensor.GetType()); } } } } }
ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/RenderTextureSensorComponentTests.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/RenderTextureSensorComponentTests.cs", "repo_id": "ml-agents", "token_count": 645 }
1,893
using NUnit.Framework; using UnityEngine; using Unity.MLAgents.Sensors; namespace Unity.MLAgents.Tests { public class VectorSensorTests { [Test] public void TestCtor() { ISensor sensor = new VectorSensor(4); Assert.AreEqual("VectorSensor_size4", sensor.GetName()); sensor = new VectorSensor(3, "test_sensor"); Assert.AreEqual("test_sensor", sensor.GetName()); } [Test] public void TestWrite() { var sensor = new VectorSensor(4); sensor.AddObservation(1f); sensor.AddObservation(2f); sensor.AddObservation(3f); sensor.AddObservation(4f); SensorTestHelper.CompareObservation(sensor, new[] { 1f, 2f, 3f, 4f }); // Check that if we don't call Update(), the same observations are produced SensorTestHelper.CompareObservation(sensor, new[] { 1f, 2f, 3f, 4f }); // Check that Update() clears the data sensor.Update(); SensorTestHelper.CompareObservation(sensor, new[] { 0f, 0f, 0f, 0f }); } [Test] public void TestAddObservationFloat() { var sensor = new VectorSensor(1); sensor.AddObservation(1.2f); SensorTestHelper.CompareObservation(sensor, new[] { 1.2f }); } [Test] public void TestObservationType() { var sensor = new VectorSensor(1); var spec = sensor.GetObservationSpec(); Assert.AreEqual((int)spec.ObservationType, (int)ObservationType.Default); sensor = new VectorSensor(1, observationType: ObservationType.Default); spec = sensor.GetObservationSpec(); Assert.AreEqual((int)spec.ObservationType, (int)ObservationType.Default); sensor = new VectorSensor(1, observationType: ObservationType.GoalSignal); spec = sensor.GetObservationSpec(); Assert.AreEqual((int)spec.ObservationType, (int)ObservationType.GoalSignal); } [Test] public void TestAddObservationInt() { var sensor = new VectorSensor(1); sensor.AddObservation(42); SensorTestHelper.CompareObservation(sensor, new[] { 42f }); } [Test] public void TestAddObservationVec() { var sensor = new VectorSensor(3); sensor.AddObservation(new Vector3(1, 2, 3)); SensorTestHelper.CompareObservation(sensor, new[] { 1f, 2f, 3f }); sensor = new VectorSensor(2); sensor.AddObservation(new Vector2(4, 5)); SensorTestHelper.CompareObservation(sensor, new[] { 4f, 5f }); } [Test] public void TestAddObservationQuaternion() { var sensor = new VectorSensor(4); sensor.AddObservation(Quaternion.identity); SensorTestHelper.CompareObservation(sensor, new[] { 0f, 0f, 0f, 1f }); } [Test] public void TestWriteEnumerable() { var sensor = new VectorSensor(4); sensor.AddObservation(new[] { 1f, 2f, 3f, 4f }); SensorTestHelper.CompareObservation(sensor, new[] { 1f, 2f, 3f, 4f }); } [Test] public void TestAddObservationBool() { var sensor = new VectorSensor(1); sensor.AddObservation(true); SensorTestHelper.CompareObservation(sensor, new[] { 1f }); } [Test] public void TestAddObservationOneHot() { var sensor = new VectorSensor(4); sensor.AddOneHotObservation(2, 4); SensorTestHelper.CompareObservation(sensor, new[] { 0f, 0f, 1f, 0f }); } [Test] public void TestWriteTooMany() { var sensor = new VectorSensor(2); sensor.AddObservation(new[] { 1f, 2f, 3f, 4f }); SensorTestHelper.CompareObservation(sensor, new[] { 1f, 2f }); } [Test] public void TestWriteNotEnough() { var sensor = new VectorSensor(4); sensor.AddObservation(new[] { 1f, 2f }); // Make sure extra zeros are added SensorTestHelper.CompareObservation(sensor, new[] { 1f, 2f, 0f, 0f }); } } }
ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/VectorSensorTests.cs/0
{ "file_path": "ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/VectorSensorTests.cs", "repo_id": "ml-agents", "token_count": 2069 }
1,894
fileFormatVersion: 2 guid: e13b73fbfc8e74e4d87af46bf55d7df6 TextScriptImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ml-agents/com.unity.ml-agents/package.json.meta/0
{ "file_path": "ml-agents/com.unity.ml-agents/package.json.meta", "repo_id": "ml-agents", "token_count": 67 }
1,895
behaviors: Hallway: trainer_type: ppo hyperparameters: batch_size: 128 buffer_size: 1024 learning_rate: 0.0003 beta: 0.03 epsilon: 0.2 lambd: 0.95 num_epoch: 3 learning_rate_schedule: linear network_settings: normalize: false hidden_units: 128 num_layers: 2 vis_encode_type: simple memory: sequence_length: 64 memory_size: 128 reward_signals: extrinsic: gamma: 0.99 strength: 1.0 keep_checkpoints: 5 max_steps: 10000000 time_horizon: 64 summary_freq: 10000
ml-agents/config/ppo/Hallway.yaml/0
{ "file_path": "ml-agents/config/ppo/Hallway.yaml", "repo_id": "ml-agents", "token_count": 300 }
1,896
behaviors: GridFoodCollector: trainer_type: sac hyperparameters: learning_rate: 0.0003 learning_rate_schedule: constant batch_size: 256 buffer_size: 2048 buffer_init_steps: 0 tau: 0.005 steps_per_update: 10.0 save_replay_buffer: false init_entcoef: 0.05 reward_signal_steps_per_update: 10.0 network_settings: normalize: false hidden_units: 256 num_layers: 1 vis_encode_type: simple reward_signals: extrinsic: gamma: 0.99 strength: 1.0 keep_checkpoints: 5 max_steps: 2000000 time_horizon: 64 summary_freq: 60000 threaded: false
ml-agents/config/sac/FoodCollector.yaml/0
{ "file_path": "ml-agents/config/sac/FoodCollector.yaml", "repo_id": "ml-agents", "token_count": 316 }
1,897
# ELO Rating System In adversarial games, the cumulative environment reward may **not be a meaningful metric** by which to track learning progress. This is because the cumulative reward is **entirely dependent on the skill of the opponent**. An agent at a particular skill level will get more or less reward against a worse or better agent, respectively. Instead, it's better to use ELO rating system, a method to calculate **the relative skill level between two players in a zero-sum game**. If the training performs correctly, **this value should steadily increase**. ## What is a zero-sum game? A zero-sum game is a game where **each player's gain or loss of utility is exactly balanced by the gain or loss of the utility of the opponent**. Simply explained, we face a zero-sum game **when one agent gets +1.0, its opponent gets -1.0 reward**. For instance, Tennis is a zero-sum game: if you win the point you get +1.0 and your opponent gets -1.0 reward. ## How works the ELO Rating System - Each player **has an initial ELO score**. It's defined in the `initial_elo` trainer config hyperparameter. - The **difference in rating between the two players** serves as the predictor of the outcomes of a match. ![Example Elo](images/elo_example.png) *For instance, if player A has an Elo score of 2100 and player B has an ELO score of 1800 the chance that player A wins is 85% against 15% for player b.* - We calculate the **expected score of each player** using this formula: ![Elo Expected Score Formula](images/elo_expected_score_formula.png) - At the end of the game, based on the outcome **we update the player’s actual Elo score**, we use a linear adjustment proportional to the amount by which the player over-performed or under-performed. The winning player takes points from the losing one: - If the *higher-rated player wins* → **a few points** will be taken from the lower-rated player. - If the *lower-rated player wins* → **a lot of points** will be taken from the high-rated player. - If it’s *a draw* → the lower-rated player gains **a few points** from higher. - We update players rating using this formula: ![Elo Score Update Formula](images/elo_score_update_formula.png) ### The Tennis example - We start to train our agents. - Both of them have the same skills. So ELO score for each of them that we defined using parameter `initial_elo = 1200.0`. We calculate the expected score E: Ea = 0.5 Eb = 0.5 So it means that each player has 50% chances of winning the point. If A wins, the new rating R would be: Ra = 1200 + 16 * (1 - 0.5) → 1208 Rb = 1200 + 16 * (0 - 0.5) → 1192 Player A has now an ELO score of 1208 and Player B an ELO score of 1192. Therefore, Player A is now a little bit **better than Player B**.
ml-agents/docs/ELO-Rating-System.md/0
{ "file_path": "ml-agents/docs/ELO-Rating-System.md", "repo_id": "ml-agents", "token_count": 762 }
1,898
{!../ml-agents-envs/README.md!}
ml-agents/docs/ML-Agents-Envs-README.md/0
{ "file_path": "ml-agents/docs/ML-Agents-Envs-README.md", "repo_id": "ml-agents", "token_count": 17 }
1,899
# Unity ML-Agents Toolkit [![docs badge](https://img.shields.io/badge/docs-reference-blue.svg)](https://github.com/Unity-Technologies/ml-agents/tree/release_21_docs/docs/) [![license badge](https://img.shields.io/badge/license-Apache--2.0-green.svg)](../LICENSE.md) ([latest release](https://github.com/Unity-Technologies/ml-agents/releases/tag/latest_release)) ([all releases](https://github.com/Unity-Technologies/ml-agents/releases)) **The Unity Machine Learning Agents Toolkit** (ML-Agents) is an open-source project that enables games and simulations to serve as environments for training intelligent agents. We provide implementations (based on PyTorch) of state-of-the-art algorithms to enable game developers and hobbyists to easily train intelligent agents for 2D, 3D and VR/AR games. Researchers can also use the provided simple-to-use Python API to train Agents using reinforcement learning, imitation learning, neuroevolution, or any other methods. These trained agents can be used for multiple purposes, including controlling NPC behavior (in a variety of settings such as multi-agent and adversarial), automated testing of game builds and evaluating different game design decisions pre-release. The ML-Agents Toolkit is mutually beneficial for both game developers and AI researchers as it provides a central platform where advances in AI can be evaluated on Unity’s rich environments and then made accessible to the wider research and game developer communities. ## Features - 17+ [example Unity environments](Learning-Environment-Examples.md) - Support for multiple environment configurations and training scenarios - Flexible Unity SDK that can be integrated into your game or custom Unity scene - Support for training single-agent, multi-agent cooperative, and multi-agent competitive scenarios via several Deep Reinforcement Learning algorithms (PPO, SAC, MA-POCA, self-play). - Support for learning from demonstrations through two Imitation Learning algorithms (BC and GAIL). - Quickly and easily add your own [custom training algorithm](Python-Custom-Trainer-Plugin.md) and/or components. - Easily definable Curriculum Learning scenarios for complex tasks - Train robust agents using environment randomization - Flexible agent control with On Demand Decision Making - Train using multiple concurrent Unity environment instances - Utilizes the [Sentis](Sentis.md) to provide native cross-platform support - Unity environment [control from Python](Python-LLAPI.md) - Wrap Unity learning environments as a [gym](Python-Gym-API.md) environment - Wrap Unity learning environments as a [PettingZoo](Python-PettingZoo-API.md) environment See our [ML-Agents Overview](ML-Agents-Overview.md) page for detailed descriptions of all these features. Or go straight to our [web docs](https://unity-technologies.github.io/ml-agents/). ## Releases & Documentation **Our latest, stable release is `Release 21`. Click [here](Getting-Started.md) to get started with the latest release of ML-Agents.** **You can also check out our new [web docs](https://unity-technologies.github.io/ml-agents/)!** The table below lists all our releases, including our `main` branch which is under active development and may be unstable. A few helpful guidelines: - The [Versioning page](Versioning.md) overviews how we manage our GitHub releases and the versioning process for each of the ML-Agents components. - The [Releases page](https://github.com/Unity-Technologies/ml-agents/releases) contains details of the changes between releases. - The [Migration page](Migrating.md) contains details on how to upgrade from earlier releases of the ML-Agents Toolkit. - The **Documentation** links in the table below include installation and usage instructions specific to each release. Remember to always use the documentation that corresponds to the release version you're using. - The `com.unity.ml-agents` package is [verified](https://docs.unity3d.com/2020.1/Documentation/Manual/pack-safe.html) for Unity 2020.1 and later. Verified packages releases are numbered 1.0.x. | **Version** | **Release Date** | **Source** | **Documentation** | **Download** | **Python Package** | **Unity Package** | |:--------------------------:|:------:|:-------------:|:-------:|:------------:|:------------:|:------------:| | **develop (unstable)** | -- | [source](https://github.com/Unity-Technologies/ml-agents/tree/develop) | [docs](https://unity-technologies.github.io/ml-agents/) | [download](https://github.com/Unity-Technologies/ml-agents/archive/develop.zip) | -- | -- | | **Release 21** | **October 9, 2023** | **[source](https://github.com/Unity-Technologies/ml-agents/tree/release_21)** | **[docs](https://unity-technologies.github.io/ml-agents/)** | **[download](https://github.com/Unity-Technologies/ml-agents/archive/release_21.zip)** | **[1.0.0](https://pypi.org/project/mlagents/1.0.0/)** | **[3.0.0](https://docs.unity3d.com/Packages/com.unity.ml-agents@3.0/manual/index.html)** | If you are a researcher interested in a discussion of Unity as an AI platform, see a pre-print of our [reference paper on Unity and the ML-Agents Toolkit](https://arxiv.org/abs/1809.02627). If you use Unity or the ML-Agents Toolkit to conduct research, we ask that you cite the following paper as a reference: ``` @article{juliani2020, title={Unity: A general platform for intelligent agents}, author={Juliani, Arthur and Berges, Vincent-Pierre and Teng, Ervin and Cohen, Andrew and Harper, Jonathan and Elion, Chris and Goy, Chris and Gao, Yuan and Henry, Hunter and Mattar, Marwan and Lange, Danny}, journal={arXiv preprint arXiv:1809.02627}, url={https://arxiv.org/pdf/1809.02627.pdf}, year={2020} } ``` Additionally, if you use the MA-POCA trainer in your research, we ask that you cite the following paper as a reference: ``` @article{cohen2022, title={On the Use and Misuse of Absorbing States in Multi-agent Reinforcement Learning}, author={Cohen, Andrew and Teng, Ervin and Berges, Vincent-Pierre and Dong, Ruo-Ping and Henry, Hunter and Mattar, Marwan and Zook, Alexander and Ganguly, Sujoy}, journal={RL in Games Workshop AAAI 2022}, url={http://aaai-rlg.mlanctot.info/papers/AAAI22-RLG_paper_32.pdf}, year={2022} } ``` ## Additional Resources We have a Unity Learn course, [ML-Agents: Hummingbirds](https://learn.unity.com/course/ml-agents-hummingbirds), that provides a gentle introduction to Unity and the ML-Agents Toolkit. We've also partnered with [CodeMonkeyUnity](https://www.youtube.com/c/CodeMonkeyUnity) to create a [series of tutorial videos](https://www.youtube.com/playlist?list=PLzDRvYVwl53vehwiN_odYJkPBzcqFw110) on how to implement and use the ML-Agents Toolkit. We have also published a series of blog posts that are relevant for ML-Agents: - (July 12, 2021) [ML-Agents plays Dodgeball](https://blog.unity.com/technology/ml-agents-plays-dodgeball) - (May 5, 2021) [ML-Agents v2.0 release: Now supports training complex cooperative behaviors](https://blogs.unity3d.com/2021/05/05/ml-agents-v2-0-release-now-supports-training-complex-cooperative-behaviors/) - (December 28, 2020) [Happy holidays from the Unity ML-Agents team!](https://blogs.unity3d.com/2020/12/28/happy-holidays-from-the-unity-ml-agents-team/) - (November 20, 2020) [How Eidos-Montréal created Grid Sensors to improve observations for training agents](https://blogs.unity3d.com/2020/11/20/how-eidos-montreal-created-grid-sensors-to-improve-observations-for-training-agents/) - (November 11, 2020) [2020 AI@Unity interns shoutout](https://blogs.unity3d.com/2020/11/11/2020-aiunity-interns-shoutout/) - (May 12, 2020) [Announcing ML-Agents Unity Package v1.0!](https://blogs.unity3d.com/2020/05/12/announcing-ml-agents-unity-package-v1-0/) - (February 28, 2020) [Training intelligent adversaries using self-play with ML-Agents](https://blogs.unity3d.com/2020/02/28/training-intelligent-adversaries-using-self-play-with-ml-agents/) - (November 11, 2019) [Training your agents 7 times faster with ML-Agents](https://blogs.unity3d.com/2019/11/11/training-your-agents-7-times-faster-with-ml-agents/) - (October 21, 2019) [The AI@Unity interns help shape the world](https://blogs.unity3d.com/2019/10/21/the-aiunity-interns-help-shape-the-world/) - (April 15, 2019) [Unity ML-Agents Toolkit v0.8: Faster training on real games](https://blogs.unity3d.com/2019/04/15/unity-ml-agents-toolkit-v0-8-faster-training-on-real-games/) - (March 1, 2019) [Unity ML-Agents Toolkit v0.7: A leap towards cross-platform inference](https://blogs.unity3d.com/2019/03/01/unity-ml-agents-toolkit-v0-7-a-leap-towards-cross-platform-inference/) - (December 17, 2018) [ML-Agents Toolkit v0.6: Improved usability of Brains and Imitation Learning](https://blogs.unity3d.com/2018/12/17/ml-agents-toolkit-v0-6-improved-usability-of-brains-and-imitation-learning/) - (October 2, 2018) [Puppo, The Corgi: Cuteness Overload with the Unity ML-Agents Toolkit](https://blogs.unity3d.com/2018/10/02/puppo-the-corgi-cuteness-overload-with-the-unity-ml-agents-toolkit/) - (September 11, 2018) [ML-Agents Toolkit v0.5, new resources for AI researchers available now](https://blogs.unity3d.com/2018/09/11/ml-agents-toolkit-v0-5-new-resources-for-ai-researchers-available-now/) - (June 26, 2018) [Solving sparse-reward tasks with Curiosity](https://blogs.unity3d.com/2018/06/26/solving-sparse-reward-tasks-with-curiosity/) - (June 19, 2018) [Unity ML-Agents Toolkit v0.4 and Udacity Deep Reinforcement Learning Nanodegree](https://blogs.unity3d.com/2018/06/19/unity-ml-agents-toolkit-v0-4-and-udacity-deep-reinforcement-learning-nanodegree/) - (May 24, 2018) [Imitation Learning in Unity: The Workflow](https://blogs.unity3d.com/2018/05/24/imitation-learning-in-unity-the-workflow/) - (March 15, 2018) [ML-Agents Toolkit v0.3 Beta released: Imitation Learning, feedback-driven features, and more](https://blogs.unity3d.com/2018/03/15/ml-agents-v0-3-beta-released-imitation-learning-feedback-driven-features-and-more/) - (December 11, 2017) [Using Machine Learning Agents in a real game: a beginner’s guide](https://blogs.unity3d.com/2017/12/11/using-machine-learning-agents-in-a-real-game-a-beginners-guide/) - (December 8, 2017) [Introducing ML-Agents Toolkit v0.2: Curriculum Learning, new environments, and more](https://blogs.unity3d.com/2017/12/08/introducing-ml-agents-v0-2-curriculum-learning-new-environments-and-more/) - (September 19, 2017) [Introducing: Unity Machine Learning Agents Toolkit](https://blogs.unity3d.com/2017/09/19/introducing-unity-machine-learning-agents/) - Overviewing reinforcement learning concepts ([multi-armed bandit](https://blogs.unity3d.com/2017/06/26/unity-ai-themed-blog-entries/) and [Q-learning](https://blogs.unity3d.com/2017/08/22/unity-ai-reinforcement-learning-with-q-learning/)) ### More from Unity - [Unity Sentis](https://unity.com/products/sentis) - [Introducing Unity Muse and Sentis](https://blog.unity.com/engine-platform/introducing-unity-muse-and-unity-sentis-ai) ## Community and Feedback The ML-Agents Toolkit is an open-source project and we encourage and welcome contributions. If you wish to contribute, be sure to review our [contribution guidelines](CONTRIBUTING.md) and [code of conduct](CODE_OF_CONDUCT.md). For problems with the installation and setup of the ML-Agents Toolkit, or discussions about how to best setup or train your agents, please create a new thread on the [Unity ML-Agents forum](https://forum.unity.com/forums/ml-agents.453/) and make sure to include as much detail as possible. If you run into any other problems using the ML-Agents Toolkit or have a specific feature request, please [submit a GitHub issue](https://github.com/Unity-Technologies/ml-agents/issues). Please tell us which samples you would like to see shipped with the ML-Agents Unity package by replying to [this forum thread](https://forum.unity.com/threads/feedback-wanted-shipping-sample-s-with-the-ml-agents-package.1073468/). Your opinion matters a great deal to us. Only by hearing your thoughts on the Unity ML-Agents Toolkit can we continue to improve and grow. Please take a few minutes to [let us know about it](https://unitysoftware.co1.qualtrics.com/jfe/form/SV_55pQKCZ578t0kbc). For any other questions or feedback, connect directly with the ML-Agents team at ml-agents@unity3d.com. ## Privacy In order to improve the developer experience for Unity ML-Agents Toolkit, we have added in-editor analytics. Please refer to "Information that is passively collected by Unity" in the [Unity Privacy Policy](https://unity3d.com/legal/privacy-policy).
ml-agents/docs/Readme.md/0
{ "file_path": "ml-agents/docs/Readme.md", "repo_id": "ml-agents", "token_count": 3899 }
1,900
# Doxygen files To generate the API reference as HTML files, run: doxygen dox-ml-agents.conf
ml-agents/docs/doxygen/Readme.md/0
{ "file_path": "ml-agents/docs/doxygen/Readme.md", "repo_id": "ml-agents", "token_count": 34 }
1,901
# Proximal Policy Optimization를 이용한 학습 ML-Agents는 [Proximal Policy Optimization (PPO)](https://openai.com/research/openai-baselines-ppo) 라는 강화학습 기법을 사용합니다. PPO는 에이전트의 관측 (Observation)을 통해 에이전트가 주어진 상태에서 최선의 행동을 선택할 수 있도록 하는 이상적인 함수를 인공신경망을 이용하여 근사하는 기법입니다. ML-agents의 PPO 알고리즘은 텐서플로우로 구현되었으며 별도의 파이썬 프로세스 (소켓 통신을 통해 실행중인 유니티 프로그램과 통신)에서 실행됩니다. 에이전트를 학습하기 위해서 사용자는 에이전트가 최대화하도록 시도하는 보상 시그널을 하나 혹은 그 이상 설정해야합니다. 사용 가능한 보상 시그널들과 관련된 하이퍼파라미터에 대해서는 [보상 시그널](Reward-Signals.md) 문서를 참고해주십시오. `learn.py`를 이용하여 학습 프로그램을 실행하는 방법은 [ML-Agents 학습](Training-ML-Agents.md) 문서를 참고해주십시오. 만약 에이전트에게 기억력을 부여하기 위해 순환 신경망 (Recurrent Neural Network, RNN)을 사용하는 경우, 순환 신경망에 대한 구체적인 학습 방법을 설명하는 [순환 신경망 사용하기](Feature-Memory.md) 문서를 참고해주십시오. 만약 에이전트에게 제시된 문제의 난이도를 점차적으로 증가시키며 학습하는 커리큘럼 학습 (Curriculum Learning)을 사용하는 경우 [커리큘럼 학습을 통한 에이전트 학습](Training-Curriculum-Learning.md) 문서를 참고해주십니오. 모방 학습 (Imitation Learning)에 대한 정보를 얻고 싶으시다면 [모방 학습을 통한 에이전트 학습](Training-Imitation-Learning.md) 문서를 참고해주십시오. ## PPO 학습을 위한 하이퍼파라미터 강화학습 모델을 성공적으로 학습하기 위해서는 학습과 관련된 하이퍼파라미터 튜닝이 필요합니다. 이 가이드는 기본적인 파라미터들을 이용하여 학습했을 때 사용자가 원하는 성능을 만족하지 못한 경우 파라미터 튜닝을 수행하는 방법에 대해 설명합니다. ## 하이퍼파라미터 ### Reward Signals 강화학습에서 목표는 보상을 최대로 하는 정책 (Policy)을 학습하는 것입니다. 기본적으로 보상은 환경으로부터 주어집니다. 그러나 우리는 다양한 다른 행동을 통해 에이전트에게 보상을 주는 것을 생각해볼 수 있습니다. 예를 들어 에이전트가 새로운 상태를 탐험했을 때 에이전트에게 보상을 줄 수 있습니다. 이런 보상 시그널을 추가하여 학습 과정에 도움을 줄 수도 있습니다. `reward_signals`는 [보상 시그널](Reward-Signals.md)을 정의합니다. ML-Agents는 기본적으로 두개의 보상 시그널을 제공합니다. 하나는 외부 (환경) 보상이며 다른 하나는 호기심 (Curiosity) 보상입니다. 이 호기심 보상은 외부 보상이 희소성을 가지는 환경 (Sparse Extrinsic Reward Environment)에서 더 다양한 탐험을 수행할 수 있도록 도와줍니다. ### Lambda `lambd` 는 `람다(lambda)` 파라미터를 의미하며 일반화된 이득 추정 (Generalized Advantage Estimate, [GAE]((https://arxiv.org/abs/1506.02438))) 계산에 사용됩니다. 이는 업데이트된 가치를 예측할 때 현재 예측된 가치에 얼마나 의존할지 결정하는 값입니다. 이 값이 낮으면 현재 예측된 가치에 더 의존하는 것을 의미하며 (높은 편향 (bias) 발생 가능), 값이 높으면 환경을 통해 얻은 실제 보상에 더 의존하는 것을 의미합니다 (높은 분산 (variance) 발생 가능). 즉 이 파라미터를 어떻게 선택하냐에 따라 두 특성간에 트레이드오프 (trade-off)가 존재합니다. 또한 이 파라미터를 적절하게 선택하면 더 안정적인 학습이 가능합니다. 일반적인 범위: `0.9` - `0.95` ### Buffer Size `buffer_size` 는 모델 학습을 시작하기 전 얼마나 많은 경험들(관측, 행동, 보상 등)을 저장할지 결정합니다. **이 값은 `batch_size`의 배수로 설정되어야 합니다.** 일반적으로 큰 `buffer_size`는 더 안정적인 학습을 가능하게 합니다. 일반적인 범위: `2048` - `409600` ### Batch Size `batch_size` 는 한번의 경사하강(Gradient Descent) 업데이트를 수행할 때 사용할 경험들의 수를 의미합니다. **이 값은 항상 `buffer_size`의 약수로 설정되어야 합니다.** 만약 연속적인 행동 공간 (Continuous Action Space) 환경을 사용하는 경우 이 값은 크게 설정되어야 합니다 (1000의 단위). 만약 이산적인 행동 공간 (Discrete Action Space) 환경을 사용하는 경우 이 값은 더 작게 설정되어야 합니다. (10의 단위). 일반적인 범위 (연속적인 행동): `512` - `5120` 일반적인 범위 (이산적인 행동): `32` - `512` ### Number of Epochs `num_epoch` 는 경사 하강 (Gradient Descent) 학습 동안 경험 버퍼 (Experience Buffer) 데이터에 대해 학습을 몇번 수행할 지 결정합니다. `batch_size`가 클수록 이 값도 커져야합니다. 이 값을 줄이면 더 안정적인 업데이트가 보장되지만 학습 속도가 느려집니다. 일반적인 범위: `3` - `10` ### Learning Rate `learning_rate` 는 경사 하강 (Gradient Descent) 학습의 정도를 결정합니다. 학습이 불안정하고 에이전트가 얻는 보상이 증가하지 않는 경우 일반적으로 학습률을 감소시킵니다. 일반적인 범위: `1e-5` - `1e-3` ### Time Horizon `time_horizon` 은 경험 버퍼 (Experience Buffer)에 저장하기 전 에이전트당 수집할 경험의 스텝 수를 의미합니다. 에피소드가 끝나기 전에 이 한도에 도달하면 가치 평가를 통해 에이전트의 현재 상태로부터 기대되는 전체 보상을 예측합니다. 따라서 이 값의 설정에 따라 덜 편향되지만 분산이 커질수도 있고 (긴 time horizon), 더 편향 (bias)되지만 분산 (variance)이 작아질 수도 있습니다 (짧은 time horizon). 한 에피소드 동안 보상이 빈번하게 발생하는 경우나 에피소드가 엄청나게 긴 경우에는 time horizon 값은 작게 설정하는 것이 이상적입니다. 이 값은 에이전트가 취하는 일련의 행동 내에서 중요한 행동을 모두 포착할 수 있을 만큼 큰 값을 가져야 합니다. 일반적인 범위: `32` - `2048` ### Max Steps `max_steps` 은 학습 과정 동안 얼마나 많은 시뮬레이션 스텝 (프레임 스킵을 곱한만큼) 을 실행할지 결정합니다. 이 값은 복잡한 문제일수록 크게 설정해야합니다. 일반적인 범위: `5e5` - `1e7` ### Beta `beta` 는 엔트로피 정규화 (Entropy Regularization)의 정도를 결정하며 이를 통해 정책을 더 랜덤하게 만들 수 있습니다. 이 값을 통해 에이전트는 학습 동안 액션 공간을 적절하게 탐험할 수 있습니다. 이 값을 증가시키면 에이전트가 더 많이 랜덤 행동을 취하게 됩니다. 엔트로피 (텐서보드를 통해 측정 가능)는 보상이 증가함에 따라 서서히 크기를 감소시켜야합니다. 만약 엔트로피가 너무 빠르게 떨어지면 `beta`를 증가시켜야합니다. 만약 엔트로피가 너무 느리게 떨어지면 `beta`를 감소시켜야 합니다. 일반적인 범위: 1e-4 - 1e-2 ### Epsilon `epsilon` 은 경사 하강 업데이트 동안 사용하는 이전 정책과 새로운 정책 사이의 비율을 일정 범위의 크기로 제한하는 값입니다. 이 값이 작게 설정되면 더 안정적인 학습이 가능하지만 학습이 느리게 진행될 것입니다. 일반적인 범위: `0.1` - `0.3` ### Normalize `normalize`는 벡터 관측 (Vector Observation) 입력을 정규화 (Normalization)할지 결정합니다. 이 정규화는 벡터 관측의 이동 평균 및 분산을 기반으로 수행합니다. 정규화는 복잡하고 연속적인 제어 문제에서 도움이 될 수 있지만 단순하고 이산적인 제어 문제에서는 정규화를 사용하는 것이 좋지 않을 수 있습니다. ### Number of Layers `num_layers` 는 관측 입력 후 혹은 시각적 관측 (Visual Observation)의 CNN 인코딩 이후 몇개의 은닉층 (Hidden Layer)을 사용할지 결정합니다. 간단한 문제에서는 적은 수의 층을 사용하여 빠르고 효율적으로 학습해야합니다. 복잡한 제어 문제에서는 많은 층을 사용할 필요가 있습니다. 일반적인 범위: `1` - `3` ### Hidden Units `hidden_units` 은 인공신경망의 각 완전연결층 (Fully Connected Layer)에 몇개의 유닛을 사용할지 결정합니다. 최적의 행동이 관측 입력의 간단한 조합으로 결정되는 단순한 문제에 대해서는 이 값을 작게 설정합니다. 최적의 행동이 관측 입력의 복잡한 관계에 의해 결정되는 어려운 문제에 대해서는 이 값을 크게 설정합니다. 일반적인 범위: `32` - `512` ## (선택적) 순환신경망의 하이퍼파라미터 아래의 하이퍼파라미터들은 `use_recurrent` 이 참(True)으로 결정된 경우에만 사용합니다. ### Sequence Length `sequence_length` 는 학습 동안 네트워크를 통과하는 연속적인 경험들의 길이를 의미합니다. 에이전트가 긴 시간에 대해 기억해야하는 정보가 있다면 이 값을 충분히 길게 설정해야합니다. 예를 들어 에이전트가 물체의 속도를 기억해야하는 경우 이 값은 작게 설정해도 괜찮습니다. 만약 에이전트가 에피소드 초반에 한번 주어진 정보를 계속 기억해야한다면 이 값을 크게 설정해야 합니다. 일반적인 범위: `4` - `128` ### Memory Size `memory_size` 는 순환신경망의 은닉 상태(hidden state)를 저장하는데 사용되는 배열의 크기를 의미합니다. 이 값은 반드시 4의 배수로 설정되어야 하며 에이전트가 임무를 성공적으로 완수하기 위해서 기억해야하는 정보의 양에 따라 크기를 조절해야합니다. 일반적인 범위: `64` - `512` ## Training Statistics 학습의 상태를 확인하려면 텐서보드 (TensorBoard)를 사용해야합니다. 텐서보드를 실행하고 사용하는 것에 대한 정보를 알고싶으신 경우 이 [문서](./Getting-Started-with-Balance-Ball.md#observing-training-progress)를 참고해주십시오. ### Cumulative Reward 보상은 일반적으로 지속적으로 증가하는 경향을 가져야합니다. 작은 기복이 발생할수는 있습니다. 문제의 복잡도에 따라 수백만 스텝의 학습이 진행되어도 보상이 증가하지 않을수도 있습니다. ### Entropy 이 값은 브레인이 결정이 얼마나 무작위인지 나타냅니다. 이 값은 학습이 진행되는 동안 지속적으로 감소해야합니다. 만약 이 값이 너무 빠르게 감소하거나 아예 감소하지 않는 경우 `beta`의 크기를 조절해야합니다. (이산적인 행동 공간을 사용하는 경우) ### Learning Rate 이 값은 시간이 지남에 따라 선형적으로 감소합니다. ### Policy Loss 이 값들은 학습이 진행되는 동안 진동합니다. 일반적으로 이 값들은 1보다 작아야합니다. ### Value Estimate 이 값들은 누적 보상이 증가함에 따라 커져야합니다. 이 값들은 주어진 시점에서 에이전트가 스스로 받을 것이라 예측하는 미래의 보상이 얼마나 될것인지를 나타냅니다. ### Value Loss 이 값들은 보상이 증가하면 증가하고 보상이 안정되면 감소합니다. ## 한글 번역 해당 문서의 한글 번역은 [민규식 (Kyushik Min)]([https://github.com/Kyushik](https://github.com/Kyushik))에 의해 진행되었습니다. 내용상 오류나 오탈자가 있는 경우 kyushikmin@gmail.com 으로 연락주시면 감사드리겠습니다.
ml-agents/localized_docs/KR/docs/Training-PPO.md/0
{ "file_path": "ml-agents/localized_docs/KR/docs/Training-PPO.md", "repo_id": "ml-agents", "token_count": 9565 }
1,902
from typing import Callable, Optional from mlagents_envs.communicator_objects.unity_output_pb2 import UnityOutputProto from mlagents_envs.communicator_objects.unity_input_pb2 import UnityInputProto # Function to call while waiting for a connection timeout. # This should raise an exception if it needs to break from waiting for the timeout. PollCallback = Callable[[], None] class Communicator: def __init__(self, worker_id=0, base_port=5005): """ Python side of the communication. Must be used in pair with the right Unity Communicator equivalent. :int worker_id: Offset from base_port. Used for training multiple environments simultaneously. :int base_port: Baseline port number to connect to Unity environment over. worker_id increments over this. """ def initialize( self, inputs: UnityInputProto, poll_callback: Optional[PollCallback] = None ) -> UnityOutputProto: """ Used to exchange initialization parameters between Python and the Environment :param inputs: The initialization input that will be sent to the environment. :param poll_callback: Optional callback to be used while polling the connection. :return: UnityOutput: The initialization output sent by Unity """ def exchange( self, inputs: UnityInputProto, poll_callback: Optional[PollCallback] = None ) -> Optional[UnityOutputProto]: """ Used to send an input and receive an output from the Environment :param inputs: The UnityInput that needs to be sent the Environment :param poll_callback: Optional callback to be used while polling the connection. :return: The UnityOutputs generated by the Environment """ def close(self): """ Sends a shutdown signal to the unity environment, and closes the connection. """
ml-agents/ml-agents-envs/mlagents_envs/communicator.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator.py", "repo_id": "ml-agents", "token_count": 582 }
1,903
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: mlagents_envs/communicator_objects/demonstration_meta.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='mlagents_envs/communicator_objects/demonstration_meta.proto', package='communicator_objects', syntax='proto3', serialized_pb=_b('\n;mlagents_envs/communicator_objects/demonstration_meta.proto\x12\x14\x63ommunicator_objects\"\x8d\x01\n\x16\x44\x65monstrationMetaProto\x12\x13\n\x0b\x61pi_version\x18\x01 \x01(\x05\x12\x1a\n\x12\x64\x65monstration_name\x18\x02 \x01(\t\x12\x14\n\x0cnumber_steps\x18\x03 \x01(\x05\x12\x17\n\x0fnumber_episodes\x18\x04 \x01(\x05\x12\x13\n\x0bmean_reward\x18\x05 \x01(\x02\x42%\xaa\x02\"Unity.MLAgents.CommunicatorObjectsb\x06proto3') ) _DEMONSTRATIONMETAPROTO = _descriptor.Descriptor( name='DemonstrationMetaProto', full_name='communicator_objects.DemonstrationMetaProto', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='api_version', full_name='communicator_objects.DemonstrationMetaProto.api_version', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='demonstration_name', full_name='communicator_objects.DemonstrationMetaProto.demonstration_name', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='number_steps', full_name='communicator_objects.DemonstrationMetaProto.number_steps', index=2, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='number_episodes', full_name='communicator_objects.DemonstrationMetaProto.number_episodes', index=3, number=4, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='mean_reward', full_name='communicator_objects.DemonstrationMetaProto.mean_reward', index=4, number=5, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=86, serialized_end=227, ) DESCRIPTOR.message_types_by_name['DemonstrationMetaProto'] = _DEMONSTRATIONMETAPROTO _sym_db.RegisterFileDescriptor(DESCRIPTOR) DemonstrationMetaProto = _reflection.GeneratedProtocolMessageType('DemonstrationMetaProto', (_message.Message,), dict( DESCRIPTOR = _DEMONSTRATIONMETAPROTO, __module__ = 'mlagents_envs.communicator_objects.demonstration_meta_pb2' # @@protoc_insertion_point(class_scope:communicator_objects.DemonstrationMetaProto) )) _sym_db.RegisterMessage(DemonstrationMetaProto) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\252\002\"Unity.MLAgents.CommunicatorObjects')) # @@protoc_insertion_point(module_scope)
ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/demonstration_meta_pb2.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/demonstration_meta_pb2.py", "repo_id": "ml-agents", "token_count": 1658 }
1,904
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: mlagents_envs/communicator_objects/unity_output.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from mlagents_envs.communicator_objects import unity_rl_output_pb2 as mlagents__envs_dot_communicator__objects_dot_unity__rl__output__pb2 from mlagents_envs.communicator_objects import unity_rl_initialization_output_pb2 as mlagents__envs_dot_communicator__objects_dot_unity__rl__initialization__output__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='mlagents_envs/communicator_objects/unity_output.proto', package='communicator_objects', syntax='proto3', serialized_pb=_b('\n5mlagents_envs/communicator_objects/unity_output.proto\x12\x14\x63ommunicator_objects\x1a\x38mlagents_envs/communicator_objects/unity_rl_output.proto\x1aGmlagents_envs/communicator_objects/unity_rl_initialization_output.proto\"\xa9\x01\n\x10UnityOutputProto\x12;\n\trl_output\x18\x01 \x01(\x0b\x32(.communicator_objects.UnityRLOutputProto\x12X\n\x18rl_initialization_output\x18\x02 \x01(\x0b\x32\x36.communicator_objects.UnityRLInitializationOutputProtoB%\xaa\x02\"Unity.MLAgents.CommunicatorObjectsb\x06proto3') , dependencies=[mlagents__envs_dot_communicator__objects_dot_unity__rl__output__pb2.DESCRIPTOR,mlagents__envs_dot_communicator__objects_dot_unity__rl__initialization__output__pb2.DESCRIPTOR,]) _UNITYOUTPUTPROTO = _descriptor.Descriptor( name='UnityOutputProto', full_name='communicator_objects.UnityOutputProto', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='rl_output', full_name='communicator_objects.UnityOutputProto.rl_output', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='rl_initialization_output', full_name='communicator_objects.UnityOutputProto.rl_initialization_output', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=211, serialized_end=380, ) _UNITYOUTPUTPROTO.fields_by_name['rl_output'].message_type = mlagents__envs_dot_communicator__objects_dot_unity__rl__output__pb2._UNITYRLOUTPUTPROTO _UNITYOUTPUTPROTO.fields_by_name['rl_initialization_output'].message_type = mlagents__envs_dot_communicator__objects_dot_unity__rl__initialization__output__pb2._UNITYRLINITIALIZATIONOUTPUTPROTO DESCRIPTOR.message_types_by_name['UnityOutputProto'] = _UNITYOUTPUTPROTO _sym_db.RegisterFileDescriptor(DESCRIPTOR) UnityOutputProto = _reflection.GeneratedProtocolMessageType('UnityOutputProto', (_message.Message,), dict( DESCRIPTOR = _UNITYOUTPUTPROTO, __module__ = 'mlagents_envs.communicator_objects.unity_output_pb2' # @@protoc_insertion_point(class_scope:communicator_objects.UnityOutputProto) )) _sym_db.RegisterMessage(UnityOutputProto) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\252\002\"Unity.MLAgents.CommunicatorObjects')) # @@protoc_insertion_point(module_scope)
ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_output_pb2.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_output_pb2.py", "repo_id": "ml-agents", "token_count": 1440 }
1,905
from urllib.parse import urlparse, parse_qs def _behavior_to_agent_id(behavior_name: str, unique_id: int) -> str: return f"{behavior_name}?agent_id={unique_id}" def _agent_id_to_behavior(agent_id: str) -> str: return agent_id.split("?agent_id=")[0] def _unwrap_batch_steps(batch_steps, behavior_name): decision_batch, termination_batch = batch_steps decision_id = [ _behavior_to_agent_id(behavior_name, i) for i in decision_batch.agent_id ] termination_id = [ _behavior_to_agent_id(behavior_name, i) for i in termination_batch.agent_id ] agents = decision_id + termination_id obs = { agent_id: [batch_obs[i] for batch_obs in termination_batch.obs] for i, agent_id in enumerate(termination_id) } if decision_batch.action_mask is not None: obs.update( { agent_id: { "observation": [batch_obs[i] for batch_obs in decision_batch.obs], "action_mask": [mask[i] for mask in decision_batch.action_mask], } for i, agent_id in enumerate(decision_id) } ) else: obs.update( { agent_id: [batch_obs[i] for batch_obs in decision_batch.obs] for i, agent_id in enumerate(decision_id) } ) obs = {k: v if len(v) > 1 else v[0] for k, v in obs.items()} dones = {agent_id: True for agent_id in termination_id} dones.update({agent_id: False for agent_id in decision_id}) rewards = { agent_id: termination_batch.reward[i] for i, agent_id in enumerate(termination_id) } rewards.update( {agent_id: decision_batch.reward[i] for i, agent_id in enumerate(decision_id)} ) cumulative_rewards = {k: v for k, v in rewards.items()} infos = {} for i, agent_id in enumerate(decision_id): infos[agent_id] = {} infos[agent_id]["behavior_name"] = behavior_name infos[agent_id]["group_id"] = decision_batch.group_id[i] infos[agent_id]["group_reward"] = decision_batch.group_reward[i] for i, agent_id in enumerate(termination_id): infos[agent_id] = {} infos[agent_id]["behavior_name"] = behavior_name infos[agent_id]["group_id"] = termination_batch.group_id[i] infos[agent_id]["group_reward"] = termination_batch.group_reward[i] infos[agent_id]["interrupted"] = termination_batch.interrupted[i] id_map = {agent_id: i for i, agent_id in enumerate(decision_id)} return agents, obs, dones, rewards, cumulative_rewards, infos, id_map def _parse_behavior(full_behavior): parsed = urlparse(full_behavior) name = parsed.path ids = parse_qs(parsed.query) team_id: int = 0 if "team" in ids: team_id = int(ids["team"][0]) return name, team_id
ml-agents/ml-agents-envs/mlagents_envs/envs/env_helpers.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/envs/env_helpers.py", "repo_id": "ml-agents", "token_count": 1291 }
1,906
from mlagents_envs.side_channel.incoming_message import IncomingMessage # noqa from mlagents_envs.side_channel.outgoing_message import OutgoingMessage # noqa from mlagents_envs.side_channel.side_channel import SideChannel # noqa from mlagents_envs.side_channel.default_training_analytics_side_channel import ( # noqa DefaultTrainingAnalyticsSideChannel, # noqa ) # noqa
ml-agents/ml-agents-envs/mlagents_envs/side_channel/__init__.py/0
{ "file_path": "ml-agents/ml-agents-envs/mlagents_envs/side_channel/__init__.py", "repo_id": "ml-agents", "token_count": 120 }
1,907
from unittest import mock import pytest from mlagents_envs.env_utils import validate_environment_path, launch_executable from mlagents_envs.exception import UnityEnvironmentException from mlagents_envs.logging_util import ( set_log_level, get_logger, INFO, ERROR, FATAL, CRITICAL, DEBUG, ) def mock_glob_method(path): """ Given a path input, returns a list of candidates """ if ".x86" in path: return ["linux"] if ".app" in path: return ["darwin"] if ".exe" in path: return ["win32"] if "*" in path: return "Any" return [] @mock.patch("sys.platform") @mock.patch("glob.glob") def test_validate_path_empty(glob_mock, platform_mock): glob_mock.return_value = None path = validate_environment_path(" ") assert path is None @mock.patch("mlagents_envs.env_utils.get_platform") @mock.patch("glob.glob") def test_validate_path(glob_mock, platform_mock): glob_mock.side_effect = mock_glob_method for platform in ["linux", "darwin", "win32"]: platform_mock.return_value = platform path = validate_environment_path(" ") assert path == platform @mock.patch("glob.glob") @mock.patch("subprocess.Popen") def test_launch_executable(mock_popen, glob_mock): with pytest.raises(UnityEnvironmentException): launch_executable(" ", []) glob_mock.return_value = ["FakeLaunchPath"] launch_executable(" ", []) mock_popen.side_effect = PermissionError("Fake permission error") with pytest.raises(UnityEnvironmentException): launch_executable(" ", []) def test_set_logging_level(): for level in [INFO, ERROR, FATAL, CRITICAL, DEBUG]: set_log_level(level) assert get_logger("test").level == level
ml-agents/ml-agents-envs/tests/test_env_utils.py/0
{ "file_path": "ml-agents/ml-agents-envs/tests/test_env_utils.py", "repo_id": "ml-agents", "token_count": 704 }
1,908
from setuptools import setup from mlagents.plugins import ML_AGENTS_STATS_WRITER setup( name="mlagents_plugin_examples", version="0.0.1", # Example of how to add your own registration functions that will be called # by mlagents-learn. # # Here, the get_example_stats_writer() function in mlagents_plugin_examples/example_stats_writer.py # will get registered with the ML_AGENTS_STATS_WRITER plugin interface. entry_points={ ML_AGENTS_STATS_WRITER: [ "example=mlagents_plugin_examples.example_stats_writer:get_example_stats_writer" ] }, )
ml-agents/ml-agents-plugin-examples/setup.py/0
{ "file_path": "ml-agents/ml-agents-plugin-examples/setup.py", "repo_id": "ml-agents", "token_count": 228 }
1,909
from mlagents.torch_utils.torch import torch as torch # noqa from mlagents.torch_utils.torch import nn # noqa from mlagents.torch_utils.torch import set_torch_config # noqa from mlagents.torch_utils.torch import default_device # noqa
ml-agents/ml-agents/mlagents/torch_utils/__init__.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/torch_utils/__init__.py", "repo_id": "ml-agents", "token_count": 82 }
1,910
from mlagents_envs.logging_util import get_logger from typing import Deque, Dict from collections import deque from mlagents.trainers.ghost.trainer import GhostTrainer logger = get_logger(__name__) class GhostController: """ GhostController contains a queue of team ids. GhostTrainers subscribe to the GhostController and query it to get the current learning team. The GhostController cycles through team ids every 'swap_interval' which corresponds to the number of trainer steps between changing learning teams. The GhostController is a unique object and there can only be one per training run. """ def __init__(self, maxlen: int = 10): """ Create a GhostController. :param maxlen: Maximum number of GhostTrainers allowed in this GhostController """ # Tracks last swap step for each learning team because trainer # steps of all GhostTrainers do not increment together self._queue: Deque[int] = deque(maxlen=maxlen) self._learning_team: int = -1 # Dict from team id to GhostTrainer for ELO calculation self._ghost_trainers: Dict[int, GhostTrainer] = {} # Signals to the trainer control to perform a hard change_training_team self._changed_training_team = False @property def get_learning_team(self) -> int: """ Returns the current learning team. :return: The learning team id """ return self._learning_team def should_reset(self) -> bool: """ Whether or not team change occurred. Causes full reset in trainer_controller :return: The truth value of the team changing """ changed_team = self._changed_training_team if self._changed_training_team: self._changed_training_team = False return changed_team def subscribe_team_id(self, team_id: int, trainer: GhostTrainer) -> None: """ Given a team_id and trainer, add to queue and trainers if not already. The GhostTrainer is used later by the controller to get ELO ratings of agents. :param team_id: The team_id of an agent managed by this GhostTrainer :param trainer: A GhostTrainer that manages this team_id. """ if team_id not in self._ghost_trainers: self._ghost_trainers[team_id] = trainer if self._learning_team < 0: self._learning_team = team_id else: self._queue.append(team_id) def change_training_team(self, step: int) -> None: """ The current learning team is added to the end of the queue and then updated with the next in line. :param step: The step of the trainer for debugging """ self._queue.append(self._learning_team) self._learning_team = self._queue.popleft() logger.debug(f"Learning team {self._learning_team} swapped on step {step}") self._changed_training_team = True # Adapted from https://github.com/Unity-Technologies/ml-agents/pull/1975 and # https://metinmediamath.wordpress.com/2013/11/27/how-to-calculate-the-elo-rating-including-example/ # ELO calculation # TODO : Generalize this to more than two teams def compute_elo_rating_changes(self, rating: float, result: float) -> float: """ Calculates ELO. Given the rating of the learning team and result. The GhostController queries the other GhostTrainers for the ELO of their agent that is currently being deployed. Note, this could be the current agent or a past snapshot. :param rating: Rating of the learning team. :param result: Win, loss, or draw from the perspective of the learning team. :return: The change in ELO. """ opponent_rating: float = 0.0 for team_id, trainer in self._ghost_trainers.items(): if team_id != self._learning_team: opponent_rating = trainer.get_opponent_elo() r1 = pow(10, rating / 400) r2 = pow(10, opponent_rating / 400) summed = r1 + r2 e1 = r1 / summed change = result - e1 for team_id, trainer in self._ghost_trainers.items(): if team_id != self._learning_team: trainer.change_opponent_elo(change) return change
ml-agents/ml-agents/mlagents/trainers/ghost/controller.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/ghost/controller.py", "repo_id": "ml-agents", "token_count": 1634 }
1,911
import random from typing import Dict, List, Any, Tuple import numpy as np from mlagents_envs.base_env import ( ActionSpec, ObservationSpec, ObservationType, ActionTuple, BaseEnv, BehaviorSpec, DecisionSteps, TerminalSteps, BehaviorMapping, ) from .test_rpc_utils import proto_from_steps_and_action from mlagents_envs.communicator_objects.agent_info_action_pair_pb2 import ( AgentInfoActionPairProto, ) from mlagents.trainers.tests.dummy_config import create_observation_specs_with_shapes OBS_SIZE = 1 VIS_OBS_SIZE = (3, 20, 20) VAR_LEN_SIZE = (10, 5) STEP_SIZE = 0.2 TIME_PENALTY = 0.01 MIN_STEPS = int(1.0 / STEP_SIZE) + 1 SUCCESS_REWARD = 1.0 + MIN_STEPS * TIME_PENALTY def clamp(x, min_val, max_val): return max(min_val, min(x, max_val)) class SimpleEnvironment(BaseEnv): """ Very simple "game" - the agent has a position on [-1, 1], gets a reward of 1 if it reaches 1, and a reward of -1 if it reaches -1. The position is incremented by the action amount (clamped to [-step_size, step_size]). """ def __init__( self, brain_names, step_size=STEP_SIZE, num_visual=0, num_vector=1, num_var_len=0, vis_obs_size=VIS_OBS_SIZE, vec_obs_size=OBS_SIZE, var_len_obs_size=VAR_LEN_SIZE, action_sizes=(1, 0), goal_indices=None, ): super().__init__() self.num_visual = num_visual self.num_vector = num_vector self.num_var_len = num_var_len self.vis_obs_size = vis_obs_size self.vec_obs_size = vec_obs_size self.var_len_obs_size = var_len_obs_size self.goal_indices = goal_indices continuous_action_size, discrete_action_size = action_sizes discrete_tuple = tuple(2 for _ in range(discrete_action_size)) action_spec = ActionSpec(continuous_action_size, discrete_tuple) self.total_action_size = ( continuous_action_size + discrete_action_size ) # to set the goals/positions self.action_spec = action_spec self.behavior_spec = BehaviorSpec(self._make_observation_specs(), action_spec) self.action_spec = action_spec self.names = brain_names self.positions: Dict[str, List[float]] = {} self.step_count: Dict[str, float] = {} # Concatenate the arguments for a consistent random seed seed = ( brain_names, step_size, num_visual, num_vector, num_var_len, vis_obs_size, vec_obs_size, var_len_obs_size, action_sizes, ) self.random = random.Random(str(seed)) self.goal: Dict[str, int] = {} self.action = {} self.rewards: Dict[str, float] = {} self.final_rewards: Dict[str, List[float]] = {} self.step_result: Dict[str, Tuple[DecisionSteps, TerminalSteps]] = {} self.agent_id: Dict[str, int] = {} self.step_size = step_size # defines the difficulty of the test # Allow to be used as a UnityEnvironment during tests self.academy_capabilities = None for name in self.names: self.agent_id[name] = 0 self.goal[name] = self.random.choice([-1, 1]) self.rewards[name] = 0 self.final_rewards[name] = [] self._reset_agent(name) self.action[name] = None self.step_result[name] = None def _make_observation_specs(self) -> List[ObservationSpec]: obs_shape: List[Any] = [] for _ in range(self.num_vector): obs_shape.append((self.vec_obs_size,)) for _ in range(self.num_visual): obs_shape.append(self.vis_obs_size) for _ in range(self.num_var_len): obs_shape.append(self.var_len_obs_size) obs_spec = create_observation_specs_with_shapes(obs_shape) if self.goal_indices is not None: for i in range(len(obs_spec)): if i in self.goal_indices: obs_spec[i] = ObservationSpec( shape=obs_spec[i].shape, dimension_property=obs_spec[i].dimension_property, observation_type=ObservationType.GOAL_SIGNAL, name=obs_spec[i].name, ) return obs_spec def _make_obs(self, value: float) -> List[np.ndarray]: obs = [] for _ in range(self.num_vector): obs.append(np.ones((1, self.vec_obs_size), dtype=np.float32) * value) for _ in range(self.num_visual): obs.append(np.ones((1,) + self.vis_obs_size, dtype=np.float32) * value) for _ in range(self.num_var_len): obs.append(np.ones((1,) + self.var_len_obs_size, dtype=np.float32) * value) return obs @property def behavior_specs(self): behavior_dict = {} for n in self.names: behavior_dict[n] = self.behavior_spec return BehaviorMapping(behavior_dict) def set_action_for_agent(self, behavior_name, agent_id, action): pass def set_actions(self, behavior_name, action): self.action[behavior_name] = action def get_steps(self, behavior_name): return self.step_result[behavior_name] def _take_action(self, name: str) -> bool: deltas = [] _act = self.action[name] if self.action_spec.continuous_size > 0: for _cont in _act.continuous[0]: deltas.append(_cont) if self.action_spec.discrete_size > 0: for _disc in _act.discrete[0]: deltas.append(1 if _disc else -1) for i, _delta in enumerate(deltas): _delta = clamp(_delta, -self.step_size, self.step_size) self.positions[name][i] += _delta self.positions[name][i] = clamp(self.positions[name][i], -1, 1) self.step_count[name] += 1 # Both must be in 1.0 to be done done = all(pos >= 1.0 or pos <= -1.0 for pos in self.positions[name]) return done def _generate_mask(self): action_mask = None if self.action_spec.discrete_size > 0: # LL-Python API will return an empty dim if there is only 1 agent. ndmask = np.array( 2 * self.action_spec.discrete_size * [False], dtype=np.bool ) ndmask = np.expand_dims(ndmask, axis=0) action_mask = [ndmask] return action_mask def _compute_reward(self, name: str, done: bool) -> float: if done: reward = 0.0 for _pos in self.positions[name]: reward += (SUCCESS_REWARD * _pos * self.goal[name]) / len( self.positions[name] ) else: reward = -TIME_PENALTY return reward def _reset_agent(self, name): self.goal[name] = self.random.choice([-1, 1]) self.positions[name] = [0.0 for _ in range(self.total_action_size)] self.step_count[name] = 0 self.rewards[name] = 0 self.agent_id[name] = self.agent_id[name] + 1 def _make_batched_step( self, name: str, done: bool, reward: float, group_reward: float ) -> Tuple[DecisionSteps, TerminalSteps]: m_vector_obs = self._make_obs(self.goal[name]) m_reward = np.array([reward], dtype=np.float32) m_agent_id = np.array([self.agent_id[name]], dtype=np.int32) m_group_id = np.array([0], dtype=np.int32) m_group_reward = np.array([group_reward], dtype=np.float32) action_mask = self._generate_mask() decision_step = DecisionSteps( m_vector_obs, m_reward, m_agent_id, action_mask, m_group_id, m_group_reward ) terminal_step = TerminalSteps.empty(self.behavior_spec) if done: self.final_rewards[name].append(self.rewards[name]) self._reset_agent(name) new_vector_obs = self._make_obs(self.goal[name]) ( new_reward, new_done, new_agent_id, new_action_mask, new_group_id, new_group_reward, ) = self._construct_reset_step(name) decision_step = DecisionSteps( new_vector_obs, new_reward, new_agent_id, new_action_mask, new_group_id, new_group_reward, ) terminal_step = TerminalSteps( m_vector_obs, m_reward, np.array([False], dtype=np.bool), m_agent_id, m_group_id, m_group_reward, ) return (decision_step, terminal_step) def _construct_reset_step( self, name: str ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: new_reward = np.array([0.0], dtype=np.float32) new_done = np.array([False], dtype=np.bool) new_agent_id = np.array([self.agent_id[name]], dtype=np.int32) new_action_mask = self._generate_mask() new_group_id = np.array([0], dtype=np.int32) new_group_reward = np.array([0.0], dtype=np.float32) return ( new_reward, new_done, new_agent_id, new_action_mask, new_group_id, new_group_reward, ) def step(self) -> None: assert all(action is not None for action in self.action.values()) for name in self.names: done = self._take_action(name) reward = self._compute_reward(name, done) self.rewards[name] += reward self.step_result[name] = self._make_batched_step(name, done, reward, 0.0) def reset(self) -> None: # type: ignore for name in self.names: self._reset_agent(name) self.step_result[name] = self._make_batched_step(name, False, 0.0, 0.0) @property def reset_parameters(self) -> Dict[str, str]: return {} def close(self): pass class MemoryEnvironment(SimpleEnvironment): def __init__(self, brain_names, action_sizes=(1, 0), step_size=0.2): super().__init__(brain_names, action_sizes=action_sizes, step_size=step_size) # Number of steps to reveal the goal for. Lower is harder. Should be # less than 1/step_size to force agent to use memory self.num_show_steps = 2 def _make_batched_step( self, name: str, done: bool, reward: float, group_reward: float ) -> Tuple[DecisionSteps, TerminalSteps]: recurrent_obs_val = ( self.goal[name] if self.step_count[name] <= self.num_show_steps else 0 ) m_vector_obs = self._make_obs(recurrent_obs_val) m_reward = np.array([reward], dtype=np.float32) m_agent_id = np.array([self.agent_id[name]], dtype=np.int32) m_group_id = np.array([0], dtype=np.int32) m_group_reward = np.array([group_reward], dtype=np.float32) action_mask = self._generate_mask() decision_step = DecisionSteps( m_vector_obs, m_reward, m_agent_id, action_mask, m_group_id, m_group_reward ) terminal_step = TerminalSteps.empty(self.behavior_spec) if done: self.final_rewards[name].append(self.rewards[name]) self._reset_agent(name) recurrent_obs_val = ( self.goal[name] if self.step_count[name] <= self.num_show_steps else 0 ) new_vector_obs = self._make_obs(recurrent_obs_val) ( new_reward, new_done, new_agent_id, new_action_mask, new_group_id, new_group_reward, ) = self._construct_reset_step(name) decision_step = DecisionSteps( new_vector_obs, new_reward, new_agent_id, new_action_mask, new_group_id, new_group_reward, ) terminal_step = TerminalSteps( m_vector_obs, m_reward, np.array([False], dtype=np.bool), m_agent_id, m_group_id, m_group_reward, ) return (decision_step, terminal_step) class MultiAgentEnvironment(BaseEnv): """ The MultiAgentEnvironment maintains a list of SimpleEnvironment, one for each agent. When sending DecisionSteps and TerminalSteps to the trainers, it first batches the decision steps from the individual environments. When setting actions, it indexes the batched ActionTuple to obtain the ActionTuple for individual agents """ def __init__( self, brain_names, step_size=STEP_SIZE, num_visual=0, num_vector=1, num_var_len=0, vis_obs_size=VIS_OBS_SIZE, vec_obs_size=OBS_SIZE, var_len_obs_size=VAR_LEN_SIZE, action_sizes=(1, 0), num_agents=2, goal_indices=None, ): super().__init__() self.envs = {} self.dones = {} self.just_died = set() self.names = brain_names self.final_rewards: Dict[str, List[float]] = {} for name in brain_names: self.final_rewards[name] = [] for i in range(num_agents): name_and_num = name + str(i) self.envs[name_and_num] = SimpleEnvironment( [name], step_size, num_visual, num_vector, num_var_len, vis_obs_size, vec_obs_size, var_len_obs_size, action_sizes, goal_indices, ) self.dones[name_and_num] = False self.envs[name_and_num].reset() # All envs have the same behavior spec, so just get the last one. self.behavior_spec = self.envs[name_and_num].behavior_spec self.action_spec = self.envs[name_and_num].action_spec self.num_agents = num_agents @property def all_done(self): return all(self.dones.values()) @property def behavior_specs(self): behavior_dict = {} for n in self.names: behavior_dict[n] = self.behavior_spec return BehaviorMapping(behavior_dict) def set_action_for_agent(self, behavior_name, agent_id, action): pass def set_actions(self, behavior_name, action): # The ActionTuple contains the actions for all n_agents. This # slices the ActionTuple into an action tuple for each environment # and sets it. The index j is used to ignore agents that have already # reached done. j = 0 for i in range(self.num_agents): _act = ActionTuple() name_and_num = behavior_name + str(i) env = self.envs[name_and_num] if not self.dones[name_and_num]: if self.action_spec.continuous_size > 0: _act.add_continuous(action.continuous[j : j + 1]) if self.action_spec.discrete_size > 0: _disc_list = [action.discrete[j, :]] _act.add_discrete(np.array(_disc_list)) j += 1 env.action[behavior_name] = _act def get_steps(self, behavior_name): # This gets the individual DecisionSteps and TerminalSteps # from the envs and merges them into a batch to be sent # to the AgentProcessor. dec_vec_obs = [] dec_reward = [] dec_group_reward = [] dec_agent_id = [] dec_group_id = [] ter_vec_obs = [] ter_reward = [] ter_group_reward = [] ter_agent_id = [] ter_group_id = [] interrupted = [] action_mask = None terminal_step = TerminalSteps.empty(self.behavior_spec) decision_step = None for i in range(self.num_agents): name_and_num = behavior_name + str(i) env = self.envs[name_and_num] _dec, _term = env.step_result[behavior_name] if not self.dones[name_and_num]: dec_agent_id.append(i) dec_group_id.append(1) if len(dec_vec_obs) > 0: for j, obs in enumerate(_dec.obs): dec_vec_obs[j] = np.concatenate((dec_vec_obs[j], obs), axis=0) else: for obs in _dec.obs: dec_vec_obs.append(obs) dec_reward.append(_dec.reward[0]) dec_group_reward.append(_dec.group_reward[0]) if _dec.action_mask is not None: if action_mask is None: action_mask = [] if len(action_mask) > 0: action_mask[0] = np.concatenate( (action_mask[0], _dec.action_mask[0]), axis=0 ) else: action_mask.append(_dec.action_mask[0]) if len(_term.reward) > 0 and name_and_num in self.just_died: ter_agent_id.append(i) ter_group_id.append(1) if len(ter_vec_obs) > 0: for j, obs in enumerate(_term.obs): ter_vec_obs[j] = np.concatenate((ter_vec_obs[j], obs), axis=0) else: for obs in _term.obs: ter_vec_obs.append(obs) ter_reward.append(_term.reward[0]) ter_group_reward.append(_term.group_reward[0]) interrupted.append(False) self.just_died.remove(name_and_num) decision_step = DecisionSteps( dec_vec_obs, dec_reward, dec_agent_id, action_mask, dec_group_id, dec_group_reward, ) terminal_step = TerminalSteps( ter_vec_obs, ter_reward, interrupted, ter_agent_id, ter_group_id, ter_group_reward, ) return (decision_step, terminal_step) def step(self) -> None: # Steps all environments and calls reset if all agents are done. for name in self.names: for i in range(self.num_agents): name_and_num = name + str(i) # Does not step the env if done if not self.dones[name_and_num]: env = self.envs[name_and_num] # Reproducing part of env step to intercept Dones assert all(action is not None for action in env.action.values()) done = env._take_action(name) reward = env._compute_reward(name, done) self.dones[name_and_num] = done if done: self.just_died.add(name_and_num) if self.all_done: env.step_result[name] = env._make_batched_step( name, done, 0.0, reward ) self.final_rewards[name].append(reward) self.reset() elif done: # This agent has finished but others are still running. # This gives a reward of the time penalty if this agent # is successful and the negative env reward if it fails. ceil_reward = min(-TIME_PENALTY, reward) env.step_result[name] = env._make_batched_step( name, done, ceil_reward, 0.0 ) self.final_rewards[name].append(reward) else: env.step_result[name] = env._make_batched_step( name, done, reward, 0.0 ) def reset(self) -> None: # type: ignore for name in self.names: for i in range(self.num_agents): name_and_num = name + str(i) self.dones[name_and_num] = False @property def reset_parameters(self) -> Dict[str, str]: return {} def close(self): pass class RecordEnvironment(SimpleEnvironment): def __init__( self, brain_names, step_size=0.2, num_visual=0, num_vector=1, action_sizes=(1, 0), n_demos=30, ): super().__init__( brain_names, step_size=step_size, num_visual=num_visual, num_vector=num_vector, action_sizes=action_sizes, ) self.demonstration_protos: Dict[str, List[AgentInfoActionPairProto]] = {} self.n_demos = n_demos for name in self.names: self.demonstration_protos[name] = [] def step(self) -> None: super().step() for name in self.names: discrete_actions = ( self.action[name].discrete if self.action_spec.discrete_size > 0 else None ) continuous_actions = ( self.action[name].continuous if self.action_spec.continuous_size > 0 else None ) self.demonstration_protos[name] += proto_from_steps_and_action( self.step_result[name][0], self.step_result[name][1], continuous_actions, discrete_actions, ) self.demonstration_protos[name] = self.demonstration_protos[name][ -self.n_demos : ] def solve(self) -> None: self.reset() for _ in range(self.n_demos): for name in self.names: if self.action_spec.discrete_size > 0: self.action[name] = ActionTuple( np.array([], dtype=np.float32), np.array( [[1]] if self.goal[name] > 0 else [[0]], dtype=np.int32 ), ) else: self.action[name] = ActionTuple( np.array([[float(self.goal[name])]], dtype=np.float32), np.array([], dtype=np.int32), ) self.step() class UnexpectedExceptionEnvironment(SimpleEnvironment): def __init__(self, brain_names, use_discrete, to_raise): super().__init__(brain_names, use_discrete) self.to_raise = to_raise def step(self) -> None: raise self.to_raise()
ml-agents/ml-agents/mlagents/trainers/tests/simple_test_envs.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/simple_test_envs.py", "repo_id": "ml-agents", "token_count": 12062 }
1,912
import pytest from unittest import mock import torch # noqa I201 from mlagents.torch_utils import set_torch_config, default_device from mlagents.trainers.settings import TorchSettings @pytest.mark.parametrize( "device_str, expected_type, expected_index, expected_tensor_type", [ ("cpu", "cpu", None, torch.FloatTensor), ("cuda", "cuda", None, torch.cuda.FloatTensor), ("cuda:42", "cuda", 42, torch.cuda.FloatTensor), ("opengl", "opengl", None, torch.FloatTensor), ], ) @mock.patch.object(torch, "set_default_tensor_type") def test_set_torch_device( mock_set_default_tensor_type, device_str, expected_type, expected_index, expected_tensor_type, ): try: torch_settings = TorchSettings(device=device_str) set_torch_config(torch_settings) assert default_device().type == expected_type if expected_index is None: assert default_device().index is None else: assert default_device().index == expected_index mock_set_default_tensor_type.assert_called_once_with(expected_tensor_type) except Exception: raise finally: # restore the defaults torch_settings = TorchSettings(device=None) set_torch_config(torch_settings)
ml-agents/ml-agents/mlagents/trainers/tests/test_torch_utils.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/test_torch_utils.py", "repo_id": "ml-agents", "token_count": 531 }
1,913
import pytest from mlagents.torch_utils import torch import numpy as np from mlagents.trainers.torch_entities.layers import linear_layer from mlagents.trainers.torch_entities.conditioning import ConditionalEncoder def test_conditional_layer_initialization(): b, input_size, goal_size, h, num_cond_layers, num_normal_layers = 7, 10, 8, 16, 2, 1 conditional_enc = ConditionalEncoder( input_size, goal_size, h, num_normal_layers + num_cond_layers, num_cond_layers ) input_tensor = torch.ones(b, input_size) goal_tensor = torch.ones(b, goal_size) output = conditional_enc.forward(input_tensor, goal_tensor) assert output.shape == (b, h) @pytest.mark.parametrize("num_cond_layers", [1, 2, 3]) def test_predict_with_condition(num_cond_layers): np.random.seed(1336) torch.manual_seed(1336) input_size, goal_size, h, num_normal_layers = 10, 1, 16, 1 conditional_enc = ConditionalEncoder( input_size, goal_size, h, num_normal_layers + num_cond_layers, num_cond_layers ) l_layer = linear_layer(h, 1) optimizer = torch.optim.Adam( list(conditional_enc.parameters()) + list(l_layer.parameters()), lr=0.001 ) batch_size = 200 for _ in range(300): input_tensor = torch.rand((batch_size, input_size)) goal_tensor = (torch.rand((batch_size, goal_size)) > 0.5).float() # If the goal is 1: do the sum of the inputs, else, return 0 target = torch.sum(input_tensor, dim=1, keepdim=True) * goal_tensor target.detach() prediction = l_layer(conditional_enc(input_tensor, goal_tensor)) error = torch.mean((prediction - target) ** 2, dim=1) error = torch.mean(error) / 2 print(error.item()) optimizer.zero_grad() error.backward() optimizer.step() assert error.item() < 0.02
ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_conditioning.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_conditioning.py", "repo_id": "ml-agents", "token_count": 764 }
1,914
import pytest from mlagents.torch_utils import torch from mlagents.trainers.buffer import BufferKey, RewardSignalUtil from mlagents.trainers.sac.optimizer_torch import TorchSACOptimizer from mlagents.trainers.policy.torch_policy import TorchPolicy from mlagents.trainers.torch_entities.networks import SimpleActor from mlagents.trainers.tests import mock_brain as mb from mlagents.trainers.settings import NetworkSettings from mlagents.trainers.tests.dummy_config import ( # noqa: F401 sac_dummy_config, curiosity_dummy_config, ) @pytest.fixture def dummy_config(): return sac_dummy_config() VECTOR_ACTION_SPACE = 2 VECTOR_OBS_SPACE = 8 DISCRETE_ACTION_SPACE = [3, 3, 3, 2] BUFFER_INIT_SAMPLES = 64 NUM_AGENTS = 12 def create_sac_optimizer_mock(dummy_config, use_rnn, use_discrete, use_visual): mock_brain = mb.setup_test_behavior_specs( use_discrete, use_visual, vector_action_space=DISCRETE_ACTION_SPACE if use_discrete else VECTOR_ACTION_SPACE, vector_obs_space=VECTOR_OBS_SPACE if not use_visual else 0, ) trainer_settings = dummy_config trainer_settings.network_settings.memory = ( NetworkSettings.MemorySettings(sequence_length=16, memory_size=12) if use_rnn else None ) actor_kwargs = { "conditional_sigma": False, "tanh_squash": False, } policy = TorchPolicy( 0, mock_brain, trainer_settings.network_settings, SimpleActor, actor_kwargs ) optimizer = TorchSACOptimizer(policy, trainer_settings) return optimizer @pytest.mark.parametrize("discrete", [True, False], ids=["discrete", "continuous"]) @pytest.mark.parametrize("visual", [True, False], ids=["visual", "vector"]) @pytest.mark.parametrize("rnn", [True, False], ids=["rnn", "no_rnn"]) def test_sac_optimizer_update(dummy_config, rnn, visual, discrete): torch.manual_seed(0) # Test evaluate optimizer = create_sac_optimizer_mock( dummy_config, use_rnn=rnn, use_discrete=discrete, use_visual=visual ) # Test update update_buffer = mb.simulate_rollout( BUFFER_INIT_SAMPLES, optimizer.policy.behavior_spec, memory_size=12 ) # Mock out reward signal eval update_buffer[RewardSignalUtil.rewards_key("extrinsic")] = update_buffer[ BufferKey.ENVIRONMENT_REWARDS ] # Mock out value memories update_buffer[BufferKey.CRITIC_MEMORY] = update_buffer[BufferKey.MEMORY] return_stats = optimizer.update( update_buffer, num_sequences=update_buffer.num_experiences // optimizer.policy.sequence_length, ) # Make sure we have the right stats required_stats = [ "Losses/Policy Loss", "Losses/Value Loss", "Losses/Q1 Loss", "Losses/Q2 Loss", "Policy/Continuous Entropy Coeff", "Policy/Discrete Entropy Coeff", "Policy/Learning Rate", ] for stat in required_stats: assert stat in return_stats.keys() @pytest.mark.parametrize("discrete", [True, False], ids=["discrete", "continuous"]) def test_sac_update_reward_signals( dummy_config, curiosity_dummy_config, discrete # noqa: F811 ): # Add a Curiosity module dummy_config.reward_signals = curiosity_dummy_config optimizer = create_sac_optimizer_mock( dummy_config, use_rnn=False, use_discrete=discrete, use_visual=False ) # Test update, while removing PPO-specific buffer elements. update_buffer = mb.simulate_rollout( BUFFER_INIT_SAMPLES, optimizer.policy.behavior_spec ) # Mock out reward signal eval update_buffer[RewardSignalUtil.rewards_key("extrinsic")] = update_buffer[ BufferKey.ENVIRONMENT_REWARDS ] update_buffer[RewardSignalUtil.rewards_key("curiosity")] = update_buffer[ BufferKey.ENVIRONMENT_REWARDS ] return_stats = optimizer.update_reward_signals(update_buffer) required_stats = ["Losses/Curiosity Forward Loss", "Losses/Curiosity Inverse Loss"] for stat in required_stats: assert stat in return_stats.keys() if __name__ == "__main__": pytest.main()
ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_sac.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_sac.py", "repo_id": "ml-agents", "token_count": 1651 }
1,915
import numpy as np from typing import Dict from mlagents.trainers.buffer import AgentBuffer, BufferKey from mlagents.trainers.torch_entities.components.reward_providers.base_reward_provider import ( BaseRewardProvider, ) from mlagents_envs.base_env import BehaviorSpec from mlagents.trainers.settings import RewardSignalSettings class ExtrinsicRewardProvider(BaseRewardProvider): """ Evaluates extrinsic reward. For single-agent, this equals the individual reward given to the agent. For the POCA algorithm, we want not only the individual reward but also the team and the individual rewards of the other agents. """ def __init__(self, specs: BehaviorSpec, settings: RewardSignalSettings) -> None: super().__init__(specs, settings) self.add_groupmate_rewards = False def evaluate(self, mini_batch: AgentBuffer) -> np.ndarray: indiv_rewards = np.array( mini_batch[BufferKey.ENVIRONMENT_REWARDS], dtype=np.float32 ) total_rewards = indiv_rewards if BufferKey.GROUPMATE_REWARDS in mini_batch and self.add_groupmate_rewards: groupmate_rewards_list = mini_batch[BufferKey.GROUPMATE_REWARDS] groupmate_rewards_sum = np.array( [sum(_rew) for _rew in groupmate_rewards_list], dtype=np.float32 ) total_rewards += groupmate_rewards_sum if BufferKey.GROUP_REWARD in mini_batch: group_rewards = np.array( mini_batch[BufferKey.GROUP_REWARD], dtype=np.float32 ) # Add all the group rewards to the individual rewards total_rewards += group_rewards return total_rewards def update(self, mini_batch: AgentBuffer) -> Dict[str, np.ndarray]: return {}
ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/extrinsic_reward_provider.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/extrinsic_reward_provider.py", "repo_id": "ml-agents", "token_count": 705 }
1,916
# # Unity ML-Agents Toolkit from typing import List, Deque, Dict import abc from collections import deque from mlagents_envs.logging_util import get_logger from mlagents_envs.base_env import BehaviorSpec from mlagents.trainers.stats import StatsReporter from mlagents.trainers.trajectory import Trajectory from mlagents.trainers.agent_processor import AgentManagerQueue from mlagents.trainers.policy import Policy from mlagents.trainers.behavior_id_utils import BehaviorIdentifiers from mlagents.trainers.settings import TrainerSettings logger = get_logger(__name__) class Trainer(abc.ABC): """This class is the base class for the mlagents_envs.trainers""" def __init__( self, brain_name: str, trainer_settings: TrainerSettings, training: bool, load: bool, artifact_path: str, reward_buff_cap: int = 1, ): """ Responsible for collecting experiences and training a neural network model. :param brain_name: Brain name of brain to be trained. :param trainer_settings: The parameters for the trainer (dictionary). :param training: Whether the trainer is set for training. :param artifact_path: The directory within which to store artifacts from this trainer :param reward_buff_cap: """ self.brain_name = brain_name self.trainer_settings = trainer_settings self._threaded = trainer_settings.threaded self._stats_reporter = StatsReporter(brain_name) self.is_training = training self.load = load self._reward_buffer: Deque[float] = deque(maxlen=reward_buff_cap) self.policy_queues: List[AgentManagerQueue[Policy]] = [] self.trajectory_queues: List[AgentManagerQueue[Trajectory]] = [] self._step: int = 0 self.artifact_path = artifact_path self.summary_freq = self.trainer_settings.summary_freq self.policies: Dict[str, Policy] = {} @property def stats_reporter(self): """ Returns the stats reporter associated with this Trainer. """ return self._stats_reporter @property def parameters(self) -> TrainerSettings: """ Returns the trainer parameters of the trainer. """ return self.trainer_settings @property def get_max_steps(self) -> int: """ Returns the maximum number of steps. Is used to know when the trainer should be stopped. :return: The maximum number of steps of the trainer """ return self.trainer_settings.max_steps @property def get_step(self) -> int: """ Returns the number of steps the trainer has performed :return: the step count of the trainer """ return self._step @property def threaded(self) -> bool: """ Whether or not to run the trainer in a thread. True allows the trainer to update the policy while the environment is taking steps. Set to False to enforce strict on-policy updates (i.e. don't update the policy when taking steps.) """ return self._threaded @property def should_still_train(self) -> bool: """ Returns whether or not the trainer should train. A Trainer could stop training if it wasn't training to begin with, or if max_steps is reached. """ return self.is_training and self.get_step <= self.get_max_steps @property def reward_buffer(self) -> Deque[float]: """ Returns the reward buffer. The reward buffer contains the cumulative rewards of the most recent episodes completed by agents using this trainer. :return: the reward buffer. """ return self._reward_buffer @abc.abstractmethod def save_model(self) -> None: """ Saves model file(s) for the policy or policies associated with this trainer. """ pass @abc.abstractmethod def end_episode(self): """ A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets. """ pass @abc.abstractmethod def create_policy( self, parsed_behavior_id: BehaviorIdentifiers, behavior_spec: BehaviorSpec, ) -> Policy: """ Creates a Policy object """ pass @abc.abstractmethod def add_policy( self, parsed_behavior_id: BehaviorIdentifiers, policy: Policy ) -> None: """ Adds policy to trainer. """ pass def get_policy(self, name_behavior_id: str) -> Policy: """ Gets policy associated with name_behavior_id :param name_behavior_id: Fully qualified behavior name :return: Policy associated with name_behavior_id """ return self.policies[name_behavior_id] @abc.abstractmethod def advance(self) -> None: """ Advances the trainer. Typically, this means grabbing trajectories from all subscribed trajectory queues (self.trajectory_queues), and updating a policy using the steps in them, and if needed pushing a new policy onto the right policy queues (self.policy_queues). """ pass def publish_policy_queue(self, policy_queue: AgentManagerQueue[Policy]) -> None: """ Adds a policy queue to the list of queues to publish to when this Trainer makes a policy update :param policy_queue: Policy queue to publish to. """ self.policy_queues.append(policy_queue) def subscribe_trajectory_queue( self, trajectory_queue: AgentManagerQueue[Trajectory] ) -> None: """ Adds a trajectory queue to the list of queues for the trainer to ingest Trajectories from. :param trajectory_queue: Trajectory queue to read from. """ self.trajectory_queues.append(trajectory_queue) @staticmethod def get_trainer_name() -> str: raise NotImplementedError
ml-agents/ml-agents/mlagents/trainers/trainer/trainer.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/trainer/trainer.py", "repo_id": "ml-agents", "token_count": 2316 }
1,917
syntax = "proto3"; option csharp_namespace = "Unity.MLAgents.CommunicatorObjects"; package communicator_objects; enum CommandProto { STEP = 0; RESET = 1; QUIT = 2; }
ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/command.proto/0
{ "file_path": "ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/command.proto", "repo_id": "ml-agents", "token_count": 87 }
1,918
[pytest] addopts = --strict-markers markers = slow: Slow tests (likely from training)
ml-agents/pytest.ini/0
{ "file_path": "ml-agents/pytest.ini", "repo_id": "ml-agents", "token_count": 33 }
1,919
fileFormatVersion: 2 guid: dfe267f4b0fe1a349a23184f840622bd timeCreated: 1489377018 licenseType: Pro TextScriptImporter: userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Examples/10_SignatureLoader/Resources/signatured2.lua.bytes.meta/0
{ "file_path": "xLua/Assets/XLua/Examples/10_SignatureLoader/Resources/signatured2.lua.bytes.meta", "repo_id": "xLua", "token_count": 71 }
1,920
## xLua通用版本 xLua通用版本致力于在C#环境提供lua脚本支持。相比Unity版本,仅去掉了诸如print重定向到Console窗口,Unity专用的脚本加载器。其它的一切功能都保留。特性列表请看[这里](../Assets/XLua/Doc/features.md)。 ## 如何使用 将XLua.Mini.dll放入工程,对应版本的xlua本地动态库放到能通过pinvoke加载的路径下(比如程序执行目录)。 ## 生成代码[可选] XLua.Mini.dll是通过反射来实现lua与C#间的交互,需要更高性能,可以通过生成代码获得。 1、按教程[XLua的配置.doc](../Assets/XLua/Doc/XLua的配置.doc)配置好要生成的类型; 2、重新编译后,用配套的工具XLuaGenerate对工程的编译结果(exe或者dll)执行代码生成:XLuaGenerate xxx.exe/xxx.dll,生成代码会放在当前目录下的Gen目录。 3、新建一个和原来一样的工程,添加XLUA_GENERAL宏 4、删除XLua.Mini.dll,加入XLua的配套源码包(发布包的Src目录),加入步骤2的生成代码; 5、这工程生成exe或者dll已经通过生成代码适配。 ## Hotfix 对已经生成了代码的exe或者dll,用工具XLuaHotfixInject执行注入即可,Hotfix特性的详细使用请看[Hotfix操作指南](../Assets/XLua/Doc/hotfix.md) ## 快速入门 ~~~csharp using XLua; public class XLuaTest { public static void Main() { LuaEnv luaenv = new LuaEnv(); luaenv.DoString("CS.System.Console.WriteLine('hello world')"); luaenv.Dispose(); } } ~~~
xLua/General/README.md/0
{ "file_path": "xLua/General/README.md", "repo_id": "xLua", "token_count": 953 }
1,921
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{0E713D15-FA69-5C67-239C-41EC0FF43B73}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>XLuaHotfixInject</RootNamespace> <AssemblyName>XLuaHotfixInject</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>..\Tools\</OutputPath> <BaseIntermediateOutputPath>obj\Any CPU\Debug\XLuaHotfixInject\</BaseIntermediateOutputPath> <IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath> <DefineConstants>_DEBUG;DEBUG;TRACE;;HOTFIX_ENABLE;XLUA_GENERAL</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>..\Tools\</OutputPath> <BaseIntermediateOutputPath>obj\Any CPU\Release\XLuaHotfixInject\</BaseIntermediateOutputPath> <IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath> <DefineConstants>;HOTFIX_ENABLE;XLUA_GENERAL</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System"> <HintPath>C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity\System.dll</HintPath> </Reference> <Reference Include="System.Core"> <HintPath>C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity\System.Core.dll</HintPath> </Reference> <Reference Include="Mono.Cecil"> <HintPath>..\Lib\Mono.Cecil.dll</HintPath> </Reference> <Reference Include="Mono.Cecil.Mdb"> <HintPath>..\Lib\Mono.Cecil.Mdb.dll</HintPath> </Reference> <Reference Include="Mono.Cecil.Pdb"> <HintPath>..\Lib\Mono.Cecil.Pdb.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> <Compile Include="..\..\Assets\XLua\Src\Editor\Hotfix.cs"> <Link>Assets\XLua\Src\Editor\Hotfix.cs</Link> </Compile> <Compile Include="..\Src\XLuaHotfixInject.cs"> <Link>Src\XLuaHotfixInject.cs</Link> </Compile> </ItemGroup> <ItemGroup> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
xLua/General/vs2013/XLuaHotfixInject.csproj/0
{ "file_path": "xLua/General/vs2013/XLuaHotfixInject.csproj", "repo_id": "xLua", "token_count": 1271 }
1,922
## 目录说明 * UnitTest : 单元测试用例 * PrefTest : 性能测试用例 ## 使用说明 * 把对应目录下的所有目录拷贝到Assets下,比如你要执行单元测试用例,把UnitTest下两个目录都拷贝到Assets下,然后运行main.unity; * luajit版本比lua53版本性能要好很多,打开HOTFIX_ENABLE或者THREAD_SAFT宏,性能会略降,因为会对所有C#调用lua的地方都会加上锁,所以你要和其它方案对比的话,用luajit版本测试并确认HOTFIX_ENABLE或者THREAD_SAFT没打开; ## 性能用例的说明 * 用例和网上流行的不太一样,原因是: * Unity API本身的开销会影响到测试结果。举个例子:方案A的Lua调用C#函数开销是1ms,方案B是2ms,那么结论应该是A方案性能是B方案两倍,但如果被调用C#函数本身耗时100ms,那结论就是两个方案性能差不多,甚至有时会因为误差得出B方案性能更好的结论; * 如果测试中包含重载函数,对比也是不恰当的,因为每个方案的生成代码对于重载判断的顺序不一定一样,不一样的时候,对比也意义不大; * 测试Lua调用C#部分用例选择了Vector3,这其实是错误的,市面上大多方案的Vector3是完全在Lua测重新实现,完全没有达到测试“Lua调用C#”的目的; * xLua本质上做C#和lua之间的适配,所以所有用例的设计原则都是被调用方无开销,比如函数都是直接return ## 几个值类型的方法的性能说明 * 前面也提到,其它方案的Vector3(相类似的还有Vector2,Vector4,Quaternion,Color等)由于直接在lua测实现,而xLua默认仍然是调用C#的实现,测试这些类型的方法的话,xLua性能相比会低很多 * 你可以选择在lua实现这些方法,配合xlua.genaccessor,性能可以达到同一个数量级。 * xLua一直坚持使用C#原生实现,一年多的项目应用中,也没有反馈因此而造成的性能问题,应该性能是够用的,如果真的出现不够用的情况,选择在lua实现这块逻辑也是不恰当的,应该直接在C#实现比较合适些。
xLua/Test/README.md/0
{ "file_path": "xLua/Test/README.md", "repo_id": "xLua", "token_count": 1466 }
1,923
require("ltest.init") gTestNumber = 1 function islua53() return not not math.type end -- for test case CMyTestCaseLuaCallCSReflect = TestCase:new() function CMyTestCaseLuaCallCSReflect:new(oo) local o = oo or {} o.count = 1 setmetatable(o, self) self.__index = self return o end function CMyTestCaseLuaCallCSReflect.SetUpTestCase(self) self.count = 1 + self.count print("CMyTestCaseLuaCallCSReflect.SetUpTestCase") end function CMyTestCaseLuaCallCSReflect.TearDownTestCase(self) self.count = 1 + self.count print("CMyTestCaseLuaCallCSReflect.TearDownTestCase") end function CMyTestCaseLuaCallCSReflect.SetUp(self) self.count = 1 + self.count print("CMyTestCaseLuaCallCSReflect.SetUp") end function CMyTestCaseLuaCallCSReflect.TearDown(self) self.count = 1 + self.count print("CMyTestCaseLuaCallCSReflect.TearDown") end function CMyTestCaseLuaCallCSReflect.CaseDefaultParamFunc1(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.DefaultParaFuncSingle(100, "abc") ASSERT_EQ(ret, 100) end function CMyTestCaseLuaCallCSReflect.CaseDefaultParamFunc2(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.DefaultParaFuncSingle(100) ASSERT_EQ(ret, 100) end function CMyTestCaseLuaCallCSReflect.CaseDefaultParamFunc3(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.DefaultParaFuncMulti(100, "") ASSERT_EQ(ret, 101) end function CMyTestCaseLuaCallCSReflect.CaseDefaultParamFunc4(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.DefaultParaFuncMulti(100, "efg", 1) ASSERT_EQ(ret, 101) end function CMyTestCaseLuaCallCSReflect.CaseDefaultParamFunc5(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.DefaultParaFuncMulti(100, "efg", 1, 98) ASSERT_EQ(ret, 101) end function CMyTestCaseLuaCallCSReflect.CaseDefaultParamFunc6(self) self.count = 1 + self.count --if (CS.LuaTestCommon.IsMacPlatform() == false) then if (true) then local ret, error = pcall(function() CS.LuaTestObjReflect.DefaultParaFuncMulti(100, "efg", 1, 98, 0) end) ASSERT_EQ(ret, false) else ASSERT_EQ(true, false) end end function CMyTestCaseLuaCallCSReflect.CaseVariableParamFunc1(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.VariableParamFunc(0) ASSERT_EQ(ret, 0) end function CMyTestCaseLuaCallCSReflect.CaseVariableParamFunc2(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.VariableParamFunc(0, "a") ASSERT_EQ(ret, 0) end function CMyTestCaseLuaCallCSReflect.CaseVariableParamFunc3(self) self.count = 1 + self.count --if (CS.LuaTestCommon.IsMacPlatform() == false) then if (true) then local ret, error = pcall(function() CS.LuaTestObjReflect.VariableParamFunc(0, "a", 1, "b") end) ASSERT_EQ(ret, true) else ASSERT_EQ(true, false) end end function CMyTestCaseLuaCallCSReflect.CaseLuaAccessEnum1(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.TestEnumFunc(CS.LuaTestTypeReflect.DEF) ASSERT_EQ(ret, 1) end --[[ 2016.11.25 新版本不支持整数直接当枚举用 function CMyTestCaseLuaCallCSReflect.CaseLuaAccessEnum2(self) self.count = 1 + self.count local enumValue = -1 local ret = CS.LuaTestObjReflect.TestEnumFunc(enumValue) ASSERT_EQ(ret, -1) end ]] function CMyTestCaseLuaCallCSReflect.CaseLuaAccessEnum3(self) self.count = 1 + self.count local enumValue = CS.LuaTestTypeReflect.__CastFrom(2) local ret = CS.LuaTestObjReflect.TestEnumFunc(enumValue) ASSERT_EQ(ret, 2) end function CMyTestCaseLuaCallCSReflect.CaseLuaAccessEnum4(self) self.count = 1 + self.count local enumValue = CS.LuaTestTypeReflect.__CastFrom(4) local ret = CS.LuaTestObjReflect.TestEnumFunc(enumValue) ASSERT_EQ(ret, 4) end function CMyTestCaseLuaCallCSReflect.CaseLuaAccessEnum5(self) self.count = 1 + self.count local enumValue = CS.LuaTestTypeReflect.__CastFrom("GHI") local ret = CS.LuaTestObjReflect.TestEnumFunc(enumValue) ASSERT_EQ(ret, 2) end function CMyTestCaseLuaCallCSReflect.CaseLuaAccessEnum6(self) self.count = 1 + self.count --if (CS.LuaTestCommon.IsMacPlatform() == false and CS.LuaTestCommon.IsIOSPlatform() == false) then if (true) then local ret, error = pcall(function() CS.LuaTestObjReflect.TestEnumFunc(CS.LuaTestTypeReflect.__CastFrom("BCD")) end) ASSERT_EQ(ret, false) else ASSERT_EQ(true, false) end end function CMyTestCaseLuaCallCSReflect.CaseGetType1(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.TestGetType(typeof(CS.LuaTestObjReflect)) ASSERT_EQ(ret, "LuaTestObjReflect") end function CMyTestCaseLuaCallCSReflect.CaseGetType2(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.TestGetType(typeof(CS.System.String)) ASSERT_EQ(ret, "System.String") end function CMyTestCaseLuaCallCSReflect.CaseGetType3(self) self.count = 1 + self.count if CS.LuaTestCommon.IsXLuaGeneral() then return end local ret = CS.LuaTestObjReflect.TestGetType(typeof(CS.UnityEngine.Vector3)) ASSERT_EQ(ret, "UnityEngine.Vector3") end function CMyTestCaseLuaCallCSReflect.CaseGetType4(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.TestGetType(typeof(CS.System.Int16)) ASSERT_EQ(ret, "System.Int16") end function CMyTestCaseLuaCallCSReflect.CaseGetType5(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.TestGetType(typeof(CS.XLua.LuaTable)) ASSERT_EQ(ret, "XLua.LuaTable") end function CMyTestCaseLuaCallCSReflect.CaseGetType6(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.TestGetType(typeof(CS.XLua.LuaFunction)) ASSERT_EQ(ret, "XLua.LuaFunction") end --[[ v2.1.0中已将LuaUserData类去掉 function CMyTestCaseLuaCallCSReflect.CaseGetType7(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.TestGetType(typeof(CS.XLua.LuaUserData)) ASSERT_EQ(ret, "XLua.LuaUserData") end ]] function CMyTestCaseLuaCallCSReflect.Case64BitInt1(self) self.count = 1 + self.count CS.LuaTestObjReflect.Gen64BitInt() local x1 = CS.LuaTestObjReflect.ulX1 local x2 = CS.LuaTestObjReflect.ulX2 local ret = x1 + x2 ASSERT_EQ("6917529027641081856", tostring(ret)) ret = x2 - x1 --ASSERT_EQ("16140901064495857664", tostring(ret)) ASSERT_EQ("-2305843009213693952", tostring(ret)) x1 = CS.LuaTestObjReflect.lY1 x2 = CS.LuaTestObjReflect.lY2 ret = x1 + x2 ASSERT_EQ("6917529027641081856", tostring(ret)) ret = x2 - x1 ASSERT_EQ("-2305843009213693952", tostring(ret)) x1 = CS.LuaTestObjReflect.i64Z1 x2 = CS.LuaTestObjReflect.i64Z2 ret = x1 + x2 ASSERT_EQ("6917529027641081856", tostring(ret)) ret = x2 - x1 ASSERT_EQ("-2305843009213693952", tostring(ret)) end function CMyTestCaseLuaCallCSReflect.Case64BitInt2(self) self.count = 1 + self.count CS.LuaTestObjReflect.Gen64BitInt() local x1 = CS.LuaTestObjReflect.ulX1 local x2 = CS.LuaTestObjReflect.ulX2 ASSERT_EQ(true, x2 < x1) ASSERT_EQ(true, x2 <= x1) ASSERT_EQ(false, x1 <= x2) ASSERT_EQ(false, x1 < x2) end function CMyTestCaseLuaCallCSReflect.Case64BitInt3(self) self.count = 1 + self.count CS.LuaTestObjReflect.Gen64BitInt() local y = CS.LuaTestObjReflect.lY3 y = y * 100 ASSERT_EQ(tostring(y), "112589990684262400") y = y / 10000 if islua53() then ASSERT_EQ(tostring(y), "11258999068426.0") else ASSERT_EQ(tostring(y), "11258999068426") end y = y % 1000 if islua53() then ASSERT_EQ(tostring(y), "426.240234375") else ASSERT_EQ(tostring(y), "426") end end function CMyTestCaseLuaCallCSReflect.Case64BitInt4(self) self.count = 1 + self.count CS.LuaTestObjReflect.Gen64BitInt() local ret = CS.LuaTestObjReflect.lY3 * CS.LuaTestObjReflect.lY4 ASSERT_EQ(tostring(ret), "138485688541642752") ret = CS.LuaTestObjReflect.lY3 / CS.LuaTestObjReflect.lY5 if islua53() then ASSERT_EQ(tostring(ret), "91202908614.226") else ASSERT_EQ(tostring(ret), "91202908614") end ret = CS.LuaTestObjReflect.lY3 % CS.LuaTestObjReflect.lY6 ASSERT_EQ(tostring(ret), "52636") end function CMyTestCaseLuaCallCSReflect.CaseCast1(self) self.count = 1 + self.count local castObj = CS.TestCastClassReflect() cast(castObj, typeof(CS.TestCastClassReflect)) ASSERT_EQ(true, castObj:TestFunc1()) end function CMyTestCaseLuaCallCSReflect.CaseCast2(self) self.count = 1 + self.count local castObj = CS.LuaTestObjReflect.CreateTestLuaObj() cast(castObj, typeof(CS.TestLuaClassReflect)) ASSERT_EQ(true, castObj:TestFunc1()) end function LuaFunc1(x) return x + 1 end function LuaFunc2(x) return x * 2 end function CMyTestCaseLuaCallCSReflect.CaseDelgate1(self) self.count = 1 + self.count CS.LuaTestObjReflect.initNumber = 5 CS.LuaTestObjReflect.GenDelegate() local luaDelgateLink = CS.LuaTestObjReflect.csDelegate luaDelgateLink = CS.LuaTestObjReflect.csDelegate1 luaDelgateLink = luaDelgateLink + CS.LuaTestObjReflect.csDelegate2 luaDelgateLink = luaDelgateLink + CS.LuaTestObjReflect.csDelegate3 local ret = luaDelgateLink(1) ASSERT_EQ(5, ret) luaDelgateLink = luaDelgateLink + LuaFunc1 ret = luaDelgateLink(1) ASSERT_EQ(2, ret) CS.LuaTestObjReflect.csDelegate4 = LuaFunc2 luaDelgateLink = luaDelgateLink + CS.LuaTestObjReflect.csDelegate4 ret = luaDelgateLink(2) ASSERT_EQ(4, ret) luaDelgateLink = luaDelgateLink - LuaFunc1 ret = luaDelgateLink(10) ASSERT_EQ(20 ,ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate4 ret = luaDelgateLink(19) ASSERT_EQ(1900, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate3 ret = luaDelgateLink(2) ASSERT_EQ(1900, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate2 ret = luaDelgateLink(3) ASSERT_EQ(1903, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate2 ret = luaDelgateLink(4) ASSERT_EQ(1907, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate1 local ret, error = pcall(function() luaDelgateLink(5) end) ASSERT_EQ(false, ret) CS.LuaTestObjReflect.initNumber = 5 luaDelgateLink = CS.LuaTestObjReflect.csDelegate3 ret = luaDelgateLink(1) ASSERT_EQ(5, ret) luaDelgateLink = luaDelgateLink + CS.LuaTestObjReflect.csDelegate1 ret = luaDelgateLink(1) ASSERT_EQ(6, ret) luaDelgateLink = luaDelgateLink + CS.LuaTestObjReflect.csDelegate1 ret = luaDelgateLink(1) ASSERT_EQ(8, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate1 ret = luaDelgateLink(1) ASSERT_EQ(9, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate1 ret = luaDelgateLink(1) ASSERT_EQ(9, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate3 CS.LuaTestObjReflect.initNumber = 1 local function LuaFunc4(x) CS.LuaTestObjReflect.initNumber = CS.LuaTestObjReflect.initNumber * 2 return CS.LuaTestObjReflect.initNumber end luaDelgateLink = CS.LuaTestObjReflect.csDelegate1 luaDelgateLink = luaDelgateLink + LuaFunc4 ret = luaDelgateLink(1) ASSERT_EQ(ret, 4) luaDelgateLink = luaDelgateLink + LuaFunc4 ret = luaDelgateLink(1) ASSERT_EQ(ret, 20) luaDelgateLink = luaDelgateLink - LuaFunc4 ret = luaDelgateLink(1) ASSERT_EQ(ret, 42) luaDelgateLink = luaDelgateLink - LuaFunc4 ret = luaDelgateLink(1) ASSERT_EQ(ret, 43) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate1 CS.LuaTestObjReflect.initNumber = 1907 luaDelgateLink = LuaFunc1 ret = luaDelgateLink(1) ASSERT_EQ(2, ret) luaDelgateLink = luaDelgateLink + CS.LuaTestObjReflect.csDelegate1 ret = luaDelgateLink(2) ASSERT_EQ(1909, ret) luaDelgateLink = luaDelgateLink + CS.LuaTestObjReflect.csDelegate4 ret = luaDelgateLink(3) ASSERT_EQ(6, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate1 ret = luaDelgateLink(4) ASSERT_EQ(8, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate1 ret = luaDelgateLink(5) ASSERT_EQ(10, ret) luaDelgateLink = luaDelgateLink - LuaFunc1 ret = luaDelgateLink(6) ASSERT_EQ(12, ret) luaDelgateLink = luaDelgateLink - LuaFunc1 ret = luaDelgateLink(7) ASSERT_EQ(14, ret) luaDelgateLink = luaDelgateLink - CS.LuaTestObjReflect.csDelegate4 local ret, error = pcall(function() luaDelgateLink(8) end) ASSERT_EQ(false, ret) end function EvtFunc11(y) gTestNumber = y + gTestNumber return gTestNumber end function EvtFunc12(y) gTestNumber = y + 1 + gTestNumber return gTestNumber end function CMyTestCaseLuaCallCSReflect.CaseEvent1(self) self.count = 1 + self.count gTestNumber = 1 local testObj = CS.LuaTestObjReflect() testObj:TestEvent1('+', EvtFunc11) local ret = testObj:CallEvent(1) ASSERT_EQ(2, ret) testObj:TestEvent1('+', EvtFunc12) local ret = testObj:CallEvent(2) ASSERT_EQ(7, ret) testObj:TestEvent1('+', EvtFunc12) local ret = testObj:CallEvent(1) ASSERT_EQ(12, ret) testObj:TestEvent1('-', EvtFunc12) local ret = testObj:CallEvent(1) ASSERT_EQ(15, ret) testObj:TestEvent1('-', EvtFunc12) local ret = testObj:CallEvent(1) ASSERT_EQ(16, ret) testObj:TestEvent1('-', EvtFunc12) local ret = testObj:CallEvent(1) ASSERT_EQ(17, ret) testObj:TestEvent1('-', EvtFunc11) end function CMyTestCaseLuaCallCSReflect.CaseCalc1(self) self.count = 1 + self.count local a = CS.LuaTestObjReflect() a.testVar = 100 local b = CS.LuaTestObjReflect() b.testVar = 200 local ret = a + b ASSERT_EQ(ret.testVar, 300) ret = a - b ASSERT_EQ(ret.testVar, -100) ret = a * b ASSERT_EQ(ret.testVar, 20000) ret = b / a ASSERT_EQ(ret.testVar, 2) ret = b % a ASSERT_EQ(ret.testVar, 0) ret = a < b ASSERT_EQ(true, ret) ret = a <= b ASSERT_EQ(true, ret) ret = -a ASSERT_EQ(ret.testVar, -100) local c = CS.LuaTestObjReflect() c.testArr[0] = 1000 ret = c[0] ASSERT_EQ(1000, ret) c[1] = 10000 ret = c.testArr[1] ASSERT_EQ(10000, ret) a.testVar = 100 b.testVar = 200 c.testVar = 300 local d = CS.LuaTestObjReflect() d.testVar = 20 local e = CS.LuaTestObjReflect() e.testVar = 7 ret = (a + b) * c / d % e ASSERT_EQ(ret.testVar, 6) end function CMyTestCaseLuaCallCSReflect.CaseCalc2(self) self.count = 1 + self.count local a = CS.LuaTestObjReflect() a.testVar = 100 local ret = 300 + a + 200 ASSERT_EQ(ret.testVar, 600) ret = 100 - a - 400 ASSERT_EQ(ret.testVar, -400) ret = 2 * a * 3 ASSERT_EQ(600, ret.testVar) ret = 20000 / a / 2 ASSERT_EQ(100, ret.testVar) end function CMyTestCaseLuaCallCSReflect.CaseOverLoad1(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.OverLoad1(1, 2) ASSERT_EQ(ret, 1) ret = CS.LuaTestObjReflect.OverLoad2("1", "2") ASSERT_EQ(ret, 4); ret = CS.LuaTestObjReflect.OverLoad3(1) ASSERT_EQ(ret, 5); end function CMyTestCaseLuaCallCSReflect.CaseOutRef1(self) self.count = 1 + self.count local a = 2 local b a, b = CS.LuaTestObjReflect.OutRefFunc1(1, a, b) ASSERT_EQ(a, 100) b, a = CS.LuaTestObjReflect.OutRefFunc2(b, 1, a) ASSERT_EQ(a, 200) a, b = CS.LuaTestObjReflect.OutRefFunc3(1, a, b) ASSERT_EQ(a, 300) ret, a, b = CS.LuaTestObjReflect.OutRefFunc4(1, a, b) ASSERT_EQ(a, 400) ASSERT_EQ(ret, 400) ret, b, a = CS.LuaTestObjReflect.OutRefFunc5(b, 1, a) ASSERT_EQ(a, 500) ASSERT_EQ(ret, 500) ret = CS.LuaTestObjReflect.OutRefFunc6(1, 2) ASSERT_EQ(ret, 600) end function CMyTestCaseLuaCallCSReflect.CaseOutRef2(self) self.count = 1 + self.count local a = CS.LuaTestObjReflect.CreateTestLuaObj() local b = CS.LuaTestObjReflect.CreateTestLuaObj() local c = CS.LuaTestObjReflect.CreateTestLuaObj() a, b = CS.LuaTestObjReflect.OutRefFunc11(c, a, b) ASSERT_EQ(a.cmpTarget, 100) b, a = CS.LuaTestObjReflect.OutRefFunc12(b, c, a) ASSERT_EQ(a.cmpTarget, 200) a, b = CS.LuaTestObjReflect.OutRefFunc13(c, a, b) ASSERT_EQ(a.cmpTarget, 300) ret, a, b = CS.LuaTestObjReflect.OutRefFunc14(c, a, b) ASSERT_EQ(a.cmpTarget, 400) ASSERT_EQ(ret, 400) ret, b, a = CS.LuaTestObjReflect.OutRefFunc15(b, c, a) ASSERT_EQ(a.cmpTarget, 500) ASSERT_EQ(ret, 500) ret = CS.LuaTestObjReflect.OutRefFunc16(a, b) ASSERT_EQ(ret, 600) end function CMyTestCaseLuaCallCSReflect.CaseOutRef3(self) self.count = 1 + self.count local a = CS.LuaTestObjReflect.csDelegate11 local b = CS.LuaTestObjReflect.csDelegate12 local c = CS.LuaTestObjReflect.csDelegate13 CS.LuaTestObjReflect.initNumber = 1 a, b = CS.LuaTestObjReflect.OutRefFunc21(c, a, b) ASSERT_EQ(a(1), 2) b, a = CS.LuaTestObjReflect.OutRefFunc22(b, c, a) ASSERT_EQ(a(1), 3) a, b = CS.LuaTestObjReflect.OutRefFunc23(c, a, b) ASSERT_EQ(a(1), 4) ret, a, b = CS.LuaTestObjReflect.OutRefFunc24(c, a, b) ASSERT_EQ(a(1), 6) ASSERT_EQ(ret, 5) ret, b, a = CS.LuaTestObjReflect.OutRefFunc25(b, c, a) ASSERT_EQ(a(1), 8) ASSERT_EQ(ret, 7) ret = CS.LuaTestObjReflect.OutRefFunc26(a, b) ASSERT_EQ(ret, 600) end function CMyTestCaseLuaCallCSReflect.CaseNewClass1And5(self) self.count = 1 + self.count local class = CS.NoContClass() local ret = class:add(1,2) ASSERT_EQ(ret, 3) end function CMyTestCaseLuaCallCSReflect.CaseNewClass2(self) self.count = 1 + self.count local class = CS.testLuaCallCS.OneParamContClass(2) local ret = class:add(1,2) ASSERT_EQ(ret, 3) ASSERT_EQ(class.key1, 2) ASSERT_EQ(class.key2, 1) end function CMyTestCaseLuaCallCSReflect.CaseNewClass3(self) self.count = 1 + self.count local class = CS.testLuaCallCS.TwoParamsContClass(2, 3) local ret = class:add(1,2) ASSERT_EQ(ret, 3) ASSERT_EQ(class.key1, 2) ASSERT_EQ(class.key2, 3) end function CMyTestCaseLuaCallCSReflect.CaseNewClass4(self) self.count = 1 + self.count local class1 = CS.testLuaCallCS.MultiContClass(2) local class2 = CS.testLuaCallCS.MultiContClass() local ret = class1:add(1,2) ASSERT_EQ(ret, 3) ASSERT_EQ(class1.key1, 2) ASSERT_EQ(class1.key2, 1) ret = class2:add(2,2) ASSERT_EQ(ret, 4) ASSERT_EQ(class2.key1, 1) ASSERT_EQ(class2.key2, 1) end function CMyTestCaseLuaCallCSReflect.CaseNewClass6(self) self.count = 1 + self.count local class = CS.testLuaCallCS.OverClassA() local ret = class:add(1,2) ASSERT_EQ(ret, 3) ret = class:sub(9, 1) ASSERT_EQ(ret, 8) ASSERT_EQ(class.key1, 1) ASSERT_EQ(class.key2, 1) ASSERT_EQ(class.key3, 0) end function CMyTestCaseLuaCallCSReflect.CaseNewClass7(self) self.count = 1 + self.count CS.testLuaCallCS.StaticTestClass.n = 0 CS.testLuaCallCS.StaticTestClass:Add() ASSERT_EQ(CS.testLuaCallCS.StaticTestClass.n, 1) end function CMyTestCaseLuaCallCSReflect.CaseVisitStaticMemFunc_1(self) self.count = 1 + self.count CS.testLuaCallCS.MultiContClass.d = 3 local ret = CS.testLuaCallCS.MultiContClass.d ASSERT_EQ(ret, 3) ret = CS.testLuaCallCS.MultiContClass.dec(10, 1) ASSERT_EQ(ret, 9) end function CMyTestCaseLuaCallCSReflect.CaseVisitStaticMemFunc_2(self) self.count = 1 + self.count CS.NoContClass.d = 4 local ret = CS.NoContClass.d ASSERT_EQ(ret, 4) ret = CS.NoContClass.dec(10, 1) ASSERT_EQ(ret, 9) end function CMyTestCaseLuaCallCSReflect.CaseVisitStaticMemFunc_3(self) self.count = 1 + self.count CS.testLuaCallCS.StaticTestClass.n = 2 CS.testLuaCallCS.StaticTestClass:Add() ASSERT_EQ(CS.testLuaCallCS.StaticTestClass.n, 3) end function CMyTestCaseLuaCallCSReflect.CaseVisitClassMemFunc_1(self) self.count = 1 + self.count local class = CS.NoContClass() local ret = class:add(1,2) ASSERT_EQ(ret, 3) class.key3 = false; ASSERT_EQ(class.key3, false) end function CMyTestCaseLuaCallCSReflect.CaseVisitClassMemFunc_2(self) self.count = 1 + self.count local class = CS.testLuaCallCS.OneParamContClass(2) local ret = class:add(1,2) ASSERT_EQ(ret, 3) class.key1 = 3 class.key2 = 4 ASSERT_EQ(class.key1, 3) ASSERT_EQ(class.key2, 4) end function CMyTestCaseLuaCallCSReflect.CaseVisitFatherClassMemFunc_1_1(self) self.count = 1 + self.count local class = CS.testLuaCallCS.OverClassC() CS.testLuaCallCS.OverClassC.bValue = true ASSERT_EQ(CS.testLuaCallCS.OverClassC.bValue, true) CS.testLuaCallCS.OverClassC.Set(false) ASSERT_EQ(CS.testLuaCallCS.OverClassC.bValue, false) CS.testLuaCallCS.OverClassC.d = 3 ASSERT_EQ(CS.testLuaCallCS.OverClassC.d, 3) local ret = CS.testLuaCallCS.OverClassC.dec(10, 1) ASSERT_EQ(ret, 9) class.key4 = 5 class.key1 = 1 class.key3 = false ret = class:sub(10, 1) ASSERT_EQ(ret, 10) ASSERT_EQ(class.key4 , 5) ASSERT_EQ(class.key1 , 1) ASSERT_EQ(class.key3 , false) ASSERT_EQ(class:add(1,2), 3) --ASSERT_EQ(class:sum(1, 2, 3), 6) end function CMyTestCaseLuaCallCSReflect.CaseVisitFatherClassMemFunc_1_2(self) self.count = 1 + self.count local class = CS.testLuaCallCS.OverClassB() CS.testLuaCallCS.OverClassB.d = 3 ASSERT_EQ(CS.testLuaCallCS.OverClassB.d, 3) local ret = CS.testLuaCallCS.OverClassB.dec(10, 1) ASSERT_EQ(ret, 9) class.key1 = 2 class.key2 = 3 ret = class:add(10, 1) ASSERT_EQ(ret, 11) ASSERT_EQ(class.key1, 2) ASSERT_EQ(class.key2, 3) ret = class:sub(10, 1) ASSERT_EQ(ret, 9) end function CMyTestCaseLuaCallCSReflect.CaseVisitFatherClassMemFunc_2(self) self.count = 1 + self.count local class = CS.testLuaCallCS.OverClassCDeriveNGA() --[[CS.testLuaCallCS.OverClassCDeriveNGA.bValue = true ASSERT_EQ(CS.testLuaCallCS.OverClassCDeriveNGA.bValue, true) CS.testLuaCallCS.OverClassCDeriveNGA.Set(false) ASSERT_EQ(CS.testLuaCallCS.OverClassCDeriveNGA.bValue, false)]] CS.testLuaCallCS.OverClassCDeriveNGA.d = 3 ASSERT_EQ(CS.testLuaCallCS.OverClassCDeriveNGA.d, 3) local ret = CS.testLuaCallCS.OverClassCDeriveNGA.dec(10, 1) ASSERT_EQ(ret, 9) --class.key4 = 5 class.key1 = 1 class.key3 = false --ret = class:sub(10, 1) --ASSERT_EQ(ret, 9) --ASSERT_EQ(class.key4 , 5) ASSERT_EQ(class.key1 , 1) ASSERT_EQ(class.key3 , false) ASSERT_EQ(class:add(1,2), 3) end function CMyTestCaseLuaCallCSReflect.CaseVisitFatherClassMemFunc_3(self) self.count = 1 + self.count local class = CS.testLuaCallCS.ChildCalss() local ret = class:add(10, 1) ASSERT_EQ(ret, 11) class.a = 3 ASSERT_EQ(class:getA() , 3) class:setA(4) ASSERT_EQ(class:getA() , 4) end function CMyTestCaseLuaCallCSReflect.CaseGetChineseString(self) self.count = 1 + self.count local class = CS.TestChineseStringReflect() local ret = class:GetShortChinString() ASSERT_EQ(ret, "中文字符串") ASSERT_EQ(class:GetLongChineString() , "为Unity3D增加Lua脚本编程的能力,进而提供代码逻辑增量更新的可能,支持lua的所有基本类型,哈哈哈哈") ASSERT_EQ(class:GetCombineString() , "中文字符串.* ? [ ] ^ $~`!@#$%^&()_-+=[];',““〈〉〖【℃ $ ¤№ ☆ ★■ⅷ②㈣12345abc") ASSERT_EQ(class:GetComplexString() , "繁體國陸") ASSERT_EQ(class:GetHuoxingString() , "吙煋呅僦媞這樣孒") end function CMyTestCaseLuaCallCSReflect.CaseVisitUlong(self) self.count = 1 + self.count local class = CS.TestUlongAndLongTypeReflect() local ulong_max = class.UlongMax --ASSERT_EQ(tostring(ulong_max), "18446744073709551615") ASSERT_EQ(tostring(ulong_max), "-1") --V2.1.1 --ASSERT_EQ(tostring(class:UlongAdd()), "18446744073709550616") ASSERT_EQ(tostring(class:UlongAdd()), "-1000") --V2.1.1 local ulong_min = class.UlongMin ASSERT_EQ(tostring(ulong_min), "0") local ulong_mid = class.UlongMid --ASSERT_EQ(tostring(ulong_mid), "9223372036854775808") ASSERT_EQ(tostring(ulong_mid), "-9223372036854775808") --v2.1.1 class.UlongMax = 1844674407370955 ulong_max = class.UlongMax ASSERT_EQ(tostring(ulong_max), "1844674407370955") class.UlongMin = 100 ulong_min = class.UlongMin ASSERT_EQ(tostring(ulong_min), "100") local ulong_add = ulong_min + ulong_mid --ASSERT_EQ(tostring(ulong_add), "9223372036854775908") ASSERT_EQ(tostring(ulong_add), "-9223372036854775708") --V2.1.1 end function CMyTestCaseLuaCallCSReflect.CaseVisitlong(self) self.count = 1 + self.count local class = CS.TestUlongAndLongTypeReflect() local long_max = class.LongMax ASSERT_EQ(tostring(long_max), "9223372036854775807") ASSERT_EQ(tostring(class:LongAdd()), "9223372036854774808") local long_min = class.LongMin ASSERT_EQ(tostring(long_min), "-9223372036854775808") local long_mid = class.LongMid ASSERT_EQ(tostring(long_mid), "4611686018427387904") class.LongMax = 461168601842738 long_max = class.LongMax ASSERT_EQ(tostring(long_max), "461168601842738") class.LongMin = 100 long_min = class.LongMin ASSERT_EQ(tostring(long_min), "100") local long_add = long_min + long_mid ASSERT_EQ(tostring(long_add), "4611686018427388004") class.UlongMin = 100 ulong_min = class.UlongMin ASSERT_EQ(tostring(ulong_min), "100") --local ret,errMessage = pcall(ulong_min + long_min) --ASSERT_EQ(errMessage, "type not match, lhs is UInt64, rhs is Int64") end function CMyTestCaseLuaCallCSReflect.CaseVisitExtensionMethodForClass(self) self.count = 1 + self.count local class = CS.TestChineseStringReflect() class:PrintAllString() local length = class:GetLongStringLength() ASSERT_EQ(54, length) length = class:Add(class) ASSERT_EQ(108, length) local class_a = CS.TestChineseStringReflect() class_a.short_simple_string = "啊" ASSERT_EQ(class_a:GetShortChinString() , "啊") local class_d = CS.TestChineseStringReflect() class_d.short_simple_string = "ha" local ret1 local ret2 ret1, ret2 = class:Replace(class_d, class_a) ASSERT_EQ(ret1:GetShortChinString(), "中文字符串") ASSERT_EQ(ret2:GetCombineString(), "中文字符串") ASSERT_EQ(ret2:GetShortChinString(), "中文字符串ha") end function CMyTestCaseLuaCallCSReflect.CaseVisitExtensionMethodForStruct(self) self.count = 1 + self.count local employ_1 = CS.EmployeestructReflect() employ_1.Name = "HONGFANG" employ_1.Age = 30 employ_1.Salary = 12000 employ_1.AnnualBonus = 30000 employ_1:PrintSalary() local income = employ_1:GetIncomeForOneYear() ASSERT_EQ(income, 174000) local employ_2 = CS.EmployeestructReflect() employ_2.Name = "xiaojun" employ_2.Age =25 employ_2.Salary = 5000 employ_2.AnnualBonus = 10000 employ_2:PrintSalary() local cost = employ_1:Add(employ_2) ASSERT_EQ(cost, 244000) local employ_3 = CS.EmployeestructReflect() employ_3.Name = "xiaojuan" employ_3.Age =25 employ_3.Salary = 5000 employ_3.AnnualBonus = 10000 employ_3:PrintSalary() local ret1 local ret2 ret1, ret2 = employ_1:Sub(employ_2, employ_3) ASSERT_EQ(ret1.Name, "xiaojun") ASSERT_EQ(ret1.Salary, 10000) ASSERT_EQ(ret2.Name, "xiaojuan") ASSERT_EQ(ret2.Salary, 7000) end function CMyTestCaseLuaCallCSReflect.CaseVisitStruct_21(self) --21.A继承B,B继承C, A,C生成代码,B不生成代码--->B也需要生成代码,或者A,B,C全部不生成代码 self.count = 1 + self.count --22.A的实例访问B,C的struct类型属性 local class_a = CS.AClassReflect(1, 2, "haha") ASSERT_EQ(class_a.BConStruct.x, 1) ASSERT_EQ(class_a.BConStruct.y, 2) ASSERT_EQ(class_a.BConStruct.z, "haha") ASSERT_EQ(class_a.CConStruct.x, 1) ASSERT_EQ(class_a.CConStruct.y, 2) ASSERT_EQ(class_a.CConStruct.z, "haha") --23.A的实例调用B的输入,输出,输入输出为struct类型的方法 local struct_1 = CS.HasConstructStructReflect(2, 3, "TEST") ASSERT_EQ(struct_1.x, 2) ASSERT_EQ(struct_1.y, 3) ASSERT_EQ(struct_1.z, "TEST") local struct_2 = CS.HasConstructStructReflect(10, 1, "heihei") local ret1, ret2 = class_a:Sub(struct_1, struct_2) ASSERT_EQ(struct_2.x, 2) ASSERT_EQ(ret1.x, 2) ASSERT_EQ(ret1.y, 1) ASSERT_EQ(ret1.z, "heihei") ASSERT_EQ(ret2.x, -8) ASSERT_EQ(ret2.y, 3) ASSERT_EQ(ret2.z, "TEST") --24.A的实例调用C的输入,输出,输入输出为struct类型的方法 local ret3, ret4 = class_a:Add(struct_1, struct_2) ASSERT_EQ(struct_2.x, 2) ASSERT_EQ(ret3.x, 2) ASSERT_EQ(ret3.y, 1) ASSERT_EQ(ret3.z, "heihei") ASSERT_EQ(ret4.x, 4) ASSERT_EQ(ret4.y, 3) ASSERT_EQ(ret4.z, "TEST") end function CMyTestCaseLuaCallCSReflect.CaseVisitStructVaribleParam(self) --可变函数参数为struct self.count = 1 + self.count local struct_1 = CS.HasConstructStructReflect(2, 3, "TEST") local struct_2 = CS.HasConstructStructReflect(10, 1, "heihei") local class_c = CS.CClassReflect(1, 2, "haha") local ret = class_c:VariableParamFunc(struct_1, struct_2) ASSERT_EQ(ret, 12) end function CMyTestCaseLuaCallCSReflect.CaseEventStatic(self) self.count = 1 + self.count gTestNumber = 1 CS.LuaTestObjReflect.TestStaticEvent1('+', EvtFunc11) local ret = CS.LuaTestObjReflect.CallStaticEvent(1) ASSERT_EQ(2, ret) CS.LuaTestObjReflect.TestStaticEvent1('+', EvtFunc12) local ret = CS.LuaTestObjReflect.CallStaticEvent(2) ASSERT_EQ(7, ret) CS.LuaTestObjReflect.TestStaticEvent1('+', EvtFunc12) local ret = CS.LuaTestObjReflect.CallStaticEvent(1) ASSERT_EQ(12, ret) CS.LuaTestObjReflect.TestStaticEvent1('-', EvtFunc12) local ret = CS.LuaTestObjReflect.CallStaticEvent(1) ASSERT_EQ(15, ret) CS.LuaTestObjReflect.TestStaticEvent1('-', EvtFunc12) local ret = CS.LuaTestObjReflect.CallStaticEvent(1) ASSERT_EQ(16, ret) CS.LuaTestObjReflect.TestStaticEvent1('-', EvtFunc12) local ret = CS.LuaTestObjReflect.CallStaticEvent(1) ASSERT_EQ(17, ret) CS.LuaTestObjReflect.TestStaticEvent1('-', EvtFunc11) end function CMyTestCaseLuaCallCSReflect.CaseUpLowerMethod(self) self.count = 1 + self.count CS.LuaTestObjReflect.initNumber = 5 local ret = CS.LuaTestObjReflect.CalcAdd(1) ASSERT_EQ(6, ret) local ret = CS.LuaTestObjReflect.calcadd(2) ASSERT_EQ(8, ret) end function CMyTestCaseLuaCallCSReflect.CaseUpLowerMethod(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.OverLoad1(1, 2, 3, 5) ASSERT_EQ(11, ret) end function CMyTestCaseLuaCallCSReflect.CaseGetStaticSum(self) self.count = 1 + self.count local ret = CS.LuaTestObj.Sum(1, 2) ASSERT_EQ(ret, 3) end function CMyTestCaseLuaCallCSReflect.CaseGetSum(self) self.count = 1 + self.count local class = CS.LuaTestObj() local ret = class:Sum(1, 2, 6) ASSERT_EQ(ret, 9) end function CMyTestCaseLuaCallCSReflect.CaseVisitTemplateMethod(self) self.count = 1 + self.count ASSERT_EQ(CS.EmployeeTemplateReflect.GetBasicSalary, nil) ASSERT_EQ(CS.EmployeeTemplateReflect.AddBonus, nil) local class = CS.ManagerReflect() ASSERT_EQ(1, class:GetBasicSalary()) end function CMyTestCaseLuaCallCSReflect.CaseVisitGenericMethod(self) self.count = 1 + self.count local class = CS.LuaTestObjReflect() local a = "abc" if (true) then local ret, error = pcall(function() class:GenericMethod(a) end) ASSERT_EQ(ret, false) else ASSERT_EQ(true, false) end end function CMyTestCaseLuaCallCSReflect.CaseVisitIntPtr(self) self.count = 1 + self.count local class = CS.LuaTestObjReflect() local ptr = class.ptr print(ptr) local ptr1 = class:GetPtr() print(ptr1) local bytevar = class:PrintPtr(ptr1) ASSERT_EQ(bytevar, 97) end function CMyTestCaseLuaCallCSReflect.CaseVisitVarAndDefaultFunc1(self) self.count = 1 + self.count local class = CS.LuaTestObjReflect() local ret = class:VariableParamFuncDefault(1) ASSERT_EQ(ret, 2) local ret = CS.LuaTestObjReflect.StaticVariableParamFuncDefault(1.0) ASSERT_EQ(ret, 2.0) end function CMyTestCaseLuaCallCSReflect.CaseVisitVarAndDefaultFunc2(self) self.count = 1 + self.count local class = CS.LuaTestObjReflect() local ret = class:VariableParamFuncDefault(1, 2, "john", "che") ASSERT_EQ(ret, 3) local ret = CS.LuaTestObjReflect.StaticVariableParamFuncDefault(1.0, 2.0, "john", "che") ASSERT_EQ(ret, 3.0) end function CMyTestCaseLuaCallCSReflect.CaseFuncReturnByteArray(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.FuncReturnByteArray() ASSERT_EQ(ret, "abc") end function CMyTestCaseLuaCallCSReflect.CaseFuncReturnByte(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.FuncReturnByte() ASSERT_EQ(ret, 97) end function CMyTestCaseLuaCallCSReflect.CaseFuncReturnIntArray(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.FuncReturnIntArray() ASSERT_EQ(type(ret), "userdata") end function CMyTestCaseLuaCallCSReflect.CaseFuncReturnInt(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.FuncReturnInt() ASSERT_EQ(ret, 97) end function CMyTestCaseLuaCallCSReflect.CaseTableAutoTransSimpleClassMethod(self) self.count = 1 + self.count local class = CS.TestTableAutoTransClassReflect() local ret = class:SimpleClassMethod({x=97, y="123", z=100000000000}) ASSERT_EQ(ret.x, 97) ASSERT_EQ(ret.y, "123") ASSERT_EQ(tostring(ret.z), "100000000000") end function CMyTestCaseLuaCallCSReflect.CaseTableAutoTransComplexClassMethod(self) self.count = 1 + self.count local class = CS.TestTableAutoTransClassReflect() local ret = class:ComplexClassMethod({A=97, B={x=97, y="123", z=100000000000}}) ASSERT_EQ(ret.IntVar, 97) ASSERT_EQ(ret.ClassVar.IntVar, 97) ASSERT_EQ(ret.ClassVar.StringVar, "123") ASSERT_EQ(tostring(ret.ClassVar.LongVar), "100000000000") end function CMyTestCaseLuaCallCSReflect.CaseTableAutoTransSimpleStructMethod(self) self.count = 1 + self.count local class = CS.TestTableAutoTransClassReflect() local ret = class:SimpleStructMethod({a=97}) ASSERT_EQ(ret.a, 97) end function CMyTestCaseLuaCallCSReflect.CaseTableAutoTransComplexStructMethod(self) self.count = 1 + self.count local class = CS.TestTableAutoTransClassReflect() local ret = class:ComplexStructMethod({a=-101, b=1000, c=1.000000132, d={a=97}}) ASSERT_EQ(ret.a, -101) ASSERT_EQ(ret.b, 1000) ASSERT_EQ(string.sub(tostring(ret.c), 1, 11), "1.000000132") ASSERT_EQ(ret.d.a, 97) end function CMyTestCaseLuaCallCSReflect.CaseTableAutoTransOneListMethod(self) self.count = 1 + self.count local class = CS.TestTableAutoTransClassReflect() local ret = class:OneListMethod({1, 2, 3, 4, 5}) ASSERT_EQ(ret, 15) end function CMyTestCaseLuaCallCSReflect.CaseTableAutoTransTwoDimensionListMethod(self) self.count = 1 + self.count local class = CS.TestTableAutoTransClassReflect() local ret = class:TwoDimensionListMethod({{1, 2, 3},{4, 5, 6}}) ASSERT_EQ(ret, 21) end function CMyTestCaseLuaCallCSReflect.CaseTestImplicit(self) self.count = 1 + self.count if CS.LuaTestCommon.IsXLuaGeneral() then return end local ret = CS.LuaTestObjReflect.TestImplicit():GetType() ASSERT_EQ(ret, typeof(CS.UnityEngine.LayerMask)) end function CMyTestCaseLuaCallCSReflect.CaseVariableParamFunc2_1_4(self) self.count = 1 + self.count local ret, err = pcall(function() CS.LuaTestObjReflect.VariableParamFunc(0, CS.LuaTestObjReflect()) end) ASSERT_EQ(ret, false) ASSERT_TRUE(err:find("invalid arguments")) end function CMyTestCaseLuaCallCSReflect.CaseFirstPushEnum(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.FirstPushEnumFunc(1) ASSERT_EQ(ret, "1") local ret = CS.LuaTestObjReflect.FirstPushEnumFunc(2) ASSERT_EQ(ret, "4") end function CMyTestCaseLuaCallCSReflect.CaseReferTestClass(self) self.count = 1 + self.count local int_x = 10 local int_y = 12 local str_z = "abc" local class1, ret_y, ret_z = CS.ReferTestClassReflect(int_x, int_y) local ret = class1:Get_X_Y_ADD() ASSERT_EQ(ret, 22) ASSERT_EQ(ret_y, 11) ASSERT_EQ(ret_z, "test1") local class3, ret_z = CS.ReferTestClassReflect(int_x) local ret = class3:Get_X_Y_ADD() ASSERT_EQ(ret, 20) ASSERT_EQ(ret_z, "test3") end function CMyTestCaseLuaCallCSReflect.CaseVariableParamFuncNoParam(self) self.count = 1 + self.count local ret = CS.LuaTestObjReflect.VariableParamFunc2() ASSERT_EQ(ret, 0) local ret = CS.LuaTestObjReflect.VariableParamFunc2("abc", "haha") ASSERT_EQ(ret, 2) end
xLua/Test/UnitTest/StreamingAssets/luaCallCsReflect.lua/0
{ "file_path": "xLua/Test/UnitTest/StreamingAssets/luaCallCsReflect.lua", "repo_id": "xLua", "token_count": 15376 }
1,924
fileFormatVersion: 2 guid: 88bc84a96f56e814ca9205beefdb5665 timeCreated: 1483528414 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Test/UnitTest/StreamingAssets/testxxx2.tdr.meta/0
{ "file_path": "xLua/Test/UnitTest/StreamingAssets/testxxx2.tdr.meta", "repo_id": "xLua", "token_count": 69 }
1,925
fileFormatVersion: 2 guid: 7e0c4d2e49abdf748bf76ad0328dca25 timeCreated: 1483527551 licenseType: Pro TextScriptImporter: userData: assetBundleName: assetBundleVariant:
xLua/Test/UnitTest/xLuaTest/CSharpCallLua/Resources/error.lua.txt.meta/0
{ "file_path": "xLua/Test/UnitTest/xLuaTest/CSharpCallLua/Resources/error.lua.txt.meta", "repo_id": "xLua", "token_count": 72 }
1,926
#if !XLUA_GENERAL using UnityEngine; using System.Collections; using XLua; public class Main : MonoBehaviour { LuaEnv luaenv; // Use this for initialization void Start () { luaenv = LuaEnvSingleton.Instance; luaenv.DoString ("require 'main'"); } // Update is called once per frame void Update () { luaenv.GC (); } } #endif
xLua/Test/UnitTest/xLuaTest/Main.cs/0
{ "file_path": "xLua/Test/UnitTest/xLuaTest/Main.cs", "repo_id": "xLua", "token_count": 124 }
1,927
body { color: #000000 ; background-color: #FFFFFF ; font-family: Helvetica, Arial, sans-serif ; text-align: justify ; margin-right: 30px ; margin-left: 30px ; } h1, h2, h3, h4 { font-family: Verdana, Geneva, sans-serif ; font-weight: normal ; font-style: italic ; } h2 { padding-top: 0.4em ; padding-bottom: 0.4em ; padding-left: 30px ; padding-right: 30px ; margin-left: -30px ; background-color: #E0E0FF ; } h3 { padding-left: 0.5em ; border-left: solid #E0E0FF 1em ; } table h3 { padding-left: 0px ; border-left: none ; } a:link { color: #000080 ; background-color: inherit ; text-decoration: none ; } a:visited { background-color: inherit ; text-decoration: none ; } a:link:hover, a:visited:hover { color: #000080 ; background-color: #E0E0FF ; } a:link:active, a:visited:active { color: #FF0000 ; } hr { border: 0 ; height: 1px ; color: #a0a0a0 ; background-color: #a0a0a0 ; } :target { background-color: #F8F8F8 ; padding: 8px ; border: solid #a0a0a0 2px ; } .footer { color: gray ; font-size: small ; } input[type=text] { border: solid #a0a0a0 2px ; border-radius: 2em ; -moz-border-radius: 2em ; background-image: url('images/search.png') ; background-repeat: no-repeat; background-position: 4px center ; padding-left: 20px ; height: 2em ; }
xLua/build/lua-5.1.5/doc/lua.css/0
{ "file_path": "xLua/build/lua-5.1.5/doc/lua.css", "repo_id": "xLua", "token_count": 575 }
1,928
-- -- strict.lua -- checks uses of undeclared global variables -- All global variables must be 'declared' through a regular assignment -- (even assigning nil will do) in a main chunk before being used -- anywhere or assigned to inside a function. -- local getinfo, error, rawset, rawget = debug.getinfo, error, rawset, rawget local mt = getmetatable(_G) if mt == nil then mt = {} setmetatable(_G, mt) end mt.__declared = {} local function what () local d = getinfo(3, "S") return d and d.what or "C" end mt.__newindex = function (t, n, v) if not mt.__declared[n] then local w = what() if w ~= "main" and w ~= "C" then error("assign to undeclared variable '"..n.."'", 2) end mt.__declared[n] = true end rawset(t, n, v) end mt.__index = function (t, n) if not mt.__declared[n] and what() ~= "C" then error("variable '"..n.."' is not declared", 2) end return rawget(t, n) end
xLua/build/lua-5.1.5/etc/strict.lua/0
{ "file_path": "xLua/build/lua-5.1.5/etc/strict.lua", "repo_id": "xLua", "token_count": 348 }
1,929
/* ** $Id: lfunc.h,v 2.4.1.1 2007/12/27 13:02:25 roberto Exp $ ** Auxiliary functions to manipulate prototypes and closures ** See Copyright Notice in lua.h */ #ifndef lfunc_h #define lfunc_h #include "lobject.h" #define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \ cast(int, sizeof(TValue)*((n)-1))) #define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ cast(int, sizeof(TValue *)*((n)-1))) LUAI_FUNC Proto *luaF_newproto (lua_State *L); LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e); LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e); LUAI_FUNC UpVal *luaF_newupval (lua_State *L); LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); LUAI_FUNC void luaF_close (lua_State *L, StkId level); LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); LUAI_FUNC void luaF_freeclosure (lua_State *L, Closure *c); LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv); LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, int pc); #endif
xLua/build/lua-5.1.5/src/lfunc.h/0
{ "file_path": "xLua/build/lua-5.1.5/src/lfunc.h", "repo_id": "xLua", "token_count": 516 }
1,930
/* ** $Id: loslib.c,v 1.19.1.3 2008/01/18 16:38:18 roberto Exp $ ** Standard Operating System library ** See Copyright Notice in lua.h */ #include <errno.h> #include <locale.h> #include <stdlib.h> #include <string.h> #include <time.h> #define loslib_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" static int os_pushresult (lua_State *L, int i, const char *filename) { int en = errno; /* calls to Lua API may change this value */ if (i) { lua_pushboolean(L, 1); return 1; } else { lua_pushnil(L); lua_pushfstring(L, "%s: %s", filename, strerror(en)); lua_pushinteger(L, en); return 3; } } //static int os_execute (lua_State *L) { // lua_pushinteger(L, system(luaL_optstring(L, 1, NULL))); // return 1; //} static int os_remove (lua_State *L) { const char *filename = luaL_checkstring(L, 1); return os_pushresult(L, remove(filename) == 0, filename); } static int os_rename (lua_State *L) { const char *fromname = luaL_checkstring(L, 1); const char *toname = luaL_checkstring(L, 2); return os_pushresult(L, rename(fromname, toname) == 0, fromname); } static int os_tmpname (lua_State *L) { char buff[LUA_TMPNAMBUFSIZE]; int err; lua_tmpnam(buff, err); if (err) return luaL_error(L, "unable to generate a unique filename"); lua_pushstring(L, buff); return 1; } static int os_getenv (lua_State *L) { #if defined(WINAPI_FAMILY_PARTITION) return luaL_error(L, "unsupport api in uwp platform"); #else lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ return 1; #endif } static int os_clock (lua_State *L) { lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); return 1; } /* ** {====================================================== ** Time/Date operations ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, ** wday=%w+1, yday=%j, isdst=? } ** ======================================================= */ static void setfield (lua_State *L, const char *key, int value) { lua_pushinteger(L, value); lua_setfield(L, -2, key); } static void setboolfield (lua_State *L, const char *key, int value) { if (value < 0) /* undefined? */ return; /* does not set field */ lua_pushboolean(L, value); lua_setfield(L, -2, key); } static int getboolfield (lua_State *L, const char *key) { int res; lua_getfield(L, -1, key); res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1); lua_pop(L, 1); return res; } static int getfield (lua_State *L, const char *key, int d) { int res; lua_getfield(L, -1, key); if (lua_isnumber(L, -1)) res = (int)lua_tointeger(L, -1); else { if (d < 0) return luaL_error(L, "field " LUA_QS " missing in date table", key); res = d; } lua_pop(L, 1); return res; } static int os_date (lua_State *L) { const char *s = luaL_optstring(L, 1, "%c"); time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL)); struct tm *stm; if (*s == '!') { /* UTC? */ stm = gmtime(&t); s++; /* skip `!' */ } else stm = localtime(&t); if (stm == NULL) /* invalid date? */ lua_pushnil(L); else if (strcmp(s, "*t") == 0) { lua_createtable(L, 0, 9); /* 9 = number of fields */ setfield(L, "sec", stm->tm_sec); setfield(L, "min", stm->tm_min); setfield(L, "hour", stm->tm_hour); setfield(L, "day", stm->tm_mday); setfield(L, "month", stm->tm_mon+1); setfield(L, "year", stm->tm_year+1900); setfield(L, "wday", stm->tm_wday+1); setfield(L, "yday", stm->tm_yday+1); setboolfield(L, "isdst", stm->tm_isdst); } else { char cc[3]; luaL_Buffer b; cc[0] = '%'; cc[2] = '\0'; luaL_buffinit(L, &b); for (; *s; s++) { if (*s != '%' || *(s + 1) == '\0') /* no conversion specifier? */ luaL_addchar(&b, *s); else { size_t reslen; char buff[200]; /* should be big enough for any conversion result */ cc[1] = *(++s); reslen = strftime(buff, sizeof(buff), cc, stm); luaL_addlstring(&b, buff, reslen); } } luaL_pushresult(&b); } return 1; } static int os_time (lua_State *L) { time_t t; if (lua_isnoneornil(L, 1)) /* called without args? */ t = time(NULL); /* get current time */ else { struct tm ts; luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); /* make sure table is at the top */ ts.tm_sec = getfield(L, "sec", 0); ts.tm_min = getfield(L, "min", 0); ts.tm_hour = getfield(L, "hour", 12); ts.tm_mday = getfield(L, "day", -1); ts.tm_mon = getfield(L, "month", -1) - 1; ts.tm_year = getfield(L, "year", -1) - 1900; ts.tm_isdst = getboolfield(L, "isdst"); t = mktime(&ts); } if (t == (time_t)(-1)) lua_pushnil(L); else lua_pushnumber(L, (lua_Number)t); return 1; } static int os_difftime (lua_State *L) { lua_pushnumber(L, difftime((time_t)(luaL_checknumber(L, 1)), (time_t)(luaL_optnumber(L, 2, 0)))); return 1; } /* }====================================================== */ static int os_setlocale (lua_State *L) { static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME}; static const char *const catnames[] = {"all", "collate", "ctype", "monetary", "numeric", "time", NULL}; const char *l = luaL_optstring(L, 1, NULL); int op = luaL_checkoption(L, 2, "all", catnames); lua_pushstring(L, setlocale(cat[op], l)); return 1; } static int os_exit (lua_State *L) { exit(luaL_optint(L, 1, EXIT_SUCCESS)); } static const luaL_Reg syslib[] = { {"clock", os_clock}, {"date", os_date}, {"difftime", os_difftime}, //{"execute", os_execute}, {"exit", os_exit}, {"getenv", os_getenv}, {"remove", os_remove}, {"rename", os_rename}, {"setlocale", os_setlocale}, {"time", os_time}, {"tmpname", os_tmpname}, {NULL, NULL} }; /* }====================================================== */ LUALIB_API int luaopen_os (lua_State *L) { luaL_register(L, LUA_OSLIBNAME, syslib); return 1; }
xLua/build/lua-5.1.5/src/loslib.c/0
{ "file_path": "xLua/build/lua-5.1.5/src/loslib.c", "repo_id": "xLua", "token_count": 2732 }
1,931
/* ** $Id: luaconf.h,v 1.82.1.7 2008/02/11 16:25:08 roberto Exp $ ** Configuration file for Lua ** See Copyright Notice in lua.h */ #ifndef lconfig_h #define lconfig_h #include <limits.h> #include <stddef.h> /* ** ================================================================== ** Search for "@@" to find all configurable definitions. ** =================================================================== */ /* @@ LUA_ANSI controls the use of non-ansi features. ** CHANGE it (define it) if you want Lua to avoid the use of any ** non-ansi feature or library. */ #if defined(__STRICT_ANSI__) #define LUA_ANSI #endif #if !defined(LUA_ANSI) && defined(_WIN32) #define LUA_WIN #endif #if defined(LUA_USE_LINUX) #define LUA_USE_POSIX #define LUA_USE_DLOPEN /* needs an extra library: -ldl */ #define LUA_USE_READLINE /* needs some extra libraries */ #endif #if defined(LUA_USE_MACOSX) #define LUA_USE_POSIX #define LUA_DL_DYLD /* does not need extra library */ #endif /* @@ LUA_USE_POSIX includes all functionallity listed as X/Open System @* Interfaces Extension (XSI). ** CHANGE it (define it) if your system is XSI compatible. */ #if defined(LUA_USE_POSIX) #define LUA_USE_MKSTEMP #define LUA_USE_ISATTY #define LUA_USE_POPEN #define LUA_USE_ULONGJMP #endif /* @@ LUA_PATH and LUA_CPATH are the names of the environment variables that @* Lua check to set its paths. @@ LUA_INIT is the name of the environment variable that Lua @* checks for initialization code. ** CHANGE them if you want different names. */ #define LUA_PATH "LUA_PATH" #define LUA_CPATH "LUA_CPATH" #define LUA_INIT "LUA_INIT" /* @@ LUA_PATH_DEFAULT is the default path that Lua uses to look for @* Lua libraries. @@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for @* C libraries. ** CHANGE them if your machine has a non-conventional directory ** hierarchy or if you want to install your libraries in ** non-conventional directories. */ #if defined(_WIN32) /* ** In Windows, any exclamation mark ('!') in the path is replaced by the ** path of the directory of the executable file of the current process. */ #define LUA_LDIR "!\\lua\\" #define LUA_CDIR "!\\" #define LUA_PATH_DEFAULT \ ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua" #define LUA_CPATH_DEFAULT \ ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" #else #define LUA_ROOT "/usr/local/" #define LUA_LDIR LUA_ROOT "share/lua/5.1/" #define LUA_CDIR LUA_ROOT "lib/lua/5.1/" #define LUA_PATH_DEFAULT \ "./?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua" #define LUA_CPATH_DEFAULT \ "./?.so;" LUA_CDIR"?.so;" LUA_CDIR"loadall.so" #endif /* @@ LUA_DIRSEP is the directory separator (for submodules). ** CHANGE it if your machine does not use "/" as the directory separator ** and is not Windows. (On Windows Lua automatically uses "\".) */ #if defined(_WIN32) #define LUA_DIRSEP "\\" #else #define LUA_DIRSEP "/" #endif /* @@ LUA_PATHSEP is the character that separates templates in a path. @@ LUA_PATH_MARK is the string that marks the substitution points in a @* template. @@ LUA_EXECDIR in a Windows path is replaced by the executable's @* directory. @@ LUA_IGMARK is a mark to ignore all before it when bulding the @* luaopen_ function name. ** CHANGE them if for some reason your system cannot use those ** characters. (E.g., if one of those characters is a common character ** in file/directory names.) Probably you do not need to change them. */ #define LUA_PATHSEP ";" #define LUA_PATH_MARK "?" #define LUA_EXECDIR "!" #define LUA_IGMARK "-" /* @@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger. ** CHANGE that if ptrdiff_t is not adequate on your machine. (On most ** machines, ptrdiff_t gives a good choice between int or long.) */ #define LUA_INTEGER ptrdiff_t /* @@ LUA_API is a mark for all core API functions. @@ LUALIB_API is a mark for all standard library functions. ** CHANGE them if you need to define those functions in some special way. ** For instance, if you want to create one Windows DLL with the core and ** the libraries, you may want to use the following definition (define ** LUA_BUILD_AS_DLL to get it). */ #if defined(LUA_BUILD_AS_DLL) #if defined(LUA_CORE) || defined(LUA_LIB) #define LUA_API __declspec(dllexport) #else #define LUA_API __declspec(dllimport) #endif #else #define LUA_API extern #endif /* more often than not the libs go together with the core */ #define LUALIB_API LUA_API /* @@ LUAI_FUNC is a mark for all extern functions that are not to be @* exported to outside modules. @@ LUAI_DATA is a mark for all extern (const) variables that are not to @* be exported to outside modules. ** CHANGE them if you need to mark them in some special way. Elf/gcc ** (versions 3.2 and later) mark them as "hidden" to optimize access ** when Lua is compiled as a shared library. */ #if defined(luaall_c) #define LUAI_FUNC static #define LUAI_DATA /* empty */ #elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ defined(__ELF__) #define LUAI_FUNC __attribute__((visibility("hidden"))) extern #define LUAI_DATA LUAI_FUNC #else #define LUAI_FUNC extern #define LUAI_DATA extern #endif /* @@ LUA_QL describes how error messages quote program elements. ** CHANGE it if you want a different appearance. */ #define LUA_QL(x) "'" x "'" #define LUA_QS LUA_QL("%s") /* @@ LUA_IDSIZE gives the maximum size for the description of the source @* of a function in debug information. ** CHANGE it if you want a different size. */ #define LUA_IDSIZE 150 /* ** {================================================================== ** Stand-alone configuration ** =================================================================== */ #if defined(lua_c) || defined(luaall_c) /* @@ lua_stdin_is_tty detects whether the standard input is a 'tty' (that @* is, whether we're running lua interactively). ** CHANGE it if you have a better definition for non-POSIX/non-Windows ** systems. */ #if defined(LUA_USE_ISATTY) #include <unistd.h> #define lua_stdin_is_tty() isatty(0) #elif defined(LUA_WIN) #include <io.h> #include <stdio.h> #define lua_stdin_is_tty() _isatty(_fileno(stdin)) #else #define lua_stdin_is_tty() 1 /* assume stdin is a tty */ #endif /* @@ LUA_PROMPT is the default prompt used by stand-alone Lua. @@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua. ** CHANGE them if you want different prompts. (You can also change the ** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.) */ #define LUA_PROMPT "> " #define LUA_PROMPT2 ">> " /* @@ LUA_PROGNAME is the default name for the stand-alone Lua program. ** CHANGE it if your stand-alone interpreter has a different name and ** your system is not able to detect that name automatically. */ #define LUA_PROGNAME "lua" /* @@ LUA_MAXINPUT is the maximum length for an input line in the @* stand-alone interpreter. ** CHANGE it if you need longer lines. */ #define LUA_MAXINPUT 512 /* @@ lua_readline defines how to show a prompt and then read a line from @* the standard input. @@ lua_saveline defines how to "save" a read line in a "history". @@ lua_freeline defines how to free a line read by lua_readline. ** CHANGE them if you want to improve this functionality (e.g., by using ** GNU readline and history facilities). */ #if defined(LUA_USE_READLINE) #include <stdio.h> #include <readline/readline.h> #include <readline/history.h> #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) #define lua_saveline(L,idx) \ if (lua_strlen(L,idx) > 0) /* non-empty line? */ \ add_history(lua_tostring(L, idx)); /* add it to history */ #define lua_freeline(L,b) ((void)L, free(b)) #else #define lua_readline(L,b,p) \ ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ #define lua_saveline(L,idx) { (void)L; (void)idx; } #define lua_freeline(L,b) { (void)L; (void)b; } #endif #endif /* }================================================================== */ /* @@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles @* as a percentage. ** CHANGE it if you want the GC to run faster or slower (higher values ** mean larger pauses which mean slower collection.) You can also change ** this value dynamically. */ #define LUAI_GCPAUSE 200 /* 200% (wait memory to double before next GC) */ /* @@ LUAI_GCMUL defines the default speed of garbage collection relative to @* memory allocation as a percentage. ** CHANGE it if you want to change the granularity of the garbage ** collection. (Higher values mean coarser collections. 0 represents ** infinity, where each step performs a full collection.) You can also ** change this value dynamically. */ #define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */ /* @@ LUA_COMPAT_GETN controls compatibility with old getn behavior. ** CHANGE it (define it) if you want exact compatibility with the ** behavior of setn/getn in Lua 5.0. */ #undef LUA_COMPAT_GETN /* @@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib. ** CHANGE it to undefined as soon as you do not need a global 'loadlib' ** function (the function is still available as 'package.loadlib'). */ #undef LUA_COMPAT_LOADLIB /* @@ LUA_COMPAT_VARARG controls compatibility with old vararg feature. ** CHANGE it to undefined as soon as your programs use only '...' to ** access vararg parameters (instead of the old 'arg' table). */ #define LUA_COMPAT_VARARG /* @@ LUA_COMPAT_MOD controls compatibility with old math.mod function. ** CHANGE it to undefined as soon as your programs use 'math.fmod' or ** the new '%' operator instead of 'math.mod'. */ #define LUA_COMPAT_MOD /* @@ LUA_COMPAT_LSTR controls compatibility with old long string nesting @* facility. ** CHANGE it to 2 if you want the old behaviour, or undefine it to turn ** off the advisory error when nesting [[...]]. */ #define LUA_COMPAT_LSTR 1 /* @@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name. ** CHANGE it to undefined as soon as you rename 'string.gfind' to ** 'string.gmatch'. */ #define LUA_COMPAT_GFIND /* @@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib' @* behavior. ** CHANGE it to undefined as soon as you replace to 'luaL_register' ** your uses of 'luaL_openlib' */ #define LUA_COMPAT_OPENLIB /* @@ luai_apicheck is the assert macro used by the Lua-C API. ** CHANGE luai_apicheck if you want Lua to perform some checks in the ** parameters it gets from API calls. This may slow down the interpreter ** a bit, but may be quite useful when debugging C code that interfaces ** with Lua. A useful redefinition is to use assert.h. */ #if defined(LUA_USE_APICHECK) #include <assert.h> #define luai_apicheck(L,o) { (void)L; assert(o); } #else #define luai_apicheck(L,o) { (void)L; } #endif /* @@ LUAI_BITSINT defines the number of bits in an int. ** CHANGE here if Lua cannot automatically detect the number of bits of ** your machine. Probably you do not need to change this. */ /* avoid overflows in comparison */ #if INT_MAX-20 < 32760 #define LUAI_BITSINT 16 #elif INT_MAX > 2147483640L /* int has at least 32 bits */ #define LUAI_BITSINT 32 #else #error "you must define LUA_BITSINT with number of bits in an integer" #endif /* @@ LUAI_UINT32 is an unsigned integer with at least 32 bits. @@ LUAI_INT32 is an signed integer with at least 32 bits. @@ LUAI_UMEM is an unsigned integer big enough to count the total @* memory used by Lua. @@ LUAI_MEM is a signed integer big enough to count the total memory @* used by Lua. ** CHANGE here if for some weird reason the default definitions are not ** good enough for your machine. (The definitions in the 'else' ** part always works, but may waste space on machines with 64-bit ** longs.) Probably you do not need to change this. */ #if LUAI_BITSINT >= 32 #define LUAI_UINT32 unsigned int #define LUAI_INT32 int #define LUAI_MAXINT32 INT_MAX #define LUAI_UMEM size_t #define LUAI_MEM ptrdiff_t #else /* 16-bit ints */ #define LUAI_UINT32 unsigned long #define LUAI_INT32 long #define LUAI_MAXINT32 LONG_MAX #define LUAI_UMEM unsigned long #define LUAI_MEM long #endif /* @@ LUAI_MAXCALLS limits the number of nested calls. ** CHANGE it if you need really deep recursive calls. This limit is ** arbitrary; its only purpose is to stop infinite recursion before ** exhausting memory. */ #define LUAI_MAXCALLS 20000 /* @@ LUAI_MAXCSTACK limits the number of Lua stack slots that a C function @* can use. ** CHANGE it if you need lots of (Lua) stack space for your C ** functions. This limit is arbitrary; its only purpose is to stop C ** functions to consume unlimited stack space. (must be smaller than ** -LUA_REGISTRYINDEX) */ #define LUAI_MAXCSTACK 8000 /* ** {================================================================== ** CHANGE (to smaller values) the following definitions if your system ** has a small C stack. (Or you may want to change them to larger ** values if your system has a large C stack and these limits are ** too rigid for you.) Some of these constants control the size of ** stack-allocated arrays used by the compiler or the interpreter, while ** others limit the maximum number of recursive calls that the compiler ** or the interpreter can perform. Values too large may cause a C stack ** overflow for some forms of deep constructs. ** =================================================================== */ /* @@ LUAI_MAXCCALLS is the maximum depth for nested C calls (short) and @* syntactical nested non-terminals in a program. */ #define LUAI_MAXCCALLS 200 /* @@ LUAI_MAXVARS is the maximum number of local variables per function @* (must be smaller than 250). */ #define LUAI_MAXVARS 200 /* @@ LUAI_MAXUPVALUES is the maximum number of upvalues per function @* (must be smaller than 250). */ #define LUAI_MAXUPVALUES 60 /* @@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. */ #define LUAL_BUFFERSIZE BUFSIZ /* }================================================================== */ /* ** {================================================================== @@ LUA_NUMBER is the type of numbers in Lua. ** CHANGE the following definitions only if you want to build Lua ** with a number type different from double. You may also need to ** change lua_number2int & lua_number2integer. ** =================================================================== */ #define LUA_NUMBER_DOUBLE #define LUA_NUMBER double /* @@ LUAI_UACNUMBER is the result of an 'usual argument conversion' @* over a number. */ #define LUAI_UACNUMBER double /* @@ LUA_NUMBER_SCAN is the format for reading numbers. @@ LUA_NUMBER_FMT is the format for writing numbers. @@ lua_number2str converts a number to a string. @@ LUAI_MAXNUMBER2STR is maximum size of previous conversion. @@ lua_str2number converts a string to a number. */ #define LUA_NUMBER_SCAN "%lf" #define LUA_NUMBER_FMT "%.14g" #define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) #define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */ #define lua_str2number(s,p) strtod((s), (p)) /* @@ The luai_num* macros define the primitive operations over numbers. */ #if defined(LUA_CORE) #include <math.h> #define luai_numadd(a,b) ((a)+(b)) #define luai_numsub(a,b) ((a)-(b)) #define luai_nummul(a,b) ((a)*(b)) #define luai_numdiv(a,b) ((a)/(b)) #define luai_nummod(a,b) ((a) - floor((a)/(b))*(b)) #define luai_numpow(a,b) (pow(a,b)) #define luai_numunm(a) (-(a)) #define luai_numeq(a,b) ((a)==(b)) #define luai_numlt(a,b) ((a)<(b)) #define luai_numle(a,b) ((a)<=(b)) #define luai_numisnan(a) (!luai_numeq((a), (a))) #endif /* @@ lua_number2int is a macro to convert lua_Number to int. @@ lua_number2integer is a macro to convert lua_Number to lua_Integer. ** CHANGE them if you know a faster way to convert a lua_Number to ** int (with any rounding method and without throwing errors) in your ** system. In Pentium machines, a naive typecast from double to int ** in C is extremely slow, so any alternative is worth trying. */ /* On a Pentium, resort to a trick */ #if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \ (defined(__i386) || defined (_M_IX86) || defined(__i386__)) /* On a Microsoft compiler, use assembler */ #if defined(_MSC_VER) #define lua_number2int(i,d) __asm fld d __asm fistp i #define lua_number2integer(i,n) lua_number2int(i, n) /* the next trick should work on any Pentium, but sometimes clashes with a DirectX idiosyncrasy */ #else union luai_Cast { double l_d; long l_l; }; #define lua_number2int(i,d) \ { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; } #define lua_number2integer(i,n) lua_number2int(i, n) #endif /* this option always works, but may be slow */ #else #define lua_number2int(i,d) ((i)=(int)(d)) #define lua_number2integer(i,d) ((i)=(lua_Integer)(d)) #endif /* }================================================================== */ /* @@ LUAI_USER_ALIGNMENT_T is a type that requires maximum alignment. ** CHANGE it if your system requires alignments larger than double. (For ** instance, if your system supports long doubles and they must be ** aligned in 16-byte boundaries, then you should add long double in the ** union.) Probably you do not need to change this. */ #define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; } /* @@ LUAI_THROW/LUAI_TRY define how Lua does exception handling. ** CHANGE them if you prefer to use longjmp/setjmp even with C++ ** or if want/don't to use _longjmp/_setjmp instead of regular ** longjmp/setjmp. By default, Lua handles errors with exceptions when ** compiling as C++ code, with _longjmp/_setjmp when asked to use them, ** and with longjmp/setjmp otherwise. */ #if defined(__cplusplus) /* C++ exceptions */ #define LUAI_THROW(L,c) throw(c) #define LUAI_TRY(L,c,a) try { a } catch(...) \ { if ((c)->status == 0) (c)->status = -1; } #define luai_jmpbuf int /* dummy variable */ #elif defined(LUA_USE_ULONGJMP) /* in Unix, try _longjmp/_setjmp (more efficient) */ #define LUAI_THROW(L,c) _longjmp((c)->b, 1) #define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } #define luai_jmpbuf jmp_buf #else /* default handling with long jumps */ #define LUAI_THROW(L,c) longjmp((c)->b, 1) #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } #define luai_jmpbuf jmp_buf #endif /* @@ LUA_MAXCAPTURES is the maximum number of captures that a pattern @* can do during pattern-matching. ** CHANGE it if you need more captures. This limit is arbitrary. */ #define LUA_MAXCAPTURES 32 /* @@ lua_tmpnam is the function that the OS library uses to create a @* temporary name. @@ LUA_TMPNAMBUFSIZE is the maximum size of a name created by lua_tmpnam. ** CHANGE them if you have an alternative to tmpnam (which is considered ** insecure) or if you want the original tmpnam anyway. By default, Lua ** uses tmpnam except when POSIX is available, where it uses mkstemp. */ #if defined(loslib_c) || defined(luaall_c) #if defined(LUA_USE_MKSTEMP) #include <unistd.h> #define LUA_TMPNAMBUFSIZE 32 #define lua_tmpnam(b,e) { \ strcpy(b, "/tmp/lua_XXXXXX"); \ e = mkstemp(b); \ if (e != -1) close(e); \ e = (e == -1); } #else #define LUA_TMPNAMBUFSIZE L_tmpnam #define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } #endif #endif /* @@ lua_popen spawns a new process connected to the current one through @* the file streams. ** CHANGE it if you have a way to implement it in your system. */ #if defined(LUA_USE_POPEN) #define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m)) #define lua_pclose(L,file) ((void)L, (pclose(file) != -1)) #elif defined(LUA_WIN) #define lua_popen(L,c,m) ((void)L, _popen(c,m)) #define lua_pclose(L,file) ((void)L, (_pclose(file) != -1)) #else #define lua_popen(L,c,m) ((void)((void)c, m), \ luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0) #define lua_pclose(L,file) ((void)((void)L, file), 0) #endif /* @@ LUA_DL_* define which dynamic-library system Lua should use. ** CHANGE here if Lua has problems choosing the appropriate ** dynamic-library system for your platform (either Windows' DLL, Mac's ** dyld, or Unix's dlopen). If your system is some kind of Unix, there ** is a good chance that it has dlopen, so LUA_DL_DLOPEN will work for ** it. To use dlopen you also need to adapt the src/Makefile (probably ** adding -ldl to the linker options), so Lua does not select it ** automatically. (When you change the makefile to add -ldl, you must ** also add -DLUA_USE_DLOPEN.) ** If you do not want any kind of dynamic library, undefine all these ** options. ** By default, _WIN32 gets LUA_DL_DLL and MAC OS X gets LUA_DL_DYLD. */ #if defined(LUA_USE_DLOPEN) #define LUA_DL_DLOPEN #endif #if defined(LUA_WIN) #define LUA_DL_DLL #endif /* @@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State @* (the data goes just *before* the lua_State pointer). ** CHANGE (define) this if you really need that. This value must be ** a multiple of the maximum alignment required for your machine. */ #define LUAI_EXTRASPACE 0 /* @@ luai_userstate* allow user-specific actions on threads. ** CHANGE them if you defined LUAI_EXTRASPACE and need to do something ** extra when a thread is created/deleted/resumed/yielded. */ #define luai_userstateopen(L) ((void)L) #define luai_userstateclose(L) ((void)L) #define luai_userstatethread(L,L1) ((void)L) #define luai_userstatefree(L) ((void)L) #define luai_userstateresume(L,n) ((void)L) #define luai_userstateyield(L,n) ((void)L) /* @@ LUA_INTFRMLEN is the length modifier for integer conversions @* in 'string.format'. @@ LUA_INTFRM_T is the integer type correspoding to the previous length @* modifier. ** CHANGE them if your system supports long long or does not support long. */ #if defined(LUA_USELONGLONG) #define LUA_INTFRMLEN "ll" #define LUA_INTFRM_T long long #else #define LUA_INTFRMLEN "l" #define LUA_INTFRM_T long #endif /* =================================================================== */ /* ** Local configuration. You can use this space to add your redefinitions ** without modifying the main part of the file. */ #endif
xLua/build/lua-5.1.5/src/luaconf.h/0
{ "file_path": "xLua/build/lua-5.1.5/src/luaconf.h", "repo_id": "xLua", "token_count": 7760 }
1,932
--- This file is part of LuaDist project name = "lua" version = "5.3.2" desc = "Lua is a powerful, fast, light-weight, embeddable scripting language." author = "Roberto Ierusalimschy, Waldemar Celes, Luiz Henrique de Figueiredo" license = "MIT/X11" url = "http://www.lua.org" maintainer = "Peter Drahoš"
xLua/build/lua-5.3.3/dist.info/0
{ "file_path": "xLua/build/lua-5.3.3/dist.info", "repo_id": "xLua", "token_count": 109 }
1,933
/* ** $Id: ldump.c $ ** save precompiled Lua chunks ** See Copyright Notice in lua.h */ #define ldump_c #define LUA_CORE #include "lprefix.h" #include <stddef.h> #include "lua.h" #include "lobject.h" #include "lstate.h" #include "lundump.h" typedef struct { lua_State *L; lua_Writer writer; void *data; int strip; int status; } DumpState; /* ** All high-level dumps go through dumpVector; you can change it to ** change the endianness of the result */ #define dumpVector(D,v,n) dumpBlock(D,v,(n)*sizeof((v)[0])) #define dumpLiteral(D, s) dumpBlock(D,s,sizeof(s) - sizeof(char)) static void dumpBlock (DumpState *D, const void *b, size_t size) { if (D->status == 0 && size > 0) { lua_unlock(D->L); D->status = (*D->writer)(D->L, b, size, D->data); lua_lock(D->L); } } #define dumpVar(D,x) dumpVector(D,&x,1) static void dumpByte (DumpState *D, int y) { lu_byte x = (lu_byte)y; dumpVar(D, x); } /* dumpInt Buff Size */ #define DIBS ((sizeof(size_t) * 8 / 7) + 1) static void dumpSize (DumpState *D, size_t x) { lu_byte buff[DIBS]; int n = 0; do { buff[DIBS - (++n)] = x & 0x7f; /* fill buffer in reverse order */ x >>= 7; } while (x != 0); buff[DIBS - 1] |= 0x80; /* mark last byte */ dumpVector(D, buff + DIBS - n, n); } static void dumpInt (DumpState *D, int x) { dumpSize(D, x); } static void dumpNumber (DumpState *D, lua_Number x) { dumpVar(D, x); } static void dumpInteger (DumpState *D, lua_Integer x) { dumpVar(D, x); } static void dumpString (DumpState *D, const TString *s) { if (s == NULL) dumpSize(D, 0); else { size_t size = tsslen(s); const char *str = getstr(s); dumpSize(D, size + 1); dumpVector(D, str, size); } } static void dumpCode (DumpState *D, const Proto *f) { dumpInt(D, f->sizecode); dumpVector(D, f->code, f->sizecode); } static void dumpFunction(DumpState *D, const Proto *f, TString *psource); static void dumpConstants (DumpState *D, const Proto *f) { int i; int n = f->sizek; dumpInt(D, n); for (i = 0; i < n; i++) { const TValue *o = &f->k[i]; int tt = ttypetag(o); dumpByte(D, tt); switch (tt) { case LUA_VNUMFLT: dumpNumber(D, fltvalue(o)); break; case LUA_VNUMINT: dumpInteger(D, ivalue(o)); break; case LUA_VSHRSTR: case LUA_VLNGSTR: dumpString(D, tsvalue(o)); break; default: lua_assert(tt == LUA_VNIL || tt == LUA_VFALSE || tt == LUA_VTRUE); } } } static void dumpProtos (DumpState *D, const Proto *f) { int i; int n = f->sizep; dumpInt(D, n); for (i = 0; i < n; i++) dumpFunction(D, f->p[i], f->source); } static void dumpUpvalues (DumpState *D, const Proto *f) { int i, n = f->sizeupvalues; dumpInt(D, n); for (i = 0; i < n; i++) { dumpByte(D, f->upvalues[i].instack); dumpByte(D, f->upvalues[i].idx); dumpByte(D, f->upvalues[i].kind); } } static void dumpDebug (DumpState *D, const Proto *f) { int i, n; n = (D->strip) ? 0 : f->sizelineinfo; dumpInt(D, n); dumpVector(D, f->lineinfo, n); n = (D->strip) ? 0 : f->sizeabslineinfo; dumpInt(D, n); for (i = 0; i < n; i++) { dumpInt(D, f->abslineinfo[i].pc); dumpInt(D, f->abslineinfo[i].line); } n = (D->strip) ? 0 : f->sizelocvars; dumpInt(D, n); for (i = 0; i < n; i++) { dumpString(D, f->locvars[i].varname); dumpInt(D, f->locvars[i].startpc); dumpInt(D, f->locvars[i].endpc); } n = (D->strip) ? 0 : f->sizeupvalues; dumpInt(D, n); for (i = 0; i < n; i++) dumpString(D, f->upvalues[i].name); } static void dumpFunction (DumpState *D, const Proto *f, TString *psource) { if (D->strip || f->source == psource) dumpString(D, NULL); /* no debug info or same source as its parent */ else dumpString(D, f->source); dumpInt(D, f->linedefined); dumpInt(D, f->lastlinedefined); dumpByte(D, f->numparams); dumpByte(D, f->is_vararg); dumpByte(D, f->maxstacksize); dumpCode(D, f); dumpConstants(D, f); dumpUpvalues(D, f); dumpProtos(D, f); dumpDebug(D, f); } static void dumpHeader (DumpState *D) { dumpLiteral(D, LUA_SIGNATURE); dumpByte(D, LUAC_VERSION); dumpByte(D, LUAC_FORMAT); dumpLiteral(D, LUAC_DATA); dumpByte(D, sizeof(Instruction)); dumpByte(D, sizeof(lua_Integer)); dumpByte(D, sizeof(lua_Number)); dumpInteger(D, LUAC_INT); dumpNumber(D, LUAC_NUM); } /* ** dump Lua function as precompiled chunk */ int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data, int strip) { DumpState D; D.L = L; D.writer = w; D.data = data; D.strip = strip; D.status = 0; dumpHeader(&D); dumpByte(&D, f->sizeupvalues); dumpFunction(&D, f, NULL); return D.status; }
xLua/build/lua-5.4.1/src/ldump.c/0
{ "file_path": "xLua/build/lua-5.4.1/src/ldump.c", "repo_id": "xLua", "token_count": 2152 }
1,934
/* ** $Id: lobject.h $ ** Type definitions for Lua objects ** See Copyright Notice in lua.h */ #ifndef lobject_h #define lobject_h #include <stdarg.h> #include "llimits.h" #include "lua.h" /* ** Extra types for collectable non-values */ #define LUA_TUPVAL LUA_NUMTYPES /* upvalues */ #define LUA_TPROTO (LUA_NUMTYPES+1) /* function prototypes */ /* ** number of all possible types (including LUA_TNONE) */ #define LUA_TOTALTYPES (LUA_TPROTO + 2) /* ** tags for Tagged Values have the following use of bits: ** bits 0-3: actual tag (a LUA_T* constant) ** bits 4-5: variant bits ** bit 6: whether value is collectable */ /* add variant bits to a type */ #define makevariant(t,v) ((t) | ((v) << 4)) /* ** Union of all Lua values */ typedef union Value { struct GCObject *gc; /* collectable objects */ void *p; /* light userdata */ lua_CFunction f; /* light C functions */ lua_Integer i; /* integer numbers */ lua_Number n; /* float numbers */ } Value; /* ** Tagged Values. This is the basic representation of values in Lua: ** an actual value plus a tag with its type. */ #define TValuefields Value value_; lu_byte tt_ typedef struct TValue { TValuefields; } TValue; #define val_(o) ((o)->value_) #define valraw(o) (&val_(o)) /* raw type tag of a TValue */ #define rawtt(o) ((o)->tt_) /* tag with no variants (bits 0-3) */ #define novariant(t) ((t) & 0x0F) /* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */ #define withvariant(t) ((t) & 0x3F) #define ttypetag(o) withvariant(rawtt(o)) /* type of a TValue */ #define ttype(o) (novariant(rawtt(o))) /* Macros to test type */ #define checktag(o,t) (rawtt(o) == (t)) #define checktype(o,t) (ttype(o) == (t)) /* Macros for internal tests */ /* collectable object has the same tag as the original value */ #define righttt(obj) (ttypetag(obj) == gcvalue(obj)->tt) /* ** Any value being manipulated by the program either is non ** collectable, or the collectable object has the right tag ** and it is not dead. The option 'L == NULL' allows other ** macros using this one to be used where L is not available. */ #define checkliveness(L,obj) \ ((void)L, lua_longassert(!iscollectable(obj) || \ (righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj)))))) /* Macros to set values */ /* set a value's tag */ #define settt_(o,t) ((o)->tt_=(t)) /* main macro to copy values (from 'obj1' to 'obj2') */ #define setobj(L,obj1,obj2) \ { TValue *io1=(obj1); const TValue *io2=(obj2); \ io1->value_ = io2->value_; settt_(io1, io2->tt_); \ checkliveness(L,io1); lua_assert(!isnonstrictnil(io1)); } /* ** Different types of assignments, according to source and destination. ** (They are mostly equal now, but may be different in the future.) */ /* from stack to stack */ #define setobjs2s(L,o1,o2) setobj(L,s2v(o1),s2v(o2)) /* to stack (not from same stack) */ #define setobj2s(L,o1,o2) setobj(L,s2v(o1),o2) /* from table to same table */ #define setobjt2t setobj /* to new object */ #define setobj2n setobj /* to table */ #define setobj2t setobj /* ** Entries in the Lua stack */ typedef union StackValue { TValue val; } StackValue; /* index to stack elements */ typedef StackValue *StkId; /* convert a 'StackValue' to a 'TValue' */ #define s2v(o) (&(o)->val) /* ** {================================================================== ** Nil ** =================================================================== */ /* Standard nil */ #define LUA_VNIL makevariant(LUA_TNIL, 0) /* Empty slot (which might be different from a slot containing nil) */ #define LUA_VEMPTY makevariant(LUA_TNIL, 1) /* Value returned for a key not found in a table (absent key) */ #define LUA_VABSTKEY makevariant(LUA_TNIL, 2) /* macro to test for (any kind of) nil */ #define ttisnil(v) checktype((v), LUA_TNIL) /* macro to test for a standard nil */ #define ttisstrictnil(o) checktag((o), LUA_VNIL) #define setnilvalue(obj) settt_(obj, LUA_VNIL) #define isabstkey(v) checktag((v), LUA_VABSTKEY) /* ** macro to detect non-standard nils (used only in assertions) */ #define isnonstrictnil(v) (ttisnil(v) && !ttisstrictnil(v)) /* ** By default, entries with any kind of nil are considered empty. ** (In any definition, values associated with absent keys must also ** be accepted as empty.) */ #define isempty(v) ttisnil(v) /* macro defining a value corresponding to an absent key */ #define ABSTKEYCONSTANT {NULL}, LUA_VABSTKEY /* mark an entry as empty */ #define setempty(v) settt_(v, LUA_VEMPTY) /* }================================================================== */ /* ** {================================================================== ** Booleans ** =================================================================== */ #define LUA_VFALSE makevariant(LUA_TBOOLEAN, 0) #define LUA_VTRUE makevariant(LUA_TBOOLEAN, 1) #define ttisboolean(o) checktype((o), LUA_TBOOLEAN) #define ttisfalse(o) checktag((o), LUA_VFALSE) #define ttistrue(o) checktag((o), LUA_VTRUE) #define l_isfalse(o) (ttisfalse(o) || ttisnil(o)) #define setbfvalue(obj) settt_(obj, LUA_VFALSE) #define setbtvalue(obj) settt_(obj, LUA_VTRUE) /* }================================================================== */ /* ** {================================================================== ** Threads ** =================================================================== */ #define LUA_VTHREAD makevariant(LUA_TTHREAD, 0) #define ttisthread(o) checktag((o), ctb(LUA_VTHREAD)) #define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc)) #define setthvalue(L,obj,x) \ { TValue *io = (obj); lua_State *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTHREAD)); \ checkliveness(L,io); } #define setthvalue2s(L,o,t) setthvalue(L,s2v(o),t) /* }================================================================== */ /* ** {================================================================== ** Collectable Objects ** =================================================================== */ /* ** Common Header for all collectable objects (in macro form, to be ** included in other objects) */ #define CommonHeader struct GCObject *next; lu_byte tt; lu_byte marked /* Common type for all collectable objects */ typedef struct GCObject { CommonHeader; } GCObject; /* Bit mark for collectable types */ #define BIT_ISCOLLECTABLE (1 << 6) #define iscollectable(o) (rawtt(o) & BIT_ISCOLLECTABLE) /* mark a tag as collectable */ #define ctb(t) ((t) | BIT_ISCOLLECTABLE) #define gcvalue(o) check_exp(iscollectable(o), val_(o).gc) #define gcvalueraw(v) ((v).gc) #define setgcovalue(L,obj,x) \ { TValue *io = (obj); GCObject *i_g=(x); \ val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); } /* }================================================================== */ /* ** {================================================================== ** Numbers ** =================================================================== */ /* Variant tags for numbers */ #define LUA_VNUMINT makevariant(LUA_TNUMBER, 0) /* integer numbers */ #define LUA_VNUMFLT makevariant(LUA_TNUMBER, 1) /* float numbers */ #define ttisnumber(o) checktype((o), LUA_TNUMBER) #define ttisfloat(o) checktag((o), LUA_VNUMFLT) #define ttisinteger(o) checktag((o), LUA_VNUMINT) #define nvalue(o) check_exp(ttisnumber(o), \ (ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o))) #define fltvalue(o) check_exp(ttisfloat(o), val_(o).n) #define ivalue(o) check_exp(ttisinteger(o), val_(o).i) #define fltvalueraw(v) ((v).n) #define ivalueraw(v) ((v).i) #define setfltvalue(obj,x) \ { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_VNUMFLT); } #define chgfltvalue(obj,x) \ { TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); } #define setivalue(obj,x) \ { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_VNUMINT); } #define chgivalue(obj,x) \ { TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); } /* }================================================================== */ /* ** {================================================================== ** Strings ** =================================================================== */ /* Variant tags for strings */ #define LUA_VSHRSTR makevariant(LUA_TSTRING, 0) /* short strings */ #define LUA_VLNGSTR makevariant(LUA_TSTRING, 1) /* long strings */ #define ttisstring(o) checktype((o), LUA_TSTRING) #define ttisshrstring(o) checktag((o), ctb(LUA_VSHRSTR)) #define ttislngstring(o) checktag((o), ctb(LUA_VLNGSTR)) #define tsvalueraw(v) (gco2ts((v).gc)) #define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc)) #define setsvalue(L,obj,x) \ { TValue *io = (obj); TString *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \ checkliveness(L,io); } /* set a string to the stack */ #define setsvalue2s(L,o,s) setsvalue(L,s2v(o),s) /* set a string to a new object */ #define setsvalue2n setsvalue /* ** Header for a string value. */ typedef struct TString { CommonHeader; lu_byte extra; /* reserved words for short strings; "has hash" for longs */ lu_byte shrlen; /* length for short strings */ unsigned int hash; union { size_t lnglen; /* length for long strings */ struct TString *hnext; /* linked list for hash table */ } u; char contents[1]; } TString; /* ** Get the actual string (array of bytes) from a 'TString'. */ #define getstr(ts) ((ts)->contents) /* get the actual string (array of bytes) from a Lua value */ #define svalue(o) getstr(tsvalue(o)) /* get string length from 'TString *s' */ #define tsslen(s) ((s)->tt == LUA_VSHRSTR ? (s)->shrlen : (s)->u.lnglen) /* get string length from 'TValue *o' */ #define vslen(o) tsslen(tsvalue(o)) /* }================================================================== */ /* ** {================================================================== ** Userdata ** =================================================================== */ /* ** Light userdata should be a variant of userdata, but for compatibility ** reasons they are also different types. */ #define LUA_VLIGHTUSERDATA makevariant(LUA_TLIGHTUSERDATA, 0) #define LUA_VUSERDATA makevariant(LUA_TUSERDATA, 0) #define ttislightuserdata(o) checktag((o), LUA_VLIGHTUSERDATA) #define ttisfulluserdata(o) checktag((o), ctb(LUA_VUSERDATA)) #define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p) #define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc)) #define pvalueraw(v) ((v).p) #define setpvalue(obj,x) \ { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_VLIGHTUSERDATA); } #define setuvalue(L,obj,x) \ { TValue *io = (obj); Udata *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VUSERDATA)); \ checkliveness(L,io); } /* Ensures that addresses after this type are always fully aligned. */ typedef union UValue { TValue uv; LUAI_MAXALIGN; /* ensures maximum alignment for udata bytes */ } UValue; /* ** Header for userdata with user values; ** memory area follows the end of this structure. */ typedef struct Udata { CommonHeader; unsigned short nuvalue; /* number of user values */ size_t len; /* number of bytes */ struct Table *metatable; GCObject *gclist; UValue uv[1]; /* user values */ } Udata; /* ** Header for userdata with no user values. These userdata do not need ** to be gray during GC, and therefore do not need a 'gclist' field. ** To simplify, the code always use 'Udata' for both kinds of userdata, ** making sure it never accesses 'gclist' on userdata with no user values. ** This structure here is used only to compute the correct size for ** this representation. (The 'bindata' field in its end ensures correct ** alignment for binary data following this header.) */ typedef struct Udata0 { CommonHeader; unsigned short nuvalue; /* number of user values */ size_t len; /* number of bytes */ struct Table *metatable; union {LUAI_MAXALIGN;} bindata; } Udata0; /* compute the offset of the memory area of a userdata */ #define udatamemoffset(nuv) \ ((nuv) == 0 ? offsetof(Udata0, bindata) \ : offsetof(Udata, uv) + (sizeof(UValue) * (nuv))) /* get the address of the memory block inside 'Udata' */ #define getudatamem(u) (cast_charp(u) + udatamemoffset((u)->nuvalue)) /* compute the size of a userdata */ #define sizeudata(nuv,nb) (udatamemoffset(nuv) + (nb)) /* }================================================================== */ /* ** {================================================================== ** Prototypes ** =================================================================== */ #define LUA_VPROTO makevariant(LUA_TPROTO, 0) /* ** Description of an upvalue for function prototypes */ typedef struct Upvaldesc { TString *name; /* upvalue name (for debug information) */ lu_byte instack; /* whether it is in stack (register) */ lu_byte idx; /* index of upvalue (in stack or in outer function's list) */ lu_byte kind; /* kind of corresponding variable */ } Upvaldesc; /* ** Description of a local variable for function prototypes ** (used for debug information) */ typedef struct LocVar { TString *varname; int startpc; /* first point where variable is active */ int endpc; /* first point where variable is dead */ } LocVar; /* ** Associates the absolute line source for a given instruction ('pc'). ** The array 'lineinfo' gives, for each instruction, the difference in ** lines from the previous instruction. When that difference does not ** fit into a byte, Lua saves the absolute line for that instruction. ** (Lua also saves the absolute line periodically, to speed up the ** computation of a line number: we can use binary search in the ** absolute-line array, but we must traverse the 'lineinfo' array ** linearly to compute a line.) */ typedef struct AbsLineInfo { int pc; int line; } AbsLineInfo; /* ** Function Prototypes */ typedef struct Proto { CommonHeader; lu_byte numparams; /* number of fixed (named) parameters */ lu_byte is_vararg; lu_byte maxstacksize; /* number of registers needed by this function */ int sizeupvalues; /* size of 'upvalues' */ int sizek; /* size of 'k' */ int sizecode; int sizelineinfo; int sizep; /* size of 'p' */ int sizelocvars; int sizeabslineinfo; /* size of 'abslineinfo' */ int linedefined; /* debug information */ int lastlinedefined; /* debug information */ TValue *k; /* constants used by the function */ Instruction *code; /* opcodes */ struct Proto **p; /* functions defined inside the function */ Upvaldesc *upvalues; /* upvalue information */ ls_byte *lineinfo; /* information about source lines (debug information) */ AbsLineInfo *abslineinfo; /* idem */ LocVar *locvars; /* information about local variables (debug information) */ TString *source; /* used for debug information */ GCObject *gclist; } Proto; /* }================================================================== */ /* ** {================================================================== ** Closures ** =================================================================== */ #define LUA_VUPVAL makevariant(LUA_TUPVAL, 0) /* Variant tags for functions */ #define LUA_VLCL makevariant(LUA_TFUNCTION, 0) /* Lua closure */ #define LUA_VLCF makevariant(LUA_TFUNCTION, 1) /* light C function */ #define LUA_VCCL makevariant(LUA_TFUNCTION, 2) /* C closure */ #define ttisfunction(o) checktype(o, LUA_TFUNCTION) #define ttisclosure(o) ((rawtt(o) & 0x1F) == LUA_VLCL) #define ttisLclosure(o) checktag((o), ctb(LUA_VLCL)) #define ttislcf(o) checktag((o), LUA_VLCF) #define ttisCclosure(o) checktag((o), ctb(LUA_VCCL)) #define isLfunction(o) ttisLclosure(o) #define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc)) #define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc)) #define fvalue(o) check_exp(ttislcf(o), val_(o).f) #define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc)) #define fvalueraw(v) ((v).f) #define setclLvalue(L,obj,x) \ { TValue *io = (obj); LClosure *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VLCL)); \ checkliveness(L,io); } #define setclLvalue2s(L,o,cl) setclLvalue(L,s2v(o),cl) #define setfvalue(obj,x) \ { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_VLCF); } #define setclCvalue(L,obj,x) \ { TValue *io = (obj); CClosure *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VCCL)); \ checkliveness(L,io); } /* ** Upvalues for Lua closures */ typedef struct UpVal { CommonHeader; lu_byte tbc; /* true if it represents a to-be-closed variable */ TValue *v; /* points to stack or to its own value */ union { struct { /* (when open) */ struct UpVal *next; /* linked list */ struct UpVal **previous; } open; TValue value; /* the value (when closed) */ } u; } UpVal; #define ClosureHeader \ CommonHeader; lu_byte nupvalues; GCObject *gclist typedef struct CClosure { ClosureHeader; lua_CFunction f; TValue upvalue[1]; /* list of upvalues */ } CClosure; typedef struct LClosure { ClosureHeader; struct Proto *p; UpVal *upvals[1]; /* list of upvalues */ } LClosure; typedef union Closure { CClosure c; LClosure l; } Closure; #define getproto(o) (clLvalue(o)->p) /* }================================================================== */ /* ** {================================================================== ** Tables ** =================================================================== */ #define LUA_VTABLE makevariant(LUA_TTABLE, 0) #define ttistable(o) checktag((o), ctb(LUA_VTABLE)) #define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc)) #define sethvalue(L,obj,x) \ { TValue *io = (obj); Table *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTABLE)); \ checkliveness(L,io); } #define sethvalue2s(L,o,h) sethvalue(L,s2v(o),h) /* ** Nodes for Hash tables: A pack of two TValue's (key-value pairs) ** plus a 'next' field to link colliding entries. The distribution ** of the key's fields ('key_tt' and 'key_val') not forming a proper ** 'TValue' allows for a smaller size for 'Node' both in 4-byte ** and 8-byte alignments. */ typedef union Node { struct NodeKey { TValuefields; /* fields for value */ lu_byte key_tt; /* key type */ int next; /* for chaining */ Value key_val; /* key value */ } u; TValue i_val; /* direct access to node's value as a proper 'TValue' */ } Node; /* copy a value into a key */ #define setnodekey(L,node,obj) \ { Node *n_=(node); const TValue *io_=(obj); \ n_->u.key_val = io_->value_; n_->u.key_tt = io_->tt_; \ checkliveness(L,io_); } /* copy a value from a key */ #define getnodekey(L,obj,node) \ { TValue *io_=(obj); const Node *n_=(node); \ io_->value_ = n_->u.key_val; io_->tt_ = n_->u.key_tt; \ checkliveness(L,io_); } /* ** About 'alimit': if 'isrealasize(t)' is true, then 'alimit' is the ** real size of 'array'. Otherwise, the real size of 'array' is the ** smallest power of two not smaller than 'alimit' (or zero iff 'alimit' ** is zero); 'alimit' is then used as a hint for #t. */ #define BITRAS (1 << 7) #define isrealasize(t) (!((t)->flags & BITRAS)) #define setrealasize(t) ((t)->flags &= cast_byte(~BITRAS)) #define setnorealasize(t) ((t)->flags |= BITRAS) typedef struct Table { CommonHeader; lu_byte flags; /* 1<<p means tagmethod(p) is not present */ lu_byte lsizenode; /* log2 of size of 'node' array */ unsigned int alimit; /* "limit" of 'array' array */ TValue *array; /* array part */ Node *node; Node *lastfree; /* any free position is before this position */ struct Table *metatable; GCObject *gclist; } Table; /* ** Macros to manipulate keys inserted in nodes */ #define keytt(node) ((node)->u.key_tt) #define keyval(node) ((node)->u.key_val) #define keyisnil(node) (keytt(node) == LUA_TNIL) #define keyisinteger(node) (keytt(node) == LUA_VNUMINT) #define keyival(node) (keyval(node).i) #define keyisshrstr(node) (keytt(node) == ctb(LUA_VSHRSTR)) #define keystrval(node) (gco2ts(keyval(node).gc)) #define setnilkey(node) (keytt(node) = LUA_TNIL) #define keyiscollectable(n) (keytt(n) & BIT_ISCOLLECTABLE) #define gckey(n) (keyval(n).gc) #define gckeyN(n) (keyiscollectable(n) ? gckey(n) : NULL) /* ** Use a "nil table" to mark dead keys in a table. Those keys serve ** to keep space for removed entries, which may still be part of ** chains. Note that the 'keytt' does not have the BIT_ISCOLLECTABLE ** set, so these values are considered not collectable and are different ** from any valid value. */ #define setdeadkey(n) (keytt(n) = LUA_TTABLE, gckey(n) = NULL) /* }================================================================== */ /* ** 'module' operation for hashing (size is always a power of 2) */ #define lmod(s,size) \ (check_exp((size&(size-1))==0, (cast_int((s) & ((size)-1))))) #define twoto(x) (1<<(x)) #define sizenode(t) (twoto((t)->lsizenode)) /* size of buffer for 'luaO_utf8esc' function */ #define UTF8BUFFSZ 8 LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x); LUAI_FUNC int luaO_ceillog2 (unsigned int x); LUAI_FUNC int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2, TValue *res); LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2, StkId res); LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o); LUAI_FUNC int luaO_hexavalue (int c); LUAI_FUNC void luaO_tostring (lua_State *L, TValue *obj); LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp); LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t srclen); #endif
xLua/build/lua-5.4.1/src/lobject.h/0
{ "file_path": "xLua/build/lua-5.4.1/src/lobject.h", "repo_id": "xLua", "token_count": 8078 }
1,935
/* ** $Id: ltm.c $ ** Tag methods ** See Copyright Notice in lua.h */ #define ltm_c #define LUA_CORE #include "lprefix.h" #include <string.h> #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lgc.h" #include "lobject.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #include "lvm.h" static const char udatatypename[] = "userdata"; LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTYPES] = { "no value", "nil", "boolean", udatatypename, "number", "string", "table", "function", udatatypename, "thread", "upvalue", "proto" /* these last cases are used for tests only */ }; void luaT_init (lua_State *L) { static const char *const luaT_eventname[] = { /* ORDER TM */ "__index", "__newindex", "__gc", "__mode", "__len", "__eq", "__add", "__sub", "__mul", "__mod", "__pow", "__div", "__idiv", "__band", "__bor", "__bxor", "__shl", "__shr", "__unm", "__bnot", "__lt", "__le", "__concat", "__call", "__close" }; int i; for (i=0; i<TM_N; i++) { G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]); luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */ } } /* ** function to be used with macro "fasttm": optimized for absence of ** tag methods */ const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { const TValue *tm = luaH_getshortstr(events, ename); lua_assert(event <= TM_EQ); if (notm(tm)) { /* no tag method? */ events->flags |= cast_byte(1u<<event); /* cache this fact */ return NULL; } else return tm; } const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) { Table *mt; switch (ttype(o)) { case LUA_TTABLE: mt = hvalue(o)->metatable; break; case LUA_TUSERDATA: mt = uvalue(o)->metatable; break; default: mt = G(L)->mt[ttype(o)]; } return (mt ? luaH_getshortstr(mt, G(L)->tmname[event]) : &G(L)->nilvalue); } /* ** Return the name of the type of an object. For tables and userdata ** with metatable, use their '__name' metafield, if present. */ const char *luaT_objtypename (lua_State *L, const TValue *o) { Table *mt; if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) || (ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) { const TValue *name = luaH_getshortstr(mt, luaS_new(L, "__name")); if (ttisstring(name)) /* is '__name' a string? */ return getstr(tsvalue(name)); /* use it as type name */ } return ttypename(ttype(o)); /* else use standard type name */ } void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, const TValue *p2, const TValue *p3) { StkId func = L->top; setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ setobj2s(L, func + 1, p1); /* 1st argument */ setobj2s(L, func + 2, p2); /* 2nd argument */ setobj2s(L, func + 3, p3); /* 3rd argument */ L->top = func + 4; /* metamethod may yield only when called from Lua code */ if (isLuacode(L->ci)) luaD_call(L, func, 0); else luaD_callnoyield(L, func, 0); } void luaT_callTMres (lua_State *L, const TValue *f, const TValue *p1, const TValue *p2, StkId res) { ptrdiff_t result = savestack(L, res); StkId func = L->top; setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ setobj2s(L, func + 1, p1); /* 1st argument */ setobj2s(L, func + 2, p2); /* 2nd argument */ L->top += 3; /* metamethod may yield only when called from Lua code */ if (isLuacode(L->ci)) luaD_call(L, func, 1); else luaD_callnoyield(L, func, 1); res = restorestack(L, result); setobjs2s(L, res, --L->top); /* move result to its place */ } static int callbinTM (lua_State *L, const TValue *p1, const TValue *p2, StkId res, TMS event) { const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ if (notm(tm)) tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ if (notm(tm)) return 0; luaT_callTMres(L, tm, p1, p2, res); return 1; } void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, StkId res, TMS event) { if (!callbinTM(L, p1, p2, res, event)) { switch (event) { case TM_BAND: case TM_BOR: case TM_BXOR: case TM_SHL: case TM_SHR: case TM_BNOT: { if (ttisnumber(p1) && ttisnumber(p2)) luaG_tointerror(L, p1, p2); else luaG_opinterror(L, p1, p2, "perform bitwise operation on"); } /* calls never return, but to avoid warnings: *//* FALLTHROUGH */ default: luaG_opinterror(L, p1, p2, "perform arithmetic on"); } } } void luaT_tryconcatTM (lua_State *L) { StkId top = L->top; if (!callbinTM(L, s2v(top - 2), s2v(top - 1), top - 2, TM_CONCAT)) luaG_concaterror(L, s2v(top - 2), s2v(top - 1)); } void luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2, int flip, StkId res, TMS event) { if (flip) luaT_trybinTM(L, p2, p1, res, event); else luaT_trybinTM(L, p1, p2, res, event); } void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2, int flip, StkId res, TMS event) { TValue aux; setivalue(&aux, i2); luaT_trybinassocTM(L, p1, &aux, flip, res, event); } /* ** Calls an order tag method. ** For lessequal, LUA_COMPAT_LT_LE keeps compatibility with old ** behavior: if there is no '__le', try '__lt', based on l <= r iff ** !(r < l) (assuming a total order). If the metamethod yields during ** this substitution, the continuation has to know about it (to negate ** the result of r<l); bit CIST_LEQ in the call status keeps that ** information. */ int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2, TMS event) { if (callbinTM(L, p1, p2, L->top, event)) /* try original event */ return !l_isfalse(s2v(L->top)); #if defined(LUA_COMPAT_LT_LE) else if (event == TM_LE) { /* try '!(p2 < p1)' for '(p1 <= p2)' */ L->ci->callstatus |= CIST_LEQ; /* mark it is doing 'lt' for 'le' */ if (callbinTM(L, p2, p1, L->top, TM_LT)) { L->ci->callstatus ^= CIST_LEQ; /* clear mark */ return l_isfalse(s2v(L->top)); } /* else error will remove this 'ci'; no need to clear mark */ } #endif luaG_ordererror(L, p1, p2); /* no metamethod found */ return 0; /* to avoid warnings */ } int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2, int flip, int isfloat, TMS event) { TValue aux; const TValue *p2; if (isfloat) { setfltvalue(&aux, cast_num(v2)); } else setivalue(&aux, v2); if (flip) { /* arguments were exchanged? */ p2 = p1; p1 = &aux; /* correct them */ } else p2 = &aux; return luaT_callorderTM(L, p1, p2, event); } void luaT_adjustvarargs (lua_State *L, int nfixparams, CallInfo *ci, const Proto *p) { int i; int actual = cast_int(L->top - ci->func) - 1; /* number of arguments */ int nextra = actual - nfixparams; /* number of extra arguments */ ci->u.l.nextraargs = nextra; luaD_checkstack(L, p->maxstacksize + 1); /* copy function to the top of the stack */ setobjs2s(L, L->top++, ci->func); /* move fixed parameters to the top of the stack */ for (i = 1; i <= nfixparams; i++) { setobjs2s(L, L->top++, ci->func + i); setnilvalue(s2v(ci->func + i)); /* erase original parameter (for GC) */ } ci->func += actual + 1; ci->top += actual + 1; lua_assert(L->top <= ci->top && ci->top <= L->stack_last); } void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted) { int i; int nextra = ci->u.l.nextraargs; if (wanted < 0) { wanted = nextra; /* get all extra arguments available */ checkstackGCp(L, nextra, where); /* ensure stack space */ L->top = where + nextra; /* next instruction will need top */ } for (i = 0; i < wanted && i < nextra; i++) setobjs2s(L, where + i, ci->func - nextra + i); for (; i < wanted; i++) /* complete required results with nil */ setnilvalue(s2v(where + i)); }
xLua/build/lua-5.4.1/src/ltm.c/0
{ "file_path": "xLua/build/lua-5.4.1/src/ltm.c", "repo_id": "xLua", "token_count": 3701 }
1,936
mkdir -p build_unix && cd build_unix cmake -DLUAC_COMPATIBLE_FORMAT=ON ../ cd .. cmake --build build_unix --config Release
xLua/build/luac/make_unix.sh/0
{ "file_path": "xLua/build/luac/make_unix.sh", "repo_id": "xLua", "token_count": 49 }
1,937
/* ** Fast function IDs. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_FF_H #define _LJ_FF_H /* Fast function ID. */ typedef enum { FF_LUA_ = FF_LUA, /* Lua function (must be 0). */ FF_C_ = FF_C, /* Regular C function (must be 1). */ #define FFDEF(name) FF_##name, #include "lj_ffdef.h" FF__MAX } FastFunc; #endif
xLua/build/luajit-2.1.0b2/src/lj_ff.h/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_ff.h", "repo_id": "xLua", "token_count": 156 }
1,938
/* ** Bytecode instruction modes. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #define lj_bc_c #define LUA_CORE #include "lj_obj.h" #include "lj_bc.h" /* Bytecode offsets and bytecode instruction modes. */ #include "lj_bcdef.h"
xLua/build/luajit-2.1.0b3/src/lj_bc.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_bc.c", "repo_id": "xLua", "token_count": 100 }
1,939
/* ** LuaJIT core and libraries amalgamation. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #define ljamalg_c #define LUA_CORE /* To get the mremap prototype. Must be defined before any system includes. */ #if defined(__linux__) && !defined(_GNU_SOURCE) #define _GNU_SOURCE #endif #ifndef WINVER #define WINVER 0x0501 #endif #include "lua.h" #include "lauxlib.h" #include "lj_assert.c" #include "lj_gc.c" #include "lj_err.c" #include "lj_char.c" #include "lj_bc.c" #include "lj_obj.c" #include "lj_buf.c" #include "lj_str.c" #include "lj_tab.c" #include "lj_func.c" #include "lj_udata.c" #include "lj_meta.c" #include "lj_debug.c" #include "lj_prng.c" #include "lj_state.c" #include "lj_dispatch.c" #include "lj_vmevent.c" #include "lj_vmmath.c" #include "lj_strscan.c" #include "lj_strfmt.c" #include "lj_strfmt_num.c" #include "lj_serialize.c" #include "lj_api.c" #include "lj_profile.c" #include "lj_lex.c" #include "lj_parse.c" #include "lj_bcread.c" #include "lj_bcwrite.c" #include "lj_load.c" #include "lj_ctype.c" #include "lj_cdata.c" #include "lj_cconv.c" #include "lj_ccall.c" #include "lj_ccallback.c" #include "lj_carith.c" #include "lj_clib.c" #include "lj_cparse.c" #include "lj_lib.c" #include "lj_ir.c" #include "lj_opt_mem.c" #include "lj_opt_fold.c" #include "lj_opt_narrow.c" #include "lj_opt_dce.c" #include "lj_opt_loop.c" #include "lj_opt_split.c" #include "lj_opt_sink.c" #include "lj_mcode.c" #include "lj_snap.c" #include "lj_record.c" #include "lj_crecord.c" #include "lj_ffrecord.c" #include "lj_asm.c" #include "lj_trace.c" #include "lj_gdbjit.c" #include "lj_alloc.c" #include "lib_aux.c" #include "lib_base.c" #include "lib_math.c" #include "lib_string.c" #include "lib_table.c" #include "lib_io.c" #include "lib_os.c" #include "lib_package.c" #include "lib_debug.c" #include "lib_bit.c" #include "lib_jit.c" #include "lib_ffi.c" #include "lib_buffer.c" #include "lib_init.c"
xLua/build/luajit-2.1.0b3/src/ljamalg.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/ljamalg.c", "repo_id": "xLua", "token_count": 941 }
1,940
|// Low-level VM code for IBM z/Architecture (s390x) CPUs in LJ_GC64 mode. |// Bytecode interpreter, fast functions and helper functions. |// Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h | |// This assembly targets the instruction set available on z10 (and newer) |// machines. | |// ELF ABI registers: |// r0,r1 | | volatile | |// r2 | parameter and return value | volatile | |// r3-r5 | parameter | volatile | |// r6 | parameter | saved | |// r7-r11 | | saved | |// r12 | GOT pointer (needed?) | saved | |// r13 | literal pool (not needed) | saved | |// r14 | return address | volatile | |// r15 | stack pointer | saved | |// f0,f2,f4,f6 | parameter and return value | volatile | |// f1,f3,f5,f7 | | volatile | |// f8-f15 | | saved | |// ar0,ar1 | TLS | volatile | |// ar2-ar15 | | volatile | | |.arch s390x |.section code_op, code_sub | |.actionlist build_actionlist |.globals GLOB_ |.globalnames globnames |.externnames extnames | |//----------------------------------------------------------------------- | |// Fixed register assignments for the interpreter, callee-saved. |.define KBASE, r8 // Constants of current Lua function. |.define PC, r9 // Next PC. |.define DISPATCH, r10 // Opcode dispatch table. |.define ITYPE, r11 // Temporary used for type information. |.define BASE, r13 // Base of current Lua stack frame. | |// The following temporaries are not saved across C calls, except for RB. |.define RA, r4 // Overlaps CARG3. |.define RB, r7 // Must be callee-save. |.define RC, r5 // Overlaps CARG4. |.define RD, r6 // Overlaps CARG5. | |// Calling conventions. Also used as temporaries. |.define CARG1, r2 |.define CARG2, r3 |.define CARG3, r4 |.define CARG4, r5 |.define CARG5, r6 | |.define FARG1, f0 |.define FARG2, f2 |.define FARG3, f4 |.define FARG4, f6 | |.define CRET1, r2 | |.define TMPR0, r0 |.define TMPR1, r1 |.define OP, r2 | |// Stack layout while in interpreter. Must match with lj_frame.h. |.define CFRAME_SPACE, 240 // Delta for sp, 8 byte aligned. | |// Register save area. |.define SAVE_GPRS, 288(sp) // Save area for r6-r15 (10*8 bytes). |.define SAVE_GPRS_P, 48(sp) // Save area for r6-r15 (10*8 bytes) in prologue (before stack frame is allocated). | |// Argument save area. |.define SAVE_ERRF, 280(sp) // Argument 4, in r5. |.define SAVE_NRES, 272(sp) // Argument 3, in r4. Size is 4-bytes. |.define SAVE_CFRAME, 264(sp) // Argument 2, in r3. |.define SAVE_L, 256(sp) // Argument 1, in r2. |.define RESERVED, 248(sp) // Reserved for compiler use. |.define BACKCHAIN, 240(sp) // <- sp entering interpreter. | |// Interpreter stack frame. |.define SAVE_FPR15, 232(sp) |.define SAVE_FPR14, 224(sp) |.define SAVE_FPR13, 216(sp) |.define SAVE_FPR12, 208(sp) |.define SAVE_FPR11, 200(sp) |.define SAVE_FPR10, 192(sp) |.define SAVE_FPR9, 184(sp) |.define SAVE_FPR8, 176(sp) |.define SAVE_PC, 168(sp) |.define SAVE_MULTRES, 160(sp) |.define SAVE_TMP, 160(sp) // Overlaps SAVE_MULTRES |.define SAVE_TMP_HI, 164(sp) // High 32-bits (to avoid SAVE_MULTRES). | |// Callee save area (allocated by interpreter). |.define CALLEESAVE, 000(sp) // <- sp in interpreter. | |.macro saveregs | stmg r6, r15, SAVE_GPRS_P | lay sp, -CFRAME_SPACE(sp) // Allocate stack frame. | std f8, SAVE_FPR8 // f8-f15 are callee-saved. | std f9, SAVE_FPR9 | std f10, SAVE_FPR10 | std f11, SAVE_FPR11 | std f12, SAVE_FPR12 | std f13, SAVE_FPR13 | std f14, SAVE_FPR14 | std f15, SAVE_FPR15 |.endmacro | |.macro restoreregs | ld f8, SAVE_FPR8 // f8-f15 are callee-saved. | ld f9, SAVE_FPR9 | ld f10, SAVE_FPR10 | ld f11, SAVE_FPR11 | ld f12, SAVE_FPR12 | ld f13, SAVE_FPR13 | ld f14, SAVE_FPR14 | ld f15, SAVE_FPR15 | lmg r6, r15, SAVE_GPRS // Restores the stack pointer. |.endmacro | |// Type definitions. Some of these are only used for documentation. |.type L, lua_State |.type GL, global_State |.type TVALUE, TValue |.type GCOBJ, GCobj |.type STR, GCstr |.type TAB, GCtab |.type LFUNC, GCfuncL |.type CFUNC, GCfuncC |.type PROTO, GCproto |.type UPVAL, GCupval |.type NODE, Node |.type NARGS, int |.type TRACE, GCtrace |.type SBUF, SBuf | |//----------------------------------------------------------------------- | |// Instruction headers. |.macro ins_A; .endmacro |.macro ins_AD; .endmacro |.macro ins_AJ; .endmacro |.macro ins_ABC; srlg RB, RD, 8; llgcr RC, RD; .endmacro |.macro ins_AB_; srlg RB, RD, 8; .endmacro |.macro ins_A_C; llgcr RC, RD; .endmacro |.macro ins_AND; lghi TMPR1, -1; xgr RD, TMPR1; .endmacro // RD = ~RD | |// Instruction decode+dispatch. |.macro ins_NEXT | llgc OP, 3(PC) | llgh RD, 0(PC) | llgc RA, 2(PC) | sllg TMPR1, OP, 3 | lg TMPR1, 0(TMPR1, DISPATCH) | la PC, 4(PC) | br TMPR1 |.endmacro | |// Instruction footer. |.if 1 | // Replicated dispatch. Less unpredictable branches, but higher I-Cache use. | .define ins_next, ins_NEXT | .define ins_next_, ins_NEXT |.else | // Common dispatch. Lower I-Cache use, only one (very) unpredictable branch. | .macro ins_next | j ->ins_next | .endmacro | .macro ins_next_ | ->ins_next: | ins_NEXT | .endmacro |.endif | |// Call decode and dispatch. |.macro ins_callt | // BASE = new base, RB = LFUNC, RD = nargs+1, -8(BASE) = PC | lg PC, LFUNC:RB->pc | llgc OP, 3(PC) | llgc RA, 2(PC) | sllg TMPR1, OP, 3 | la PC, 4(PC) | lg TMPR1, 0(TMPR1, DISPATCH) | br TMPR1 |.endmacro | |.macro ins_call | // BASE = new base, RB = LFUNC, RD = nargs+1 | stg PC, -8(BASE) | ins_callt |.endmacro | |// Assumes DISPATCH is relative to GL. #define DISPATCH_GL(field) (GG_DISP2G + (int)offsetof(global_State, field)) #define DISPATCH_J(field) (GG_DISP2J + (int)offsetof(jit_State, field)) | #define PC2PROTO(field) ((int)offsetof(GCproto, field)-(int)sizeof(GCproto)) | |//----------------------------------------------------------------------- | |// Macros to clear or set tags. |.macro cleartp, reg | nihf reg, 0x7fff |.endmacro |.macro settp, reg, tp | oihf reg, tp<<15 |.endmacro |.macro settp, dst, reg, tp | llihf dst, tp<<15 | ogr dst, reg |.endmacro |.macro setint, reg | settp reg, LJ_TISNUM |.endmacro |.macro setint, dst, reg | settp dst, reg, LJ_TISNUM |.endmacro | |// Macros to test operand types. |.macro checktp_nc, reg, tp, target | srag ITYPE, reg, 47 | clfi ITYPE, tp | jne target |.endmacro |.macro checktp, reg, tp, target | srag ITYPE, reg, 47 | cleartp reg | clfi ITYPE, tp | jne target |.endmacro |.macro checktptp, src, tp, target | srag ITYPE, src, 47 | clfi ITYPE, tp | jne target |.endmacro |.macro checkstr, reg, target; checktp reg, LJ_TSTR, target; .endmacro |.macro checktab, reg, target; checktp reg, LJ_TTAB, target; .endmacro |.macro checkfunc, reg, target; checktp reg, LJ_TFUNC, target; .endmacro | |.macro checknumx, reg, target, jump | srag ITYPE, reg, 47 | clfi ITYPE, LJ_TISNUM | jump target |.endmacro |.macro checkint, reg, target; checknumx reg, target, jne; .endmacro |.macro checkinttp, src, target; checknumx src, target, jne; .endmacro |.macro checknum, reg, target; checknumx reg, target, jhe; .endmacro |.macro checknumtp, src, target; checknumx src, target, jhe; .endmacro |.macro checknumber, src, target; checknumx src, target, jh; .endmacro | |.macro load_false, reg; lghi reg, -1; iihl reg, 0x7fff; .endmacro // assumes LJ_TFALSE == ~(1<<47) |.macro load_true, reg; lghi reg, -1; iihh reg, 0xfffe; .endmacro // assumes LJ_TTRUE == ~(2<<47) | |.define PC_OP, -1(PC) |.define PC_RA, -2(PC) |.define PC_RB, -4(PC) |.define PC_RC, -3(PC) |.define PC_RD, -4(PC) | |.macro branchPC, reg | // Must not clobber condition code. | sllg TMPR1, reg, 2 | lay PC, (-BCBIAS_J*4)(TMPR1, PC) |.endmacro | |// Set current VM state. |.macro set_vmstate, st | lghi TMPR1, ~LJ_VMST_..st | stg TMPR1, DISPATCH_GL(vmstate)(DISPATCH) |.endmacro | |// Synthesize binary floating-point constants. |.macro bfpconst_tobit, reg, tmp // Synthesize 2^52 + 2^51. | llihh tmp, 0x4338 | ldgr reg, tmp |.endmacro | |// Move table write barrier back. Overwrites reg. |.macro barrierback, tab, reg | ni tab->marked, ~LJ_GC_BLACK // black2gray(tab) | lg reg, (DISPATCH_GL(gc.grayagain))(DISPATCH) | stg tab, (DISPATCH_GL(gc.grayagain))(DISPATCH) | stg reg, tab->gclist |.endmacro #if !LJ_DUALNUM #error "Only dual-number mode supported for s390x target" #endif /* Generate subroutines used by opcodes and other parts of the VM. */ /* The .code_sub section should be last to help static branch prediction. */ static void build_subroutines(BuildCtx *ctx) { |.code_sub | |//----------------------------------------------------------------------- |//-- Return handling ---------------------------------------------------- |//----------------------------------------------------------------------- | |->vm_returnp: | tmll PC, FRAME_P | je ->cont_dispatch | | // Return from pcall or xpcall fast func. | nill PC, -8 | sgr BASE, PC // Restore caller base. | lay RA, -8(RA, PC) // Rebase RA and prepend one result. | lg PC, -8(BASE) // Fetch PC of previous frame. | // Prepending may overwrite the pcall frame, so do it at the end. | load_true ITYPE | stg ITYPE, 0(RA, BASE) // Prepend true to results. | |->vm_returnc: | aghi RD, 1 // RD = nresults+1 | je ->vm_unwind_yield | st RD, SAVE_MULTRES | tmll PC, FRAME_TYPE | je ->BC_RET_Z // Handle regular return to Lua. | |->vm_return: | // BASE = base, RA = resultofs, RD = nresults+1 (= MULTRES), PC = return | lghi TMPR1, FRAME_C | xgr PC, TMPR1 | tmll PC, FRAME_TYPE | jne ->vm_returnp | | // Return to C. | set_vmstate C | nill PC, -8 | sgr PC, BASE | lcgr PC, PC // Previous base = BASE - delta. | | aghi RD, -1 | je >2 |1: // Move results down. | lg RB, 0(BASE, RA) | stg RB, -16(BASE) | la BASE, 8(BASE) | aghi RD, -1 | jne <1 |2: | lg L:RB, SAVE_L | stg PC, L:RB->base |3: | llgf RD, SAVE_MULTRES | lgf RA, SAVE_NRES // RA = wanted nresults+1 |4: | cgr RA, RD | jne >6 // More/less results wanted? |5: | lay BASE, -16(BASE) | stg BASE, L:RB->top | |->vm_leave_cp: | lg RA, SAVE_CFRAME // Restore previous C frame. | stg RA, L:RB->cframe | lghi CRET1, 0 // Ok return status for vm_pcall. | |->vm_leave_unw: | restoreregs | br r14 | |6: | jl >7 // Less results wanted? | // More results wanted. Check stack size and fill up results with nil. | cg BASE, L:RB->maxstack | jh >8 | lghi TMPR1, LJ_TNIL | stg TMPR1, -16(BASE) | la BASE, 8(BASE) | aghi RD, 1 | j <4 | |7: // Fewer results wanted. | cghi RA, 0 | je <5 // But check for LUA_MULTRET+1. | sgr RA, RD // Negative result! | sllg TMPR1, RA, 3 | la BASE, 0(TMPR1, BASE) // Correct top. | j <5 | |8: // Corner case: need to grow stack for filling up results. | // This can happen if: | // - A C function grows the stack (a lot). | // - The GC shrinks the stack in between. | // - A return back from a lua_call() with (high) nresults adjustment. | stg BASE, L:RB->top // Save current top held in BASE (yes). | st RD, SAVE_MULTRES // Need to fill only remainder with nil. | lgr CARG2, RA | lgr CARG1, L:RB | brasl r14, extern lj_state_growstack // (lua_State *L, int n) | lg BASE, L:RB->top // Need the (realloced) L->top in BASE. | j <3 | |->vm_unwind_yield: | lghi CRET1, LUA_YIELD | j ->vm_unwind_c_eh | |->vm_unwind_c: // Unwind C stack, return from vm_pcall. | // (void *cframe, int errcode) | lgr sp, CARG1 | lgfr CARG2, CRET1 // Error return status for vm_pcall. |->vm_unwind_c_eh: // Landing pad for external unwinder. | lg L:RB, SAVE_L | lg GL:RB, L:RB->glref | lghi TMPR1, ~LJ_VMST_C | stg TMPR1, GL:RB->vmstate | j ->vm_leave_unw | |->vm_unwind_ff: // Unwind C stack, return from ff pcall. | // (void *cframe) | nill CARG1, CFRAME_RAWMASK // Assumes high 48-bits set in CFRAME_RAWMASK. | lgr sp, CARG1 |->vm_unwind_ff_eh: // Landing pad for external unwinder. | lg L:RB, SAVE_L | lghi RD, 1+1 // Really 1+2 results, incr. later. | lg BASE, L:RB->base | lg DISPATCH, L:RB->glref // Setup pointer to dispatch table. | la DISPATCH, GG_G2DISP(DISPATCH) | lg PC, -8(BASE) // Fetch PC of previous frame. | load_false RA | lg RB, 0(BASE) | stg RA, -16(BASE) // Prepend false to error message. | stg RB, -8(BASE) | lghi RA, -16 // Results start at BASE+RA = BASE-16. | set_vmstate INTERP | j ->vm_returnc // Increments RD/MULTRES and returns. | |//----------------------------------------------------------------------- |//-- Grow stack for calls ----------------------------------------------- |//----------------------------------------------------------------------- | |->vm_growstack_c: // Grow stack for C function. | lghi CARG2, LUA_MINSTACK | j >2 | |->vm_growstack_v: // Grow stack for vararg Lua function. | aghi RD, -16 // LJ_FR2 | j >1 | |->vm_growstack_f: // Grow stack for fixarg Lua function. | // BASE = new base, RD = nargs+1, RB = L, PC = first PC | sllg RD, NARGS:RD, 3 | lay RD, -8(RD, BASE) |1: | llgc RA, (PC2PROTO(framesize)-4)(PC) | la PC, 4(PC) // Must point after first instruction. | stg BASE, L:RB->base | stg RD, L:RB->top | stg PC, SAVE_PC | lgr CARG2, RA |2: | // RB = L, L->base = new base, L->top = top | lgr CARG1, L:RB | brasl r14, extern lj_state_growstack // (lua_State *L, int n) | lg BASE, L:RB->base | lg RD, L:RB->top | lg LFUNC:RB, -16(BASE) | cleartp LFUNC:RB | sgr RD, BASE | srlg RD, RD, 3 | aghi NARGS:RD, 1 | // BASE = new base, RB = LFUNC, RD = nargs+1 | ins_callt // Just retry the call. | |//----------------------------------------------------------------------- |//-- Entry points into the assembler VM --------------------------------- |//----------------------------------------------------------------------- | |->vm_resume: // Setup C frame and resume thread. | // (lua_State *L, TValue *base, int nres1 = 0, ptrdiff_t ef = 0) | saveregs | lgr L:RB, CARG1 | stg CARG1, SAVE_L | lgr RA, CARG2 | lghi PC, FRAME_CP | lghi RD, 0 | la KBASE, CFRAME_RESUME(sp) | lg DISPATCH, L:RB->glref // Setup pointer to dispatch table. | aghi DISPATCH, GG_G2DISP | stg RD, SAVE_PC // Any value outside of bytecode is ok. | stg RD, SAVE_CFRAME | st RD, SAVE_NRES | stg RD, SAVE_ERRF | stg KBASE, L:RB->cframe | clm RD, 1, L:RB->status | je >2 // Initial resume (like a call). | | // Resume after yield (like a return). | stg L:RB, (DISPATCH_GL(cur_L))(DISPATCH) | set_vmstate INTERP | stc RD, L:RB->status | lg BASE, L:RB->base | lg RD, L:RB->top | sgr RD, RA | srlg RD, RD, 3 | aghi RD, 1 // RD = nresults+1 | sgr RA, BASE // RA = resultofs | lg PC, -8(BASE) | st RD, SAVE_MULTRES | tmll PC, FRAME_TYPE | je ->BC_RET_Z | j ->vm_return | |->vm_pcall: // Setup protected C frame and enter VM. | // (lua_State *L, TValue *base, int nres1, ptrdiff_t ef) | saveregs | lghi PC, FRAME_CP | llgfr CARG4, CARG4 | stg CARG4, SAVE_ERRF | j >1 | |->vm_call: // Setup C frame and enter VM. | // (lua_State *L, TValue *base, int nres1) | saveregs | lghi PC, FRAME_C | |1: // Entry point for vm_pcall above (PC = ftype). | st CARG3, SAVE_NRES | lgr L:RB, CARG1 | stg CARG1, SAVE_L | lgr RA, CARG2 // Caveat: RA = CARG3. | | lg DISPATCH, L:RB->glref // Setup pointer to dispatch table. | lg KBASE, L:RB->cframe // Add our C frame to cframe chain. | stg KBASE, SAVE_CFRAME | stg L:RB, SAVE_PC // Any value outside of bytecode is ok. | aghi DISPATCH, GG_G2DISP | stg sp, L:RB->cframe | |2: // Entry point for vm_resume/vm_cpcall (RA = base, RB = L, PC = ftype). | stg L:RB, DISPATCH_GL(cur_L)(DISPATCH) | set_vmstate INTERP | lg BASE, L:RB->base // BASE = old base (used in vmeta_call). | agr PC, RA | sgr PC, BASE // PC = frame delta + frame type | | lg RD, L:RB->top | sgr RD, RA | srlg NARGS:RD, NARGS:RD, 3 | aghi NARGS:RD, 1 // RD = nargs+1 | |->vm_call_dispatch: | lg LFUNC:RB, -16(RA) | checkfunc LFUNC:RB, ->vmeta_call // Ensure KBASE defined and != BASE. | |->vm_call_dispatch_f: | lgr BASE, RA | ins_call | // BASE = new base, RB = func, RD = nargs+1, PC = caller PC | |->vm_cpcall: // Setup protected C frame, call C. | // (lua_State *L, lua_CFunction func, void *ud, lua_CPFunction cp) | saveregs | lgr L:RB, CARG1 | stg L:RB, SAVE_L | stg L:RB, SAVE_PC // Any value outside of bytecode is ok. | | lg KBASE, L:RB->stack // Compute -savestack(L, L->top). | sg KBASE, L:RB->top | lg DISPATCH, L:RB->glref // Setup pointer to dispatch table. | lghi TMPR0, 0 | stg TMPR0, SAVE_ERRF // No error function. | st KBASE, SAVE_NRES // Neg. delta means cframe w/o frame. | aghi DISPATCH, GG_G2DISP | // Handler may change cframe_nres(L->cframe) or cframe_errfunc(L->cframe). | | lg KBASE, L:RB->cframe // Add our C frame to cframe chain. | stg KBASE, SAVE_CFRAME | stg sp, L:RB->cframe | stg L:RB, DISPATCH_GL(cur_L)(DISPATCH) | | basr r14, CARG4 // (lua_State *L, lua_CFunction func, void *ud) | // TValue * (new base) or NULL returned in r2 (CRET1/). | cghi CRET1, 0 | je ->vm_leave_cp // No base? Just remove C frame. | lgr RA, CRET1 | lghi PC, FRAME_CP | j <2 // Else continue with the call. | |//----------------------------------------------------------------------- |//-- Metamethod handling ------------------------------------------------ |//----------------------------------------------------------------------- | |//-- Continuation dispatch ---------------------------------------------- | |->cont_dispatch: | // BASE = meta base, RA = resultofs, RD = nresults+1 (also in MULTRES) | agr RA, BASE | nill PC, -8 | lgr RB, BASE | sgr BASE, PC // Restore caller BASE. | sllg TMPR1, RD, 3 | lghi TMPR0, LJ_TNIL | stg TMPR0, -8(RA, TMPR1) // Ensure one valid arg. | lgr RC, RA // ... in [RC] | lg PC, -24(RB) // Restore PC from [cont|PC]. | lg RA, -32(RB) |.if FFI | clfi RA, 1 | jle >1 |.endif | lg LFUNC:KBASE, -16(BASE) | cleartp LFUNC:KBASE | lg KBASE, LFUNC:KBASE->pc | lg KBASE, (PC2PROTO(k))(KBASE) | // BASE = base, RC = result, RB = meta base | br RA // Jump to continuation. | |.if FFI |1: | je ->cont_ffi_callback // cont = 1: return from FFI callback. | // cont = 0: Tail call from C function. | sgr RB, BASE | srl RB, 3 | ahi RB, -3 | llgfr RD, RB | j ->vm_call_tail |.endif | |->cont_cat: // BASE = base, RC = result, RB = mbase | llgc RA, PC_RB | sllg RA, RA, 3 | aghi RB, -32 | la RA, 0(RA, BASE) | sgr RA, RB | je ->cont_ra | lcgr RA, RA | srlg RA, RA, 3 | lg L:CARG1, SAVE_L | stg BASE, L:CARG1->base | lgfr CARG3, RA // Caveat: RA == CARG3. | lg TMPR0, 0(RC) | stg TMPR0, 0(RB) | lgr CARG2, RB | j ->BC_CAT_Z | |//-- Table indexing metamethods ----------------------------------------- | |->vmeta_tgets: | settp STR:RC, LJ_TSTR // STR:RC = GCstr * | stg STR:RC, SAVE_TMP | la RC, SAVE_TMP | llgc TMPR1, PC_OP | cghi TMPR1, BC_GGET | jne >1 | settp TAB:RA, TAB:RB, LJ_TTAB // TAB:RB = GCtab * | lay RB, (DISPATCH_GL(tmptv))(DISPATCH) // Store fn->l.env in g->tmptv. | stg TAB:RA, 0(RB) | j >2 | |->vmeta_tgetb: | llgc RC, PC_RC | setint RC | stg RC, SAVE_TMP | la RC, SAVE_TMP | j >1 | |->vmeta_tgetv: | llgc RC, PC_RC // Reload TValue *k from RC. | sllg RC, RC, 3 | la RC, 0(RC, BASE) |1: | llgc RB, PC_RB // Reload TValue *t from RB. | sllg RB, RB, 3 | la RB, 0(RB, BASE) |2: | lg L:CARG1, SAVE_L | stg BASE, L:CARG1->base | lgr CARG2, RB | lgr CARG3, RC | lgr L:RB, L:CARG1 | stg PC, SAVE_PC | brasl r14, extern lj_meta_tget // (lua_State *L, TValue *o, TValue *k) | // TValue * (finished) or NULL (metamethod) returned in r2 (CRET1). | lg BASE, L:RB->base | ltgr RC, CRET1 | je >3 |->cont_ra: // BASE = base, RC = result | llgc RA, PC_RA | sllg RA, RA, 3 | lg RB, 0(RC) | stg RB, 0(RA, BASE) | ins_next | |3: // Call __index metamethod. | // BASE = base, L->top = new base, stack = cont/func/t/k | lg RA, L:RB->top | stg PC, -24(RA) // [cont|PC] | la PC, FRAME_CONT(RA) | sgr PC, BASE | lg LFUNC:RB, -16(RA) // Guaranteed to be a function here. | lghi NARGS:RD, 2+1 // 2 args for func(t, k). | cleartp LFUNC:RB | j ->vm_call_dispatch_f | |->vmeta_tgetr: | lgr CARG1, TAB:RB | lgfr CARG2, RC | brasl r14, extern lj_tab_getinth // (GCtab *t, int32_t key) | // cTValue * or NULL returned in r2 (CRET1). | llgc RA, PC_RA | ltgr RC, CRET1 | jne ->BC_TGETR_Z | lghi ITYPE, LJ_TNIL | j ->BC_TGETR2_Z | |//----------------------------------------------------------------------- | |->vmeta_tsets: | settp STR:RC, LJ_TSTR // STR:RC = GCstr * | stg STR:RC, SAVE_TMP | la RC, SAVE_TMP | llgc TMPR0, PC_OP | cghi TMPR0, BC_GSET | jne >1 | settp TAB:RA, TAB:RB, LJ_TTAB // TAB:RB = GCtab * | lay RB, (DISPATCH_GL(tmptv))(DISPATCH) // Store fn->l.env in g->tmptv. | stg TAB:RA, 0(RB) | j >2 | |->vmeta_tsetb: | llgc RC, PC_RC | setint RC | stg RC, SAVE_TMP | la RC, SAVE_TMP | j >1 | |->vmeta_tsetv: | llgc RC, PC_RC // Reload TValue *k from RC. | sllg RC, RC, 3 | la RC, 0(RC, BASE) |1: | llgc RB, PC_RB // Reload TValue *t from RB. | sllg RB, RB, 3 | la RB, 0(RB, BASE) |2: | lg L:CARG1, SAVE_L | stg BASE, L:CARG1->base | lgr CARG2, RB | lgr CARG3, RC | lgr L:RB, L:CARG1 | stg PC, SAVE_PC | brasl r14, extern lj_meta_tset // (lua_State *L, TValue *o, TValue *k) | // TValue * (finished) or NULL (metamethod) returned in r2 (CRET1). | lg BASE, L:RB->base | ltgr RC, CRET1 | je >3 | // NOBARRIER: lj_meta_tset ensures the table is not black. | llgc RA, PC_RA | sllg RA, RA, 3 | lg RB, 0(RA, BASE) | stg RB, 0(RC) |->cont_nop: // BASE = base, (RC = result) | ins_next | |3: // Call __newindex metamethod. | // BASE = base, L->top = new base, stack = cont/func/t/k/(v) | lg RA, L:RB->top | stg PC, -24(RA) // [cont|PC] | llgc RC, PC_RA | // Copy value to third argument. | sllg RB, RC, 3 | lg RB, 0(RB, BASE) | stg RB, 16(RA) | la PC, FRAME_CONT(RA) | sgr PC, BASE | lg LFUNC:RB, -16(RA) // Guaranteed to be a function here. | lghi NARGS:RD, 3+1 // 3 args for func(t, k, v). | cleartp LFUNC:RB | j ->vm_call_dispatch_f | |->vmeta_tsetr: | lg L:CARG1, SAVE_L | lgr CARG2, TAB:RB | stg BASE, L:CARG1->base | lgfr CARG3, RC | stg PC, SAVE_PC | brasl r14, extern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key) | // TValue * returned in r2 (CRET1). | lgr RC, CRET1 | llgc RA, PC_RA | j ->BC_TSETR_Z | |//-- Comparison metamethods --------------------------------------------- | |->vmeta_comp: | llgh RD, PC_RD | sllg RD, RD, 3 | llgc RA, PC_RA | sllg RA, RA, 3 | lg L:RB, SAVE_L | stg BASE, L:RB->base | la CARG2, 0(RA, BASE) | la CARG3, 0(RD, BASE) // Caveat: RA == CARG3 | lgr CARG1, L:RB | llgc CARG4, PC_OP | stg PC, SAVE_PC | brasl r14, extern lj_meta_comp // (lua_State *L, TValue *o1, *o2, int op) | // 0/1 or TValue * (metamethod) returned in r2 (CRET1). |3: | lgr RC, CRET1 | lg BASE, L:RB->base | clgfi RC, 1 | jh ->vmeta_binop |4: | la PC, 4(PC) | jl >6 |5: | llgh RD, PC_RD | branchPC RD |6: | ins_next | |->cont_condt: // BASE = base, RC = result | la PC, 4(PC) | lg ITYPE, 0(RC) | srag ITYPE, ITYPE, 47 | lghi TMPR0, LJ_TISTRUECOND | clr ITYPE, TMPR0 // Branch if result is true. | jl <5 | j <6 | |->cont_condf: // BASE = base, RC = result | lg ITYPE, 0(RC) | srag ITYPE, ITYPE, 47 | lghi TMPR0, LJ_TISTRUECOND | clr ITYPE, TMPR0 // Branch if result is false. | j <4 | |->vmeta_equal: | cleartp TAB:RD | lay PC, -4(PC) | lgr CARG2, RA | lgfr CARG4, RB | lg L:RB, SAVE_L | stg BASE, L:RB->base | lgr CARG3, RD | lgr CARG1, L:RB | stg PC, SAVE_PC | brasl r14, extern lj_meta_equal // (lua_State *L, GCobj *o1, *o2, int ne) | // 0/1 or TValue * (metamethod) returned in r2 (CRET1). | j <3 | |->vmeta_equal_cd: |.if FFI | lay PC, -4(PC) | lg L:RB, SAVE_L | stg BASE, L:RB->base | lgr CARG1, L:RB | llgf CARG2, -4(PC) | stg PC, SAVE_PC | brasl r14, extern lj_meta_equal_cd // (lua_State *L, BCIns ins) | // 0/1 or TValue * (metamethod) returned in r2 (CRET1). | j <3 |.endif | |->vmeta_istype: | lg L:RB, SAVE_L | stg BASE, L:RB->base | llgfr CARG2, RA | llgfr CARG3, RD // Caveat: CARG3 == RA. | lgr L:CARG1, L:RB | stg PC, SAVE_PC | brasl r14, extern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp) | lg BASE, L:RB->base | j <6 | |//-- Arithmetic metamethods --------------------------------------------- | |->vmeta_arith_vno: | llgc RB, PC_RB | llgc RC, PC_RC |->vmeta_arith_vn: | sllg RB, RB, 3 | sllg RC, RC, 3 | la RB, 0(RB, BASE) | la RC, 0(RC, KBASE) | j >1 | |->vmeta_arith_nvo: | llgc RC, PC_RC | llgc RB, PC_RB |->vmeta_arith_nv: | sllg RC, RC, 3 | sllg RB, RB, 3 | la TMPR1, 0(RC, KBASE) | la RC, 0(RB, BASE) | lgr RB, TMPR1 | j >1 | |->vmeta_unm: | llgh RD, PC_RD | sllg RD, RD, 3 | la RC, 0(RD, BASE) | lgr RB, RC | j >1 | |->vmeta_arith_vvo: | llgc RB, PC_RB | llgc RC, PC_RC |->vmeta_arith_vv: | sllg RC, RC, 3 | sllg RB, RB, 3 | la RB, 0(RB, BASE) | la RC, 0(RC, BASE) |1: | llgc RA, PC_RA | sllg RA, RA, 3 | la RA, 0(RA, BASE) | llgc CARG5, PC_OP // Caveat: CARG5 == RD. | lgr CARG2, RA | lgr CARG3, RB // Caveat: CARG3 == RA. | // lgr CARG4, RC // Caveat: CARG4 == RC (nop, so commented out). | lg L:CARG1, SAVE_L | stg BASE, L:CARG1->base | lgr L:RB, L:CARG1 | stg PC, SAVE_PC | brasl r14, extern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op) | // NULL (finished) or TValue * (metamethod) returned in r2 (CRET1). | lg BASE, L:RB->base | cghi CRET1, 0 | lgr RC, CRET1 | je ->cont_nop | | // Call metamethod for binary op. |->vmeta_binop: | // BASE = base, RC = new base, stack = cont/func/o1/o2 | lgr RA, RC | sgr RC, BASE | stg PC, -24(RA) // [cont|PC] | la PC, FRAME_CONT(RC) | lghi NARGS:RD, 2+1 // 2 args for func(o1, o2). | j ->vm_call_dispatch | |->vmeta_len: | llgh RD, PC_RD | sllg RD, RD, 3 | lg L:RB, SAVE_L | stg BASE, L:RB->base | la CARG2, 0(RD, BASE) | lgr L:CARG1, L:RB | stg PC, SAVE_PC | brasl r14, extern lj_meta_len // (lua_State *L, TValue *o) | // NULL (retry) or TValue * (metamethod) returned in r2 (CRET1). | lgr RC, CRET1 | lg BASE, L:RB->base #if LJ_52 | cghi RC, 0 | jne ->vmeta_binop // Binop call for compatibility. | llgh RD, PC_RD | sllg RD, RD, 3 | lg TAB:CARG1, 0(RD, BASE) | cleartp TAB:CARG1 | j ->BC_LEN_Z #else | j ->vmeta_binop // Binop call for compatibility. #endif | |//-- Call metamethod ---------------------------------------------------- | |->vmeta_call_ra: | la RA, 16(RA, BASE) // RA previously set to RA*8. |->vmeta_call: // Resolve and call __call metamethod. | // BASE = old base, RA = new base, RC = nargs+1, PC = return | stg NARGS:RD, SAVE_TMP // Save RA, RC for us (not sure about this). | lgr RB, RA | lg L:CARG1, SAVE_L | stg BASE, L:CARG1->base | lay CARG2, -16(RA) | sllg RD, RD, 3 | lay CARG3, -8(RA, RD) // Caveat: CARG3 == RA. | stg PC, SAVE_PC | brasl r14, extern lj_meta_call // (lua_State *L, TValue *func, TValue *top) | lgr RA, RB | lg L:RB, SAVE_L | lg BASE, L:RB->base | lg NARGS:RD, SAVE_TMP | lg LFUNC:RB, -16(RA) | aghi NARGS:RD, 1 // 32-bit on x64. | // This is fragile. L->base must not move, KBASE must always be defined. | cgr KBASE, BASE // Continue with CALLT if flag set. | je ->BC_CALLT_Z | cleartp LFUNC:RB | lgr BASE, RA | ins_call // Otherwise call resolved metamethod. | |//-- Argument coercion for 'for' statement ------------------------------ | |->vmeta_for: | lg L:RB, SAVE_L | stg BASE, L:RB->base | lgr CARG2, RA | lgr CARG1, RB | stg PC, SAVE_PC | brasl r14, extern lj_meta_for // (lua_State *L, TValue *base) | lg BASE, L:RB->base | llgc OP, PC_OP | llgc RA, PC_RA | llgh RD, PC_RD | sllg TMPR1, OP, 3 | lg TMPR1, GG_DISP2STATIC(TMPR1, DISPATCH) // Retry FORI or JFORI. | br TMPR1 | |//----------------------------------------------------------------------- |//-- Fast functions ----------------------------------------------------- |//----------------------------------------------------------------------- | |.macro .ffunc, name |->ff_ .. name: |.endmacro | |.macro .ffunc_1, name |->ff_ .. name: | clfi NARGS:RD, 1+1; jl ->fff_fallback |.endmacro | |.macro .ffunc_2, name |->ff_ .. name: | clfi NARGS:RD, 2+1; jl ->fff_fallback |.endmacro | |.macro .ffunc_n, name, op | .ffunc_1 name | lg TMPR0, 0(BASE) | checknumtp TMPR0, ->fff_fallback | op f0, 0(BASE) |.endmacro | |.macro .ffunc_n, name | .ffunc_n name, ld |.endmacro | |.macro .ffunc_nn, name | .ffunc_2 name | lg TMPR1, 0(BASE) | lg TMPR0, 8(BASE) | ld FARG1, 0(BASE) | ld FARG2, 8(BASE) | checknumtp TMPR1, ->fff_fallback | checknumtp TMPR0, ->fff_fallback |.endmacro | |// Inlined GC threshold check. Caveat: uses label 1. |.macro ffgccheck | lg RB, (DISPATCH_GL(gc.total))(DISPATCH) | clg RB, (DISPATCH_GL(gc.threshold))(DISPATCH) | jl >1 | brasl r14, ->fff_gcstep |1: |.endmacro | |//-- Base library: checks ----------------------------------------------- | |.ffunc_1 assert | lg RB, 0(BASE) | srag ITYPE, RB, 47 | clfi ITYPE, LJ_TISTRUECOND; jhe ->fff_fallback | lg PC, -8(BASE) | st RD, SAVE_MULTRES | lg RB, 0(BASE) | stg RB, -16(BASE) | ahi RD, -2 | je >2 | lgr RA, BASE |1: | la RA, 8(RA) | lg RB, 0(RA) | stg RB, -16(RA) | brct RD, <1 |2: | llgf RD, SAVE_MULTRES | j ->fff_res_ | |.ffunc_1 type | lg RC, 0(BASE) | srag RC, RC, 47 | lghi RB, LJ_TISNUM | clgr RC, RB | jnl >1 | lgr RC, RB |1: | lghi TMPR0, -1 | xgr RC, TMPR0 |2: | lg CFUNC:RB, -16(BASE) | cleartp CFUNC:RB | sllg RC, RC, 3 | lg STR:RC, ((char *)(&((GCfuncC *)0)->upvalue))(RC, CFUNC:RB) | lg PC, -8(BASE) | settp STR:RC, LJ_TSTR | stg STR:RC, -16(BASE) | j ->fff_res1 | |//-- Base library: getters and setters --------------------------------- | |.ffunc_1 getmetatable | lg TAB:RB, 0(BASE) | lg PC, -8(BASE) | checktab TAB:RB, >6 |1: // Field metatable must be at same offset for GCtab and GCudata! | lg TAB:RB, TAB:RB->metatable |2: | lghi TMPR0, LJ_TNIL | stg TMPR0, -16(BASE) | cghi TAB:RB, 0 | je ->fff_res1 | settp TAB:RC, TAB:RB, LJ_TTAB | stg TAB:RC, -16(BASE) // Store metatable as default result. | lg STR:RC, (DISPATCH_GL(gcroot)+8*(GCROOT_MMNAME+MM_metatable))(DISPATCH) | llgf RA, TAB:RB->hmask | n RA, STR:RC->hash | settp STR:RC, LJ_TSTR | mghi RA, #NODE | ag NODE:RA, TAB:RB->node |3: // Rearranged logic, because we expect _not_ to find the key. | cg STR:RC, NODE:RA->key | je >5 |4: | ltg NODE:RA, NODE:RA->next | jne <3 | j ->fff_res1 // Not found, keep default result. |5: | lg RB, NODE:RA->val | cghi RB, LJ_TNIL; je ->fff_res1 // Ditto for nil value. | stg RB, -16(BASE) // Return value of mt.__metatable. | j ->fff_res1 | |6: | clfi ITYPE, LJ_TUDATA; je <1 | clfi ITYPE, LJ_TISNUM; jh >7 | lhi ITYPE, LJ_TISNUM |7: | lhi TMPR0, -1 | xr ITYPE, TMPR0 // not ITYPE | llgfr ITYPE, ITYPE | sllg ITYPE, ITYPE, 3 | lg TAB:RB, (DISPATCH_GL(gcroot[GCROOT_BASEMT]))(ITYPE, DISPATCH) | j <2 | |.ffunc_2 setmetatable | lg TAB:RB, 0(BASE) | lgr TAB:TMPR1, TAB:RB | checktab TAB:RB, ->fff_fallback | // Fast path: no mt for table yet and not clearing the mt. | lghi TMPR0, 0 | cg TMPR0, TAB:RB->metatable; jne ->fff_fallback | lg TAB:RA, 8(BASE) | checktab TAB:RA, ->fff_fallback | stg TAB:RA, TAB:RB->metatable | lg PC, -8(BASE) | stg TAB:TMPR1, -16(BASE) // Return original table. | tm TAB:RB->marked, LJ_GC_BLACK // isblack(table) | je >1 | // Possible write barrier. Table is black, but skip iswhite(mt) check. | barrierback TAB:RB, RC |1: | j ->fff_res1 | |.ffunc_2 rawget | lg TAB:CARG2, 0(BASE) | checktab TAB:CARG2, ->fff_fallback | la CARG3, 8(BASE) | lg CARG1, SAVE_L | brasl r14, extern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key) | // cTValue * returned in r2 (CRET1). | // Copy table slot. | lg RB, 0(CRET1) | lg PC, -8(BASE) | stg RB, -16(BASE) | j ->fff_res1 | |//-- Base library: conversions ------------------------------------------ | |.ffunc tonumber | // Only handles the number case inline (without a base argument). | clfi NARGS:RD, 1+1; jne ->fff_fallback // Exactly one argument. | lg RB, 0(BASE) | checknumber RB, ->fff_fallback | lg PC, -8(BASE) | stg RB, -16(BASE) | j ->fff_res1 | |.ffunc_1 tostring | // Only handles the string or number case inline. | lg PC, -8(BASE) | lg STR:RB, 0(BASE) | checktp_nc STR:RB, LJ_TSTR, >3 | // A __tostring method in the string base metatable is ignored. |2: | stg STR:RB, -16(BASE) | j ->fff_res1 |3: // Handle numbers inline, unless a number base metatable is present. | clfi ITYPE, LJ_TISNUM; jh ->fff_fallback_1 | lghi TMPR0, 0 | cg TMPR0, (DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM]))(DISPATCH) | jne ->fff_fallback | ffgccheck // Caveat: uses label 1. | lg L:RB, SAVE_L | stg BASE, L:RB->base // Add frame since C call can throw. | stg PC, SAVE_PC // Redundant (but a defined value). | lgr CARG2, BASE // Otherwise: CARG2 == BASE | lgr L:CARG1, L:RB | brasl r14, extern lj_strfmt_number // (lua_State *L, cTValue *o) | // GCstr returned in r2 (CRET1). | lg BASE, L:RB->base | settp STR:RB, CRET1, LJ_TSTR | j <2 | |//-- Base library: iterators ------------------------------------------- | |.ffunc_1 next | je >2 // Missing 2nd arg? |1: | lg CARG2, 0(BASE) | checktab CARG2, ->fff_fallback | lg L:RB, SAVE_L | stg BASE, L:RB->base // Add frame since C call can throw. | stg BASE, L:RB->top // Dummy frame length is ok. | lg PC, -8(BASE) | la CARG3, 8(BASE) | lgr CARG1, L:RB | stg PC, SAVE_PC // Needed for ITERN fallback. | brasl r14, extern lj_tab_next // (lua_State *L, GCtab *t, TValue *key) | // Flag returned in r2 (CRET1). | lg BASE, L:RB->base | ltr RD, CRET1; je >3 // End of traversal? | // Copy key and value to results. | lg RB, 8(BASE) | lg RD, 16(BASE) | stg RB, -16(BASE) | stg RD, -8(BASE) |->fff_res2: | lghi RD, 1+2 | j ->fff_res |2: // Set missing 2nd arg to nil. | lghi TMPR0, LJ_TNIL | stg TMPR0, 8(BASE) | j <1 |3: // End of traversal: return nil. | lghi TMPR0, LJ_TNIL | stg TMPR0, -16(BASE) | j ->fff_res1 | |.ffunc_1 pairs | lg TAB:RB, 0(BASE) | lgr TMPR1, TAB:RB | checktab TAB:RB, ->fff_fallback #if LJ_52 | ltg TMPR0, TAB:RB->metatable; jne ->fff_fallback #endif | lg CFUNC:RD, -16(BASE) | cleartp CFUNC:RD | lg CFUNC:RD, CFUNC:RD->upvalue[0] | settp CFUNC:RD, LJ_TFUNC | lg PC, -8(BASE) | stg CFUNC:RD, -16(BASE) | stg TMPR1, -8(BASE) | lghi TMPR0, LJ_TNIL | stg TMPR0, 0(BASE) | lghi RD, 1+3 | j ->fff_res | |.ffunc_2 ipairs_aux | lg TAB:RB, 0(BASE) | checktab TAB:RB, ->fff_fallback | lg RA, 8(BASE) | checkint RA, ->fff_fallback | lg PC, -8(BASE) | aghi RA, 1 | setint ITYPE, RA | stg ITYPE, -16(BASE) | cl RA, TAB:RB->asize; jhe >2 // Not in array part? | lg RD, TAB:RB->array | lgfr TMPR1, RA | sllg TMPR1, TMPR1, 3 | la RD, 0(TMPR1, RD) |1: | lg TMPR0, 0(RD) | cghi TMPR0, LJ_TNIL; je ->fff_res0 | // Copy array slot. | stg TMPR0, -8(BASE) | j ->fff_res2 |2: // Check for empty hash part first. Otherwise call C function. | lt TMPR0, TAB:RB->hmask; je ->fff_res0 | lgr CARG1, TAB:RB | lgfr CARG2, RA | brasl r14, extern lj_tab_getinth // (GCtab *t, int32_t key) | // cTValue * or NULL returned in r2 (CRET1). | ltgr RD, CRET1 | jne <1 |->fff_res0: | lghi RD, 1+0 | j ->fff_res | |.ffunc_1 ipairs | lg TAB:RB, 0(BASE) | lgr TMPR1, TAB:RB | checktab TAB:RB, ->fff_fallback #if LJ_52 | lghi TMPR0, 0 | cg TMPR0, TAB:RB->metatable; jne ->fff_fallback #endif | lg CFUNC:RD, -16(BASE) | cleartp CFUNC:RD | lg CFUNC:RD, CFUNC:RD->upvalue[0] | settp CFUNC:RD, LJ_TFUNC | lg PC, -8(BASE) | stg CFUNC:RD, -16(BASE) | stg TMPR1, -8(BASE) | llihf RD, LJ_TISNUM<<15 | stg RD, 0(BASE) | lghi RD, 1+3 | j ->fff_res | |//-- Base library: catch errors ---------------------------------------- | |.ffunc_1 pcall | la RA, 16(BASE) | aghi NARGS:RD, -1 | lghi PC, 16+FRAME_PCALL |1: | llgc RB, (DISPATCH_GL(hookmask))(DISPATCH) | srlg RB, RB, HOOK_ACTIVE_SHIFT(r0) | nill RB, 1 // High bits already zero (from load). | agr PC, RB // Remember active hook before pcall. | // Note: this does a (harmless) copy of the function to the PC slot, too. | lgr KBASE, RD |2: | sllg TMPR1, KBASE, 3 | lg RB, -24(TMPR1, RA) | stg RB, -16(TMPR1, RA) | aghi KBASE, -1 | jh <2 | j ->vm_call_dispatch | |.ffunc_2 xpcall | lg LFUNC:RA, 8(BASE) | checktp_nc LFUNC:RA, LJ_TFUNC, ->fff_fallback | lg LFUNC:RB, 0(BASE) // Swap function and traceback. | stg LFUNC:RA, 0(BASE) | stg LFUNC:RB, 8(BASE) | la RA, 24(BASE) | aghi NARGS:RD, -2 | lghi PC, 24+FRAME_PCALL | j <1 | |//-- Coroutine library -------------------------------------------------- | |.macro coroutine_resume_wrap, resume |.if resume |.ffunc_1 coroutine_resume | lg L:RB, 0(BASE) | lgr L:TMPR0, L:RB // Save type for checktptp. | cleartp L:RB |.else |.ffunc coroutine_wrap_aux | lg CFUNC:RB, -16(BASE) | cleartp CFUNC:RB | lg L:RB, CFUNC:RB->upvalue[0].gcr | cleartp L:RB |.endif | lg PC, -8(BASE) | stg PC, SAVE_PC | stg L:RB, SAVE_TMP |.if resume | checktptp L:TMPR0, LJ_TTHREAD, ->fff_fallback |.endif | ltg TMPR0, L:RB->cframe; jne ->fff_fallback | cli L:RB->status, LUA_YIELD; jh ->fff_fallback | lg RA, L:RB->top | je >1 // Status != LUA_YIELD (i.e. 0)? | cg RA, L:RB->base // Check for presence of initial func. | je ->fff_fallback | lg PC, -8(RA) // Move initial function up. | stg PC, 0(RA) | la RA, 8(RA) |1: | sllg TMPR1, NARGS:RD, 3 |.if resume | lay PC, -16(TMPR1, RA) // Check stack space (-1-thread). |.else | lay PC, -8(TMPR1, RA) // Check stack space (-1). |.endif | clg PC, L:RB->maxstack; jh ->fff_fallback | stg PC, L:RB->top | | lg L:RB, SAVE_L | stg BASE, L:RB->base |.if resume | la BASE, 8(BASE) // Keep resumed thread in stack for GC. |.endif | stg BASE, L:RB->top |.if resume | lay RB, -24(TMPR1, BASE) // RB = end of source for stack move. |.else | lay RB, -16(TMPR1, BASE) // RB = end of source for stack move. |.endif | sgr RB, PC // Relative to PC. | | cgr PC, RA | je >3 |2: // Move args to coroutine. | lg RC, 0(RB, PC) | stg RC, -8(PC) | lay PC, -8(PC) | cgr PC, RA | jne <2 |3: | lgr CARG2, RA | lg L:CARG1, SAVE_TMP | lghi CARG3, 0 | lghi CARG4, 0 | brasl r14, ->vm_resume // (lua_State *L, TValue *base, 0, 0) | | lg L:RB, SAVE_L | lg L:PC, SAVE_TMP | lg BASE, L:RB->base | stg L:RB, (DISPATCH_GL(cur_L))(DISPATCH) | set_vmstate INTERP | | clfi CRET1, LUA_YIELD | jh >8 |4: | lg RA, L:PC->base | lg KBASE, L:PC->top | stg RA, L:PC->top // Clear coroutine stack. | lgr PC, KBASE | sgr PC, RA | je >6 // No results? | la RD, 0(PC, BASE) | llgfr PC, PC | srlg PC, PC, 3 | clg RD, L:RB->maxstack | jh >9 // Need to grow stack? | | lgr RB, BASE | sgr RB, RA |5: // Move results from coroutine. | lg RD, 0(RA) | stg RD, 0(RA, RB) | la RA, 8(RA) | cgr RA, KBASE | jne <5 |6: |.if resume | la RD, 2(PC) // nresults+1 = 1 + true + results. | load_true ITYPE // Prepend true to results. | stg ITYPE, -8(BASE) |.else | la RD, 1(PC) // nresults+1 = 1 + results. |.endif |7: | lg PC, SAVE_PC | st RD, SAVE_MULTRES |.if resume | lghi RA, -8 |.else | lghi RA, 0 |.endif | tmll PC, FRAME_TYPE | je ->BC_RET_Z | j ->vm_return | |8: // Coroutine returned with error (at co->top-1). |.if resume | load_false ITYPE // Prepend false to results. | stg ITYPE, -8(BASE) | lg RA, L:PC->top | aghi RA, -8 | stg RA, L:PC->top // Clear error from coroutine stack. | // Copy error message. | lg RD, 0(RA) | stg RD, 0(BASE) | lghi RD, 1+2 // nresults+1 = 1 + false + error. | j <7 |.else | lgr CARG2, L:PC | lgr CARG1, L:RB | brasl r14, extern lj_ffh_coroutine_wrap_err // (lua_State *L, lua_State *co) | // Error function does not return. |.endif | |9: // Handle stack expansion on return from yield. | lg L:RA, SAVE_TMP | stg KBASE, L:RA->top // Undo coroutine stack clearing. | lgr CARG2, PC | lgr CARG1, L:RB | brasl r14, extern lj_state_growstack // (lua_State *L, int n) | lg L:PC, SAVE_TMP | lg BASE, L:RB->base | j <4 // Retry the stack move. |.endmacro | | coroutine_resume_wrap 1 // coroutine.resume | coroutine_resume_wrap 0 // coroutine.wrap | |.ffunc coroutine_yield | lg L:RB, SAVE_L | lg TMPR0, L:RB->cframe | tmll TMPR0, CFRAME_RESUME | je ->fff_fallback | stg BASE, L:RB->base | sllg RD, NARGS:RD, 3 | lay RD, -8(RD, BASE) | stg RD, L:RB->top | lghi RD, 0 | stg RD, L:RB->cframe | lghi CRET1, LUA_YIELD | stc CRET1, L:RB->status | j ->vm_leave_unw | |//-- Math library ------------------------------------------------------- | |.ffunc_1 math_abs | lg RB, 0(BASE) | checkint RB, >3 | lpr RB, RB; jo >2 |->fff_resbit: |->fff_resi: | setint RB |->fff_resRB: | lg PC, -8(BASE) | stg RB, -16(BASE) | j ->fff_res1 |2: | llihh RB, 0x41e0 // 2^31 | j ->fff_resRB |3: | jh ->fff_fallback | nihh RB, 0x7fff // Clear sign bit. | lg PC, -8(BASE) | stg RB, -16(BASE) | j ->fff_res1 | |.ffunc_n math_sqrt, sqdb |->fff_resf0: | lg PC, -8(BASE) | stdy f0, -16(BASE) | // fallthrough | |->fff_res1: | lghi RD, 1+1 |->fff_res: | st RD, SAVE_MULTRES |->fff_res_: | tmll PC, FRAME_TYPE | jne >7 |5: | llgc TMPR1, PC_RB | clgr TMPR1, RD // More results expected? | jh >6 | // Adjust BASE. KBASE is assumed to be set for the calling frame. | llgc RA, PC_RA | lcgr RA, RA | sllg RA, RA, 3 | lay BASE, -16(RA, BASE) // base = base - (RA+2)*8 | ins_next | |6: // Fill up results with nil. | sllg TMPR1, RD, 3 | lghi TMPR0, LJ_TNIL | stg TMPR0, -24(TMPR1, BASE) | la RD, 1(RD) | j <5 | |7: // Non-standard return case. | lghi RA, -16 // Results start at BASE+RA = BASE-16. | j ->vm_return | |.macro math_round, func | .ffunc math_ .. func | lg RB, 0(BASE) | ld f0, 0(BASE) | checknumx RB, ->fff_resRB, je | jh ->fff_fallback | brasl r14, ->vm_ .. func | cfdbr RB, 0, f0 | jo ->fff_resf0 | llgfr RB, RB | j ->fff_resi |.endmacro | | math_round floor | math_round ceil | |.ffunc math_log | chi NARGS:RD, 1+1; jne ->fff_fallback // Exactly one argument. | lg TMPR0, 0(BASE) | ld FARG1, 0(BASE) | checknumtp TMPR0, ->fff_fallback | brasl r14, extern log | j ->fff_resf0 | |.macro math_extern, func | .ffunc_n math_ .. func | brasl r14, extern func | j ->fff_resf0 |.endmacro | |.macro math_extern2, func | .ffunc_nn math_ .. func | brasl r14, extern func | j ->fff_resf0 |.endmacro | | math_extern log10 | math_extern exp | math_extern sin | math_extern cos | math_extern tan | math_extern asin | math_extern acos | math_extern atan | math_extern sinh | math_extern cosh | math_extern tanh | math_extern2 pow | math_extern2 atan2 | math_extern2 fmod | |.ffunc_2 math_ldexp | lg TMPR0, 0(BASE) | ld FARG1, 0(BASE) | lg CARG1, 8(BASE) | checknumtp TMPR0, ->fff_fallback | checkinttp CARG1, ->fff_fallback | lgfr CARG1, CARG1 | brasl r14, extern ldexp // (double, int) | j ->fff_resf0 | |.ffunc_n math_frexp | la CARG1, SAVE_TMP | brasl r14, extern frexp | llgf RB, SAVE_TMP | lg PC, -8(BASE) | stdy f0, -16(BASE) | setint RB | stg RB, -8(BASE) | lghi RD, 1+2 | j ->fff_res | |.ffunc_n math_modf | lay CARG1, -16(BASE) | brasl r14, extern modf // (double, double*) | lg PC, -8(BASE) | stdy f0, -8(BASE) | lghi RD, 1+2 | j ->fff_res | |.macro math_minmax, name, cjmp | .ffunc name | lghi RA, 2*8 | sllg TMPR1, RD, 3 | lg RB, 0(BASE) | ld f0, 0(BASE) | checkint RB, >4 |1: // Handle integers. | clgr RA, TMPR1; jhe ->fff_resRB | lg TMPR0, -8(RA, BASE) | checkint TMPR0, >3 | cr RB, TMPR0 | cjmp >2 | lgr RB, TMPR0 |2: | aghi RA, 8 | j <1 |3: | jh ->fff_fallback | // Convert intermediate result to number and continue below. | cdfbr f0, RB | ldgr f1, TMPR0 | j >6 |4: | jh ->fff_fallback |5: // Handle numbers or integers. | clgr RA, TMPR1; jhe ->fff_resf0 | lg RB, -8(RA, BASE) | ldy f1, -8(RA, BASE) | checknumx RB, >6, jl | jh ->fff_fallback | cdfbr f1, RB |6: | cdbr f0, f1 | cjmp >7 | ldr f0, f1 |7: | aghi RA, 8 | j <5 |.endmacro | | math_minmax math_min, jnh | math_minmax math_max, jnl | |//-- String library ----------------------------------------------------- | |.ffunc string_byte // Only handle the 1-arg case here. | chi NARGS:RD, 1+1; jne ->fff_fallback | lg STR:RB, 0(BASE) | checkstr STR:RB, ->fff_fallback | lg PC, -8(BASE) | ltg TMPR0, STR:RB->len | je ->fff_res0 // Return no results for empty string. | llgc RB, STR:RB[1] | j ->fff_resi | |.ffunc string_char // Only handle the 1-arg case here. | ffgccheck | chi NARGS:RD, 1+1; jne ->fff_fallback // *Exactly* 1 arg. | lg RB, 0(BASE) | checkint RB, ->fff_fallback | clfi RB, 255; jh ->fff_fallback | strvh RB, SAVE_TMP // Store [c,0]. | lghi TMPR1, 1 | la RD, SAVE_TMP // Points to stack. Little-endian. |->fff_newstr: | lg L:RB, SAVE_L | stg BASE, L:RB->base | llgfr CARG3, TMPR1 // Zero-extended to size_t. | lgr CARG2, RD | lgr CARG1, L:RB | stg PC, SAVE_PC | brasl r14, extern lj_str_new // (lua_State *L, char *str, size_t l) |->fff_resstr: | // GCstr * returned in r2 (CRET1). | lgr STR:RD, CRET1 | lg BASE, L:RB->base | lg PC, -8(BASE) | settp STR:RD, LJ_TSTR | stg STR:RD, -16(BASE) | j ->fff_res1 | |.ffunc string_sub | ffgccheck | lghi TMPR1, -1 | clfi NARGS:RD, 1+2; jl ->fff_fallback | jnh >1 | lg TMPR1, 16(BASE) | checkint TMPR1, ->fff_fallback |1: | lg STR:RB, 0(BASE) | checkstr STR:RB, ->fff_fallback | lg ITYPE, 8(BASE) | lgfr RA, ITYPE | srag ITYPE, ITYPE, 47 | cghi ITYPE, LJ_TISNUM | jne ->fff_fallback | llgf RC, STR:RB->len | clr RC, TMPR1 // len < end? (unsigned compare) | jl >5 |2: | cghi RA, 0 // start <= 0? | jle >7 |3: | sr TMPR1, RA // start > end? | jnhe ->fff_emptystr | la RD, (#STR-1)(RA, STR:RB) | ahi TMPR1, 1 |4: | j ->fff_newstr | |5: // Negative end or overflow. | chi TMPR1, 0 | jnl >6 | ahi TMPR1, 1 | ar TMPR1, RC // end = end+(len+1) | j <2 |6: // Overflow. | lr TMPR1, RC // end = len | j <2 | |7: // Negative start or underflow. | je >8 | agr RA, RC // start = start+(len+1) | aghi RA, 1 | jh <3 // start > 0? |8: // Underflow. | lghi RA, 1 // start = 1 | j <3 | |->fff_emptystr: // Range underflow. | lghi TMPR1, 0 | j <4 | |.macro ffstring_op, name | .ffunc_1 string_ .. name | ffgccheck | lg STR:CARG2, 0(BASE) | checkstr STR:CARG2, ->fff_fallback | lg L:RB, SAVE_L | lay SBUF:CARG1, (DISPATCH_GL(tmpbuf))(DISPATCH) | stg BASE, L:RB->base | lg RC, SBUF:CARG1->b | stg L:RB, SBUF:CARG1->L | stg RC, SBUF:CARG1->p | stg PC, SAVE_PC | brasl r14, extern lj_buf_putstr_ .. name | // lgr CARG1, CRET1 (nop, CARG1==CRET1) | brasl r14, extern lj_buf_tostr | j ->fff_resstr |.endmacro | |ffstring_op reverse |ffstring_op lower |ffstring_op upper | |//-- Bit library -------------------------------------------------------- | |.macro .ffunc_bit, name, kind, fdef | fdef name |.if kind == 2 | bfpconst_tobit f1, RB |.endif | lg RB, 0(BASE) | ld f0, 0(BASE) | checkint RB, >1 |.if kind > 0 | j >2 |.else | j ->fff_resbit |.endif |1: | jh ->fff_fallback |.if kind < 2 | bfpconst_tobit f1, RB |.endif | adbr f0, f1 | lgdr RB, f0 | llgfr RB, RB |2: |.endmacro | |.macro .ffunc_bit, name, kind | .ffunc_bit name, kind, .ffunc_1 |.endmacro | |.ffunc_bit bit_tobit, 0 | j ->fff_resbit | |.macro .ffunc_bit_op, name, ins | .ffunc_bit name, 2 | lgr TMPR1, NARGS:RD // Save for fallback. | sllg RD, NARGS:RD, 3 | lay RD, -16(RD, BASE) |1: | clgr RD, BASE | jle ->fff_resbit | lg RA, 0(RD) | checkint RA, >2 | ins RB, RA | aghi RD, -8 | j <1 |2: | jh ->fff_fallback_bit_op | ldgr f0, RA | adbr f0, f1 | lgdr RA, f0 | ins RB, RA | aghi RD, -8 | j <1 |.endmacro | |.ffunc_bit_op bit_band, nr |.ffunc_bit_op bit_bor, or |.ffunc_bit_op bit_bxor, xr | |.ffunc_bit bit_bswap, 1 | lrvr RB, RB | j ->fff_resbit | |.ffunc_bit bit_bnot, 1 | xilf RB, -1 | j ->fff_resbit | |->fff_fallback_bit_op: | lgr NARGS:RD, TMPR1 // Restore for fallback | j ->fff_fallback | |.macro .ffunc_bit_sh, name, ins | .ffunc_bit name, 1, .ffunc_2 | // Note: no inline conversion from number for 2nd argument! | lg RA, 8(BASE) | checkint RA, ->fff_fallback | nill RA, 0x1f // Limit shift to 5-bits. | ins RB, 0(RA) | j ->fff_resbit |.endmacro | |.ffunc_bit_sh bit_lshift, sll |.ffunc_bit_sh bit_rshift, srl |.ffunc_bit_sh bit_arshift, sra | |.ffunc_bit bit_rol, 1, .ffunc_2 | // Note: no inline conversion from number for 2nd argument! | lg RA, 8(BASE) | checkint RA, ->fff_fallback | rll RB, RB, 0(RA) | j ->fff_resbit | |.ffunc_bit bit_ror, 1, .ffunc_2 | // Note: no inline conversion from number for 2nd argument! | lg RA, 8(BASE) | checkint RA, ->fff_fallback | lcr RA, RA // Right rotate equivalent to negative left rotate. | rll RB, RB, 0(RA) | j ->fff_resbit | |//----------------------------------------------------------------------- | |->fff_fallback_2: | lghi NARGS:RD, 1+2 // Other args are ignored, anyway. | j ->fff_fallback |->fff_fallback_1: | lghi NARGS:RD, 1+1 // Other args are ignored, anyway. |->fff_fallback: // Call fast function fallback handler. | // BASE = new base, RD = nargs+1 | lg L:RB, SAVE_L | lg PC, -8(BASE) // Fallback may overwrite PC. | stg PC, SAVE_PC // Redundant (but a defined value). | stg BASE, L:RB->base | sllg RD, NARGS:RD, 3 | lay RD, -8(RD, BASE) | la RA, (8*LUA_MINSTACK)(RD) // Ensure enough space for handler. | stg RD, L:RB->top | lg CFUNC:RD, -16(BASE) | cleartp CFUNC:RD | clg RA, L:RB->maxstack | jh >5 // Need to grow stack. | lgr CARG1, L:RB | lg TMPR1, CFUNC:RD->f | basr r14, TMPR1 // (lua_State *L) | lg BASE, L:RB->base | // Either throws an error, or recovers and returns -1, 0 or nresults+1. | lgr RD, CRET1 | cghi RD, 0; jh ->fff_res // Returned nresults+1? |1: | lg RA, L:RB->top | sgr RA, BASE | srlg RA, RA, 3 | cghi RD, 0 | la NARGS:RD, 1(RA) | lg LFUNC:RB, -16(BASE) | jne ->vm_call_tail // Returned -1? | cleartp LFUNC:RB | ins_callt // Returned 0: retry fast path. | |// Reconstruct previous base for vmeta_call during tailcall. |->vm_call_tail: | lgr RA, BASE | tmll PC, FRAME_TYPE | jne >3 | llgc RB, PC_RA | lcgr RB, RB | sllg RB, RB, 3 | lay BASE, -16(RB, BASE) // base = base - (RB+2)*8 | j ->vm_call_dispatch // Resolve again for tailcall. |3: | lgr RB, PC | nill RB, -8 | sgr BASE, RB | j ->vm_call_dispatch // Resolve again for tailcall. | |5: // Grow stack for fallback handler. | lghi CARG2, LUA_MINSTACK | lgr CARG1, L:RB | brasl r14, extern lj_state_growstack // (lua_State *L, int n) | lg BASE, L:RB->base | lghi RD, 0 // Simulate a return 0. | j <1 // Dumb retry (goes through ff first). | |->fff_gcstep: // Call GC step function. | // BASE = new base, RD = nargs+1 | stg r14, SAVE_TMP // Save return address | lg L:RB, SAVE_L | stg PC, SAVE_PC // Redundant (but a defined value). | stg BASE, L:RB->base | sllg RD, NARGS:RD, 3 | lay RD, -8(RD, BASE) | lgr CARG1, L:RB | stg RD, L:RB->top | brasl r14, extern lj_gc_step // (lua_State *L) | lg BASE, L:RB->base | lg RD, L:RB->top | sgr RD, BASE | srlg RD, RD, 3 | aghi NARGS:RD, 1 | lg r14, SAVE_TMP // Restore return address. | br r14 | |//----------------------------------------------------------------------- |//-- Special dispatch targets ------------------------------------------- |//----------------------------------------------------------------------- | |->vm_record: // Dispatch target for recording phase. | stg r0, 0 | stg r0, 0 | |->vm_rethook: // Dispatch target for return hooks. | llgc RD, (DISPATCH_GL(hookmask))(DISPATCH) | tmll RD, HOOK_ACTIVE | jne >5 | j >1 | |->vm_inshook: // Dispatch target for instr/line hooks. | llgc RD, (DISPATCH_GL(hookmask))(DISPATCH) | tmll RD, HOOK_ACTIVE // Hook already active? | jne >5 | | tmll RD, LUA_MASKLINE|LUA_MASKCOUNT | je >5 | ly TMPR0, (DISPATCH_GL(hookcount))(DISPATCH) | ahi TMPR0, -1 | sty TMPR0, (DISPATCH_GL(hookcount))(DISPATCH) | je >1 | tmll RD, LUA_MASKLINE | je >5 |1: | lg L:RB, SAVE_L | stg BASE, L:RB->base | lgr CARG2, PC | lgr CARG1, L:RB | // SAVE_PC must hold the _previous_ PC. The callee updates it with PC. | brasl r14, extern lj_dispatch_ins // (lua_State *L, const BCIns *pc) |3: | lg BASE, L:RB->base |4: | llgc RA, PC_RA |5: | llgc OP, PC_OP | sllg TMPR1, OP, 3 | llgh RD, PC_RD | lg TMPR1, GG_DISP2STATIC(TMPR1, DISPATCH) | br TMPR1 | |->cont_hook: // Continue from hook yield. | stg r0, 0 | stg r0, 0 | |->vm_hotloop: // Hot loop counter underflow. | stg r0, 0 | stg r0, 0 | |->vm_callhook: // Dispatch target for call hooks. | stg PC, SAVE_PC |.if JIT | j >1 |.endif | |->vm_hotcall: // Hot call counter underflow. |.if JIT | stg PC, SAVE_PC | oill PC, 1 // Marker for hot call. |1: |.endif | sllg RD, NARGS:RD, 3 | lay RD, -8(RD, BASE) | lg L:RB, SAVE_L | stg BASE, L:RB->base | stg RD, L:RB->top | lgr CARG2, PC | lgr CARG1, L:RB | brasl r14, extern lj_dispatch_call // (lua_State *L, const BCIns *pc) | // ASMFunction returned in r2 (CRET1). | lghi TMPR0, 0 | stg TMPR0, SAVE_PC // Invalidate for subsequent line hook. |.if JIT | nill PC, -2 |.endif | lg BASE, L:RB->base | lg RD, L:RB->top | sgr RD, BASE | lgr RB, CRET1 | llgc RA, PC_RA | srl RD, 3 | ahi NARGS:RD, 1 | llgfr RD, RD | br RB | |->cont_stitch: // Trace stitching. | stg r0, 0 | stg r0, 0 | |->vm_profhook: // Dispatch target for profiler hook. | stg r0, 0 | stg r0, 0 | |//----------------------------------------------------------------------- |//-- Trace exit handler ------------------------------------------------- |//----------------------------------------------------------------------- | |// Called from an exit stub with the exit number on the stack. |// The 16 bit exit number is stored with two (sign-extended) push imm8. |->vm_exit_handler: | stg r0, 0 | stg r0, 0 |->vm_exit_interp: | stg r0, 0 | stg r0, 0 | |//----------------------------------------------------------------------- |//-- Math helper functions ---------------------------------------------- |//----------------------------------------------------------------------- | |// FP value rounding. Called by math.floor/math.ceil fast functions. |// Value to round is in f0. May clobber f0-f7 and r0. Return address is r14. |.macro vm_round, name, mask |->name: | lghi r0, 1 | cdfbr f1, r0 | didbr f0, f2, f1, mask // f0=remainder, f2=quotient. | jnle >1 | ldr f0, f2 | br r14 |1: // partial remainder (sanity check) | stg r0, 0 |.endmacro | | vm_round vm_floor, 7 // Round towards -inf. | vm_round vm_ceil, 6 // Round towards +inf. | vm_round vm_trunc, 5 // Round towards 0. | |// FP modulo x%y. Called by BC_MOD* and vm_arith. |->vm_mod: // NYI. | stg r0, 0 | stg r0, 0 | |//----------------------------------------------------------------------- |//-- Assertions --------------------------------------------------------- |//----------------------------------------------------------------------- | |->assert_bad_for_arg_type: | stg r0, 0 | stg r0, 0 #ifdef LUA_USE_ASSERT #endif | |//----------------------------------------------------------------------- |//-- FFI helper functions ----------------------------------------------- |//----------------------------------------------------------------------- | |// Handler for callback functions. Callback slot number in ah/al. |->vm_ffi_callback: | stg r0, 0 | stg r0, 0 | |->cont_ffi_callback: // Return from FFI callback. | stg r0, 0 | stg r0, 0 | |->vm_ffi_call: // Call C function via FFI. | // Caveat: needs special frame unwinding, see below. |.if FFI | .type CCSTATE, CCallState, r8 | stmg r6, r15, 48(sp) | lgr r13, sp // Use r13 as frame pointer. | lgr CCSTATE, CARG1 | lg r7, CCSTATE->func | | // Readjust stack. | sgf sp, CCSTATE->spadj | | // Copy stack slots. | llgc r1, CCSTATE->nsp | chi r1, 0 | jh >2 |1: | lmg CARG1, CARG5, CCSTATE->gpr[0] | // TODO: conditionally load FPRs? | ld FARG1, CCSTATE->fpr[0] | ld FARG2, CCSTATE->fpr[1] | ld FARG3, CCSTATE->fpr[2] | ld FARG4, CCSTATE->fpr[3] | basr r14, r7 | | stg CRET1, CCSTATE->gpr[0] | std f0, CCSTATE->fpr[0] | | lgr sp, r13 | lmg r6, r15, 48(sp) | br r14 | |2: | sll r1, 3 | la r10, (offsetof(CCallState, stack))(CCSTATE) // Source. | la r11, (CCALL_SPS_EXTRA*8)(sp) // Destination. |3: | chi r1, 256 | jl >4 | mvc 0(256, r11), 0(r10) | la r10, 256(r10) | la r11, 256(r11) | ahi r1, -256 | j <3 | |4: | ahi r1, -1 | jl <1 | larl r9, >5 | ex r1, 0(r9) | j <1 | |5: | // exrl target | mvc 0(1, r11), 0(r10) |.endif |// Note: vm_ffi_call must be the last function in this object file! | |//----------------------------------------------------------------------- } /* Generate the code for a single instruction. */ static void build_ins(BuildCtx *ctx, BCOp op, int defop) { int vk = 0; (void)vk; |// Note: aligning all instructions does not pay off. |=>defop: switch (op) { /* -- Comparison ops ---------------------------------------------------- */ /* Remember: all ops branch for a true comparison, fall through otherwise. */ |.macro jmp_comp, lt, ge, le, gt, target ||switch (op) { ||case BC_ISLT: | lt target ||break; ||case BC_ISGE: | ge target ||break; ||case BC_ISLE: | le target ||break; ||case BC_ISGT: | gt target ||break; ||default: break; /* Shut up GCC. */ ||} |.endmacro case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT: | // RA = src1, RD = src2, JMP with RD = target | ins_AD | sllg RA, RA, 3 | sllg RD, RD, 3 | ld f0, 0(RA, BASE) | ld f1, 0(RD, BASE) | lg RA, 0(RA, BASE) | lg RD, 0(RD, BASE) | srag ITYPE, RA, 47 | srag RB, RD, 47 | | clfi ITYPE, LJ_TISNUM; jne >7 | clfi RB, LJ_TISNUM; jne >8 | // Both are integers. | la PC, 4(PC) | cr RA, RD | jmp_comp jhe, jl, jh, jle, >9 |6: | llgh RD, PC_RD | branchPC RD |9: | ins_next | |7: // RA is not an integer. | jh ->vmeta_comp | // RA is a number. | clfi RB, LJ_TISNUM; jl >1; jne ->vmeta_comp | // RA is a number, RD is an integer. | cdfbr f1, RD | j >1 | |8: // RA is an integer, RD is not an integer. | jh ->vmeta_comp | // RA is an integer, RD is a number. | cdfbr f0, RA |1: | la PC, 4(PC) | cdbr f0, f1 | // To preserve NaN semantics GE/GT branch on unordered, but LT/LE don't. | jmp_comp jnl, jl, jnle, jle, <9 | j <6 break; case BC_ISEQV: case BC_ISNEV: vk = op == BC_ISEQV; | ins_AD // RA = src1, RD = src2, JMP with RD = target | sllg RD, RD, 3 | ld f1, 0(RD, BASE) | lg RD, 0(RD, BASE) | sllg RA, RA, 3 | ld f0, 0(RA, BASE) | lg RA, 0(RA, BASE) | la PC, 4(PC) | srag RB, RD, 47 | srag ITYPE, RA, 47 | clfi RB, LJ_TISNUM; jne >7 | clfi ITYPE, LJ_TISNUM; jne >8 | cr RD, RA if (vk) { | jne >9 } else { | je >9 } | llgh RD, PC_RD | branchPC RD |9: | ins_next | |7: // RD is not an integer. | jh >5 | // RD is a number. | clfi ITYPE, LJ_TISNUM; jl >1; jne >5 | // RD is a number, RA is an integer. | cdfbr f0, RA | j >1 | |8: // RD is an integer, RA is not an integer. | jh >5 | // RD is an integer, RA is a number. | cdfbr f1, RD | j >1 | |1: | cdbr f0, f1 |4: iseqne_fp: if (vk) { | jne >2 // Unordered means not equal. } else { | je >1 // Unordered means not equal. } iseqne_end: if (vk) { |1: // EQ: Branch to the target. | llgh RD, PC_RD | branchPC RD |2: // NE: Fallthrough to next instruction. |.if not FFI |3: |.endif } else { |.if not FFI |3: |.endif |2: // NE: Branch to the target. | llgh RD, PC_RD | branchPC RD |1: // EQ: Fallthrough to next instruction. } if (LJ_DUALNUM && (op == BC_ISEQV || op == BC_ISNEV || op == BC_ISEQN || op == BC_ISNEN)) { | j <9 } else { | ins_next } | if (op == BC_ISEQV || op == BC_ISNEV) { |5: // Either or both types are not numbers. |.if FFI | clfi RB, LJ_TCDATA; je ->vmeta_equal_cd | clfi ITYPE, LJ_TCDATA; je ->vmeta_equal_cd |.endif | cgr RA, RD | je <1 // Same GCobjs or pvalues? | cr RB, ITYPE | jne <2 // Not the same type? | clfi RB, LJ_TISTABUD | jh <2 // Different objects and not table/ud? | | // Different tables or userdatas. Need to check __eq metamethod. | // Field metatable must be at same offset for GCtab and GCudata! | cleartp TAB:RA | lg TAB:RB, TAB:RA->metatable | cghi TAB:RB, 0 | je <2 // No metatable? | tm TAB:RB->nomm, 1<<MM_eq | jne <2 // Or 'no __eq' flag set? if (vk) { | lghi RB, 0 // ne = 0 } else { | lghi RB, 1 // ne = 1 } | j ->vmeta_equal // Handle __eq metamethod. } else { |.if FFI |3: | clfi ITYPE, LJ_TCDATA if (LJ_DUALNUM && vk) { | jne <9 } else { | jne <2 } | j ->vmeta_equal_cd |.endif } break; case BC_ISEQS: case BC_ISNES: vk = op == BC_ISEQS; | ins_AND // RA = src, RD = str const, JMP with RD = target | sllg RA, RA, 3 | sllg RD, RD, 3 | lg RB, 0(RA, BASE) | la PC, 4(PC) | checkstr RB, >3 | cg RB, 0(RD, KBASE) iseqne_test: if (vk) { | jne >2 } else { | je >1 } goto iseqne_end; case BC_ISEQN: case BC_ISNEN: vk = op == BC_ISEQN; | ins_AD // RA = src, RD = num const, JMP with RD = target | sllg RA, RA, 3 | sllg RD, RD, 3 | ld f0, 0(RA, BASE) | lg RB, 0(RA, BASE) | ld f1, 0(RD, KBASE) | lg RD, 0(RD, KBASE) | la PC, 4(PC) | checkint RB, >7 | checkint RD, >8 | cr RB, RD if (vk) { | jne >9 } else { | je >9 } | llgh RD, PC_RD | branchPC RD |9: | ins_next | |7: // RA is not an integer. | jh >3 | // RA is a number. | checkint RD, >1 | // RA is a number, RD is an integer. | cdfbr f1, RD | j >1 | |8: // RA is an integer, RD is a number. | cdfbr f0, RB | cdbr f0, f1 | j >4 |1: | cdbr f0, f1 |4: goto iseqne_fp; case BC_ISEQP: case BC_ISNEP: vk = op == BC_ISEQP; | ins_AND // RA = src, RD = primitive type (~), JMP with RD = target | sllg RA, RA, 3 | lg RB, 0(RA, BASE) | srag RB, RB, 47 | la PC, 4(PC) | cr RB, RD if (!LJ_HASFFI) goto iseqne_test; if (vk) { | jne >3 | llgh RD, PC_RD | branchPC RD |2: | ins_next |3: | cghi RB, LJ_TCDATA; jne <2 | j ->vmeta_equal_cd } else { | je >2 | cghi RB, LJ_TCDATA; je ->vmeta_equal_cd | llgh RD, PC_RD | branchPC RD |2: | ins_next } break; /* -- Unary test and copy ops ------------------------------------------- */ case BC_ISTC: case BC_ISFC: case BC_IST: case BC_ISF: | ins_AD // RA = dst or unused, RD = src, JMP with RD = target | sllg RD, RD, 3 | sllg RA, RA, 3 | lg ITYPE, 0(RD, BASE) | la PC, 4(PC) if (op == BC_ISTC || op == BC_ISFC) { | lgr RB, ITYPE } | srag ITYPE, ITYPE, 47 | clfi ITYPE, LJ_TISTRUECOND if (op == BC_IST || op == BC_ISTC) { | jhe >1 } else { | jl >1 } if (op == BC_ISTC || op == BC_ISFC) { | stg RB, 0(RA, BASE) } | llgh RD, PC_RD | branchPC RD |1: // Fallthrough to the next instruction. | ins_next break; case BC_ISTYPE: | ins_AD // RA = src, RD = -type | lghr RD, RD | sllg RA, RA, 3 | lg RB, 0(RA, BASE) | srag RB, RB, 47 | agr RB, RD | jne ->vmeta_istype | ins_next break; case BC_ISNUM: | ins_AD // RA = src, RD = -(TISNUM-1) | sllg TMPR1, RA, 3 | lg TMPR1, 0(TMPR1, BASE) | checknumtp TMPR1, ->vmeta_istype | ins_next break; case BC_MOV: | ins_AD // RA = dst, RD = src | sllg RD, RD, 3 | lg RB, 0(RD, BASE) | sllg RA, RA, 3 | stg RB, 0(RA, BASE) | ins_next_ break; case BC_NOT: | ins_AD // RA = dst, RD = src | sllg RD, RD, 3 | sllg RA, RA, 3 | lg RB, 0(RD, BASE) | srag RB, RB, 47 | load_false RC | cghi RB, LJ_TTRUE | je >1 | load_true RC |1: | stg RC, 0(RA, BASE) | ins_next break; case BC_UNM: | ins_AD // RA = dst, RD = src | sllg RA, RA, 3 | sllg RD, RD, 3 | lg RB, 0(RD, BASE) | checkint RB, >3 | lcr RB, RB; jo >2 |1: | stg RB, 0(RA, BASE) | ins_next |2: | llihh RB, 0x41e0 // (double)2^31 | j <1 |3: | jh ->vmeta_unm | // Toggle sign bit. | llihh TMPR0, 0x8000 | xgr RB, TMPR0 | j <1 break; case BC_LEN: | ins_AD // RA = dst, RD = src | sllg RD, RD, 3 | lg RD, 0(RD, BASE) | checkstr RD, >2 | llgf RD, STR:RD->len |1: | sllg RA, RA, 3 | setint RD | stg RD, 0(RA, BASE) | ins_next |2: | cghi ITYPE, LJ_TTAB; jne ->vmeta_len | lgr TAB:CARG1, TAB:RD #if LJ_52 | lg TAB:RB, TAB:RD->metatable | cghi TAB:RB, 0 | jne >9 |3: #endif |->BC_LEN_Z: | brasl r14, extern lj_tab_len // (GCtab *t) | // Length of table returned in r2 (CRET1). | lgr RD, CRET1 | llgc RA, PC_RA | j <1 #if LJ_52 |9: // Check for __len. | tm TAB:RB->nomm, 1<<MM_len | jne <3 | j ->vmeta_len // 'no __len' flag NOT set: check. #endif break; /* -- Binary ops -------------------------------------------------------- */ |.macro ins_arithpre | ins_ABC | sllg RB, RB, 3 | sllg RC, RC, 3 | sllg RA, RA, 3 |.endmacro | |.macro ins_arithfp, ins | ins_arithpre ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN); ||switch (vk) { ||case 0: | ld f0, 0(RB, BASE) | ld f1, 0(RC, KBASE) | lg RB, 0(RB, BASE) | lg RC, 0(RC, KBASE) | checknumtp RB, ->vmeta_arith_vno | checknumtp RC, ->vmeta_arith_vno | ins f0, f1 || break; ||case 1: | ld f1, 0(RB, BASE) | ld f0, 0(RC, KBASE) | lg RB, 0(RB, BASE) | lg RC, 0(RC, KBASE) | checknumtp RB, ->vmeta_arith_nvo | checknumtp RC, ->vmeta_arith_nvo | ins f0, f1 || break; ||default: | ld f0, 0(RB, BASE) | ld f1, 0(RC, BASE) | lg RB, 0(RB, BASE) | lg RC, 0(RC, BASE) | checknumtp RB, ->vmeta_arith_vvo | checknumtp RC, ->vmeta_arith_vvo | ins f0, f1 || break; ||} | std f0, 0(RA, BASE) | ins_next |.endmacro | |.macro ins_arithdn, intins | ins_arithpre ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN); ||switch (vk) { ||case 0: | lg RB, 0(RB, BASE) | lg RC, 0(RC, KBASE) | checkint RB, ->vmeta_arith_vno | checkint RC, ->vmeta_arith_vno | intins RB, RC; jo ->vmeta_arith_vno || break; ||case 1: | lg RB, 0(RB, BASE) | lg RC, 0(RC, KBASE) | checkint RB, ->vmeta_arith_nvo | checkint RC, ->vmeta_arith_nvo | intins RC, RB; jo ->vmeta_arith_nvo || break; ||default: | lg RB, 0(RB, BASE) | lg RC, 0(RC, BASE) | checkint RB, ->vmeta_arith_vvo | checkint RC, ->vmeta_arith_vvo | intins RB, RC; jo ->vmeta_arith_vvo || break; ||} ||if (vk == 1) { | // setint RC | stg RC, 0(RA, BASE) ||} else { | // setint RB | stg RB, 0(RA, BASE) ||} | ins_next |.endmacro | // RA = dst, RB = src1 or num const, RC = src2 or num const case BC_ADDVN: case BC_ADDNV: case BC_ADDVV: | ins_arithdn ar break; case BC_SUBVN: case BC_SUBNV: case BC_SUBVV: | ins_arithdn sr break; case BC_MULVN: case BC_MULNV: case BC_MULVV: | ins_arithpre | // For multiplication we use msgfr and check if the result | // fits in an int32_t. switch(op) { case BC_MULVN: | lg RB, 0(RB, BASE) | lg RC, 0(RC, KBASE) | checkint RB, ->vmeta_arith_vno | checkint RC, ->vmeta_arith_vno | lgfr RB, RB | msgfr RB, RC | lgfr RC, RB | cgr RB, RC; jne ->vmeta_arith_vno break; case BC_MULNV: | lg RB, 0(RB, BASE) | lg RC, 0(RC, KBASE) | checkint RB, ->vmeta_arith_nvo | checkint RC, ->vmeta_arith_nvo | lgfr RB, RB | msgfr RB, RC | lgfr RC, RB | cgr RB, RC; jne ->vmeta_arith_nvo break; default: | lg RB, 0(RB, BASE) | lg RC, 0(RC, BASE) | checkint RB, ->vmeta_arith_vvo | checkint RC, ->vmeta_arith_vvo | lgfr RB, RB | msgfr RB, RC | lgfr RC, RB | cgr RB, RC; jne ->vmeta_arith_vvo break; } | llgfr RB, RB | setint RB | stg RB, 0(RA, BASE) | ins_next break; case BC_DIVVN: case BC_DIVNV: case BC_DIVVV: | ins_arithfp ddbr break; // TODO: implement fast mod operation. // x86_64 does floating point mod, however it might be better to use integer mod. case BC_MODVN: | j ->vmeta_arith_vno break; case BC_MODNV: | j ->vmeta_arith_nvo break; case BC_MODVV: | j ->vmeta_arith_vvo break; case BC_POW: | ins_ABC | sllg RB, RB, 3 | sllg RC, RC, 3 | ld FARG1, 0(RB, BASE) | ld FARG2, 0(RC, BASE) | lg TMPR0, 0(RB, BASE) | checknumtp TMPR0, ->vmeta_arith_vvo | lg TMPR0, 0(RC, BASE) | checknumtp TMPR0, ->vmeta_arith_vvo | brasl r14, extern pow // double pow(double x, double y), result in f0. | llgc RA, PC_RA | sllg RA, RA, 3 | std f0, 0(RA, BASE) | ins_next break; case BC_CAT: | ins_ABC // RA = dst, RB = src_start, RC = src_end | lg L:CARG1, SAVE_L | stg BASE, L:CARG1->base | lgr CARG3, RC | sgr CARG3, RB | sllg RC, RC, 3 | la CARG2, 0(RC, BASE) |->BC_CAT_Z: | lgr L:RB, L:CARG1 | stg PC, SAVE_PC | brasl r14, extern lj_meta_cat // (lua_State *L, TValue *top, int left) | // NULL (finished) or TValue * (metamethod) returned in r2 (CRET1). | lg BASE, L:RB->base | ltgr RC, CRET1 | jne ->vmeta_binop | llgc RB, PC_RB // Copy result to Stk[RA] from Stk[RB]. | sllg RB, RB, 3 | llgc RA, PC_RA | sllg RA, RA, 3 | lg RC, 0(RB, BASE) | stg RC, 0(RA, BASE) | ins_next break; /* -- Constant ops ------------------------------------------------------ */ case BC_KSTR: | ins_AND // RA = dst, RD = str const (~) | sllg RD, RD, 3 | lg RD, 0(RD, KBASE) | settp RD, LJ_TSTR | sllg RA, RA, 3 | stg RD, 0(RA, BASE) | ins_next break; case BC_KCDATA: |.if FFI | ins_AND // RA = dst, RD = cdata const (~) | sllg RD, RD, 3 | sllg RA, RA, 3 | lg RD, 0(RD, KBASE) | settp RD, LJ_TCDATA | stg RD, 0(RA, BASE) | ins_next |.endif break; case BC_KSHORT: | ins_AD // RA = dst, RD = signed int16 literal | // Assumes DUALNUM. | lhr RD, RD // Sign-extend literal to 32-bits. | setint RD | sllg RA, RA, 3 | stg RD, 0(RA, BASE) | ins_next break; case BC_KNUM: | ins_AD // RA = dst, RD = num const | sllg RD, RD, 3 | ld f0, 0(RD, KBASE) | sllg RA, RA, 3 | std f0, 0(RA, BASE) | ins_next break; case BC_KPRI: | ins_AD // RA = dst, RD = primitive type (~) | sllg RA, RA, 3 | sllg RD, RD, 47 | lghi TMPR0, -1 | xgr RD, TMPR0 // not | stg RD, 0(RA, BASE) | ins_next break; case BC_KNIL: | ins_AD // RA = dst_start, RD = dst_end | sllg RA, RA, 3 | sllg RD, RD, 3 | la RA, 8(RA, BASE) | la RD, 0(RD, BASE) | lghi RB, LJ_TNIL | stg RB, -8(RA) // Sets minimum 2 slots. |1: | stg RB, 0(RA) | la RA, 8(RA) | clgr RA, RD | jle <1 | ins_next break; /* -- Upvalue and function ops ------------------------------------------ */ case BC_UGET: | ins_AD // RA = dst, RD = upvalue # | sllg RA, RA, 3 | sllg RD, RD, 3 | lg LFUNC:RB, -16(BASE) | cleartp LFUNC:RB | lg UPVAL:RB, (offsetof(GCfuncL, uvptr))(RD, LFUNC:RB) | lg RB, UPVAL:RB->v | lg RD, 0(RB) | stg RD, 0(RA, BASE) | ins_next break; case BC_USETV: #define TV2MARKOFS \ ((int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv)) | ins_AD // RA = upvalue #, RD = src | lg LFUNC:RB, -16(BASE) | cleartp LFUNC:RB | sllg RA, RA, 3 | lg UPVAL:RB, (offsetof(GCfuncL, uvptr))(RA, LFUNC:RB) | tm UPVAL:RB->closed, 0xff | lg RB, UPVAL:RB->v | sllg TMPR1, RD, 3 | lg RA, 0(TMPR1, BASE) | stg RA, 0(RB) | je >1 | // Check barrier for closed upvalue. | tmy TV2MARKOFS(RB), LJ_GC_BLACK // isblack(uv) | jne >2 |1: | ins_next | |2: // Upvalue is black. Check if new value is collectable and white. | srag RD, RA, 47 | ahi RD, -LJ_TISGCV | clfi RD, LJ_TNUMX - LJ_TISGCV // tvisgcv(v) | jle <1 | cleartp GCOBJ:RA | tm GCOBJ:RA->gch.marked, LJ_GC_WHITES // iswhite(v) | je <1 | // Crossed a write barrier. Move the barrier forward. | lgr CARG2, RB | lay GL:CARG1, GG_DISP2G(DISPATCH) | brasl r14, extern lj_gc_barrieruv // (global_State *g, TValue *tv) | j <1 break; #undef TV2MARKOFS case BC_USETS: | ins_AND // RA = upvalue #, RD = str const (~) | lg LFUNC:RB, -16(BASE) | sllg RA, RA, 3 | sllg RD, RD, 3 | cleartp LFUNC:RB | lg UPVAL:RB, (offsetof(GCfuncL, uvptr))(RA, LFUNC:RB) | lg STR:RA, 0(RD, KBASE) | lg RD, UPVAL:RB->v | settp STR:ITYPE, STR:RA, LJ_TSTR | stg STR:ITYPE, 0(RD) | tm UPVAL:RB->marked, LJ_GC_BLACK // isblack(uv) | jne >2 |1: | ins_next | |2: // Check if string is white and ensure upvalue is closed. | tm GCOBJ:RA->gch.marked, LJ_GC_WHITES // iswhite(str) | je <1 | tm UPVAL:RB->closed, 0xff | je <1 | // Crossed a write barrier. Move the barrier forward. | lgr CARG2, RD | lay GL:CARG1, GG_DISP2G(DISPATCH) | brasl r14, extern lj_gc_barrieruv // (global_State *g, TValue *tv) | j <1 break; case BC_USETN: | ins_AD // RA = upvalue #, RD = num const | lg LFUNC:RB, -16(BASE) | sllg RA, RA, 3 | sllg RD, RD, 3 | cleartp LFUNC:RB | ld f0, 0(RD, KBASE) | lg UPVAL:RB, (offsetof(GCfuncL, uvptr))(RA, LFUNC:RB) | lg RA, UPVAL:RB->v | std f0, 0(RA) | ins_next break; case BC_USETP: | ins_AD // RA = upvalue #, RD = primitive type (~) | lg LFUNC:RB, -16(BASE) | sllg RA, RA, 3 | cleartp LFUNC:RB | lg UPVAL:RB, (offsetof(GCfuncL, uvptr))(RA, LFUNC:RB) | sllg RD, RD, 47 | lghi TMPR0, -1 | xgr RD, TMPR0 | lg RA, UPVAL:RB->v | stg RD, 0(RA) | ins_next break; case BC_UCLO: | ins_AD // RA = level, RD = target | branchPC RD // Do this first to free RD. | lg L:RB, SAVE_L | ltg TMPR0, L:RB->openupval | je >1 | stg BASE, L:RB->base | sllg RA, RA, 3 | la CARG2, 0(RA, BASE) | lgr L:CARG1, L:RB | brasl r14, extern lj_func_closeuv // (lua_State *L, TValue *level) | lg BASE, L:RB->base |1: | ins_next break; case BC_FNEW: | ins_AND // RA = dst, RD = proto const (~) (holding function prototype) | lg L:RB, SAVE_L | stg BASE, L:RB->base | lg CARG3, -16(BASE) | cleartp CARG3 | sllg RD, RD, 3 | lg CARG2, 0(RD, KBASE) // Fetch GCproto *. | lgr CARG1, L:RB | stg PC, SAVE_PC | // (lua_State *L, GCproto *pt, GCfuncL *parent) | brasl r14, extern lj_func_newL_gc | // GCfuncL * returned in r2 (CRET1). | lg BASE, L:RB->base | llgc RA, PC_RA | sllg RA, RA, 3 | settp LFUNC:CRET1, LJ_TFUNC | stg LFUNC:CRET1, 0(RA, BASE) | ins_next break; case BC_TNEW: | ins_AD // RA = dst, RD = hbits|asize | lg L:RB, SAVE_L | stg BASE, L:RB->base | lg RA, (DISPATCH_GL(gc.total))(DISPATCH) | clg RA, (DISPATCH_GL(gc.threshold))(DISPATCH) | stg PC, SAVE_PC | jhe >5 |1: | srlg CARG3, RD, 11 | llill TMPR0, 0x7ff | nr RD, TMPR0 | cr RD, TMPR0 | je >3 |2: | lgr L:CARG1, L:RB | llgfr CARG2, RD | brasl r14, extern lj_tab_new // (lua_State *L, uint32_t asize, uint32_t hbits) | // Table * returned in r2 (CRET1). | lg BASE, L:RB->base | llgc RA, PC_RA | sllg RA, RA, 3 | settp TAB:CRET1, LJ_TTAB | stg TAB:CRET1, 0(RA, BASE) | ins_next |3: // Turn 0x7ff into 0x801. | llill RD, 0x801 | j <2 |5: | lgr L:CARG1, L:RB | brasl r14, extern lj_gc_step_fixtop // (lua_State *L) | llgh RD, PC_RD | j <1 break; case BC_TDUP: | ins_AND // RA = dst, RD = table const (~) (holding template table) | lg L:RB, SAVE_L | lg RA, (DISPATCH_GL(gc.total))(DISPATCH) | stg PC, SAVE_PC | clg RA, (DISPATCH_GL(gc.threshold))(DISPATCH) | stg BASE, L:RB->base | jhe >3 |2: | sllg RD, RD, 3 | lg TAB:CARG2, 0(RD, KBASE) | lgr L:CARG1, L:RB | brasl r14, extern lj_tab_dup // (lua_State *L, Table *kt) | // Table * returned in r2 (CRET1). | lg BASE, L:RB->base | llgc RA, PC_RA | settp TAB:CRET1, LJ_TTAB | sllg RA, RA, 3 | stg TAB:CRET1, 0(RA, BASE) | ins_next |3: | lgr L:CARG1, L:RB | brasl r14, extern lj_gc_step_fixtop // (lua_State *L) | llgh RD, PC_RD // Need to reload RD. | lghi TMPR0, -1 | xgr RD, TMPR0 // not RD | j <2 break; case BC_GGET: | ins_AND // RA = dst, RD = str const (~) | lg LFUNC:RB, -16(BASE) | cleartp LFUNC:RB | lg TAB:RB, LFUNC:RB->env | sllg TMPR1, RD, 3 | lg STR:RC, 0(TMPR1, KBASE) | j ->BC_TGETS_Z break; case BC_GSET: | ins_AND // RA = src, RD = str const (~) | lg LFUNC:RB, -16(BASE) | cleartp LFUNC:RB | lg TAB:RB, LFUNC:RB->env | sllg TMPR1, RD, 3 | lg STR:RC, 0(TMPR1, KBASE) | j ->BC_TSETS_Z break; case BC_TGETV: | ins_ABC // RA = dst, RB = table, RC = key | sllg RB, RB, 3 | lg TAB:RB, 0(RB, BASE) | sllg RC, RC, 3 | lg RC, 0(RC, BASE) | checktab TAB:RB, ->vmeta_tgetv | | // Integer key? | checkint RC, >5 | cl RC, TAB:RB->asize // Takes care of unordered, too. | jhe ->vmeta_tgetv // Not in array part? Use fallback. | llgfr RC, RC | sllg RC, RC, 3 | ag RC, TAB:RB->array | // Get array slot. | lg ITYPE, 0(RC) | cghi ITYPE, LJ_TNIL // Avoid overwriting RB in fastpath. | je >2 |1: | sllg RA, RA, 3 | stg ITYPE, 0(RA, BASE) | ins_next | |2: // Check for __index if table value is nil. | lg TAB:TMPR1, TAB:RB->metatable | cghi TAB:TMPR1, 0 | je <1 | tm TAB:TMPR1->nomm, 1<<MM_index | je ->vmeta_tgetv // 'no __index' flag NOT set: check. | j <1 | |5: // String key? | cghi ITYPE, LJ_TSTR; jne ->vmeta_tgetv | cleartp STR:RC | j ->BC_TGETS_Z break; case BC_TGETS: | ins_ABC | sllg RB, RB, 3 | lg TAB:RB, 0(RB, BASE) | lghi TMPR1, -1 | xgr RC, TMPR1 | sllg RC, RC, 3 | lg STR:RC, 0(RC, KBASE) | checktab TAB:RB, ->vmeta_tgets |->BC_TGETS_Z: // RB = GCtab *, RC = GCstr * | l TMPR1, TAB:RB->hmask | n TMPR1, STR:RC->hash | lgfr TMPR1, TMPR1 | mghi TMPR1, #NODE | ag NODE:TMPR1, TAB:RB->node | settp ITYPE, STR:RC, LJ_TSTR |1: | cg ITYPE, NODE:TMPR1->key | jne >4 | // Get node value. | lg ITYPE, NODE:TMPR1->val | cghi ITYPE, LJ_TNIL | je >5 // Key found, but nil value? |2: | sllg RA, RA, 3 | stg ITYPE, 0(RA, BASE) | ins_next | |4: // Follow hash chain. | lg NODE:TMPR1, NODE:TMPR1->next | cghi NODE:TMPR1, 0 | jne <1 | // End of hash chain: key not found, nil result. | lghi ITYPE, LJ_TNIL | |5: // Check for __index if table value is nil. | lg TAB:TMPR1, TAB:RB->metatable | cghi TAB:TMPR1, 0 | je <2 // No metatable: done. | tm TAB:TMPR1->nomm, 1<<MM_index | jne <2 // 'no __index' flag set: done. | j ->vmeta_tgets // Caveat: preserve STR:RC. break; case BC_TGETB: | ins_ABC // RA = dst, RB = table, RC = byte literal | sllg RB, RB, 3 | lg TAB:RB, 0(RB, BASE) | checktab TAB:RB, ->vmeta_tgetb | cl RC, TAB:RB->asize | jhe ->vmeta_tgetb | sllg RC, RC, 3 | ag RC, TAB:RB->array | // Get array slot. | lg ITYPE, 0(RC) | cghi ITYPE, LJ_TNIL | je >2 |1: | sllg RA, RA, 3 | stg ITYPE, 0(RA, BASE) | ins_next | |2: // Check for __index if table value is nil. | lg TAB:TMPR1, TAB:RB->metatable | cghi TAB:TMPR1, 0 | je <1 | tm TAB:TMPR1->nomm, 1<<MM_index | je ->vmeta_tgetb // 'no __index' flag NOT set: check. | j <1 break; case BC_TGETR: | ins_ABC // RA = dst, RB = table, RC = key | sllg RB, RB, 3 | lg TAB:RB, 0(RB, BASE) | cleartp TAB:RB | sllg RC, RC, 3 | llgf RC, 4(RC, BASE) // Load low word (big endian). | cl RC, TAB:RB->asize | jhe ->vmeta_tgetr // Not in array part? Use fallback. | sllg RC, RC, 3 | ag RC, TAB:RB->array | // Get array slot. |->BC_TGETR_Z: | lg ITYPE, 0(RC) |->BC_TGETR2_Z: | sllg RA, RA, 3 | stg ITYPE, 0(RA, BASE) | ins_next break; case BC_TSETV: | ins_ABC // RA = src, RB = table, RC = key | sllg RB, RB, 3 | lg TAB:RB, 0(RB, BASE) | sllg RC, RC, 3 | lg RC, 0(RC, BASE) | checktab TAB:RB, ->vmeta_tsetv | | // Integer key? | checkint RC, >5 | cl RC, TAB:RB->asize // Takes care of unordered, too. | jhe ->vmeta_tsetv | llgfr RC, RC | sllg RC, RC, 3 | ag RC, TAB:RB->array | lghi TMPR0, LJ_TNIL | cg TMPR0, 0(RC) | je >3 // Previous value is nil? |1: | tm TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jne >7 |2: // Set array slot. | sllg RA, RA, 3 | lg RB, 0(RA, BASE) | stg RB, 0(RC) | ins_next | |3: // Check for __newindex if previous value is nil. | lg TAB:TMPR1, TAB:RB->metatable | cghi TAB:TMPR1, 0 | je <1 | tm TAB:TMPR1->nomm, 1<<MM_newindex | je ->vmeta_tsetv // 'no __newindex' flag NOT set: check. | j <1 | |5: // String key? | cghi ITYPE, LJ_TSTR; jne ->vmeta_tsetv | cleartp STR:RC | j ->BC_TSETS_Z | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, TMPR1 | j <2 break; case BC_TSETS: | ins_ABC // RA = src, RB = table, RC = str const (~) | sllg RB, RB, 3 | lg TAB:RB, 0(RB, BASE) | lghi TMPR0, -1 | xgr RC, TMPR0 // ~RC | sllg RC, RC, 3 | lg STR:RC, 0(RC, KBASE) | checktab TAB:RB, ->vmeta_tsets |->BC_TSETS_Z: // RB = GCtab *, RC = GCstr * | l TMPR1, TAB:RB->hmask | n TMPR1, STR:RC->hash | lgfr TMPR1, TMPR1 | mghi TMPR1, #NODE | mvi TAB:RB->nomm, 0 // Clear metamethod cache. | ag NODE:TMPR1, TAB:RB->node | settp ITYPE, STR:RC, LJ_TSTR |1: | cg ITYPE, NODE:TMPR1->key | jne >5 | // Ok, key found. Assumes: offsetof(Node, val) == 0 | lghi TMPR0, LJ_TNIL | cg TMPR0, 0(TMPR1) | je >4 // Previous value is nil? |2: | tm TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jne >7 |3: // Set node value. | sllg RA, RA, 3 | lg ITYPE, 0(RA, BASE) | stg ITYPE, 0(TMPR1) | ins_next | |4: // Check for __newindex if previous value is nil. | lg TAB:ITYPE, TAB:RB->metatable | cghi TAB:ITYPE, 0 | je <2 | tm TAB:ITYPE->nomm, 1<<MM_newindex | je ->vmeta_tsets // 'no __newindex' flag NOT set: check. | j <2 | |5: // Follow hash chain. | lg NODE:TMPR1, NODE:TMPR1->next | cghi NODE:TMPR1, 0 | jne <1 | // End of hash chain: key not found, add a new one. | | // But check for __newindex first. | lg TAB:TMPR1, TAB:RB->metatable | cghi TAB:TMPR1, 0 | je >6 // No metatable: continue. | tm TAB:TMPR1->nomm, 1<<MM_newindex | je ->vmeta_tsets // 'no __newindex' flag NOT set: check. |6: | stg ITYPE, SAVE_TMP | lg L:CARG1, SAVE_L | stg BASE, L:CARG1->base | la CARG3, SAVE_TMP | lgr CARG2, TAB:RB | stg PC, SAVE_PC | brasl r14, extern lj_tab_newkey // (lua_State *L, GCtab *t, TValue *k) | // Handles write barrier for the new key. TValue * returned in r2 (CRET1). | lgr TMPR1, CRET1 | lg L:CRET1, SAVE_L | lg BASE, L:CRET1->base | llgc RA, PC_RA | j <2 // Must check write barrier for value. | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, ITYPE | j <3 break; case BC_TSETB: | ins_ABC // RA = src, RB = table, RC = byte literal | sllg RB, RB, 3 | lg TAB:RB, 0(RB, BASE) | checktab TAB:RB, ->vmeta_tsetb | cl RC, TAB:RB->asize | jhe ->vmeta_tsetb | sllg RC, RC, 3 | ag RC, TAB:RB->array | lghi TMPR0, LJ_TNIL | cg TMPR0, 0(RC) | je >3 // Previous value is nil? |1: | tm TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jne >7 |2: // Set array slot. | sllg RA, RA, 3 | lg ITYPE, 0(RA, BASE) | stg ITYPE, 0(RC) | ins_next | |3: // Check for __newindex if previous value is nil. | lg TAB:TMPR1, TAB:RB->metatable | cghi TAB:TMPR1, 0 | je <1 | tm TAB:TMPR1->nomm, 1<<MM_newindex | je ->vmeta_tsetb // 'no __newindex' flag NOT set: check. | j <1 | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, TMPR1 | j <2 break; case BC_TSETR: | ins_ABC // RA = src, RB = table, RC = key | sllg RB, RB, 3 | lg TAB:RB, 0(RB, BASE) | cleartp TAB:RB | sllg RC, RC, 3 | lg RC, 0(RC, BASE) | tm TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jne >7 |2: | cl RC, TAB:RB->asize | jhe ->vmeta_tsetr | llgfr RC, RC | sllg RC, RC, 3 | ag RC, TAB:RB->array | // Set array slot. |->BC_TSETR_Z: | sllg RA, RA, 3 | lg ITYPE, 0(RA, BASE) | stg ITYPE, 0(RC) | ins_next | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, TMPR1 | j <2 break; case BC_TSETM: | ins_AD // RA = base (table at base-1), RD = num const (start index) |1: | sllg RA, RA, 3 | sllg TMPR1, RD, 3 | llgf TMPR1, 4(TMPR1, KBASE) // Integer constant is in lo-word. | la RA, 0(RA, BASE) | lg TAB:RB, -8(RA) // Guaranteed to be a table. | cleartp TAB:RB | tm TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jne >7 |2: | llgf RD, SAVE_MULTRES | aghi RD, -1 | je >4 // Nothing to copy? | agr RD, TMPR1 // Compute needed size. | clgf RD, TAB:RB->asize | jh >5 // Doesn't fit into array part? | sgr RD, TMPR1 | sllg TMPR1, TMPR1, 3 | ag TMPR1, TAB:RB->array |3: // Copy result slots to table. | lg RB, 0(RA) | la RA, 8(RA) | stg RB, 0(TMPR1) | la TMPR1, 8(TMPR1) | brctg RD, <3 |4: | ins_next | |5: // Need to resize array part. | lg L:CARG1, SAVE_L | stg BASE, L:CARG1->base | lgr CARG2, TAB:RB | lgfr CARG3, RD | lgr L:RB, L:CARG1 | stg PC, SAVE_PC | brasl r14, extern lj_tab_reasize // (lua_State *L, GCtab *t, int nasize) | lg BASE, L:RB->base | llgc RA, PC_RA // Restore RA. | llgh RD, PC_RD // Restore RD. | j <1 // Retry. | |7: // Possible table write barrier for any value. Skip valiswhite check. | barrierback TAB:RB, RD | j <2 break; /* -- Calls and vararg handling ----------------------------------------- */ case BC_CALL: case BC_CALLM: | ins_A_C // RA = base, (RB = nresults+1,) RC = nargs+1 | extra_nargs | sllg RA, RA, 3 | lgr RD, RC if (op == BC_CALLM) { | agf NARGS:RD, SAVE_MULTRES } | lg LFUNC:RB, 0(RA, BASE) | checkfunc LFUNC:RB, ->vmeta_call_ra | la BASE, 16(RA, BASE) | ins_call break; case BC_CALLMT: | ins_AD // RA = base, RD = extra_nargs | a NARGS:RD, SAVE_MULTRES | // Fall through. Assumes BC_CALLT follows and ins_AD is a no-op. break; case BC_CALLT: | ins_AD // RA = base, RD = nargs+1 | sllg RA, RA, 3 | la RA, 16(RA, BASE) | lgr KBASE, BASE // Use KBASE for move + vmeta_call hint. | lg LFUNC:RB, -16(RA) | checktp_nc LFUNC:RB, LJ_TFUNC, ->vmeta_call |->BC_CALLT_Z: | lg PC, -8(BASE) | tmll PC, FRAME_TYPE | jne >7 |1: | stg LFUNC:RB, -16(BASE) // Copy func+tag down, reloaded below. | st NARGS:RD, SAVE_MULTRES | aghi NARGS:RD, -1 | je >3 |2: // Move args down. | lg RB, 0(RA) | la RA, 8(RA) | stg RB, 0(KBASE) | la KBASE, 8(KBASE) | brctg NARGS:RD, <2 | | lg LFUNC:RB, -16(BASE) |3: | cleartp LFUNC:RB | llgf NARGS:RD, SAVE_MULTRES | llgc TMPR1, LFUNC:RB->ffid | cghi TMPR1, 1 // (> FF_C) Calling a fast function? | jh >5 |4: | ins_callt | |5: // Tailcall to a fast function. | tmll PC, FRAME_TYPE // Lua frame below? | jne <4 | llgc RA, PC_RA | lcgr RA, RA | sllg RA, RA, 3 | lg LFUNC:KBASE, -32(RA, BASE) // Need to prepare KBASE. | cleartp LFUNC:KBASE | lg KBASE, LFUNC:KBASE->pc | lg KBASE, (PC2PROTO(k))(KBASE) | j <4 | |7: // Tailcall from a vararg function. | aghi PC, -FRAME_VARG | tmll PC, FRAME_TYPEP | jne >8 // Vararg frame below? | sgr BASE, PC // Need to relocate BASE/KBASE down. | lgr KBASE, BASE | lg PC, -8(BASE) | j <1 |8: | aghi PC, FRAME_VARG | j <1 break; case BC_ITERC: | ins_A // RA = base, (RB = nresults+1,) RC = nargs+1 (2+1) | sllg RA, RA, 3 | la RA, 16(RA, BASE) // fb = base+2 | lg RB, -32(RA) // Copy state. fb[0] = fb[-4]. | lg RC, -24(RA) // Copy control var. fb[1] = fb[-3]. | stg RB, 0(RA) | stg RC, 8(RA) | lg LFUNC:RB, -40(RA) // Copy callable. fb[-2] = fb[-5] | stg LFUNC:RB, -16(RA) | lghi NARGS:RD, 2+1 // Handle like a regular 2-arg call. | checkfunc LFUNC:RB, ->vmeta_call | lgr BASE, RA | ins_call break; case BC_ITERN: | ins_A // RA = base, (RB = nresults+1, RC = nargs+1 (2+1)) |.if JIT | // NYI: add hotloop, record BC_ITERN. |.endif | sllg RA, RA, 3 | lg TAB:RB, -16(RA, BASE) | cleartp TAB:RB | llgf RC, -4(RA, BASE) // Get index from control var. | llgf TMPR1, TAB:RB->asize | la PC, 4(PC) | lg ITYPE, TAB:RB->array |1: // Traverse array part. | clr RC, TMPR1; jhe >5 // Index points after array part? | sllg RD, RC, 3 // Warning: won't work if RD==RC! | lg TMPR0, 0(RD, ITYPE) | cghi TMPR0, LJ_TNIL; je >4 | // Copy array slot to returned value. | lgr RB, TMPR0 | stg RB, 8(RA, BASE) | // Return array index as a numeric key. | setint ITYPE, RC | stg ITYPE, 0(RA, BASE) | ahi RC, 1 | sty RC, -4(RA, BASE) // Update control var. |2: | llgh RD, PC_RD // Get target from ITERL. | branchPC RD |3: | ins_next | |4: // Skip holes in array part. | ahi RC, 1 | j <1 | |5: // Traverse hash part. | sr RC, TMPR1 |6: | cl RC, TAB:RB->hmask; jh <3 // End of iteration? Branch to ITERL+1. | llgfr ITYPE, RC | mghi ITYPE, #NODE | ag NODE:ITYPE, TAB:RB->node | lghi TMPR0, LJ_TNIL | cg TMPR0, NODE:ITYPE->val; je >7 | ar TMPR1, RC | ahi TMPR1, 1 | // Copy key and value from hash slot. | lg RB, NODE:ITYPE->key | lg RC, NODE:ITYPE->val | stg RB, 0(RA, BASE) | stg RC, 8(RA, BASE) | sty TMPR1, -4(RA, BASE) | j <2 | |7: // Skip holes in hash part. | ahi RC, 1 | j <6 break; case BC_ISNEXT: | ins_AD // RA = base, RD = target (points to ITERN) | sllg RA, RA, 3 | lg CFUNC:RB, -24(RA, BASE) | checkfunc CFUNC:RB, >5 | lg TMPR1, -16(RA, BASE) | checktptp TMPR1, LJ_TTAB, >5 | lghi TMPR0, LJ_TNIL | cg TMPR0, -8(RA, BASE); jne >5 | llgc TMPR1, CFUNC:RB->ffid | clfi TMPR1, (uint8_t)FF_next_N; jne >5 | branchPC RD | llihl TMPR1, 0x7fff | iihh TMPR1, 0xfffe | stg TMPR1, -8(RA, BASE) // Initialize control var. |1: | ins_next |5: // Despecialize bytecode if any of the checks fail. | lghi TMPR0, BC_JMP | stcy TMPR0, PC_OP | branchPC RD | mvi 3(PC), BC_ITERC | j <1 break; case BC_VARG: | ins_ABC // RA = base, RB = nresults+1, RC = numparams | sllg RA, RA, 3 | sllg RB, RB, 3 | sllg RC, RC, 3 | la TMPR1, (16+FRAME_VARG)(RC, BASE) | la RA, 0(RA, BASE) | sg TMPR1, -8(BASE) | // Note: TMPR1 may now be even _above_ BASE if nargs was < numparams. | cghi RB, 0 | je >5 // Copy all varargs? | lay RB, -8(RA, RB) | clgr TMPR1, BASE // No vararg slots? | lghi TMPR0, LJ_TNIL | jnl >2 |1: // Copy vararg slots to destination slots. | lg RC, -16(TMPR1) | la TMPR1, 8(TMPR1) | stg RC, 0(RA) | la RA, 8(RA) | clgr RA, RB // All destination slots filled? | jnl >3 | clgr TMPR1, BASE // No more vararg slots? | jl <1 |2: // Fill up remainder with nil. | stg TMPR0, 0(RA) | la RA, 8(RA) | clgr RA, RB | jl <2 |3: | ins_next | |5: // Copy all varargs. | lghi TMPR0, 1 | st TMPR0, SAVE_MULTRES // MULTRES = 0+1 | lgr RC, BASE | slgr RC, TMPR1 | jno <3 // No vararg slots? (borrow or zero) | llgfr RB, RC | srlg RB, RB, 3 | ahi RB, 1 | st RB, SAVE_MULTRES // MULTRES = #varargs+1 | lg L:RB, SAVE_L | agr RC, RA | clg RC, L:RB->maxstack | jh >7 // Need to grow stack? |6: // Copy all vararg slots. | lg RC, -16(TMPR1) | la TMPR1, 8(TMPR1) | stg RC, 0(RA) | la RA, 8(RA) | clgr TMPR1, BASE // No more vararg slots? | jl <6 | j <3 | |7: // Grow stack for varargs. | stg BASE, L:RB->base | stg RA, L:RB->top | stg PC, SAVE_PC | sgr TMPR1, BASE // Need delta, because BASE may change. | st TMPR1, SAVE_TMP_HI | llgf CARG2, SAVE_MULTRES | aghi CARG2, -1 | lgr CARG1, L:RB | brasl r14, extern lj_state_growstack // (lua_State *L, int n) | lg BASE, L:RB->base | lgf TMPR1, SAVE_TMP_HI | lg RA, L:RB->top | agr TMPR1, BASE | j <6 break; /* -- Returns ----------------------------------------------------------- */ case BC_RETM: | ins_AD // RA = results, RD = extra_nresults | agf RD, SAVE_MULTRES // MULTRES >=1, so RD >=1. | // Fall through. Assumes BC_RET follows and ins_AD is a no-op. break; case BC_RET: case BC_RET0: case BC_RET1: | ins_AD // RA = results, RD = nresults+1 if (op != BC_RET0) { | sllg RA, RA, 3 } |1: | lg PC, -8(BASE) | st RD, SAVE_MULTRES // Save nresults+1. | tmll PC, FRAME_TYPE // Check frame type marker. | jne >7 // Not returning to a fixarg Lua func? switch (op) { case BC_RET: |->BC_RET_Z: | lgr KBASE, BASE // Use KBASE for result move. | aghi RD, -1 | je >3 |2: // Move results down. | lg RB, 0(KBASE, RA) | stg RB, -16(KBASE) | la KBASE, 8(KBASE) | brctg RD, <2 |3: | llgf RD, SAVE_MULTRES // Note: MULTRES may be >256. | llgc RB, PC_RB |5: | cgr RB, RD // More results expected? | jh >6 break; case BC_RET1: | lg RB, 0(BASE, RA) | stg RB, -16(BASE) /* fallthrough */ case BC_RET0: |5: | llgc TMPR1, PC_RB | cgr TMPR1, RD | jh >6 default: break; } | llgc RA, PC_RA | lcgr RA, RA | sllg RA, RA, 3 | lay BASE, -16(RA, BASE) // base = base - (RA+2)*8 | lg LFUNC:KBASE, -16(BASE) | cleartp LFUNC:KBASE | lg KBASE, LFUNC:KBASE->pc | lg KBASE, PC2PROTO(k)(KBASE) | ins_next | |6: // Fill up results with nil. | lghi TMPR1, LJ_TNIL if (op == BC_RET) { | stg TMPR1, -16(KBASE) // Note: relies on shifted base. | la KBASE, 8(KBASE) } else { | sllg RC, RD, 3 // RC used as temp. | stg TMPR1, -24(RC, BASE) } | la RD, 1(RD) | j <5 | |7: // Non-standard return case. | lay RB, -FRAME_VARG(PC) | tmll RB, FRAME_TYPEP | jne ->vm_return | // Return from vararg function: relocate BASE down and RA up. | sgr BASE, RB if (op != BC_RET0) { | agr RA, RB } | j <1 break; /* -- Loops and branches ------------------------------------------------ */ |.define FOR_IDX, 0(RA) |.define FOR_STOP, 8(RA) |.define FOR_STEP, 16(RA) |.define FOR_EXT, 24(RA) case BC_FORL: |.if JIT | hotloop RB |.endif | // Fall through. Assumes BC_IFORL follows and ins_AJ is a no-op. break; case BC_JFORI: case BC_JFORL: #if !LJ_HASJIT break; #endif case BC_FORI: case BC_IFORL: vk = (op == BC_IFORL || op == BC_JFORL); | ins_AJ // RA = base, RD = target (after end of loop or start of loop) | sllg RA, RA, 3 | la RA, 0(RA, BASE) | lg RB, FOR_IDX | checkint RB, >9 | lg TMPR1, FOR_STOP if (!vk) { | checkint TMPR1, ->vmeta_for | lg ITYPE, FOR_STEP | chi ITYPE, 0; jl >5 | srag ITYPE, ITYPE, 47 | cghi ITYPE, LJ_TISNUM; jne ->vmeta_for } else { #ifdef LUA_USE_ASSERT | // lg TMPR1, FOR_STOP | checkinttp TMPR1, ->assert_bad_for_arg_type | lg TMPR0, FOR_STEP | checkinttp TMPR0, ->assert_bad_for_arg_type #endif | lg ITYPE, FOR_STEP | chi ITYPE, 0; jl >5 | ar RB, ITYPE; jo >1 | setint RB | stg RB, FOR_IDX } | cr RB, TMPR1 | stg RB, FOR_EXT if (op == BC_FORI) { | jle >7 |1: |6: | branchPC RD } else if (op == BC_JFORI) { | branchPC RD | llgh RD, PC_RD | jle =>BC_JLOOP |1: |6: } else if (op == BC_IFORL) { | jh >7 |6: | branchPC RD |1: } else { | jle =>BC_JLOOP |1: |6: } |7: | ins_next | |5: // Invert check for negative step. if (!vk) { | srag ITYPE, ITYPE, 47 | cghi ITYPE, LJ_TISNUM; jne ->vmeta_for } else { | ar RB, ITYPE; jo <1 | setint RB | stg RB, FOR_IDX } | cr RB, TMPR1 | stg RB, FOR_EXT if (op == BC_FORI) { | jhe <7 } else if (op == BC_JFORI) { | branchPC RD | llgh RD, PC_RD | jhe =>BC_JLOOP } else if (op == BC_IFORL) { | jl <7 } else { | jhe =>BC_JLOOP } | j <6 |9: // Fallback to FP variant. if (!vk) { | jhe ->vmeta_for } if (!vk) { | lg TMPR0, FOR_STOP | checknumtp TMPR0, ->vmeta_for } else { #ifdef LUA_USE_ASSERT | lg TMPR0, FOR_STOP | checknumtp TMPR0, ->assert_bad_for_arg_type | lg TMPR0, FOR_STEP | checknumtp TMPR0, ->assert_bad_for_arg_type #endif } | lg RB, FOR_STEP if (!vk) { | checknum RB, ->vmeta_for } | ld f0, FOR_IDX | ld f1, FOR_STOP if (vk) { | adb f0, FOR_STEP | std f0, FOR_IDX } | cghi RB, 0; jl >3 | cdbr f1, f0 |1: | std f0, FOR_EXT if (op == BC_FORI) { | jnl <7 } else if (op == BC_JFORI) { | branchPC RD | llgh RD, PC_RD | jnl =>BC_JLOOP } else if (op == BC_IFORL) { | jl <7 } else { | jnl =>BC_JLOOP } | j <6 | |3: // Invert comparison if step is negative. | cdbr f0, f1 | j <1 break; case BC_ITERL: |.if JIT | hotloop RB |.endif | // Fall through. Assumes BC_IITERL follows and ins_AJ is a no-op. break; case BC_JITERL: #if !LJ_HASJIT break; #endif case BC_IITERL: | ins_AJ // RA = base, RD = target | sllg RA, RA, 3 | la RA, 0(RA, BASE) | lg RB, 0(RA) | cghi RB, LJ_TNIL; je >1 // Stop if iterator returned nil. if (op == BC_JITERL) { | stg RB, -8(RA) | j =>BC_JLOOP } else { | branchPC RD // Otherwise save control var + branch. | stg RB, -8(RA) } |1: | ins_next break; case BC_LOOP: | ins_A // RA = base, RD = target (loop extent) | // Note: RA/RD is only used by trace recorder to determine scope/extent | // This opcode does NOT jump, it's only purpose is to detect a hot loop. |.if JIT | hotloop RBd |.endif | // Fall through. Assumes BC_ILOOP follows and ins_A is a no-op. break; case BC_ILOOP: | ins_A // RA = base, RD = target (loop extent) | ins_next break; case BC_JLOOP: | stg r0, 0 | stg r0, 0 break; case BC_JMP: | ins_AJ // RA = unused, RD = target | branchPC RD | ins_next break; /* -- Function headers -------------------------------------------------- */ /* ** Reminder: A function may be called with func/args above L->maxstack, ** i.e. occupying EXTRA_STACK slots. And vmeta_call may add one extra slot, ** too. This means all FUNC* ops (including fast functions) must check ** for stack overflow _before_ adding more slots! */ case BC_FUNCF: |.if JIT | stg r0, 0 |.endif case BC_FUNCV: /* NYI: compiled vararg functions. */ | // Fall through. Assumes BC_IFUNCF/BC_IFUNCV follow and ins_AD is a no-op. break; case BC_JFUNCF: #if !LJ_HASJIT break; #endif case BC_IFUNCF: | ins_AD // BASE = new base, RA = framesize, RD = nargs+1 | lg KBASE, (PC2PROTO(k)-4)(PC) | lg L:RB, SAVE_L | sllg RA, RA, 3 | la RA, 0(RA, BASE) // Top of frame. | clg RA, L:RB->maxstack | jh ->vm_growstack_f | llgc RA, (PC2PROTO(numparams)-4)(PC) | clgr NARGS:RD, RA // Check for missing parameters. | jle >3 |2: if (op == BC_JFUNCF) { | llgh RD, PC_RD | j =>BC_JLOOP } else { | ins_next } | |3: // Clear missing parameters. | sllg TMPR1, NARGS:RD, 3 | lghi TMPR0, LJ_TNIL |4: | stg TMPR0, -8(TMPR1, BASE) | la TMPR1, 8(TMPR1) | la RD, 1(RD) | clgr RD, RA | jle <4 | j <2 break; case BC_JFUNCV: #if !LJ_HASJIT break; #endif | stg r0, 0 // NYI: compiled vararg functions break; /* NYI: compiled vararg functions. */ case BC_IFUNCV: | ins_AD // BASE = new base, RA = framesize, RD = nargs+1 | sllg TMPR1, NARGS:RD, 3 | la RB, (FRAME_VARG+8)(TMPR1) | la RD, 8(TMPR1, BASE) | lg LFUNC:KBASE, -16(BASE) | stg RB, -8(RD) // Store delta + FRAME_VARG. | stg LFUNC:KBASE, -16(RD) // Store copy of LFUNC. | lg L:RB, SAVE_L | sllg RA, RA, 3 | la RA, 0(RA, RD) | cg RA, L:RB->maxstack | jh ->vm_growstack_v // Need to grow stack. | lgr RA, BASE | lgr BASE, RD | llgc RB, (PC2PROTO(numparams)-4)(PC) | cghi RB, 0 | je >2 | aghi RA, 8 | lghi TMPR1, LJ_TNIL |1: // Copy fixarg slots up to new frame. | la RA, 8(RA) | cgr RA, BASE | jnl >3 // Less args than parameters? | lg KBASE, -16(RA) | stg KBASE, 0(RD) | la RD, 8(RD) | stg TMPR1, -16(RA) // Clear old fixarg slot (help the GC). | brctg RB, <1 |2: if (op == BC_JFUNCV) { | llgh RD, PC_RD | j =>BC_JLOOP } else { | lg KBASE, (PC2PROTO(k)-4)(PC) | ins_next } | |3: // Clear missing parameters. | stg TMPR1, 0(RD) // TMPR1=LJ_TNIL (-1) here. | la RD, 8(RD) | brctg RB, <3 | j <2 break; case BC_FUNCC: case BC_FUNCCW: | ins_AD // BASE = new base, RD = nargs+1 | lg CFUNC:RB, -16(BASE) | cleartp CFUNC:RB | lg KBASE, CFUNC:RB->f | lg L:RB, SAVE_L | sllg RD, NARGS:RD, 3 | lay RD, -8(RD,BASE) | stg BASE, L:RB->base | la RA, (8*LUA_MINSTACK)(RD) | clg RA, L:RB->maxstack | stg RD, L:RB->top | lgr CARG1, L:RB if (op != BC_FUNCC) { | lgr CARG2, KBASE } | jh ->vm_growstack_c // Need to grow stack. | set_vmstate C if (op == BC_FUNCC) { | basr r14, KBASE // (lua_State *L) } else { | // (lua_State *L, lua_CFunction f) | lg TMPR1, (DISPATCH_GL(wrapf))(DISPATCH) | basr r14, TMPR1 } | // nresults returned in r2 (CRET1). | lgr RD, CRET1 | lg BASE, L:RB->base | stg L:RB, (DISPATCH_GL(cur_L))(DISPATCH) | set_vmstate INTERP | sllg TMPR1, RD, 3 | la RA, 0(TMPR1, BASE) | lcgr RA, RA | ag RA, L:RB->top // RA = (L->top-(L->base+nresults))*8 | lg PC, -8(BASE) // Fetch PC of caller. | j ->vm_returnc break; /* ---------------------------------------------------------------------- */ default: fprintf(stderr, "Error: undefined opcode BC_%s\n", bc_names[op]); exit(2); break; } } static int build_backend(BuildCtx *ctx) { int op; dasm_growpc(Dst, BC__MAX); build_subroutines(ctx); |.code_op for (op = 0; op < BC__MAX; op++) build_ins(ctx, (BCOp)op, op); return BC__MAX; } /* Emit pseudo frame-info for all assembler functions. */ static void emit_asm_debug(BuildCtx *ctx) { int fcofs = (int)((uint8_t *)ctx->glob[GLOB_vm_ffi_call] - ctx->code); switch (ctx->mode) { case BUILD_elfasm: fprintf(ctx->fp, "\t.section .debug_frame,\"\",@progbits\n"); fprintf(ctx->fp, ".Lframe0:\n" "\t.long .LECIE0-.LSCIE0\n" ".LSCIE0:\n" "\t.long 0xffffffff\n" "\t.byte 0x1\n" "\t.string \"\"\n" "\t.uleb128 1\n" "\t.sleb128 -8\n" "\t.byte 0xe\n" "\t.byte 0xc\n\t.uleb128 0xf\n\t.uleb128 160\n" "\t.align 8\n" ".LECIE0:\n\n"); fprintf(ctx->fp, ".LSFDE0:\n" "\t.long .LEFDE0-.LASFDE0\n" ".LASFDE0:\n" "\t.long .Lframe0\n" "\t.quad .Lbegin\n" "\t.quad %d\n" "\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */ "\t.byte 0x86\n\t.uleb128 0xe\n" /* offset r6 */ "\t.byte 0x87\n\t.uleb128 0xd\n" /* offset r7 */ "\t.byte 0x88\n\t.uleb128 0xc\n" /* offset r8 */ "\t.byte 0x89\n\t.uleb128 0xb\n" /* offset r9 */ "\t.byte 0x8a\n\t.uleb128 0xa\n" /* offset r10 */ "\t.byte 0x8b\n\t.uleb128 0x9\n" /* offset r11 */ "\t.byte 0x8c\n\t.uleb128 0x8\n" /* offset r12 */ "\t.byte 0x8d\n\t.uleb128 0x7\n" /* offset r13 */ "\t.byte 0x8e\n\t.uleb128 0x6\n" /* offset r14 */ "\t.byte 0x8f\n\t.uleb128 0x5\n" /* offset r15 */ "\t.align 8\n" ".LEFDE0:\n\n", fcofs, CFRAME_SIZE+160); #if LJ_HASFFI fprintf(ctx->fp, ".LSFDE1:\n" "\t.long .LEFDE1-.LASFDE1\n" ".LASFDE1:\n" "\t.long .Lframe0\n" "\t.quad lj_vm_ffi_call\n" "\t.quad %d\n" "\t.byte 0xe\n\t.uleb128 160\n" /* def_cfa_offset */ "\t.byte 0xd\n\t.uleb128 0xd\n" /* def_cfa_register r13 (FP) */ "\t.byte 0x86\n\t.uleb128 0xe\n" /* offset r6 */ "\t.byte 0x87\n\t.uleb128 0xd\n" /* offset r7 */ "\t.byte 0x88\n\t.uleb128 0xc\n" /* offset r8 */ "\t.byte 0x89\n\t.uleb128 0xb\n" /* offset r9 */ "\t.byte 0x8a\n\t.uleb128 0xa\n" /* offset r10 */ "\t.byte 0x8b\n\t.uleb128 0x9\n" /* offset r11 */ "\t.byte 0x8c\n\t.uleb128 0x8\n" /* offset r12 */ "\t.byte 0x8d\n\t.uleb128 0x7\n" /* offset r13 */ "\t.byte 0x8e\n\t.uleb128 0x6\n" /* offset r14 */ "\t.byte 0x8f\n\t.uleb128 0x5\n" /* offset r15 */ "\t.align 8\n" ".LEFDE1:\n\n", (int)ctx->codesz - fcofs); #endif #if !LJ_NO_UNWIND fprintf(ctx->fp, "\t.section .eh_frame,\"a\",@progbits\n"); fprintf(ctx->fp, ".Lframe1:\n" "\t.long .LECIE1-.LSCIE1\n" ".LSCIE1:\n" "\t.long 0\n" "\t.byte 0x1\n" "\t.string \"zPR\"\n" "\t.uleb128 0x1\n" "\t.sleb128 -8\n" "\t.byte 0xe\n" "\t.uleb128 6\n" /* augmentation length */ "\t.byte 0x1b\n" /* pcrel|sdata4 */ "\t.long lj_err_unwind_dwarf-.\n" "\t.byte 0x1b\n" /* pcrel|sdata4 */ "\t.byte 0xc\n\t.uleb128 0xf\n\t.uleb128 160\n" "\t.align 8\n" ".LECIE1:\n\n"); fprintf(ctx->fp, ".LSFDE2:\n" "\t.long .LEFDE2-.LASFDE2\n" ".LASFDE2:\n" "\t.long .LASFDE2-.Lframe1\n" "\t.long .Lbegin-.\n" "\t.long %d\n" "\t.uleb128 0\n" /* augmentation length */ "\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */ "\t.byte 0x86\n\t.uleb128 0xe\n" /* offset r6 */ "\t.byte 0x87\n\t.uleb128 0xd\n" /* offset r7 */ "\t.byte 0x88\n\t.uleb128 0xc\n" /* offset r8 */ "\t.byte 0x89\n\t.uleb128 0xb\n" /* offset r9 */ "\t.byte 0x8a\n\t.uleb128 0xa\n" /* offset r10 */ "\t.byte 0x8b\n\t.uleb128 0x9\n" /* offset r11 */ "\t.byte 0x8c\n\t.uleb128 0x8\n" /* offset r12 */ "\t.byte 0x8d\n\t.uleb128 0x7\n" /* offset r13 */ "\t.byte 0x8e\n\t.uleb128 0x6\n" /* offset r14 */ "\t.byte 0x8f\n\t.uleb128 0x5\n" /* offset r15 */ "\t.align 8\n" ".LEFDE2:\n\n", fcofs, CFRAME_SIZE+160); #if LJ_HASFFI fprintf(ctx->fp, ".Lframe2:\n" "\t.long .LECIE2-.LSCIE2\n" ".LSCIE2:\n" "\t.long 0\n" "\t.byte 0x1\n" "\t.string \"zR\"\n" "\t.uleb128 0x1\n" "\t.sleb128 -8\n" "\t.byte 0xe\n" "\t.uleb128 1\n" /* augmentation length */ "\t.byte 0x1b\n" /* pcrel|sdata4 */ "\t.byte 0xc\n\t.uleb128 0xf\n\t.uleb128 160\n" "\t.align 8\n" ".LECIE2:\n\n"); fprintf(ctx->fp, ".LSFDE3:\n" "\t.long .LEFDE3-.LASFDE3\n" ".LASFDE3:\n" "\t.long .LASFDE3-.Lframe2\n" "\t.long lj_vm_ffi_call-.\n" "\t.long %d\n" "\t.uleb128 0\n" /* augmentation length */ "\t.byte 0xe\n\t.uleb128 160\n" /* def_cfa_offset */ "\t.byte 0xd\n\t.uleb128 0xd\n" /* def_cfa_register r13 (FP) */ "\t.byte 0x86\n\t.uleb128 0xe\n" /* offset r6 */ "\t.byte 0x87\n\t.uleb128 0xd\n" /* offset r7 */ "\t.byte 0x88\n\t.uleb128 0xc\n" /* offset r8 */ "\t.byte 0x89\n\t.uleb128 0xb\n" /* offset r9 */ "\t.byte 0x8a\n\t.uleb128 0xa\n" /* offset r10 */ "\t.byte 0x8b\n\t.uleb128 0x9\n" /* offset r11 */ "\t.byte 0x8c\n\t.uleb128 0x8\n" /* offset r12 */ "\t.byte 0x8d\n\t.uleb128 0x7\n" /* offset r13 */ "\t.byte 0x8e\n\t.uleb128 0x6\n" /* offset r14 */ "\t.byte 0x8f\n\t.uleb128 0x5\n" /* offset r15 */ "\t.align 8\n" ".LEFDE3:\n\n", (int)ctx->codesz - fcofs); #endif #endif break; default: /* No other modes. */ break; } }
xLua/build/luajit-2.1.0b3/src/vm_s390x.dasc/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/vm_s390x.dasc", "repo_id": "xLua", "token_count": 59044 }
1,941
/*=========================================================================*\ * MIME support functions * LuaSocket toolkit \*=========================================================================*/ #include <string.h> #include "lua.h" #include "lauxlib.h" #if !defined(LUA_VERSION_NUM) || (LUA_VERSION_NUM < 501) #include "compat-5.1.h" #endif #include "mime.h" /*=========================================================================*\ * Don't want to trust escape character constants \*=========================================================================*/ typedef unsigned char UC; static const char CRLF[] = "\r\n"; static const char EQCRLF[] = "=\r\n"; /*=========================================================================*\ * Internal function prototypes. \*=========================================================================*/ static int mime_global_wrp(lua_State *L); static int mime_global_b64(lua_State *L); static int mime_global_unb64(lua_State *L); static int mime_global_qp(lua_State *L); static int mime_global_unqp(lua_State *L); static int mime_global_qpwrp(lua_State *L); static int mime_global_eol(lua_State *L); static int mime_global_dot(lua_State *L); static size_t dot(int c, size_t state, luaL_Buffer *buffer); static void b64setup(UC *base); static size_t b64encode(UC c, UC *input, size_t size, luaL_Buffer *buffer); static size_t b64pad(const UC *input, size_t size, luaL_Buffer *buffer); static size_t b64decode(UC c, UC *input, size_t size, luaL_Buffer *buffer); static void qpsetup(UC *class, UC *unbase); static void qpquote(UC c, luaL_Buffer *buffer); static size_t qpdecode(UC c, UC *input, size_t size, luaL_Buffer *buffer); static size_t qpencode(UC c, UC *input, size_t size, const char *marker, luaL_Buffer *buffer); static size_t qppad(UC *input, size_t size, luaL_Buffer *buffer); /* code support functions */ static luaL_Reg func[] = { { "dot", mime_global_dot }, { "b64", mime_global_b64 }, { "eol", mime_global_eol }, { "qp", mime_global_qp }, { "qpwrp", mime_global_qpwrp }, { "unb64", mime_global_unb64 }, { "unqp", mime_global_unqp }, { "wrp", mime_global_wrp }, { NULL, NULL } }; /*-------------------------------------------------------------------------*\ * Quoted-printable globals \*-------------------------------------------------------------------------*/ static UC qpclass[256]; static UC qpbase[] = "0123456789ABCDEF"; static UC qpunbase[256]; enum {QP_PLAIN, QP_QUOTED, QP_CR, QP_IF_LAST}; /*-------------------------------------------------------------------------*\ * Base64 globals \*-------------------------------------------------------------------------*/ static const UC b64base[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static UC b64unbase[256]; /*=========================================================================*\ * Exported functions \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Initializes module \*-------------------------------------------------------------------------*/ MIME_API int luaopen_mime_core(lua_State *L) { #if LUA_VERSION_NUM > 501 && !defined(LUA_COMPAT_MODULE) lua_newtable(L); luaL_setfuncs(L, func, 0); #else luaL_openlib(L, "mime", func, 0); #endif /* make version string available to scripts */ lua_pushstring(L, "_VERSION"); lua_pushstring(L, MIME_VERSION); lua_rawset(L, -3); /* initialize lookup tables */ qpsetup(qpclass, qpunbase); b64setup(b64unbase); return 1; } /*=========================================================================*\ * Global Lua functions \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Incrementaly breaks a string into lines. The string can have CRLF breaks. * A, n = wrp(l, B, length) * A is a copy of B, broken into lines of at most 'length' bytes. * 'l' is how many bytes are left for the first line of B. * 'n' is the number of bytes left in the last line of A. \*-------------------------------------------------------------------------*/ static int mime_global_wrp(lua_State *L) { size_t size = 0; int left = (int) luaL_checknumber(L, 1); const UC *input = (UC *) luaL_optlstring(L, 2, NULL, &size); const UC *last = input + size; int length = (int) luaL_optnumber(L, 3, 76); luaL_Buffer buffer; /* end of input black-hole */ if (!input) { /* if last line has not been terminated, add a line break */ if (left < length) lua_pushstring(L, CRLF); /* otherwise, we are done */ else lua_pushnil(L); lua_pushnumber(L, length); return 2; } luaL_buffinit(L, &buffer); while (input < last) { switch (*input) { case '\r': break; case '\n': luaL_addstring(&buffer, CRLF); left = length; break; default: if (left <= 0) { left = length; luaL_addstring(&buffer, CRLF); } luaL_addchar(&buffer, *input); left--; break; } input++; } luaL_pushresult(&buffer); lua_pushnumber(L, left); return 2; } /*-------------------------------------------------------------------------*\ * Fill base64 decode map. \*-------------------------------------------------------------------------*/ static void b64setup(UC *unbase) { int i; for (i = 0; i <= 255; i++) unbase[i] = (UC) 255; for (i = 0; i < 64; i++) unbase[b64base[i]] = (UC) i; unbase['='] = 0; } /*-------------------------------------------------------------------------*\ * Acumulates bytes in input buffer until 3 bytes are available. * Translate the 3 bytes into Base64 form and append to buffer. * Returns new number of bytes in buffer. \*-------------------------------------------------------------------------*/ static size_t b64encode(UC c, UC *input, size_t size, luaL_Buffer *buffer) { input[size++] = c; if (size == 3) { UC code[4]; unsigned long value = 0; value += input[0]; value <<= 8; value += input[1]; value <<= 8; value += input[2]; code[3] = b64base[value & 0x3f]; value >>= 6; code[2] = b64base[value & 0x3f]; value >>= 6; code[1] = b64base[value & 0x3f]; value >>= 6; code[0] = b64base[value]; luaL_addlstring(buffer, (char *) code, 4); size = 0; } return size; } /*-------------------------------------------------------------------------*\ * Encodes the Base64 last 1 or 2 bytes and adds padding '=' * Result, if any, is appended to buffer. * Returns 0. \*-------------------------------------------------------------------------*/ static size_t b64pad(const UC *input, size_t size, luaL_Buffer *buffer) { unsigned long value = 0; UC code[4] = {'=', '=', '=', '='}; switch (size) { case 1: value = input[0] << 4; code[1] = b64base[value & 0x3f]; value >>= 6; code[0] = b64base[value]; luaL_addlstring(buffer, (char *) code, 4); break; case 2: value = input[0]; value <<= 8; value |= input[1]; value <<= 2; code[2] = b64base[value & 0x3f]; value >>= 6; code[1] = b64base[value & 0x3f]; value >>= 6; code[0] = b64base[value]; luaL_addlstring(buffer, (char *) code, 4); break; default: break; } return 0; } /*-------------------------------------------------------------------------*\ * Acumulates bytes in input buffer until 4 bytes are available. * Translate the 4 bytes from Base64 form and append to buffer. * Returns new number of bytes in buffer. \*-------------------------------------------------------------------------*/ static size_t b64decode(UC c, UC *input, size_t size, luaL_Buffer *buffer) { /* ignore invalid characters */ if (b64unbase[c] > 64) return size; input[size++] = c; /* decode atom */ if (size == 4) { UC decoded[3]; int valid, value = 0; value = b64unbase[input[0]]; value <<= 6; value |= b64unbase[input[1]]; value <<= 6; value |= b64unbase[input[2]]; value <<= 6; value |= b64unbase[input[3]]; decoded[2] = (UC) (value & 0xff); value >>= 8; decoded[1] = (UC) (value & 0xff); value >>= 8; decoded[0] = (UC) value; /* take care of paddding */ valid = (input[2] == '=') ? 1 : (input[3] == '=') ? 2 : 3; luaL_addlstring(buffer, (char *) decoded, valid); return 0; /* need more data */ } else return size; } /*-------------------------------------------------------------------------*\ * Incrementally applies the Base64 transfer content encoding to a string * A, B = b64(C, D) * A is the encoded version of the largest prefix of C .. D that is * divisible by 3. B has the remaining bytes of C .. D, *without* encoding. * The easiest thing would be to concatenate the two strings and * encode the result, but we can't afford that or Lua would dupplicate * every chunk we received. \*-------------------------------------------------------------------------*/ static int mime_global_b64(lua_State *L) { UC atom[3]; size_t isize = 0, asize = 0; const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); const UC *last = input + isize; luaL_Buffer buffer; /* end-of-input blackhole */ if (!input) { lua_pushnil(L); lua_pushnil(L); return 2; } /* make sure we don't confuse buffer stuff with arguments */ lua_settop(L, 2); /* process first part of the input */ luaL_buffinit(L, &buffer); while (input < last) asize = b64encode(*input++, atom, asize, &buffer); input = (UC *) luaL_optlstring(L, 2, NULL, &isize); /* if second part is nil, we are done */ if (!input) { size_t osize = 0; asize = b64pad(atom, asize, &buffer); luaL_pushresult(&buffer); /* if the output is empty and the input is nil, return nil */ lua_tolstring(L, -1, &osize); if (osize == 0) lua_pushnil(L); lua_pushnil(L); return 2; } /* otherwise process the second part */ last = input + isize; while (input < last) asize = b64encode(*input++, atom, asize, &buffer); luaL_pushresult(&buffer); lua_pushlstring(L, (char *) atom, asize); return 2; } /*-------------------------------------------------------------------------*\ * Incrementally removes the Base64 transfer content encoding from a string * A, B = b64(C, D) * A is the encoded version of the largest prefix of C .. D that is * divisible by 4. B has the remaining bytes of C .. D, *without* encoding. \*-------------------------------------------------------------------------*/ static int mime_global_unb64(lua_State *L) { UC atom[4]; size_t isize = 0, asize = 0; const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); const UC *last = input + isize; luaL_Buffer buffer; /* end-of-input blackhole */ if (!input) { lua_pushnil(L); lua_pushnil(L); return 2; } /* make sure we don't confuse buffer stuff with arguments */ lua_settop(L, 2); /* process first part of the input */ luaL_buffinit(L, &buffer); while (input < last) asize = b64decode(*input++, atom, asize, &buffer); input = (UC *) luaL_optlstring(L, 2, NULL, &isize); /* if second is nil, we are done */ if (!input) { size_t osize = 0; luaL_pushresult(&buffer); /* if the output is empty and the input is nil, return nil */ lua_tolstring(L, -1, &osize); if (osize == 0) lua_pushnil(L); lua_pushnil(L); return 2; } /* otherwise, process the rest of the input */ last = input + isize; while (input < last) asize = b64decode(*input++, atom, asize, &buffer); luaL_pushresult(&buffer); lua_pushlstring(L, (char *) atom, asize); return 2; } /*-------------------------------------------------------------------------*\ * Quoted-printable encoding scheme * all (except CRLF in text) can be =XX * CLRL in not text must be =XX=XX * 33 through 60 inclusive can be plain * 62 through 126 inclusive can be plain * 9 and 32 can be plain, unless in the end of a line, where must be =XX * encoded lines must be no longer than 76 not counting CRLF * soft line-break are =CRLF * To encode one byte, we need to see the next two. * Worst case is when we see a space, and wonder if a CRLF is comming \*-------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------*\ * Split quoted-printable characters into classes * Precompute reverse map for encoding \*-------------------------------------------------------------------------*/ static void qpsetup(UC *cl, UC *unbase) { int i; for (i = 0; i < 256; i++) cl[i] = QP_QUOTED; for (i = 33; i <= 60; i++) cl[i] = QP_PLAIN; for (i = 62; i <= 126; i++) cl[i] = QP_PLAIN; cl['\t'] = QP_IF_LAST; cl[' '] = QP_IF_LAST; cl['\r'] = QP_CR; for (i = 0; i < 256; i++) unbase[i] = 255; unbase['0'] = 0; unbase['1'] = 1; unbase['2'] = 2; unbase['3'] = 3; unbase['4'] = 4; unbase['5'] = 5; unbase['6'] = 6; unbase['7'] = 7; unbase['8'] = 8; unbase['9'] = 9; unbase['A'] = 10; unbase['a'] = 10; unbase['B'] = 11; unbase['b'] = 11; unbase['C'] = 12; unbase['c'] = 12; unbase['D'] = 13; unbase['d'] = 13; unbase['E'] = 14; unbase['e'] = 14; unbase['F'] = 15; unbase['f'] = 15; } /*-------------------------------------------------------------------------*\ * Output one character in form =XX \*-------------------------------------------------------------------------*/ static void qpquote(UC c, luaL_Buffer *buffer) { luaL_addchar(buffer, '='); luaL_addchar(buffer, qpbase[c >> 4]); luaL_addchar(buffer, qpbase[c & 0x0F]); } /*-------------------------------------------------------------------------*\ * Accumulate characters until we are sure about how to deal with them. * Once we are sure, output to the buffer, in the correct form. \*-------------------------------------------------------------------------*/ static size_t qpencode(UC c, UC *input, size_t size, const char *marker, luaL_Buffer *buffer) { input[size++] = c; /* deal with all characters we can have */ while (size > 0) { switch (qpclass[input[0]]) { /* might be the CR of a CRLF sequence */ case QP_CR: if (size < 2) return size; if (input[1] == '\n') { luaL_addstring(buffer, marker); return 0; } else qpquote(input[0], buffer); break; /* might be a space and that has to be quoted if last in line */ case QP_IF_LAST: if (size < 3) return size; /* if it is the last, quote it and we are done */ if (input[1] == '\r' && input[2] == '\n') { qpquote(input[0], buffer); luaL_addstring(buffer, marker); return 0; } else luaL_addchar(buffer, input[0]); break; /* might have to be quoted always */ case QP_QUOTED: qpquote(input[0], buffer); break; /* might never have to be quoted */ default: luaL_addchar(buffer, input[0]); break; } input[0] = input[1]; input[1] = input[2]; size--; } return 0; } /*-------------------------------------------------------------------------*\ * Deal with the final characters \*-------------------------------------------------------------------------*/ static size_t qppad(UC *input, size_t size, luaL_Buffer *buffer) { size_t i; for (i = 0; i < size; i++) { if (qpclass[input[i]] == QP_PLAIN) luaL_addchar(buffer, input[i]); else qpquote(input[i], buffer); } if (size > 0) luaL_addstring(buffer, EQCRLF); return 0; } /*-------------------------------------------------------------------------*\ * Incrementally converts a string to quoted-printable * A, B = qp(C, D, marker) * Marker is the text to be used to replace CRLF sequences found in A. * A is the encoded version of the largest prefix of C .. D that * can be encoded without doubts. * B has the remaining bytes of C .. D, *without* encoding. \*-------------------------------------------------------------------------*/ static int mime_global_qp(lua_State *L) { size_t asize = 0, isize = 0; UC atom[3]; const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); const UC *last = input + isize; const char *marker = luaL_optstring(L, 3, CRLF); luaL_Buffer buffer; /* end-of-input blackhole */ if (!input) { lua_pushnil(L); lua_pushnil(L); return 2; } /* make sure we don't confuse buffer stuff with arguments */ lua_settop(L, 3); /* process first part of input */ luaL_buffinit(L, &buffer); while (input < last) asize = qpencode(*input++, atom, asize, marker, &buffer); input = (UC *) luaL_optlstring(L, 2, NULL, &isize); /* if second part is nil, we are done */ if (!input) { asize = qppad(atom, asize, &buffer); luaL_pushresult(&buffer); if (!(*lua_tostring(L, -1))) lua_pushnil(L); lua_pushnil(L); return 2; } /* otherwise process rest of input */ last = input + isize; while (input < last) asize = qpencode(*input++, atom, asize, marker, &buffer); luaL_pushresult(&buffer); lua_pushlstring(L, (char *) atom, asize); return 2; } /*-------------------------------------------------------------------------*\ * Accumulate characters until we are sure about how to deal with them. * Once we are sure, output the to the buffer, in the correct form. \*-------------------------------------------------------------------------*/ static size_t qpdecode(UC c, UC *input, size_t size, luaL_Buffer *buffer) { int d; input[size++] = c; /* deal with all characters we can deal */ switch (input[0]) { /* if we have an escape character */ case '=': if (size < 3) return size; /* eliminate soft line break */ if (input[1] == '\r' && input[2] == '\n') return 0; /* decode quoted representation */ c = qpunbase[input[1]]; d = qpunbase[input[2]]; /* if it is an invalid, do not decode */ if (c > 15 || d > 15) luaL_addlstring(buffer, (char *)input, 3); else luaL_addchar(buffer, (char) ((c << 4) + d)); return 0; case '\r': if (size < 2) return size; if (input[1] == '\n') luaL_addlstring(buffer, (char *)input, 2); return 0; default: if (input[0] == '\t' || (input[0] > 31 && input[0] < 127)) luaL_addchar(buffer, input[0]); return 0; } } /*-------------------------------------------------------------------------*\ * Incrementally decodes a string in quoted-printable * A, B = qp(C, D) * A is the decoded version of the largest prefix of C .. D that * can be decoded without doubts. * B has the remaining bytes of C .. D, *without* decoding. \*-------------------------------------------------------------------------*/ static int mime_global_unqp(lua_State *L) { size_t asize = 0, isize = 0; UC atom[3]; const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); const UC *last = input + isize; luaL_Buffer buffer; /* end-of-input blackhole */ if (!input) { lua_pushnil(L); lua_pushnil(L); return 2; } /* make sure we don't confuse buffer stuff with arguments */ lua_settop(L, 2); /* process first part of input */ luaL_buffinit(L, &buffer); while (input < last) asize = qpdecode(*input++, atom, asize, &buffer); input = (UC *) luaL_optlstring(L, 2, NULL, &isize); /* if second part is nil, we are done */ if (!input) { luaL_pushresult(&buffer); if (!(*lua_tostring(L, -1))) lua_pushnil(L); lua_pushnil(L); return 2; } /* otherwise process rest of input */ last = input + isize; while (input < last) asize = qpdecode(*input++, atom, asize, &buffer); luaL_pushresult(&buffer); lua_pushlstring(L, (char *) atom, asize); return 2; } /*-------------------------------------------------------------------------*\ * Incrementally breaks a quoted-printed string into lines * A, n = qpwrp(l, B, length) * A is a copy of B, broken into lines of at most 'length' bytes. * 'l' is how many bytes are left for the first line of B. * 'n' is the number of bytes left in the last line of A. * There are two complications: lines can't be broken in the middle * of an encoded =XX, and there might be line breaks already \*-------------------------------------------------------------------------*/ static int mime_global_qpwrp(lua_State *L) { size_t size = 0; int left = (int) luaL_checknumber(L, 1); const UC *input = (UC *) luaL_optlstring(L, 2, NULL, &size); const UC *last = input + size; int length = (int) luaL_optnumber(L, 3, 76); luaL_Buffer buffer; /* end-of-input blackhole */ if (!input) { if (left < length) lua_pushstring(L, EQCRLF); else lua_pushnil(L); lua_pushnumber(L, length); return 2; } /* process all input */ luaL_buffinit(L, &buffer); while (input < last) { switch (*input) { case '\r': break; case '\n': left = length; luaL_addstring(&buffer, CRLF); break; case '=': if (left <= 3) { left = length; luaL_addstring(&buffer, EQCRLF); } luaL_addchar(&buffer, *input); left--; break; default: if (left <= 1) { left = length; luaL_addstring(&buffer, EQCRLF); } luaL_addchar(&buffer, *input); left--; break; } input++; } luaL_pushresult(&buffer); lua_pushnumber(L, left); return 2; } /*-------------------------------------------------------------------------*\ * Here is what we do: \n, and \r are considered candidates for line * break. We issue *one* new line marker if any of them is seen alone, or * followed by a different one. That is, \n\n and \r\r will issue two * end of line markers each, but \r\n, \n\r etc will only issue *one* * marker. This covers Mac OS, Mac OS X, VMS, Unix and DOS, as well as * probably other more obscure conventions. * * c is the current character being processed * last is the previous character \*-------------------------------------------------------------------------*/ #define eolcandidate(c) (c == '\r' || c == '\n') static int eolprocess(int c, int last, const char *marker, luaL_Buffer *buffer) { if (eolcandidate(c)) { if (eolcandidate(last)) { if (c == last) luaL_addstring(buffer, marker); return 0; } else { luaL_addstring(buffer, marker); return c; } } else { luaL_addchar(buffer, (char) c); return 0; } } /*-------------------------------------------------------------------------*\ * Converts a string to uniform EOL convention. * A, n = eol(o, B, marker) * A is the converted version of the largest prefix of B that can be * converted unambiguously. 'o' is the context returned by the previous * call. 'n' is the new context. \*-------------------------------------------------------------------------*/ static int mime_global_eol(lua_State *L) { int ctx = luaL_checkint(L, 1); size_t isize = 0; const char *input = luaL_optlstring(L, 2, NULL, &isize); const char *last = input + isize; const char *marker = luaL_optstring(L, 3, CRLF); luaL_Buffer buffer; luaL_buffinit(L, &buffer); /* end of input blackhole */ if (!input) { lua_pushnil(L); lua_pushnumber(L, 0); return 2; } /* process all input */ while (input < last) ctx = eolprocess(*input++, ctx, marker, &buffer); luaL_pushresult(&buffer); lua_pushnumber(L, ctx); return 2; } /*-------------------------------------------------------------------------*\ * Takes one byte and stuff it if needed. \*-------------------------------------------------------------------------*/ static size_t dot(int c, size_t state, luaL_Buffer *buffer) { luaL_addchar(buffer, (char) c); switch (c) { case '\r': return 1; case '\n': return (state == 1)? 2: 0; case '.': if (state == 2) luaL_addchar(buffer, '.'); default: return 0; } } /*-------------------------------------------------------------------------*\ * Incrementally applies smtp stuffing to a string * A, n = dot(l, D) \*-------------------------------------------------------------------------*/ static int mime_global_dot(lua_State *L) { size_t isize = 0, state = (size_t) luaL_checknumber(L, 1); const char *input = luaL_optlstring(L, 2, NULL, &isize); const char *last = input + isize; luaL_Buffer buffer; /* end-of-input blackhole */ if (!input) { lua_pushnil(L); lua_pushnumber(L, 2); return 2; } /* process all input */ luaL_buffinit(L, &buffer); while (input < last) state = dot(*input++, state, &buffer); luaL_pushresult(&buffer); lua_pushnumber(L, (lua_Number) state); return 2; }
xLua/build/luasocket/mime.c/0
{ "file_path": "xLua/build/luasocket/mime.c", "repo_id": "xLua", "token_count": 10507 }
1,942
/*=========================================================================*\ * Socket compatibilization module for Unix * LuaSocket toolkit * * The code is now interrupt-safe. * The penalty of calling select to avoid busy-wait is only paid when * the I/O call fail in the first place. \*=========================================================================*/ #include <string.h> #include <signal.h> #include "socket.h" /*-------------------------------------------------------------------------*\ * Wait for readable/writable/connected socket with timeout \*-------------------------------------------------------------------------*/ #ifndef SOCKET_SELECT #include <sys/poll.h> #define WAITFD_R POLLIN #define WAITFD_W POLLOUT #define WAITFD_C (POLLIN|POLLOUT) int socket_waitfd(p_socket ps, int sw, p_timeout tm) { int ret; struct pollfd pfd; pfd.fd = *ps; pfd.events = sw; pfd.revents = 0; if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */ do { int t = (int)(timeout_getretry(tm)*1e3); ret = poll(&pfd, 1, t >= 0? t: -1); } while (ret == -1 && errno == EINTR); if (ret == -1) return errno; if (ret == 0) return IO_TIMEOUT; if (sw == WAITFD_C && (pfd.revents & (POLLIN|POLLERR))) return IO_CLOSED; return IO_DONE; } #else #define WAITFD_R 1 #define WAITFD_W 2 #define WAITFD_C (WAITFD_R|WAITFD_W) int socket_waitfd(p_socket ps, int sw, p_timeout tm) { int ret; fd_set rfds, wfds, *rp, *wp; struct timeval tv, *tp; double t; if (*ps >= FD_SETSIZE) return EINVAL; if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */ do { /* must set bits within loop, because select may have modifed them */ rp = wp = NULL; if (sw & WAITFD_R) { FD_ZERO(&rfds); FD_SET(*ps, &rfds); rp = &rfds; } if (sw & WAITFD_W) { FD_ZERO(&wfds); FD_SET(*ps, &wfds); wp = &wfds; } t = timeout_getretry(tm); tp = NULL; if (t >= 0.0) { tv.tv_sec = (int)t; tv.tv_usec = (int)((t-tv.tv_sec)*1.0e6); tp = &tv; } ret = select(*ps+1, rp, wp, NULL, tp); } while (ret == -1 && errno == EINTR); if (ret == -1) return errno; if (ret == 0) return IO_TIMEOUT; if (sw == WAITFD_C && FD_ISSET(*ps, &rfds)) return IO_CLOSED; return IO_DONE; } #endif /*-------------------------------------------------------------------------*\ * Initializes module \*-------------------------------------------------------------------------*/ int socket_open(void) { /* instals a handler to ignore sigpipe or it will crash us */ signal(SIGPIPE, SIG_IGN); return 1; } /*-------------------------------------------------------------------------*\ * Close module \*-------------------------------------------------------------------------*/ int socket_close(void) { return 1; } /*-------------------------------------------------------------------------*\ * Close and inutilize socket \*-------------------------------------------------------------------------*/ void socket_destroy(p_socket ps) { if (*ps != SOCKET_INVALID) { socket_setblocking(ps); close(*ps); *ps = SOCKET_INVALID; } } /*-------------------------------------------------------------------------*\ * Select with timeout control \*-------------------------------------------------------------------------*/ int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, p_timeout tm) { int ret; do { struct timeval tv; double t = timeout_getretry(tm); tv.tv_sec = (int) t; tv.tv_usec = (int) ((t - tv.tv_sec) * 1.0e6); /* timeout = 0 means no wait */ ret = select(n, rfds, wfds, efds, t >= 0.0 ? &tv: NULL); } while (ret < 0 && errno == EINTR); return ret; } /*-------------------------------------------------------------------------*\ * Creates and sets up a socket \*-------------------------------------------------------------------------*/ int socket_create(p_socket ps, int domain, int type, int protocol) { *ps = socket(domain, type, protocol); if (*ps != SOCKET_INVALID) return IO_DONE; else return errno; } /*-------------------------------------------------------------------------*\ * Binds or returns error message \*-------------------------------------------------------------------------*/ int socket_bind(p_socket ps, SA *addr, socklen_t len) { int err = IO_DONE; socket_setblocking(ps); if (bind(*ps, addr, len) < 0) err = errno; socket_setnonblocking(ps); return err; } /*-------------------------------------------------------------------------*\ * \*-------------------------------------------------------------------------*/ int socket_listen(p_socket ps, int backlog) { int err = IO_DONE; socket_setblocking(ps); if (listen(*ps, backlog)) err = errno; socket_setnonblocking(ps); return err; } /*-------------------------------------------------------------------------*\ * \*-------------------------------------------------------------------------*/ void socket_shutdown(p_socket ps, int how) { socket_setblocking(ps); shutdown(*ps, how); socket_setnonblocking(ps); } /*-------------------------------------------------------------------------*\ * Connects or returns error message \*-------------------------------------------------------------------------*/ int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) { int err; /* avoid calling on closed sockets */ if (*ps == SOCKET_INVALID) return IO_CLOSED; /* call connect until done or failed without being interrupted */ do if (connect(*ps, addr, len) == 0) return IO_DONE; while ((err = errno) == EINTR); /* if connection failed immediately, return error code */ if (err != EINPROGRESS && err != EAGAIN) return err; /* zero timeout case optimization */ if (timeout_iszero(tm)) return IO_TIMEOUT; /* wait until we have the result of the connection attempt or timeout */ err = socket_waitfd(ps, WAITFD_C, tm); if (err == IO_CLOSED) { if (recv(*ps, (char *) &err, 0, 0) == 0) return IO_DONE; else return errno; } else return err; } /*-------------------------------------------------------------------------*\ * Accept with timeout \*-------------------------------------------------------------------------*/ int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len, p_timeout tm) { if (*ps == SOCKET_INVALID) return IO_CLOSED; for ( ;; ) { int err; if ((*pa = accept(*ps, addr, len)) != SOCKET_INVALID) return IO_DONE; err = errno; if (err == EINTR) continue; if (err != EAGAIN && err != ECONNABORTED) return err; if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; } /* can't reach here */ return IO_UNKNOWN; } /*-------------------------------------------------------------------------*\ * Send with timeout \*-------------------------------------------------------------------------*/ int socket_send(p_socket ps, const char *data, size_t count, size_t *sent, p_timeout tm) { int err; *sent = 0; /* avoid making system calls on closed sockets */ if (*ps == SOCKET_INVALID) return IO_CLOSED; /* loop until we send something or we give up on error */ for ( ;; ) { long put = (long) send(*ps, data, count, 0); /* if we sent anything, we are done */ if (put >= 0) { *sent = put; return IO_DONE; } err = errno; /* EPIPE means the connection was closed */ if (err == EPIPE) return IO_CLOSED; /* we call was interrupted, just try again */ if (err == EINTR) continue; /* if failed fatal reason, report error */ if (err != EAGAIN) return err; /* wait until we can send something or we timeout */ if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; } /* can't reach here */ return IO_UNKNOWN; } /*-------------------------------------------------------------------------*\ * Sendto with timeout \*-------------------------------------------------------------------------*/ int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent, SA *addr, socklen_t len, p_timeout tm) { int err; *sent = 0; if (*ps == SOCKET_INVALID) return IO_CLOSED; for ( ;; ) { long put = (long) sendto(*ps, data, count, 0, addr, len); if (put >= 0) { *sent = put; return IO_DONE; } err = errno; if (err == EPIPE) return IO_CLOSED; if (err == EINTR) continue; if (err != EAGAIN) return err; if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; } return IO_UNKNOWN; } /*-------------------------------------------------------------------------*\ * Receive with timeout \*-------------------------------------------------------------------------*/ int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm) { int err; *got = 0; if (*ps == SOCKET_INVALID) return IO_CLOSED; for ( ;; ) { long taken = (long) recv(*ps, data, count, 0); if (taken > 0) { *got = taken; return IO_DONE; } err = errno; if (taken == 0) return IO_CLOSED; if (err == EINTR) continue; if (err != EAGAIN) return err; if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; } return IO_UNKNOWN; } /*-------------------------------------------------------------------------*\ * Recvfrom with timeout \*-------------------------------------------------------------------------*/ int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got, SA *addr, socklen_t *len, p_timeout tm) { int err; *got = 0; if (*ps == SOCKET_INVALID) return IO_CLOSED; for ( ;; ) { long taken = (long) recvfrom(*ps, data, count, 0, addr, len); if (taken > 0) { *got = taken; return IO_DONE; } err = errno; if (taken == 0) return IO_CLOSED; if (err == EINTR) continue; if (err != EAGAIN) return err; if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; } return IO_UNKNOWN; } /*-------------------------------------------------------------------------*\ * Write with timeout * * socket_read and socket_write are cut-n-paste of socket_send and socket_recv, * with send/recv replaced with write/read. We can't just use write/read * in the socket version, because behaviour when size is zero is different. \*-------------------------------------------------------------------------*/ int socket_write(p_socket ps, const char *data, size_t count, size_t *sent, p_timeout tm) { int err; *sent = 0; /* avoid making system calls on closed sockets */ if (*ps == SOCKET_INVALID) return IO_CLOSED; /* loop until we send something or we give up on error */ for ( ;; ) { long put = (long) write(*ps, data, count); /* if we sent anything, we are done */ if (put >= 0) { *sent = put; return IO_DONE; } err = errno; /* EPIPE means the connection was closed */ if (err == EPIPE) return IO_CLOSED; /* we call was interrupted, just try again */ if (err == EINTR) continue; /* if failed fatal reason, report error */ if (err != EAGAIN) return err; /* wait until we can send something or we timeout */ if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; } /* can't reach here */ return IO_UNKNOWN; } /*-------------------------------------------------------------------------*\ * Read with timeout * See note for socket_write \*-------------------------------------------------------------------------*/ int socket_read(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm) { int err; *got = 0; if (*ps == SOCKET_INVALID) return IO_CLOSED; for ( ;; ) { long taken = (long) read(*ps, data, count); if (taken > 0) { *got = taken; return IO_DONE; } err = errno; if (taken == 0) return IO_CLOSED; if (err == EINTR) continue; if (err != EAGAIN) return err; if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; } return IO_UNKNOWN; } /*-------------------------------------------------------------------------*\ * Put socket into blocking mode \*-------------------------------------------------------------------------*/ void socket_setblocking(p_socket ps) { int flags = fcntl(*ps, F_GETFL, 0); flags &= (~(O_NONBLOCK)); fcntl(*ps, F_SETFL, flags); } /*-------------------------------------------------------------------------*\ * Put socket into non-blocking mode \*-------------------------------------------------------------------------*/ void socket_setnonblocking(p_socket ps) { int flags = fcntl(*ps, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(*ps, F_SETFL, flags); } /*-------------------------------------------------------------------------*\ * DNS helpers \*-------------------------------------------------------------------------*/ int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) { *hp = gethostbyaddr(addr, len, AF_INET); if (*hp) return IO_DONE; else if (h_errno) return h_errno; else if (errno) return errno; else return IO_UNKNOWN; } int socket_gethostbyname(const char *addr, struct hostent **hp) { *hp = gethostbyname(addr); if (*hp) return IO_DONE; else if (h_errno) return h_errno; else if (errno) return errno; else return IO_UNKNOWN; } /*-------------------------------------------------------------------------*\ * Error translation functions * Make sure important error messages are standard \*-------------------------------------------------------------------------*/ const char *socket_hoststrerror(int err) { if (err <= 0) return io_strerror(err); switch (err) { case HOST_NOT_FOUND: return "host not found"; default: return hstrerror(err); } } const char *socket_strerror(int err) { if (err <= 0) return io_strerror(err); switch (err) { case EADDRINUSE: return "address already in use"; case EISCONN: return "already connected"; case EACCES: return "permission denied"; case ECONNREFUSED: return "connection refused"; case ECONNABORTED: return "closed"; case ECONNRESET: return "closed"; case ETIMEDOUT: return "timeout"; default: return strerror(err); } } const char *socket_ioerror(p_socket ps, int err) { (void) ps; return socket_strerror(err); } const char *socket_gaistrerror(int err) { if (err == 0) return NULL; switch (err) { case EAI_AGAIN: return "temporary failure in name resolution"; case EAI_BADFLAGS: return "invalid value for ai_flags"; #ifdef EAI_BADHINTS case EAI_BADHINTS: return "invalid value for hints"; #endif case EAI_FAIL: return "non-recoverable failure in name resolution"; case EAI_FAMILY: return "ai_family not supported"; case EAI_MEMORY: return "memory allocation failure"; case EAI_NONAME: return "host or service not provided, or not known"; case EAI_OVERFLOW: return "argument buffer overflow"; #ifdef EAI_PROTOCOL case EAI_PROTOCOL: return "resolved protocol is unknown"; #endif case EAI_SERVICE: return "service not supported for socket type"; case EAI_SOCKTYPE: return "ai_socktype not supported"; case EAI_SYSTEM: return strerror(errno); default: return gai_strerror(err); } }
xLua/build/luasocket/usocket.c/0
{ "file_path": "xLua/build/luasocket/usocket.c", "repo_id": "xLua", "token_count": 5883 }
1,943
mkdir -p build_linux64_54 && cd build_linux64_54 cmake -DLUA_VERSION=5.4.1 ../ cd .. cmake --build build_linux64_54 --config Release mkdir -p plugin_lua54/Plugins/x86_64/ cp build_linux64_54/libxlua.so plugin_lua54/Plugins/x86_64/libxlua.so
xLua/build/make_linux_lua54.sh/0
{ "file_path": "xLua/build/make_linux_lua54.sh", "repo_id": "xLua", "token_count": 103 }
1,944
/* *Tencent is pleased to support the open source community by making xLua available. *Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. *Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at *http://opensource.org/licenses/MIT *Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" #include <stdio.h> #include <string.h> #include "ltable.h" #include "lstate.h" #include "lobject.h" #include "lapi.h" #include "lgc.h" #define gnodelast(h) gnode(h, cast(size_t, sizenode(h))) static int table_size (Table *h, int fast) { if (fast) { #if LUA_VERSION_NUM >= 504 return (int)sizenode(h) + (int)h->alimit; #else return (int)sizenode(h) + (int)h->sizearray; #endif } else { Node *n, *limit = gnodelast(h); int i = (int)luaH_getn(h); for (n = gnode(h, 0); n < limit; n++) { if (!ttisnil(gval(n))) { i++; } } return i; } } typedef void (*TableSizeReport) (const void *p, int size); // type: 1: value of table(key is string), 2: value of table(key is number), 3: key of table, 4: metatable of table, 5: upvalue of closure typedef void (*ObjectRelationshipReport) (const void *parent, const void *child, int type, const char *key, double d, const char *key2); LUA_API void xlua_report_table_size(lua_State *L, TableSizeReport cb, int fast) { GCObject *p = G(L)->allgc; while (p != NULL) { if (p->tt == LUA_TTABLE) { Table *h = gco2t(p); cb(h, table_size(h, fast)); } p = p->next; } } static void report_table(Table *h, ObjectRelationshipReport cb) { Node *n, *limit = gnodelast(h); unsigned int i; if (h->metatable != NULL) { cb(h, h->metatable, 4, NULL, 0, NULL); } #if LUA_VERSION_NUM >= 504 for (i = 0; i < h->alimit; i++) #else for (i = 0; i < h->sizearray; i++) #endif { const TValue *item = &h->array[i]; if (ttistable(item)) { cb(h, gcvalue(item), 2, NULL, i + 1, NULL); } } for (n = gnode(h, 0); n < limit; n++) { if (!ttisnil(gval(n))) { #if LUA_VERSION_NUM >= 504 const TValue* key = (const TValue *)&(n->u.key_val); #else const TValue *key = gkey(n); #endif if (ttistable(key)) { cb(h, gcvalue(key), 3, NULL, 0, NULL); } const TValue *value = gval(n); if (ttistable(value)) { if (ttisstring(key)) { cb(h, gcvalue(value), 1, getstr(tsvalue(key)), 0, NULL); } else if(ttisnumber(key)) { cb(h, gcvalue(value), 2, NULL, nvalue(key), NULL); } else { // ??? #if LUA_VERSION_NUM >= 504 cb(h, gcvalue(value), 1, NULL, novariant(key->tt_), NULL); #else cb(h, gcvalue(value), 1, NULL, ttnov(key), NULL); #endif } } } } } LUA_API void xlua_report_object_relationship(lua_State *L, ObjectRelationshipReport cb) { GCObject *p = G(L)->allgc; lua_Debug ar; int i; const char *name; while (p != NULL) { if (p->tt == LUA_TTABLE) { Table *h = gco2t(p); report_table(h, cb); } #if LUA_VERSION_NUM >= 504 else if (p->tt == LUA_VLCL) #else else if (p->tt == LUA_TLCL) #endif { LClosure *cl = gco2lcl(p); lua_lock(L); #if LUA_VERSION_NUM >= 504 && LUA_VERSION_RELEASE_NUM >= 50406 setclLvalue2s(L, L->top.p, cl); #else setclLvalue(L, L->top, cl); #endif api_incr_top(L); lua_unlock(L); lua_pushvalue(L, -1); lua_getinfo(L, ">S", &ar); for (i=1;;i++) { name = lua_getupvalue(L,-1,i); if (name == NULL) break; const void *pv = lua_topointer(L, -1); if (*name != '\0' && LUA_TTABLE == lua_type(L, -1)) { cb(cl, pv, 5, ar.short_src, ar.linedefined, name); } lua_pop(L, 1); } lua_pop(L, 1); } p = p->next; } } LUA_API void *xlua_registry_pointer(lua_State *L) { return gcvalue(&G(L)->l_registry); } LUA_API void *xlua_global_pointer(lua_State *L) { Table *reg = hvalue(&G(L)->l_registry); const TValue *global; lua_lock(L); global = luaH_getint(reg, LUA_RIDX_GLOBALS); lua_unlock(L); return gcvalue(global); }
xLua/build/memory_leak_checker.c/0
{ "file_path": "xLua/build/memory_leak_checker.c", "repo_id": "xLua", "token_count": 2059 }
1,945
--- title: C# API type: guide order: 101 --- ## C# API ### LuaEnv类 #### DoString `object[] DoString(string chunk, string chunkName = "chuck", LuaTable env = null)` 执行一个代码块。 **参数** * chunk - Lua代码的字符串 * chunkName - 发生error时的debug显示信息中使用,指明某某代码块的某行错误 * env - 这个代码块的环境变量 **返回值** 代码块里return语句的返回值。 比如:`return 1, "hello"`中,DoString将返回包含两个object的数组, 一个是double类型的1, 一个是string类型的hello。 **示例** ```csharp LuaEnv luaenv = new LuaEnv(); object[] ret = luaenv.DoString("print('hello')\r\nreturn 1"); UnityEngine.Debug.Log("ret=" + ret[0]); luaenv.Dispose(); ``` #### LoadString `T LoadString<T>(string chunk, string chunkName = "chunk", LuaTable env = null)` 加载一个代码块,但不执行,只返回类型。 可以指定为一个delegate或者一个LuaFunction。 **参数** * chunk - Lua代码的字符串 * chunkName - 发生error时的debug显示信息中使用,指明某某代码块的某行错误 * env - 这个代码块的环境变量 **返回值** 代表该代码块的delegate或LuaFunction。 #### Global `LuaTable Global` 代表lua全局环境的LuaTable。 #### Tick `void Tick()` 清除Lua的未手动释放的LuaBase对象(如:LuaTable、LuaFunction),以及其它一些事情。 需要定期调用,比如每秒在MonoBehaviour的Update中调用。 参考示例:[XLua Example - U3D Scripting - LuaBehaviour.cs L82](https://github.com/Tencent/xLua/blob/master/Assets/XLua/Examples/02_U3DScripting/LuaBehaviour.cs#L82) #### AddLoader `void AddLoader(CustomLoader loader)` 添加一个自定义loader。 **参数** * loader - 一个包括了加载函数的委托,其类型为delegate byte\[\] CustomLoader\(ref string filepath\)。 当一个文件被require时,这个loader会被回调,其参数是调用require所使用的参数。如果该loader找到文件,可以将其读进内存,返回一个byte数组。如果需要支持调试的话,filepath要设置成IDE能找到的路径(相对或者绝对都可以)。 #### Dispose `void Dispose()` Dispose该LuaEnv。 **使用建议** 全局只创建一个LuaEnv实例,并在Update中调用GC方法,完全不需要时调用Dispose。 ### LuaTable类 #### Get `T Get<T>(string key)` 获取在key下,类型为T的value,如果不存在或者类型不匹配,返回null。 #### GetInPath `T GetInPath<T>(string path)` 和Get的区别是,这个函数会识别path里的`.`。 比如`var i = tbl.GetInPath<int>("a.b.c")`相当于在lua里执行`i = tbl.a.b.c`,避免仅为了获取中间变量而多次调用Get,执行效率更高。 #### SetInPath `void SetInPath<T>(string path, T val)` 和`GetInPath`对应的setter。 #### Get `void Get<TKey, TValue>(TKey key, out TValue value)` 和上面API的区别是,上面的API的Key都只能是string,而这个API无此限制。 #### Set `void Set<TKey, TValue>(TKey key, TValue value)` 对应Get的setter。 #### Cast `T Cast<T>()` 把该table转成一个T指明的类型。 可以是一个加了CSharpCallLua声明的interface,一个有默认构造函数的class或者struct,一个Dictionary,List等等。 #### SetMetaTable `void SetMetaTable(LuaTable metaTable)` 设置metaTable为table的metatable。 ### LuaFunction类 用该类访问Lua函数会有boxing,unboxing的开销。 为了性能考虑,需要频繁调用的地方不要用该类。 建议通过`table.Get<FooDelegate>`获取一个delegate调用。 在使用`table.Get<FooDelegate>`之前,注意先把`FooDelegate`添加到代码生成列表。 #### Call `object[] Call(params object[] args)` 以可变参数调用Lua函数,并返回该调用的返回值。 #### Call `object[] Call(object[] args, Type[] returnTypes)` 调用Lua函数,并指明返回参数的类型,系统会自动按指定类型进行转换。 #### SetEnv `void SetEnv(LuaTable env)` 相当于lua的setfenv函数。 ## Lua API ### CS对象 #### CS.namespace.class\(...\) 调用一个C\#类型的构造函数,并返回类型实例 **示例** ```lua local v1 = CS.UnityEngine.Vector3(1,1,1) ``` #### CS.namespace.class.field 访问一个C\#静态成员 **示例** ```lua Print(CS.UnityEngine.Vector3.one) ``` #### CS.namespace.enum.field 访问一个枚举值 #### typeof函数 类似C\#的typeof关键字,返回一个Type对象。 **示例** 比如GameObject.AddComponent其中一个重载需要一个Type参数。 ```lua newGameObj:AddComponent(typeof(CS.UnityEngine.ParticleSystem)) ``` #### 无符号64位支持 **uint64.tostring** 无符号数转字符串。 **uint64.divide** 无符号数除法。 **uint64.compare** 无符号比较,相对返回0,大于返回正数,小于返回负数。 **uint64.remainder** 无符号数取模。 **uint64.parse** 字符串转无符号数。 #### xlua.structclone 克隆一个c\#结构体 #### xlua.private\_accessible\(class\) 让一个类的私有字段,属性,方法等可用 #### cast函数 指明以特定的接口访问对象,这在实现类无法访问的时候(比如internal修饰)很有用,这时可以这么来(假设下面的calc对象实现了C\#的PerformentTest.ICalc接口) **示例** ```lua cast(calc, typeof(CS.PerformentTest.ICalc)) ``` #### 其它 访问csharp对象和访问一个table一样,调用函数跟调用lua函数一样,也可以通过操作符访问c\#的操作符,示例: ```lua local v1=CS.UnityEngine.Vector3(1,1,1) local v2=CS.UnityEngine.Vector3(1,1,1) v1.x = 100 v2.y = 100 print(v1, v2) local v3 = v1 + v2 print(v1.x, v2.x) print(CS.UnityEngine.Vector3.one) print(CS.UnityEngine.Vector3.Distance(v1, v2)) ``` ## 类型映射 ### 基本数据类型 | C\#类型 | Lua类型 | | :--- | :--- | | sbyte,byte,short,ushort,int,uint,double,char,float | number | | decimal | userdata | | long,ulong | userdata/lua\_Integer\(lua53\) | | bytes\[\] | string | | bool | boolean | | string | string | ### 复杂数据类型 | C\#类型 | Lua类型 | | :--- | :--- | | LuaTable | table | | LuaFunction | function | | class或struct的实例 | userdata,table | | method,delegate | function | #### LuaTable C\#侧指明从Lua侧输入(包括C\#方法的输入参数或者Lua方法的返回值)LuaTable类型,则要求Lua侧为table。或者Lua侧的table,在C\#侧未指明类型的情况下转换成LuaTable。 #### LuaFunction C\#侧指明从Lua侧输入(包括C\#方法的输入参数或者Lua方法的返回值)LuaFunction类型,则要求Lua侧为function。或者Lua侧的function,在C\#侧未指明类型的情况下转换成LuaFunction。 #### LuaUserData 对应非C\# Managered对象的lua userdata。 #### class或struct的实例 从C\#传一个class或者struct的实例,将映射到Lua的userdata,并通过\_\_index访问该userdata的成员 C\#侧指明从Lua侧输入指定类型对象,Lua侧为该类型实例的userdata可以直接使用;如果该指明类型有默认构造函数,Lua侧是table则会自动转换,转换规则是:调用构造函数构造实例,并用table对应字段转换到c\#对应值后赋值各成员。 #### method, delegate 成员方法以及delegate都是对应lua侧的函数。 C\#侧的普通参数以及引用参数,对应lua侧函数参数;C\#侧的返回值对应于Lua的第一个返回值;引用参数和out参数则按序对应于Lua的第2到第N个参数。 ## 宏 ### HOTFIX\_ENABLE 打开hotfix功能。 ### NOT\_GEN\_WARNING 反射时打印warning。 ### GEN\_CODE\_MINIMIZE 以偏向减少代码段的方式生成代码。
xLua/docs/source/src/v1/guide/api.md/0
{ "file_path": "xLua/docs/source/src/v1/guide/api.md", "repo_id": "xLua", "token_count": 4410 }
1,946
<nav class="nav"> <div class="border"> <img src="<%- url_for('images/logo.png')%>" /> <button class="hiden-in-phone">V2.1</button> <button id="btn-menu" class="hiden-in-pc">菜单</button> <ul class="nav-link hiden-in-phone"> <!--li> <form id="search-form"> <input type="text" id="search-query" class="search-query"> </form> </li!--> <li><a href="https://github.com/Tencent/xLua" class="nav-link-li<%- page.path.match(/download/) ? ' current' : '' %>">下载项目</a></li> <li><a href="<%- url_for("/v1/guide/use.html") %>" class="nav-link-li<%- page.path.match(/use/) ? ' current' : '' %>">使用案例</a></li> <li><a href="<%- url_for("/v1/guide/version.html") %>" class="nav-link-li<%- page.path.match(/version/) ? ' current' : '' %>">更新记录</a></li> <li><a href="<%- url_for("/v1/guide/contribution.html") %>" class="nav-link-li<%- page.path.match(/contribution/) ? ' current' : '' %>">贡献指南</li> <li><a href="<%- url_for("/v1/guide/index.html") %>" class="nav-link-li<%- page.path.match(/index/) ? ' current' : '' %>">教程</a></li> <li><a href="<%- url_for("/") %>" class="nav-link-li<%- page.path.match(/\//) ? ' current' : '' %>">首页</a></li> </ul> </div> </nav> <div id="container" class="container clear"> <%- partial('partials/sidebar') %> <%- partial('partials/article') %> </div> <footer> <div> <p><%- theme.copyright %></p> <p><%- theme.copyright_desc %></p> </div> </footer> <script> var vm = new Vue({ el : '#container', data: { sub_nav : [ ] }, created:function(){ var obj = []; $("article h3").each(function(){ obj.push({name : $(this).find("a").attr("title") , href : "#"+$(this).attr("id") }); }); this.sub_nav = obj; } }); var isShow = false; $("nav").on("click","#btn-menu" , function(){ if(!isShow){ if($(document).scrollTop() > $(".sidebar").height() - 100){ $('html, body').animate({scrollTop:0} , 300, "swing",function(){ $(".sidebar").fadeIn(); $(".container").animate({"left" : "15rem"}, 500,"swing"); }); }else{ $(".sidebar").fadeIn(); $(".container").animate({"left" : "15rem"}, 500,"swing"); } }else{ $(".sidebar").fadeOut(); $(".container").animate({"left" : "0rem"}, 500,"swing"); } isShow = !isShow; }); $(".container").on("click" , "article" , function(){ if(isShow){ $(".sidebar").fadeOut(); $(".container").animate({"left" : "0rem"}, 500,"swing"); isShow = false; } }); </script>
xLua/docs/source/themes/catlib/layout/page.ejs/0
{ "file_path": "xLua/docs/source/themes/catlib/layout/page.ejs", "repo_id": "xLua", "token_count": 1414 }
1,947
/* (C) 2019 David Lettier lettier.com */ #version 150 uniform sampler2D baseTexture; uniform sampler2D refractionTexture; uniform sampler2D foamTexture; uniform sampler2D reflectionTexture; uniform sampler2D specularTexture; out vec4 fragColor; void main() { vec2 texSize = textureSize(baseTexture, 0).xy; vec2 texCoord = gl_FragCoord.xy / texSize; vec4 base = texture(baseTexture, texCoord); vec4 refraction = texture(refractionTexture, texCoord); vec4 foam = texture(foamTexture, texCoord); vec4 reflection = texture(reflectionTexture, texCoord); vec4 specular = texture(specularTexture, texCoord); fragColor = base; fragColor.rgb = mix(fragColor.rgb, refraction.rgb, clamp(refraction.a, 0.0, 1.0)); fragColor.rgb = mix(fragColor.rgb, reflection.rgb, clamp(reflection.a, 0.0, 1.0)); fragColor.rgb = mix(fragColor.rgb, foam.rgb, clamp(foam.a, 0.0, 1.0)); fragColor.rgb += (specular.rgb * clamp(specular.a, 0.0, 1.0)); }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/base-combine.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/base-combine.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 409 }
0
/* (C) 2019 David Lettier lettier.com */ #version 150 #define MAX_SIZE 5 #define MAX_KERNEL_SIZE ((MAX_SIZE * 2 + 1) * (MAX_SIZE * 2 + 1)) uniform sampler2D colorTexture; uniform vec2 parameters; out vec4 fragColor; vec2 texSize = textureSize(colorTexture, 0).xy; vec2 texCoord = gl_FragCoord.xy / texSize; int i = 0; int j = 0; int count = 0; vec3 valueRatios = vec3(0.3, 0.59, 0.11); float values[MAX_KERNEL_SIZE]; vec4 color = vec4(0.0); vec4 meanTemp = vec4(0.0); vec4 mean = vec4(0.0); float valueMean = 0.0; float variance = 0.0; float minVariance = -1.0; void findMean(int i0, int i1, int j0, int j1) { meanTemp = vec4(0); count = 0; for (i = i0; i <= i1; ++i) { for (j = j0; j <= j1; ++j) { color = texture ( colorTexture , (gl_FragCoord.xy + vec2(i, j)) / texSize ); meanTemp += color; values[count] = dot(color.rgb, valueRatios); count += 1; } } meanTemp.rgb /= count; valueMean = dot(meanTemp.rgb, valueRatios); for (i = 0; i < count; ++i) { variance += pow(values[i] - valueMean, 2); } variance /= count; if (variance < minVariance || minVariance <= -1) { mean = meanTemp; minVariance = variance; } } void main() { fragColor = texture(colorTexture, texCoord); int size = int(parameters.x); if (size <= 0) { return; } // Lower Left findMean(-size, 0, -size, 0); // Upper Right findMean(0, size, 0, size); // Upper Left findMean(-size, 0, 0, size); // Lower Right findMean(0, size, -size, 0); fragColor.rgb = mean.rgb; }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/kuwahara-filter.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/kuwahara-filter.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 765 }
1
/* (C) 2019 David Lettier lettier.com */ #version 150 uniform mat4 lensProjection; uniform sampler2D positionFromTexture; uniform sampler2D positionToTexture; uniform sampler2D normalFromTexture; uniform vec2 rior; uniform vec2 enabled; out vec4 fragColor; void main() { float maxDistance = 5; float resolution = 0.3; int steps = 5; float thickness = 0.5; vec2 texSize = textureSize(positionFromTexture, 0).xy; vec2 texCoord = gl_FragCoord.xy / texSize; vec4 uv = vec4(texCoord.xy, 1, 1); vec4 positionFrom = texture(positionFromTexture, texCoord); if (positionFrom.w <= 0 || enabled.x != 1) { fragColor = uv; return; } vec3 unitPositionFrom = normalize(positionFrom.xyz); vec3 normalFrom = normalize(texture(normalFromTexture, texCoord).xyz); vec3 pivot = normalize(refract(unitPositionFrom, normalFrom, rior.x)); vec4 positionTo = positionFrom; vec4 startView = vec4(positionFrom.xyz + (pivot * 0), 1); vec4 endView = vec4(positionFrom.xyz + (pivot * maxDistance), 1); vec4 startFrag = startView; startFrag = lensProjection * startFrag; startFrag.xyz /= startFrag.w; startFrag.xy = startFrag.xy * 0.5 + 0.5; startFrag.xy *= texSize; vec4 endFrag = endView; endFrag = lensProjection * endFrag; endFrag.xyz /= endFrag.w; endFrag.xy = endFrag.xy * 0.5 + 0.5; endFrag.xy *= texSize; vec2 frag = startFrag.xy; uv.xy = frag / texSize; float deltaX = endFrag.x - startFrag.x; float deltaY = endFrag.y - startFrag.y; float useX = abs(deltaX) >= abs(deltaY) ? 1 : 0; float delta = mix(abs(deltaY), abs(deltaX), useX) * clamp(resolution, 0, 1); vec2 increment = vec2(deltaX, deltaY) / max(delta, 0.001); float search0 = 0; float search1 = 0; int hit0 = 0; int hit1 = 0; float viewDistance = startView.y; float depth = thickness; float i = 0; for (i = 0; i < int(delta); ++i) { frag += increment; uv.xy = frag / texSize; positionTo = texture(positionToTexture, uv.xy); search1 = mix ( (frag.y - startFrag.y) / deltaY , (frag.x - startFrag.x) / deltaX , useX ); search1 = clamp(search1, 0, 1); viewDistance = (startView.y * endView.y) / mix(endView.y, startView.y, search1); depth = viewDistance - positionTo.y; if (depth > 0 && depth < thickness) { hit0 = 1; break; } else { search0 = search1; } } search1 = search0 + ((search1 - search0) / 2); steps *= hit0; for (i = 0; i < steps; ++i) { frag = mix(startFrag.xy, endFrag.xy, search1); uv.xy = frag / texSize; positionTo = texture(positionToTexture, uv.xy); viewDistance = (startView.y * endView.y) / mix(endView.y, startView.y, search1); depth = viewDistance - positionTo.y; if (depth > 0 && depth < thickness) { hit1 = 1; search1 = search0 + ((search1 - search0) / 2); } else { float temp = search1; search1 = search1 + ((search1 - search0) / 2); search0 = temp; } } float visibility = hit1 * positionTo.w * ( 1 - max ( dot(-unitPositionFrom, pivot) , 0 ) ) * (uv.x < 0 || uv.x > 1 ? 0 : 1) * (uv.y < 0 || uv.y > 1 ? 0 : 1); visibility = clamp(visibility, 0, 1); fragColor = vec4(mix(texCoord.xy, uv.xy, visibility), 1, 1); }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/screen-space-refraction.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/screen-space-refraction.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 1540 }
2
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang=""> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" /> <meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:title" content="Cel Shading | 3D Game Shaders For Beginners" /> <meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:title" content="Cel Shading | 3D Game Shaders For Beginners" /> <meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:card" content="summary_large_image" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta name="author" content="David Lettier" /> <title>Cel Shading | 3D Game Shaders For Beginners</title> <style> code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} </style> <style> code.sourceCode > span { display: inline-block; line-height: 1.25; } code.sourceCode > span { color: inherit; text-decoration: inherit; } code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode { white-space: pre; position: relative; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { code.sourceCode { white-space: pre-wrap; } code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; background-color: #232629; color: #7a7c7d; } pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; } div.sourceCode { color: #cfcfc2; background-color: #232629; } @media screen { code.sourceCode > span > a:first-child::before { text-decoration: underline; } } code span. { color: #cfcfc2; } /* Normal */ code span.al { color: #95da4c; } /* Alert */ code span.an { color: #3f8058; } /* Annotation */ code span.at { color: #2980b9; } /* Attribute */ code span.bn { color: #f67400; } /* BaseN */ code span.bu { color: #7f8c8d; } /* BuiltIn */ code span.cf { color: #fdbc4b; } /* ControlFlow */ code span.ch { color: #3daee9; } /* Char */ code span.cn { color: #27aeae; } /* Constant */ code span.co { color: #7a7c7d; } /* Comment */ code span.cv { color: #7f8c8d; } /* CommentVar */ code span.do { color: #a43340; } /* Documentation */ code span.dt { color: #2980b9; } /* DataType */ code span.dv { color: #f67400; } /* DecVal */ code span.er { color: #da4453; } /* Error */ code span.ex { color: #0099ff; } /* Extension */ code span.fl { color: #f67400; } /* Float */ code span.fu { color: #8e44ad; } /* Function */ code span.im { color: #27ae60; } /* Import */ code span.in { color: #c45b00; } /* Information */ code span.kw { color: #cfcfc2; } /* Keyword */ code span.op { color: #cfcfc2; } /* Operator */ code span.ot { color: #27ae60; } /* Other */ code span.pp { color: #27ae60; } /* Preprocessor */ code span.re { color: #2980b9; } /* RegionMarker */ code span.sc { color: #3daee9; } /* SpecialChar */ code span.ss { color: #da4453; } /* SpecialString */ code span.st { color: #f44f4f; } /* String */ code span.va { color: #27aeae; } /* Variable */ code span.vs { color: #da4453; } /* VerbatimString */ code span.wa { color: #da4453; } /* Warning */ </style> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script> <![endif]--> <link rel="stylesheet" href="style.css" /> </head> <body> <p><a href="rim-lighting.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="normal-mapping.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> <h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1> <h2 id="cel-shading">Cel Shading</h2> <p align="center"> <img src="https://i.imgur.com/W80Ke1y.gif" alt="Cel Shaded" title="Cel Shaded"> </p> <p>Cel shading is a technique to make 3D objects look 2D or flat. In 2D, you can make an object look 3D by applying a smooth gradient. However, with cel shading, you're breaking up the gradients into abrupt transitions. Typically there is only one transition where the shading goes from fully lit to fully shadowed. When combined with <a href="outlining.html">outlining</a>, cel shading can really sell the 2D cartoon look.</p> <h2 id="diffuse">Diffuse</h2> <div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a> <span class="co">// ...</span></span> <span id="cb1-2"><a href="#cb1-2"></a></span> <span id="cb1-3"><a href="#cb1-3"></a> <span class="dt">float</span> diffuseIntensity = max(dot(normal, unitLightDirection), <span class="fl">0.0</span>);</span> <span id="cb1-4"><a href="#cb1-4"></a> diffuseIntensity = step(<span class="fl">0.1</span>, diffuseIntensity);</span> <span id="cb1-5"><a href="#cb1-5"></a></span> <span id="cb1-6"><a href="#cb1-6"></a> <span class="co">// ...</span></span></code></pre></div> <p>Revisiting the <a href="lighting.html#diffuse">lighting</a> model, modify the <code>diffuseIntensity</code> such that it is either zero or one.</p> <p align="center"> <img src="https://i.imgur.com/lyLweFc.png" alt="Step Function" title="Step Function"> </p> <p>The <code>step</code> function returns zero if the input is less than the edge and one otherwise.</p> <p align="center"> <img src="https://i.imgur.com/EI6QJ60.png" alt="Steps Function" title="Steps Function"> </p> <div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a> <span class="co">// ...</span></span> <span id="cb2-2"><a href="#cb2-2"></a></span> <span id="cb2-3"><a href="#cb2-3"></a> <span class="cf">if</span> (diffuseIntensity &gt;= <span class="fl">0.8</span>) { diffuseIntensity = <span class="fl">1.0</span>; }</span> <span id="cb2-4"><a href="#cb2-4"></a> <span class="cf">else</span> <span class="cf">if</span> (diffuseIntensity &gt;= <span class="fl">0.6</span>) { diffuseIntensity = <span class="fl">0.6</span>; }</span> <span id="cb2-5"><a href="#cb2-5"></a> <span class="cf">else</span> <span class="cf">if</span> (diffuseIntensity &gt;= <span class="fl">0.3</span>) { diffuseIntensity = <span class="fl">0.3</span>; }</span> <span id="cb2-6"><a href="#cb2-6"></a> <span class="cf">else</span> { diffuseIntensity = <span class="fl">0.0</span>; }</span> <span id="cb2-7"><a href="#cb2-7"></a></span> <span id="cb2-8"><a href="#cb2-8"></a> <span class="co">// ...</span></span></code></pre></div> <p>If you would like to have a few steps or transitions, you can perform something like the above.</p> <p align="center"> <img src="https://i.imgur.com/7KK65mi.png" alt="Step Texture" title="Step Texture"> </p> <div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a> <span class="co">// ...</span></span> <span id="cb3-2"><a href="#cb3-2"></a></span> <span id="cb3-3"><a href="#cb3-3"></a> diffuseIntensity = texture(steps, vec2(diffuseIntensity, <span class="fl">0.0</span>)).r;</span> <span id="cb3-4"><a href="#cb3-4"></a></span> <span id="cb3-5"><a href="#cb3-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>Another approach is to put your step values into a texture with the transitions going from darker to lighter. Using the <code>diffuseIntensity</code> as a U coordinate, it will automatically transform itself.</p> <h2 id="specular">Specular</h2> <div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1"></a></span> <span id="cb4-2"><a href="#cb4-2"></a> <span class="co">// ...</span></span> <span id="cb4-3"><a href="#cb4-3"></a></span> <span id="cb4-4"><a href="#cb4-4"></a> <span class="dt">float</span> specularIntensity = clamp(dot(normal, halfwayDirection), <span class="fl">0.0</span>, <span class="fl">1.0</span>);</span> <span id="cb4-5"><a href="#cb4-5"></a> specularIntensity = step(<span class="fl">0.98</span>, specularIntensity);</span> <span id="cb4-6"><a href="#cb4-6"></a></span> <span id="cb4-7"><a href="#cb4-7"></a> <span class="co">// ...</span></span></code></pre></div> <p>Using the <code>step</code> function again, set the <code>specularIntensity</code> to be either zero or one. You can also use one of the other approaches described up above for the specular highlight as well. After you've altered the <code>specularIntensity</code>, the rest of the lighting calculations are the same.</p> <h3 id="source">Source</h3> <ul> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/base.vert" target="_blank" rel="noopener noreferrer">base.vert</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/base.frag" target="_blank" rel="noopener noreferrer">base.frag</a></li> </ul> <h2 id="copyright">Copyright</h2> <p>(C) 2020 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p> <p><a href="rim-lighting.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="normal-mapping.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> </body> </html>
3d-game-shaders-for-beginners/docs/cel-shading.html/0
{ "file_path": "3d-game-shaders-for-beginners/docs/cel-shading.html", "repo_id": "3d-game-shaders-for-beginners", "token_count": 4612 }
3
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang=""> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" /> <meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:title" content="Motion Blur | 3D Game Shaders For Beginners" /> <meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:title" content="Motion Blur | 3D Game Shaders For Beginners" /> <meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:card" content="summary_large_image" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta name="author" content="David Lettier" /> <title>Motion Blur | 3D Game Shaders For Beginners</title> <style> code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} </style> <style> code.sourceCode > span { display: inline-block; line-height: 1.25; } code.sourceCode > span { color: inherit; text-decoration: inherit; } code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode { white-space: pre; position: relative; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { code.sourceCode { white-space: pre-wrap; } code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; background-color: #232629; color: #7a7c7d; } pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; } div.sourceCode { color: #cfcfc2; background-color: #232629; } @media screen { code.sourceCode > span > a:first-child::before { text-decoration: underline; } } code span. { color: #cfcfc2; } /* Normal */ code span.al { color: #95da4c; } /* Alert */ code span.an { color: #3f8058; } /* Annotation */ code span.at { color: #2980b9; } /* Attribute */ code span.bn { color: #f67400; } /* BaseN */ code span.bu { color: #7f8c8d; } /* BuiltIn */ code span.cf { color: #fdbc4b; } /* ControlFlow */ code span.ch { color: #3daee9; } /* Char */ code span.cn { color: #27aeae; } /* Constant */ code span.co { color: #7a7c7d; } /* Comment */ code span.cv { color: #7f8c8d; } /* CommentVar */ code span.do { color: #a43340; } /* Documentation */ code span.dt { color: #2980b9; } /* DataType */ code span.dv { color: #f67400; } /* DecVal */ code span.er { color: #da4453; } /* Error */ code span.ex { color: #0099ff; } /* Extension */ code span.fl { color: #f67400; } /* Float */ code span.fu { color: #8e44ad; } /* Function */ code span.im { color: #27ae60; } /* Import */ code span.in { color: #c45b00; } /* Information */ code span.kw { color: #cfcfc2; } /* Keyword */ code span.op { color: #cfcfc2; } /* Operator */ code span.ot { color: #27ae60; } /* Other */ code span.pp { color: #27ae60; } /* Preprocessor */ code span.re { color: #2980b9; } /* RegionMarker */ code span.sc { color: #3daee9; } /* SpecialChar */ code span.ss { color: #da4453; } /* SpecialString */ code span.st { color: #f44f4f; } /* String */ code span.va { color: #27aeae; } /* Variable */ code span.vs { color: #da4453; } /* VerbatimString */ code span.wa { color: #da4453; } /* Warning */ </style> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script> <![endif]--> <link rel="stylesheet" href="style.css" /> </head> <body> <p><a href="ssao.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="chromatic-aberration.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> <h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1> <h2 id="motion-blur">Motion Blur</h2> <p align="center"> <img src="https://i.imgur.com/eTnhpLr.gif" alt="Motion Blur" title="Motion Blur"> </p> <p>To really sell the illusion of speed, you can do no better than motion blur. From high speed car chases to moving at warp speed, motion blur greatly improves the look and feel of fast moving objects.</p> <p>There are a few ways to implement motion blur as a screen space technique. The less involved implementation will only blur the scene in relation to the camera's movements while the more involved version will blur any moving objects even with the camera remaining still. The less involved technique is described below but the principle is the same.</p> <h3 id="textures">Textures</h3> <div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a>uniform sampler2D positionTexture;</span> <span id="cb1-2"><a href="#cb1-2"></a>uniform sampler2D colorTexture;</span> <span id="cb1-3"><a href="#cb1-3"></a></span> <span id="cb1-4"><a href="#cb1-4"></a><span class="co">// ...</span></span></code></pre></div> <p>The input textures needed are the vertex positions in view space and the scene's colors. Refer back to <a href="ssao.html#vertex-positions">SSAO</a> for acquiring the vertex positions.</p> <h3 id="matrices">Matrices</h3> <div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a><span class="co">// ...</span></span> <span id="cb2-2"><a href="#cb2-2"></a></span> <span id="cb2-3"><a href="#cb2-3"></a>uniform mat4 previousViewWorldMat;</span> <span id="cb2-4"><a href="#cb2-4"></a>uniform mat4 worldViewMat;</span> <span id="cb2-5"><a href="#cb2-5"></a>uniform mat4 lensProjection;</span> <span id="cb2-6"><a href="#cb2-6"></a></span> <span id="cb2-7"><a href="#cb2-7"></a><span class="co">// ...</span></span></code></pre></div> <p>The motion blur technique determines the blur direction by comparing the previous frame's vertex positions with the current frame's vertex positions. To do this, you'll need the previous frame's view-to-world matrix, the current frame's world-to-view matrix, and the camera lens' projection matrix.</p> <h3 id="parameters">Parameters</h3> <div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a><span class="co">// ...</span></span> <span id="cb3-2"><a href="#cb3-2"></a></span> <span id="cb3-3"><a href="#cb3-3"></a>uniform vec2 parameters;</span> <span id="cb3-4"><a href="#cb3-4"></a></span> <span id="cb3-5"><a href="#cb3-5"></a><span class="co">// ...</span></span> <span id="cb3-6"><a href="#cb3-6"></a></span> <span id="cb3-7"><a href="#cb3-7"></a><span class="dt">void</span> main() {</span> <span id="cb3-8"><a href="#cb3-8"></a> <span class="dt">int</span> size = <span class="dt">int</span>(parameters.x);</span> <span id="cb3-9"><a href="#cb3-9"></a> <span class="dt">float</span> separation = parameters.y;</span> <span id="cb3-10"><a href="#cb3-10"></a></span> <span id="cb3-11"><a href="#cb3-11"></a><span class="co">// ...</span></span></code></pre></div> <p>The adjustable parameters are <code>size</code> and <code>separation</code>. <code>size</code> controls how many samples are taken along the blur direction. Increasing <code>size</code> increases the amount of blur at the cost of performance. <code>separation</code> controls how spread out the samples are along the blur direction. Increasing <code>separation</code> increases the amount of blur at the cost of accuracy.</p> <h3 id="blur-direction">Blur Direction</h3> <div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1"></a> <span class="co">// ...</span></span> <span id="cb4-2"><a href="#cb4-2"></a></span> <span id="cb4-3"><a href="#cb4-3"></a> vec2 texSize = textureSize(colorTexture, <span class="dv">0</span>).xy;</span> <span id="cb4-4"><a href="#cb4-4"></a> vec2 texCoord = gl_FragCoord.xy / texSize;</span> <span id="cb4-5"><a href="#cb4-5"></a></span> <span id="cb4-6"><a href="#cb4-6"></a> vec4 position1 = texture(positionTexture, texCoord);</span> <span id="cb4-7"><a href="#cb4-7"></a> vec4 position0 = worldViewMat * previousViewWorldMat * position1;</span> <span id="cb4-8"><a href="#cb4-8"></a></span> <span id="cb4-9"><a href="#cb4-9"></a> <span class="co">// ...</span></span></code></pre></div> <p>To determine which way to blur this fragment, you'll need to know where things were last frame and where things are this frame. To figure out where things are now, sample the current vertex position. To figure out where things were last frame, transform the current position from view space to world space, using the previous frame's view-to-world matrix, and then transform it back to view space from world space using this frame's world-to-view matrix. This transformed position is this fragment's previous interpolated vertex position.</p> <p align="center"> <img src="https://i.imgur.com/oQqdxM9.gif" alt="Position Projection" title="Position Projection"> </p> <div class="sourceCode" id="cb5"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb5-1"><a href="#cb5-1"></a> <span class="co">// ...</span></span> <span id="cb5-2"><a href="#cb5-2"></a></span> <span id="cb5-3"><a href="#cb5-3"></a> position0 = lensProjection * position0;</span> <span id="cb5-4"><a href="#cb5-4"></a> position0.xyz /= position0.w;</span> <span id="cb5-5"><a href="#cb5-5"></a> position0.xy = position0.xy * <span class="fl">0.5</span> + <span class="fl">0.5</span>;</span> <span id="cb5-6"><a href="#cb5-6"></a></span> <span id="cb5-7"><a href="#cb5-7"></a> position1 = lensProjection * position1;</span> <span id="cb5-8"><a href="#cb5-8"></a> position1.xyz /= position1.w;</span> <span id="cb5-9"><a href="#cb5-9"></a> position1.xy = position1.xy * <span class="fl">0.5</span> + <span class="fl">0.5</span>;</span> <span id="cb5-10"><a href="#cb5-10"></a></span> <span id="cb5-11"><a href="#cb5-11"></a> <span class="co">// ...</span></span></code></pre></div> <p>Now that you have the current and previous positions, transform them to screen space. With the positions in screen space, you can trace out the 2D direction you'll need to blur the onscreen image.</p> <div class="sourceCode" id="cb6"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb6-1"><a href="#cb6-1"></a> <span class="co">// ...</span></span> <span id="cb6-2"><a href="#cb6-2"></a></span> <span id="cb6-3"><a href="#cb6-3"></a> <span class="co">// position1.xy = position0.xy + direction;</span></span> <span id="cb6-4"><a href="#cb6-4"></a> vec2 direction = position1.xy - position0.xy;</span> <span id="cb6-5"><a href="#cb6-5"></a></span> <span id="cb6-6"><a href="#cb6-6"></a> <span class="cf">if</span> (length(direction) &lt;= <span class="fl">0.0</span>) { <span class="cf">return</span>; }</span> <span id="cb6-7"><a href="#cb6-7"></a></span> <span id="cb6-8"><a href="#cb6-8"></a> <span class="co">// ...</span></span></code></pre></div> <p>The blur direction goes from the previous position to the current position.</p> <h3 id="blurring">Blurring</h3> <div class="sourceCode" id="cb7"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb7-1"><a href="#cb7-1"></a> <span class="co">// ...</span></span> <span id="cb7-2"><a href="#cb7-2"></a></span> <span id="cb7-3"><a href="#cb7-3"></a> fragColor = texture(colorTexture, texCoord);</span> <span id="cb7-4"><a href="#cb7-4"></a></span> <span id="cb7-5"><a href="#cb7-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>Sample the current fragment's color. This will be the first of the colors blurred together.</p> <div class="sourceCode" id="cb8"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb8-1"><a href="#cb8-1"></a> <span class="co">// ...</span></span> <span id="cb8-2"><a href="#cb8-2"></a></span> <span id="cb8-3"><a href="#cb8-3"></a> direction.xy *= separation;</span> <span id="cb8-4"><a href="#cb8-4"></a></span> <span id="cb8-5"><a href="#cb8-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>Multiply the direction vector by the separation.</p> <div class="sourceCode" id="cb9"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb9-1"><a href="#cb9-1"></a> <span class="co">// ...</span></span> <span id="cb9-2"><a href="#cb9-2"></a></span> <span id="cb9-3"><a href="#cb9-3"></a> vec2 forward = texCoord;</span> <span id="cb9-4"><a href="#cb9-4"></a> vec2 backward = texCoord;</span> <span id="cb9-5"><a href="#cb9-5"></a></span> <span id="cb9-6"><a href="#cb9-6"></a> <span class="co">// ...</span></span></code></pre></div> <p>For a more seamless blur, sample in the direction of the blur and in the opposite direction of the blur. For now, set the two vectors to the fragment's UV coordinate.</p> <div class="sourceCode" id="cb10"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb10-1"><a href="#cb10-1"></a> <span class="co">// ...</span></span> <span id="cb10-2"><a href="#cb10-2"></a></span> <span id="cb10-3"><a href="#cb10-3"></a> <span class="dt">float</span> count = <span class="fl">1.0</span>;</span> <span id="cb10-4"><a href="#cb10-4"></a></span> <span id="cb10-5"><a href="#cb10-5"></a> <span class="co">// ...</span></span></code></pre></div> <p><code>count</code> is used to average all of the samples taken. It starts at one since you've already sampled the current fragment's color.</p> <div class="sourceCode" id="cb11"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb11-1"><a href="#cb11-1"></a> <span class="co">// ...</span></span> <span id="cb11-2"><a href="#cb11-2"></a></span> <span id="cb11-3"><a href="#cb11-3"></a> <span class="cf">for</span> (<span class="dt">int</span> i = <span class="dv">0</span>; i &lt; size; ++i) {</span> <span id="cb11-4"><a href="#cb11-4"></a> forward += direction;</span> <span id="cb11-5"><a href="#cb11-5"></a> backward -= direction;</span> <span id="cb11-6"><a href="#cb11-6"></a></span> <span id="cb11-7"><a href="#cb11-7"></a> fragColor +=</span> <span id="cb11-8"><a href="#cb11-8"></a> texture</span> <span id="cb11-9"><a href="#cb11-9"></a> ( colorTexture</span> <span id="cb11-10"><a href="#cb11-10"></a> , forward</span> <span id="cb11-11"><a href="#cb11-11"></a> );</span> <span id="cb11-12"><a href="#cb11-12"></a> fragColor +=</span> <span id="cb11-13"><a href="#cb11-13"></a> texture</span> <span id="cb11-14"><a href="#cb11-14"></a> ( colorTexture</span> <span id="cb11-15"><a href="#cb11-15"></a> , backward</span> <span id="cb11-16"><a href="#cb11-16"></a> );</span> <span id="cb11-17"><a href="#cb11-17"></a></span> <span id="cb11-18"><a href="#cb11-18"></a> count += <span class="fl">2.0</span>;</span> <span id="cb11-19"><a href="#cb11-19"></a> }</span> <span id="cb11-20"><a href="#cb11-20"></a></span> <span id="cb11-21"><a href="#cb11-21"></a> <span class="co">// ...</span></span></code></pre></div> <p>Sample the screen's colors both in the forward and backward direction of the blur. Be sure to add these samples together as you travel along.</p> <div class="sourceCode" id="cb12"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb12-1"><a href="#cb12-1"></a> <span class="co">// ...</span></span> <span id="cb12-2"><a href="#cb12-2"></a></span> <span id="cb12-3"><a href="#cb12-3"></a> fragColor /= count;</span> <span id="cb12-4"><a href="#cb12-4"></a>}</span></code></pre></div> <p>The final fragment color is the average color of the samples taken.</p> <h3 id="source">Source</h3> <ul> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/basic.vert" target="_blank" rel="noopener noreferrer">basic.vert</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/position.frag" target="_blank" rel="noopener noreferrer">position.frag</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/motion-blur.frag" target="_blank" rel="noopener noreferrer">motion-blur.frag</a></li> </ul> <h2 id="copyright">Copyright</h2> <p>(C) 2020 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p> <p><a href="ssao.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="chromatic-aberration.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> </body> </html>
3d-game-shaders-for-beginners/docs/motion-blur.html/0
{ "file_path": "3d-game-shaders-for-beginners/docs/motion-blur.html", "repo_id": "3d-game-shaders-for-beginners", "token_count": 7200 }
4
[:arrow_backward:](lighting.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](fresnel-factor.md) # 3D Game Shaders For Beginners ## Blinn-Phong <p align="center"> <img src="https://i.imgur.com/CFWEeGK.gif" alt="Blinn-Phong" title="Blinn-Phong"> </p> Blinn-Phong is a slight adjustment of the Phong model you saw in the [lighting](lighting.md) section. It provides more plausible or realistic specular reflections. You'll notice that Blinn-Phong produces elliptical or elongated specular reflections versus the spherical specular reflections produced by the Phong model. In certain cases, Blinn-Phong can be more efficient to calculate than Phong. ```c // ... vec3 light = normal(lightPosition.xyz - vertexPosition.xyz); vec3 eye = normalize(-vertexPosition.xyz); vec3 halfway = normalize(light + eye); // ... ``` Instead of computing the reflection vector, compute the halfway or half angle vector. This vector is between the view/camera/eye and light direction vector. <p align="center"> <img src="https://i.imgur.com/vtqd1Ox.gif" alt="Blinn-Phong vs Phong" title="Blinn-Phong vs Phong"> </p> ```c // ... float specularIntensity = dot(normal, halfway); // ... ``` The specular intensity is now the dot product of the normal and halfway vector. In the Phong model, it is the dot product of the reflection and view vector. <p align="center"> <img src="https://i.imgur.com/WZQqxEH.png" alt="Full specular intensity." title="Full specular intensity."> </p> The half angle vector (magenta arrow) will point in the same direction as the normal (green arrow) when the view vector (orange arrow) points in the same direction as the reflection vector (magenta arrow). In this case, both the Blinn-Phong and Phong specular intensity will be one. <p align="center"> <img src="https://i.imgur.com/kiSdJzt.png" alt="Blinn-Phong vs Phong" title="Blinn-Phong vs Phong"> </p> In other cases, the specular intensity for Blinn-Phong will be greater than zero while the specular intensity for Phong will be zero. ### Source - [main.cxx](../demonstration/src/main.cxx) - [base.vert](../demonstration/shaders/vertex/base.vert) - [base.frag](../demonstration/shaders/fragment/base.frag) ## Copyright (C) 2020 David Lettier <br> [lettier.com](https://www.lettier.com) [:arrow_backward:](lighting.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](fresnel-factor.md)
3d-game-shaders-for-beginners/sections/blinn-phong.md/0
{ "file_path": "3d-game-shaders-for-beginners/sections/blinn-phong.md", "repo_id": "3d-game-shaders-for-beginners", "token_count": 857 }
5
[:arrow_backward:](texturing.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](blinn-phong.md) # 3D Game Shaders For Beginners ## Lighting <p align="center"> <img src="https://i.imgur.com/zQrA8tr.gif" alt="Lighting" title="Lighting"> </p> Completing the lighting involves calculating and combining the ambient, diffuse, specular, and emission light aspects. The example code uses either Phong or Blinn-Phong lighting. ### Vertex ```c // ... uniform struct p3d_LightSourceParameters { vec4 color ; vec4 ambient ; vec4 diffuse ; vec4 specular ; vec4 position ; vec3 spotDirection ; float spotExponent ; float spotCutoff ; float spotCosCutoff ; float constantAttenuation ; float linearAttenuation ; float quadraticAttenuation ; vec3 attenuation ; sampler2DShadow shadowMap ; mat4 shadowViewMatrix ; } p3d_LightSource[NUMBER_OF_LIGHTS]; // ... ``` For every light, minus the ambient light, Panda3D gives you this convenient struct which is available to both the vertex and fragment shaders. The biggest convenience being the shadow map and shadow view matrix for transforming vertexes to shadow or light space. ```c // ... vertexPosition = p3d_ModelViewMatrix * p3d_Vertex; // ... for (int i = 0; i < p3d_LightSource.length(); ++i) { vertexInShadowSpaces[i] = p3d_LightSource[i].shadowViewMatrix * vertexPosition; } // ... ``` Starting in the vertex shader, you'll need to transform and output the vertex from view space to shadow or light space for each light in your scene. You'll need this later in the fragment shader in order to render the shadows. Shadow or light space is where every coordinate is relative to the light position (the light is the origin). ### Fragment The fragment shader is where most of the lighting calculations take place. #### Material ```c // ... uniform struct { vec4 ambient ; vec4 diffuse ; vec4 emission ; vec3 specular ; float shininess ; } p3d_Material; // ... ``` Panda3D gives us the material (in the form of a struct) for the mesh or model you are currently rendering. #### Multiple Lights ```c // ... vec4 diffuse = vec4(0.0, 0.0, 0.0, diffuseTex.a); vec4 specular = vec4(0.0, 0.0, 0.0, diffuseTex.a); // ... ``` Before you loop through the scene's lights, create an accumulator for both the diffuse and specular colors. ```c // ... for (int i = 0; i < p3d_LightSource.length(); ++i) { // ... } // ... ``` Now you can loop through the lights, calculating the diffuse and specular colors for each one. #### Light Related Vectors <p align="center"> <img src="https://i.imgur.com/0pzNh5d.gif" alt="Phong Lighting Model" title="Phong Lighting Model"> </p> Here you see the four major vectors you'll need to calculate the diffuse and specular colors contributed by each light. The light direction vector is the light blue arrow pointing to the light. The normal vector is the green arrow standing straight up. The reflection vector is the dark blue arrow mirroring the light direction vector. The eye or view vector is the orange arrow pointing towards the camera. ```c // ... vec3 lightDirection = p3d_LightSource[i].position.xyz - vertexPosition.xyz * p3d_LightSource[i].position.w; // ... ``` The light direction is from the vertex's position to the light's position. Panda3D sets `p3d_LightSource[i].position.w` to zero if this is a directional light. Directional lights do not have a position as they only have a direction. So if this is a directional light, the light direction will be the negative or opposite direction of the light as Panda3D sets `p3d_LightSource[i].position.xyz` to be `-direction` for directional lights. ```c // ... normal = normalize(vertexNormal); // ... ``` You'll need the vertex normal to be a unit vector. Unit vectors have a length of magnitude of one. ```c // ... vec3 unitLightDirection = normalize(lightDirection); vec3 eyeDirection = normalize(-vertexPosition.xyz); vec3 reflectedDirection = normalize(-reflect(unitLightDirection, normal)); // ... ``` Next you'll need three more vectors. You'll need to take the dot product involving the light direction so its best to normalize it. This gives it a distance or magnitude of one (unit vector). The eye direction is the opposite of the vertex/fragment position since the vertex/fragment position is relative to the camera's position. Remember that the vertex/fragment position is in view space. So instead of going from the camera (eye) to the vertex/fragment, you go from the vertex/fragment to the eye (camera). The [reflection vector](http://asawicki.info/news_1301_reflect_and_refract_functions.html) is a reflection of the light direction at the surface normal. As the light "ray" hits the surface, it bounces off at the same angle it came in at. The angle between the light direction vector and the normal is known as the "angle of incidence". The angle between the reflection vector and the normal is known as the "angle of reflection". You'll have to negate the reflected light vector as it needs to point in the same direction as the eye vector. Remember the eye direction is from the vertex/fragment to the camera position. You'll use the reflection vector to calculate the intensity of the specular highlight. #### Diffuse ```c // ... float diffuseIntensity = dot(normal, unitLightDirection); if (diffuseIntensity < 0.0) { continue; } // ... ``` The diffuse intensity is the dot product between the surface normal and the unit vector light direction. The dot product can range from negative one to one. If both vectors point in the same direction, the intensity is one. Any other case will be less than one. <p align="center"> <img src="https://i.imgur.com/Nb78z96.gif" alt="The light direction versus the normal direction." title="The light direction versus the normal direction."> </p> As the light vector approaches the same direction as the normal, the diffuse intensity approaches one. ```c // ... if (diffuseIntensity < 0.0) { continue; } // ... ``` If the diffuse intensity is zero or less, move on to the next light. ```c // ... vec4 diffuseTemp = vec4 ( clamp ( diffuseTex.rgb * p3d_LightSource[i].diffuse.rgb * diffuseIntensity , 0 , 1 ) , diffuseTex.a ); diffuseTemp = clamp(diffuseTemp, vec4(0), diffuseTex); // ... ``` You can now calculate the diffuse color contributed by this light. If the diffuse intensity is one, the diffuse color will be a mix between the diffuse texture color and the lights color. Any other intensity will cause the diffuse color to be darker. Notice how I clamp the diffuse color to be only as bright as the diffuse texture color is. This will protect the scene from being over exposed. When creating your diffuse textures, make sure to create them as if they were fully lit. #### Specular After diffuse, comes specular. <p align="center"> <img src="https://i.imgur.com/FnOhXxv.gif" alt="Specular Intensity" title="Specular Intensity"> </p> ```c // ... float specularIntensity = max(dot(reflectedDirection, eyeDirection), 0); vec4 specularTemp = clamp ( vec4(p3d_Material.specular, 1) * p3d_LightSource[i].specular * pow ( specularIntensity , p3d_Material.shininess ) , 0 , 1 ); // ... ``` The specular intensity is the dot product between the eye vector and the reflection vector. As with the diffuse intensity, if the two vectors point in the same direction, the specular intensity is one. Any other intensity will diminish the amount of specular color contributed by this light. <p align="center"> <img src="https://i.imgur.com/4r6wqLP.gif" alt="Shininess" title="Shininess"> </p> The material shininess determines how spread out the specular highlight is. This is typically set in a modeling program like Blender. In Blender it's known as the specular hardness. #### Spotlights ```c // ... float unitLightDirectionDelta = dot ( normalize(p3d_LightSource[i].spotDirection) , -unitLightDirection ); if (unitLightDirectionDelta < p3d_LightSource[i].spotCosCutoff) { continue; } // ... } ``` This snippet keeps fragments outside of a spotlight's cone or frustum from being affected by the light. Fortunately, Panda3D [sets up](https://github.com/panda3d/panda3d/blob/daa57733cb9b4ccdb23e28153585e8e20b5ccdb5/panda/src/display/graphicsStateGuardian.cxx#L1705) `spotDirection` and `spotCosCutoff` to also work for directional lights and points lights. Spotlights have both a position and direction. However, directional lights only have a direction and point lights only have a position. Still, this code works for all three lights avoiding the need for noisy if statements. ```c // ... , -unitLightDirection // ... ``` You must negate `unitLightDirection`. `unitLightDirection` goes from the fragment to the spotlight and you need it to go from the spotlight to the fragment since the `spotDirection` goes directly down the center of the spotlight's frustum some distance away from the spotlight's position. ```c spotCosCutoff = cosine(0.5 * spotlightLensFovAngle); ``` For a spotlight, if the dot product between the fragment-to-light vector and the spotlight's direction vector is less than the cosine of half the spotlight's field of view angle, the shader disregards this light's influence. For directional lights and point lights, Panda3D sets `spotCosCutoff` to negative one. Recall that the dot product ranges from negative one to one. So it doesn't matter what the `unitLightDirectionDelta` is because it will always be greater than or equal to negative one. ```c // ... diffuseTemp *= pow(unitLightDirectionDelta, p3d_LightSource[i].spotExponent); // ... ``` Like the `unitLightDirectionDelta` snippet, this snippet also works for all three light types. For spotlights, this will make the fragments brighter as you move closer to the center of the spotlight's frustum. For directional lights and point lights, `spotExponent` is zero. Recall that anything to the power of zero is one so the diffuse color is one times itself meaning it is unchanged. #### Shadows ```c // ... float shadow = textureProj ( p3d_LightSource[i].shadowMap , vertexInShadowSpaces[i] ); diffuseTemp.rgb *= shadow; specularTemp.rgb *= shadow; // ... ``` Panda3D makes applying shadows relatively easy by providing the shadow map and shadow transformation matrix for every scene light. To create the shadow transformation matrix yourself, you'll need to assemble a matrix that transforms view space coordinates to light space (coordinates are relative to the light's position). To create the shadow map yourself, you'll need to render the scene from the perspective of the light to a framebuffer texture. The framebuffer texture must hold the distances from the light to the fragments. This is known as a "depth map". Lastly, you'll need to manually give to your shader your DIY depth map as a `uniform sampler2DShadow` and your DIY shadow transformation matrix as a `uniform mat4`. At this point, you've recreated what Panda3D does for you automatically. The shadow snippet shown uses `textureProj` which is different from the `texure` function shown earlier. `textureProj` first divides `vertexInShadowSpaces[i].xyz` by `vertexInShadowSpaces[i].w`. After this, it uses `vertexInShadowSpaces[i].xy` to locate the depth stored in the shadow map. Next it uses `vertexInShadowSpaces[i].z` to compare this vertex's depth against the shadow map depth at `vertexInShadowSpaces[i].xy`. If the comparison passes, `textureProj` will return one. Otherwise, it will return zero. Zero meaning this vertex/fragment is in the shadow and one meaning this vertex/fragment is not in the shadow. `textureProj` can also return a value between zero and one depending on how the shadow map was set up. In this instance, `textureProj` performs multiple depth tests using neighboring depth values and returns a weighted average. This weighted average can give shadows a softer look. #### Attenuation <p align="center"> <img src="https://i.imgur.com/jyatr7l.png" alt="Attenuation" title="Attenuation"> </p> ```c // ... float lightDistance = length(lightDirection); float attenuation = 1 / ( p3d_LightSource[i].constantAttenuation + p3d_LightSource[i].linearAttenuation * lightDistance + p3d_LightSource[i].quadraticAttenuation * (lightDistance * lightDistance) ); diffuseTemp.rgb *= attenuation; specularTemp.rgb *= attenuation; // ... ``` The light's distance is just the magnitude or length of the light direction vector. Notice it's not using the normalized light direction as that distance would be one. You'll need the light distance to calculate the attenuation. Attenuation meaning the light's influence diminishes as you get further away from it. You can set `constantAttenuation`, `linearAttenuation`, and `quadraticAttenuation` to whatever values you would like. A good starting point is `constantAttenuation = 1`, `linearAttenuation = 0`, and `quadraticAttenuation = 1`. With these settings, the attenuation is one at the light's position and approaches zero as you move further away. #### Final Light Color ```c // ... diffuse += diffuseTemp; specular += specularTemp; // ... ``` To calculate the final light color, add the diffuse and specular together. Be sure to add this to the accumulator as you loop through the scene's lights. #### Ambient ```c // ... uniform sampler2D p3d_Texture1; // ... uniform struct { vec4 ambient ; } p3d_LightModel; // ... in vec2 diffuseCoord; // ... vec4 diffuseTex = texture(p3d_Texture1, diffuseCoord); // ... vec4 ambient = p3d_Material.ambient * p3d_LightModel.ambient * diffuseTex; // ... ``` The ambient component to the lighting model is based on the material's ambient color, the ambient light's color, and the diffuse texture color. There should only ever be one ambient light. Because of this, the ambient color calculation only needs to occur once. Contrast this with the diffuse and specular color which must be accumulated for each spot/directional/point light. When you reach [SSAO](ssao.md), you'll revisit the ambient color calculation. #### Putting It All Together ```c // ... vec4 outputColor = ambient + diffuse + specular + p3d_Material.emission; // ... ``` The final color is the sum of the ambient color, diffuse color, specular color, and the emission color. ### Source - [main.cxx](../demonstration/src/main.cxx) - [base.vert](../demonstration/shaders/vertex/base.vert) - [base.frag](../demonstration/shaders/fragment/base.frag) ## Copyright (C) 2019 David Lettier <br> [lettier.com](https://www.lettier.com) [:arrow_backward:](texturing.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](blinn-phong.md)
3d-game-shaders-for-beginners/sections/lighting.md/0
{ "file_path": "3d-game-shaders-for-beginners/sections/lighting.md", "repo_id": "3d-game-shaders-for-beginners", "token_count": 4756 }
6
[:arrow_backward:](render-to-texture.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](lighting.md) # 3D Game Shaders For Beginners ## Texturing <p align="center"> <img src="https://i.imgur.com/cqbgT8b.gif" alt="Diffuse Texture Only" title="Diffuse Texture Only"> </p> Texturing involves mapping some color or some other kind of vector to a fragment using UV coordinates. Both U and V range from zero to one. Each vertex gets a UV coordinate and this is outputted in the vertex shader. <p align="center"> <img src="https://i.imgur.com/JjAdNfk.png" alt="UV Interpolation" title="UV Interpolation"> </p> The fragment shader receives the UV coordinate interpolated. Interpolated meaning the UV coordinate for the fragment is somewhere between the UV coordinates for the vertexes that make up the triangle face. ### Vertex ```c #version 150 uniform mat4 p3d_ModelViewProjectionMatrix; in vec2 p3d_MultiTexCoord0; in vec4 p3d_Vertex; out vec2 texCoord; void main() { texCoord = p3d_MultiTexCoord0; gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex; } ``` Here you see the vertex shader outputting the texture coordinate to the fragment shader. Notice how it's a two dimensional vector. One dimension for U and one for V. ### Fragment ```c #version 150 uniform sampler2D p3d_Texture0; in vec2 texCoord; out vec2 fragColor; void main() { texColor = texture(p3d_Texture0, texCoord); fragColor = texColor; } ``` Here you see the fragment shader looking up the color at its UV coordinate and outputting that as the fragment color. #### Screen Filled Texture ```c #version 150 uniform sampler2D screenSizedTexture; out vec2 fragColor; void main() { vec2 texSize = textureSize(texture, 0).xy; vec2 texCoord = gl_FragCoord.xy / texSize; texColor = texture(screenSizedTexture, texCoord); fragColor = texColor; } ``` When performing render to texture, the mesh is a flat rectangle with the same aspect ratio as the screen. Because of this, you can calculate the UV coordinates knowing only A) the width and height of the screen sized texture being UV mapped to the rectangle and B) the fragment's x and y coordinate. To map x to U, divide x by the width of the input texture. Similarly, to map y to V, divide y by the height of the input texture. You'll see this technique used in the example code. ## Copyright (C) 2019 David Lettier <br> [lettier.com](https://www.lettier.com) [:arrow_backward:](render-to-texture.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](lighting.md)
3d-game-shaders-for-beginners/sections/texturing.md/0
{ "file_path": "3d-game-shaders-for-beginners/sections/texturing.md", "repo_id": "3d-game-shaders-for-beginners", "token_count": 866 }
7
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_RpcLibClientBase_hpp #define air_RpcLibClientBase_hpp #include "common/Common.hpp" #include "common/CommonStructs.hpp" #include "common/ImageCaptureBase.hpp" #include "sensors/imu/ImuBase.hpp" #include "sensors/barometer/BarometerBase.hpp" #include "sensors/magnetometer/MagnetometerBase.hpp" #include "sensors/gps/GpsBase.hpp" #include "sensors/distance/DistanceBase.hpp" #include "physics/Kinematics.hpp" #include "physics/Environment.hpp" #include "api/WorldSimApiBase.hpp" namespace msr { namespace airlib { //common methods for RCP clients of different vehicles class RpcLibClientBase { public: enum class ConnectionState : uint { Initial = 0, Connected, Disconnected, Reset, Unknown }; public: RpcLibClientBase(const string& ip_address = "localhost", uint16_t port = RpcLibPort, float timeout_sec = 60); virtual ~RpcLibClientBase(); //required for pimpl void confirmConnection(); void reset(); ConnectionState getConnectionState(); bool ping(); int getClientVersion() const; int getServerVersion() const; int getMinRequiredServerVersion() const; int getMinRequiredClientVersion() const; bool simIsPaused() const; void simPause(bool is_paused); void simContinueForTime(double seconds); void simContinueForFrames(uint32_t frames); void simSetTimeOfDay(bool is_enabled, const string& start_datetime = "", bool is_start_datetime_dst = false, float celestial_clock_speed = 1, float update_interval_secs = 60, bool move_sun = true); void simEnableWeather(bool enable); void simSetWeatherParameter(WorldSimApiBase::WeatherParameter param, float val); vector<string> simListSceneObjects(const string& name_regex = string(".*")) const; Pose simGetObjectPose(const std::string& object_name) const; bool simLoadLevel(const string& level_name); Vector3r simGetObjectScale(const std::string& object_name) const; bool simSetObjectPose(const std::string& object_name, const Pose& pose, bool teleport = true); bool simSetObjectScale(const std::string& object_name, const Vector3r& scale); std::string simSpawnObject(const std::string& object_name, const std::string& load_component, const Pose& pose, const Vector3r& scale, bool physics_enabled); bool simDestroyObject(const std::string& object_name); //task management APIs void cancelLastTask(const std::string& vehicle_name = ""); virtual RpcLibClientBase* waitOnLastTask(bool* task_result = nullptr, float timeout_sec = Utils::nan<float>()); bool simSetSegmentationObjectID(const std::string& mesh_name, int object_id, bool is_name_regex = false); int simGetSegmentationObjectID(const std::string& mesh_name) const; void simPrintLogMessage(const std::string& message, std::string message_param = "", unsigned char severity = 0); void simAddDetectionFilterMeshName(const std::string& camera_name, ImageCaptureBase::ImageType type, const std::string& mesh_name, const std::string& vehicle_name = "", bool external = false); void simSetDetectionFilterRadius(const std::string& camera_name, ImageCaptureBase::ImageType type, const float radius_cm, const std::string& vehicle_name = "", bool external = false); void simClearDetectionMeshNames(const std::string& camera_name, ImageCaptureBase::ImageType type, const std::string& vehicle_name = "", bool external = false); vector<DetectionInfo> simGetDetections(const std::string& camera_name, ImageCaptureBase::ImageType image_type, const std::string& vehicle_name = "", bool external = false); void simFlushPersistentMarkers(); void simPlotPoints(const vector<Vector3r>& points, const vector<float>& color_rgba, float size, float duration, bool is_persistent); void simPlotLineStrip(const vector<Vector3r>& points, const vector<float>& color_rgba, float thickness, float duration, bool is_persistent); void simPlotLineList(const vector<Vector3r>& points, const vector<float>& color_rgba, float thickness, float duration, bool is_persistent); void simPlotArrows(const vector<Vector3r>& points_start, const vector<Vector3r>& points_end, const vector<float>& color_rgba, float thickness, float arrow_size, float duration, bool is_persistent); void simPlotStrings(const vector<std::string>& strings, const vector<Vector3r>& positions, float scale, const vector<float>& color_rgba, float duration); void simPlotTransforms(const vector<Pose>& poses, float scale, float thickness, float duration, bool is_persistent); void simPlotTransformsWithNames(const vector<Pose>& poses, const vector<std::string>& names, float tf_scale, float tf_thickness, float text_scale, const vector<float>& text_color_rgba, float duration); bool armDisarm(bool arm, const std::string& vehicle_name = ""); bool isApiControlEnabled(const std::string& vehicle_name = "") const; void enableApiControl(bool is_enabled, const std::string& vehicle_name = ""); msr::airlib::GeoPoint getHomeGeoPoint(const std::string& vehicle_name = "") const; bool simRunConsoleCommand(const std::string& command); // sensor APIs msr::airlib::LidarData getLidarData(const std::string& lidar_name = "", const std::string& vehicle_name = "") const; msr::airlib::ImuBase::Output getImuData(const std::string& imu_name = "", const std::string& vehicle_name = "") const; msr::airlib::BarometerBase::Output getBarometerData(const std::string& barometer_name = "", const std::string& vehicle_name = "") const; msr::airlib::MagnetometerBase::Output getMagnetometerData(const std::string& magnetometer_name = "", const std::string& vehicle_name = "") const; msr::airlib::GpsBase::Output getGpsData(const std::string& gps_name = "", const std::string& vehicle_name = "") const; msr::airlib::DistanceSensorData getDistanceSensorData(const std::string& distance_sensor_name = "", const std::string& vehicle_name = "") const; Pose simGetVehiclePose(const std::string& vehicle_name = "") const; void simSetVehiclePose(const Pose& pose, bool ignore_collision, const std::string& vehicle_name = ""); void simSetTraceLine(const std::vector<float>& color_rgba, float thickness = 3.0f, const std::string& vehicle_name = ""); vector<ImageCaptureBase::ImageResponse> simGetImages(vector<ImageCaptureBase::ImageRequest> request, const std::string& vehicle_name = "", bool external = false); vector<uint8_t> simGetImage(const std::string& camera_name, ImageCaptureBase::ImageType type, const std::string& vehicle_name = "", bool external = false); //CinemAirSim std::vector<std::string> simGetPresetLensSettings(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); std::string simGetLensSettings(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); void simSetPresetLensSettings(const std::string& preset_lens_settings, const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); std::vector<std::string> simGetPresetFilmbackSettings(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); void simSetPresetFilmbackSettings(const std::string& preset_filmback_settings, const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); std::string simGetFilmbackSettings(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); float simSetFilmbackSettings(const float sensor_width, const float sensor_heigth, const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); float simGetFocalLength(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); void simSetFocalLength(float focal_length, const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); void simEnableManualFocus(const bool enable, const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); float simGetFocusDistance(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); void simSetFocusDistance(float focus_distance, const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); float simGetFocusAperture(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); void simSetFocusAperture(const float focus_aperture, const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); void simEnableFocusPlane(const bool enable, const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); std::string simGetCurrentFieldOfView(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); //end CinemAirSim bool simTestLineOfSightToPoint(const msr::airlib::GeoPoint& point, const std::string& vehicle_name = ""); bool simTestLineOfSightBetweenPoints(const msr::airlib::GeoPoint& point1, const msr::airlib::GeoPoint& point2); vector<msr::airlib::GeoPoint> simGetWorldExtents(); vector<MeshPositionVertexBuffersResponse> simGetMeshPositionVertexBuffers(); bool simAddVehicle(const std::string& vehicle_name, const std::string& vehicle_type, const Pose& pose, const std::string& pawn_path = ""); CollisionInfo simGetCollisionInfo(const std::string& vehicle_name = "") const; CameraInfo simGetCameraInfo(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false) const; void simSetDistortionParam(const std::string& camera_name, const std::string& param_name, float value, const std::string& vehicle_name = "", bool external = false); std::vector<float> simGetDistortionParams(const std::string& camera_name, const std::string& vehicle_name = "", bool external = false); void simSetCameraPose(const std::string& camera_name, const Pose& pose, const std::string& vehicle_name = "", bool external = false); void simSetCameraFov(const std::string& camera_name, float fov_degrees, const std::string& vehicle_name = "", bool external = false); bool simCreateVoxelGrid(const Vector3r& position, const int& x_size, const int& y_size, const int& z_size, const float& res, const std::string& output_file); msr::airlib::Kinematics::State simGetGroundTruthKinematics(const std::string& vehicle_name = "") const; void simSetKinematics(const Kinematics::State& state, bool ignore_collision, const std::string& vehicle_name = ""); msr::airlib::Environment::State simGetGroundTruthEnvironment(const std::string& vehicle_name = "") const; std::vector<std::string> simSwapTextures(const std::string& tags, int tex_id = 0, int component_id = 0, int material_id = 0); bool simSetObjectMaterial(const std::string& object_name, const std::string& material_name, const int component_id = 0); bool simSetObjectMaterialFromTexture(const std::string& object_name, const std::string& texture_path, const int component_id = 0); // Recording APIs void startRecording(); void stopRecording(); bool isRecording(); void simSetWind(const Vector3r& wind) const; vector<string> listVehicles(); std::string getSettingsString() const; std::vector<std::string> simListAssets() const; protected: void* getClient(); const void* getClient() const; private: struct impl; std::unique_ptr<impl> pimpl_; }; } } //namespace #endif
AirSim/AirLib/include/api/RpcLibClientBase.hpp/0
{ "file_path": "AirSim/AirLib/include/api/RpcLibClientBase.hpp", "repo_id": "AirSim", "token_count": 4215 }
8
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef common_utils_GaussianMarkov_hpp #define common_utils_GaussianMarkov_hpp #include "common/Common.hpp" #include "UpdatableObject.hpp" #include <list> #include "common_utils/RandomGenerator.hpp" namespace msr { namespace airlib { class GaussianMarkov : public UpdatableObject { public: GaussianMarkov() { } GaussianMarkov(real_T tau, real_T sigma, real_T initial_output = 0) //in seconds { initialize(tau, sigma, initial_output); } void initialize(real_T tau, real_T sigma, real_T initial_output = 0) //in seconds { tau_ = tau; sigma_ = sigma; rand_ = RandomGeneratorGausianR(0.0f, 1.0f); if (std::isnan(initial_output)) initial_output_ = getNextRandom() * sigma_; else initial_output_ = initial_output; } //*** Start: UpdatableState implementation ***// virtual void resetImplementation() override { last_time_ = clock()->nowNanos(); output_ = initial_output_; rand_.reset(); } virtual void update() override { /* Ref: A Comparison between Different Error Modeling of MEMS Applied to GPS/INS Integrated Systems Quinchia, sec 3.2, https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3812568/ A Study of the Effects of Stochastic Inertial Sensor Errors in Dead-Reckoning Navigation John H Wall, 2007, eq 2.5, pg 13, http://etd.auburn.edu/handle/10415/945 */ UpdatableObject::update(); TTimeDelta dt = clock()->updateSince(last_time_); double alpha = exp(-dt / tau_); output_ = static_cast<real_T>(alpha * output_ + (1 - alpha) * getNextRandom() * sigma_); } //*** End: UpdatableState implementation ***// real_T getNextRandom() { return rand_.next(); } real_T getOutput() const { return output_; } private: RandomGeneratorGausianR rand_; real_T tau_, sigma_; real_T output_, initial_output_; TTimePoint last_time_; }; } } //namespace #endif
AirSim/AirLib/include/common/GaussianMarkov.hpp/0
{ "file_path": "AirSim/AirLib/include/common/GaussianMarkov.hpp", "repo_id": "AirSim", "token_count": 1124 }
9
#ifndef common_utils_OnlineStats_hpp #define common_utils_OnlineStats_hpp namespace common_utils { class ColorUtils { public: static void valToRGB(double val0To1, unsigned char& r, unsigned char& g, unsigned char& b) { //actual visible spectrum is 375 to 725 but outside of 400-700 things become too black wavelengthToRGB(val0To1 * (700 - 400) + 400, r, g, b); } /** * Convert a wavelength in the visible light spectrum to a RGB color value that is suitable to be displayed on a * monitor * * @param wavelength wavelength in nm * @return RGB color encoded in int. each color is represented with 8 bits and has a layout of * 00000000RRRRRRRRGGGGGGGGBBBBBBBB where MSB is at the leftmost */ static void wavelengthToRGB(double wavelength, unsigned char& r, unsigned char& g, unsigned char& b) { double x, y, z; cie1931WavelengthToXYZFit(wavelength, x, y, z); double dr, dg, db; srgbXYZ2RGB(x, y, z, dr, dg, db); r = static_cast<unsigned char>(static_cast<int>(dr * 0xFF) & 0xFF); g = static_cast<unsigned char>(static_cast<int>(dg * 0xFF) & 0xFF); b = static_cast<unsigned char>(static_cast<int>(db * 0xFF) & 0xFF); } /** * Convert XYZ to RGB in the sRGB color space * <p> * The conversion matrix and color component transfer function is taken from http://www.color.org/srgb.pdf, which * follows the International Electrotechnical Commission standard IEC 61966-2-1 "Multimedia systems and equipment - * Colour measurement and management - Part 2-1: Colour management - Default RGB colour space - sRGB" * * @param xyz XYZ values in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] * @return RGB values in a double array, in the order of R, G, B. each value in the range of [0.0, 1.0] */ static void srgbXYZ2RGB(double x, double y, double z, double& r, double& g, double& b) { double rl = 3.2406255 * x + -1.537208 * y + -0.4986286 * z; double gl = -0.9689307 * x + 1.8757561 * y + 0.0415175 * z; double bl = 0.0557101 * x + -0.2040211 * y + 1.0569959 * z; r = srgbXYZ2RGBPostprocess(rl); g = srgbXYZ2RGBPostprocess(gl); b = srgbXYZ2RGBPostprocess(bl); } /** * helper function for {@link #srgbXYZ2RGB(double[])} */ static double srgbXYZ2RGBPostprocess(double c) { // clip if c is out of range c = c > 1 ? 1 : (c < 0 ? 0 : c); // apply the color component transfer function c = c <= 0.0031308 ? c * 12.92 : 1.055 * std::pow(c, 1. / 2.4) - 0.055; return c; } /** * A multi-lobe, piecewise Gaussian fit of CIE 1931 XYZ Color Matching Functions by Wyman el al. from Nvidia. The * code here is adopted from the Listing 1 of the paper authored by Wyman et al. * <p> * Reference: Chris Wyman, Peter-Pike Sloan, and Peter Shirley, Simple Analytic Approximations to the CIE XYZ Color * Matching Functions, Journal of Computer Graphics Techniques (JCGT), vol. 2, no. 2, 1-11, 2013. * * @param wavelength wavelength in nm * @return XYZ in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] */ static void cie1931WavelengthToXYZFit(double wavelength, double& x, double& y, double& z) { double wave = wavelength; { double t1 = (wave - 442.0) * ((wave < 442.0) ? 0.0624 : 0.0374); double t2 = (wave - 599.8) * ((wave < 599.8) ? 0.0264 : 0.0323); double t3 = (wave - 501.1) * ((wave < 501.1) ? 0.0490 : 0.0382); x = 0.362 * std::exp(-0.5 * t1 * t1) + 1.056 * std::exp(-0.5 * t2 * t2) - 0.065 * std::exp(-0.5 * t3 * t3); } { double t1 = (wave - 568.8) * ((wave < 568.8) ? 0.0213 : 0.0247); double t2 = (wave - 530.9) * ((wave < 530.9) ? 0.0613 : 0.0322); y = 0.821 * std::exp(-0.5 * t1 * t1) + 0.286 * std::exp(-0.5 * t2 * t2); } { double t1 = (wave - 437.0) * ((wave < 437.0) ? 0.0845 : 0.0278); double t2 = (wave - 459.0) * ((wave < 459.0) ? 0.0385 : 0.0725); z = 1.217 * std::exp(-0.5 * t1 * t1) + 0.681 * std::exp(-0.5 * t2 * t2); } } }; } //namespace #endif
AirSim/AirLib/include/common/common_utils/ColorUtils.hpp/0
{ "file_path": "AirSim/AirLib/include/common/common_utils/ColorUtils.hpp", "repo_id": "AirSim", "token_count": 1867 }
10
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. //there is no #pragma once in this header //following is required to support Unreal Build System #if (defined _WIN32 || defined _WIN64) && (defined UE_GAME || defined UE_EDITOR) #pragma warning(pop) #include "Windows/HideWindowsPlatformAtomics.h" #include "Windows/HideWindowsPlatformTypes.h" #include "Windows/PostWindowsApi.h" #endif
AirSim/AirLib/include/common/common_utils/WindowsApisCommonPost.hpp/0
{ "file_path": "AirSim/AirLib/include/common/common_utils/WindowsApisCommonPost.hpp", "repo_id": "AirSim", "token_count": 126 }
11
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef airsim_core_PhysicsEngineBase_hpp #define airsim_core_PhysicsEngineBase_hpp #include "common/UpdatableContainer.hpp" #include "common/Common.hpp" #include "PhysicsBody.hpp" namespace msr { namespace airlib { class PhysicsEngineBase : public UpdatableContainer<PhysicsBody*> { public: virtual void update() override { UpdatableObject::update(); } virtual void reportState(StateReporter& reporter) override { unused(reporter); //default nothing to report for physics engine } virtual void setWind(const Vector3r& wind) { unused(wind); }; }; } } //namespace #endif
AirSim/AirLib/include/physics/PhysicsEngineBase.hpp/0
{ "file_path": "AirSim/AirLib/include/physics/PhysicsEngineBase.hpp", "repo_id": "AirSim", "token_count": 303 }
12
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_DistanceSimpleParams_hpp #define msr_airlib_DistanceSimpleParams_hpp #include "common/Common.hpp" #include "common/AirSimSettings.hpp" namespace msr { namespace airlib { struct DistanceSimpleParams { real_T min_distance = 20.0f / 100; //m real_T max_distance = 4000.0f / 100; //m Pose relative_pose{ Vector3r(0, 0, -1), // position - a little above vehicle (especially for cars) or Vector3r::Zero() Quaternionr::Identity() // orientation - by default Quaternionr(1, 0, 0, 0) }; bool draw_debug_points = false; bool external_controller = true; /* Ref: A Stochastic Approach to Noise Modeling for Barometric Altimeters Angelo Maria Sabatini* and Vincenzo Genovese Sample values are from Table 1 https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3871085/ This is however not used because numbers mentioned in paper doesn't match experiments. real_T correlated_noise_sigma = 0.27f; real_T correlated_noise_tau = 0.87f; real_T uncorrelated_noise_sigma = 0.24f; */ //TODO: update sigma based on documentation, maybe as a function increasing with measured distance real_T uncorrelated_noise_sigma = 0.002f * 100; //jMavSim uses below //real_T uncorrelated_noise_sigma = 0.1f; //see PX4 param reference for EKF: https://dev.px4.io/en/advanced/parameter_reference.html real_T update_latency = 0.0f; //sec real_T update_frequency = 50; //Hz real_T startup_delay = 0; //sec void initializeFromSettings(const AirSimSettings::DistanceSetting& settings) { const auto& settings_json = settings.settings; min_distance = settings_json.getFloat("MinDistance", min_distance); max_distance = settings_json.getFloat("MaxDistance", max_distance); draw_debug_points = settings_json.getBool("DrawDebugPoints", draw_debug_points); external_controller = settings_json.getBool("ExternalController", external_controller); auto position = AirSimSettings::createVectorSetting(settings_json, VectorMath::nanVector()); auto rotation = AirSimSettings::createRotationSetting(settings_json, AirSimSettings::Rotation::nanRotation()); std::string simmode_name = AirSimSettings::singleton().simmode_name; relative_pose.position = position; if (std::isnan(relative_pose.position.x())) relative_pose.position.x() = 0; if (std::isnan(relative_pose.position.y())) relative_pose.position.y() = 0; if (std::isnan(relative_pose.position.z())) { if (simmode_name == AirSimSettings::kSimModeTypeMultirotor) relative_pose.position.z() = 0; else relative_pose.position.z() = -1; // a little bit above for cars } float pitch, roll, yaw; pitch = !std::isnan(rotation.pitch) ? rotation.pitch : 0; roll = !std::isnan(rotation.roll) ? rotation.roll : 0; yaw = !std::isnan(rotation.yaw) ? rotation.yaw : 0; relative_pose.orientation = VectorMath::toQuaternion( Utils::degreesToRadians(pitch), //pitch - rotation around Y axis Utils::degreesToRadians(roll), //roll - rotation around X axis Utils::degreesToRadians(yaw)); //yaw - rotation around Z axis } }; } } //namespace #endif
AirSim/AirLib/include/sensors/distance/DistanceSimpleParams.hpp/0
{ "file_path": "AirSim/AirLib/include/sensors/distance/DistanceSimpleParams.hpp", "repo_id": "AirSim", "token_count": 1531 }
13