text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
using UnityEngine; public class SmoothFollow : MonoBehaviour { public bool shouldRotate = true; // The target we are following [SerializeField] private Transform target; private float wantedRotationAngle; private float currentRotationAngle; private Quaternion currentRotation; private Vector3 offsetPostion; private void Start() { offsetPostion = new Vector3(0, 5, -10); } private void LateUpdate() { if (!target) { return; } // Calculate the current rotation angles wantedRotationAngle = target.eulerAngles.y; currentRotationAngle = transform.eulerAngles.y; // Damp the rotation around the y-axis currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, 0.3f); // Convert the angle into a rotation currentRotation = Quaternion.Euler(0, currentRotationAngle, 0); // Set the position of the camera on the x-z plane to: // distance meters behind the target transform.position = target.position + (currentRotation * offsetPostion); // Always look at the target transform.LookAt(target); } }
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/SmoothFollow.cs/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/SmoothFollow.cs", "repo_id": "AirSim", "token_count": 444 }
47
fileFormatVersion: 2 guid: 8fed0082e84e21745996e4376df43079 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/DataRecorder.cs.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/DataRecorder.cs.meta", "repo_id": "AirSim", "token_count": 91 }
48
using System; using AirSimUnity.DroneStructs; using System.Collections.Generic; using System.Linq; using System.Threading; using UnityEditor; using UnityEngine; namespace AirSimUnity { /* * The base class for all the vehicle models in the simulation. Holds the data to communicate between AirLib and Unity. * An implementation of IVehicleInterface with all the contracts required by VehicleCompanion. */ [RequireComponent(typeof(Rigidbody))] public abstract class Vehicle : MonoBehaviour, IVehicleInterface { protected Vector3 position; protected Quaternion rotation; protected Vector3 scale3D = Vector3.one; protected AirSimPose poseFromAirLib; protected AirSimPose currentPose; protected CollisionInfo collisionInfo; protected AirSimRCData rcData; protected bool resetVehicle; protected float time_scale = 1.0f; protected bool timeScale_changed = false; protected bool isApiEnabled = false; protected bool isServerStarted = false; bool print_log_messages_ = true; protected readonly List<DataCaptureScript> captureCameras = new List<DataCaptureScript>(); protected AutoResetEvent captureResetEvent; protected IAirSimInterface airsimInterface; protected bool isCapturingImages = false; protected ImageRequest imageRequest; protected ImageResponse imageResponse; private bool isDrone; private static bool isSegmentationUpdated; private bool calculateRayCast = false; private Vector3 startVec; private Vector3 endVec; private RaycastHit hitInfo; private bool hitResult; [SerializeField] string vehicleName; private Rigidbody vehicleRigidBody; private void Awake() { vehicleRigidBody = GetComponent(type: typeof(Rigidbody)) as Rigidbody; } //Ensure to call this method as the first statement, from derived class `Start()` method. protected void Start() { isDrone = this is Drone ? true : false; if (isDrone) { vehicleRigidBody.useGravity = false; } InitializeVehicle(); airsimInterface = VehicleCompanion.GetVehicleCompanion(vehicleName, this); isServerStarted = true; AirSimGlobal.Instance.Weather.AttachToVehicle(this); } //Ensure to call this method as the first statement, from derived class `FixedUpdate()` method. protected void FixedUpdate() { if (isServerStarted) { DataManager.SetToAirSim(transform.position, ref currentPose.position); DataManager.SetToAirSim(transform.rotation, ref currentPose.orientation); } } //Ensure to call this method as the last statement, from derived class `LateUpdate()` method. protected void LateUpdate() { if (isServerStarted) { if (timeScale_changed) { Time.timeScale = time_scale; timeScale_changed = false; } if (isSegmentationUpdated) { UpdateSegmentationView(); isSegmentationUpdated = false; } if (isCapturingImages) { var captureCamera = captureCameras.Find(element => element.GetCameraName() == imageRequest.camera_name); imageResponse = captureCamera.GetImageBasedOnRequest(imageRequest); captureResetEvent.Set(); //Release the GetSimulationImages thread with the image response. isCapturingImages = false; } if (calculateRayCast) { hitResult = Physics.Linecast(startVec, endVec, out hitInfo); calculateRayCast = false; } if (Input.GetKeyDown(KeyCode.T)) { print_log_messages_ = !print_log_messages_; } } } protected void OnCollisionEnter(Collision collision) { if (isServerStarted) { collisionInfo.has_collided = true; collisionInfo.object_id = -1; collisionInfo.collision_count++; collisionInfo.object_name = collision.collider.name; DataManager.SetToAirSim(collision.contacts[0].normal, ref collisionInfo.normal); DataManager.SetToAirSim(collision.contacts[0].point, ref collisionInfo.impact_point); collisionInfo.position = currentPose.position; collisionInfo.penetration_depth = collision.contacts[0].separation; collisionInfo.object_name = collision.collider.name; collisionInfo.time_stamp = DataManager.GetCurrentTimeInMilli(); airsimInterface.InvokeCollisionDetectionInAirSim(vehicleName, collisionInfo); } } protected void OnCollisionStay(Collision collision) { if (isServerStarted) { collisionInfo.has_collided = true; collisionInfo.object_id = -1; collisionInfo.collision_count++; collisionInfo.object_name = collision.collider.name; DataManager.SetToAirSim(collision.contacts[0].normal, ref collisionInfo.normal); DataManager.SetToAirSim(collision.contacts[0].point, ref collisionInfo.impact_point); collisionInfo.position = currentPose.position; collisionInfo.penetration_depth = collision.contacts[0].separation; collisionInfo.object_name = collision.collider.name; collisionInfo.time_stamp = DataManager.GetCurrentTimeInMilli(); } } protected void OnCollisionExit() { if (isServerStarted) { collisionInfo.has_collided = false; } } //Define the recording data that needs to be saved in the airsim_rec file for Toggle Recording button public abstract DataRecorder.ImageData GetRecordingData(); public void ResetVehicle() { resetVehicle = true; } public virtual AirSimVector GetVelocity() { var rigidBody = GetComponent<Rigidbody>(); return new AirSimVector(rigidBody.velocity.x, rigidBody.velocity.y, rigidBody.velocity.z); } public bool SetPose(AirSimPose pose, bool ignore_collision) { poseFromAirLib = pose; return true; } public AirSimPose GetPose() { return currentPose; } public UnityTransform GetTransform() { return new UnityTransform(new AirSimQuaternion(currentPose.orientation.x, currentPose.orientation.y, currentPose.orientation.z, currentPose.orientation.w), new AirSimVector(currentPose.position.x, currentPose.position.y, currentPose.position.z), new AirSimVector(scale3D.x, scale3D.y, scale3D.z)); } public RayCastHitResult GetRayCastHit(AirSimVector start, AirSimVector end) { DataManager.SetToUnity(start, ref startVec); DataManager.SetToUnity(end, ref endVec); calculateRayCast = true; int count = 500; // wait for max 0.5 second while(calculateRayCast && count > 0) { count--; } return new RayCastHitResult(hitResult, hitInfo.distance); } public bool Pause(float timeScale) { time_scale = timeScale; timeScale_changed = true; return true; } public CollisionInfo GetCollisionInfo() { return collisionInfo; } public AirSimRCData GetRCData() { return rcData; } public DataCaptureScript GetCameraCapture(string cameraName) { DataCaptureScript recordCam = captureCameras[0]; foreach (DataCaptureScript camCapture in captureCameras.Where(camCapture => camCapture.GetCameraName() == cameraName)) { recordCam = camCapture; break; } return recordCam; } public ImageResponse GetSimulationImages(ImageRequest request) { imageResponse.reset(); if (!captureCameras.Find(element => element.GetCameraName() == request.camera_name)) { return imageResponse; } imageRequest = request; isCapturingImages = true; captureResetEvent.WaitOne(); return imageResponse; } public bool SetEnableApi(bool enableApi) { isApiEnabled = enableApi; return true; } public CameraInfo GetCameraInfo(string cameraName) { CameraInfo info = new CameraInfo(); foreach (DataCaptureScript capture in captureCameras.Where(camCapture => camCapture.GetCameraName() == cameraName)) { info.fov = capture.GetFOV(); info.pose = capture.GetPose(); return info; } return info; } public bool SetCameraPose(string cameraName, AirSimPose pose) { foreach (DataCaptureScript capture in captureCameras.Where(camCapture => camCapture.GetCameraName() == cameraName)) { capture.SetPose(pose); return true; } return false; } public bool SetCameraFoV(string cameraName, float fov_degrees) { foreach (DataCaptureScript capture in captureCameras.Where(capture => capture.GetCameraName() == cameraName)) { capture.SetFoV(fov_degrees); return true; } return false; } public bool SetDistortionParam(string cameraName, string paramName, float value) { // not implemented return false; } public bool GetDistortionParams(string cameraName) { // not implemented return false; } public bool PrintLogMessage(string message, string messageParams, string vehicleName, int severity) { if (!print_log_messages_) return true; switch (severity) { case 1: Debug.LogWarning(message + " " + messageParams + " Vehicle=" + vehicleName); break; case 2: Debug.LogError(message + " " + messageParams + " Vehicle=" + vehicleName); break; default: Debug.Log(message + " " + messageParams + " Vehicle=" + vehicleName); break; } return true; } public static bool SetSegmentationObjectId(string objectName, int objectId, bool isNameRegex) { int finalId = ((objectId + 2) << 16) | ((objectId + 1) << 8) | objectId; bool result = CameraFiltersScript.SetSegmentationId(objectName, finalId, isNameRegex); isSegmentationUpdated = result; return result; } public static int GetSegmentationObjectId(string objectName) { return CameraFiltersScript.GetSegmentationId(objectName); } public virtual bool SetRotorSpeed(int rotorIndex, RotorInfo rotorInfo) { throw new NotImplementedException("This is supposed to be implemented in Drone sub class"); } public virtual bool SetCarControls(CarStructs.CarControls controls) { throw new NotImplementedException("This is supposed to be implemented in Car sub class"); } public virtual CarStructs.CarState GetCarState() { throw new NotImplementedException("This is supposed to be implemented in Car sub class"); } /****************** Methods for vehicle management **************************/ private void InitializeVehicle() { //Setting the initial get pose(HomePoint in AirLib) values to that of vehicle's location in the scene for initial setup in AirLib DataManager.SetToAirSim(transform.position, ref currentPose.position); DataManager.SetToAirSim(transform.rotation, ref currentPose.orientation); collisionInfo.SetDefaultValues(); SetUpCameras(); captureResetEvent = new AutoResetEvent(false); } //Register all the capture cameras in the scene for recording and data capture. //Make sure every camera is a child of a gameobject with tag "CaptureCameras" private void SetUpCameras() { GameObject camerasParent = GameObject.FindGameObjectWithTag("CaptureCameras"); if (!camerasParent) { Debug.LogWarning("No Cameras found in the scene to capture data"); return; } for (int i = 0; i < camerasParent.transform.childCount; i++) { DataCaptureScript camCapture = camerasParent.transform.GetChild(i).GetComponent<DataCaptureScript>(); captureCameras.Add(camCapture); camCapture.SetUpCamera(camCapture.GetCameraName(), isDrone); } } private void UpdateSegmentationView() { GameObject viewCameras = GameObject.FindGameObjectWithTag("ViewCameras"); if (viewCameras) { foreach (CameraFiltersScript viewCam in viewCameras.GetComponentsInChildren<CameraFiltersScript>()) { if (viewCam.effect != ImageType.Segmentation) { continue; } viewCam.SetShaderEffect(ImageType.Segmentation); } } } } }
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Vehicles/Vehicle.cs/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Vehicles/Vehicle.cs", "repo_id": "AirSim", "token_count": 6363 }
49
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1 &2161695231079865698 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2161695231079865697} - component: {fileID: 2161695231079865703} - component: {fileID: 2161695231079865696} m_Layer: 0 m_Name: Label m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2161695231079865697 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695231079865698} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 2161695232377047715} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 9, y: -0.5} m_SizeDelta: {x: -28, y: -3} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &2161695231079865703 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695231079865698} m_CullTransparentMesh: 0 --- !u!114 &2161695231079865696 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695231079865698} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.8773585, g: 0.8773585, b: 0.8773585, a: 1} m_RaycastTarget: 1 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 m_FontStyle: 0 m_BestFit: 0 m_MinSize: 10 m_MaxSize: 40 m_Alignment: 0 m_AlignByGeometry: 0 m_RichText: 1 m_HorizontalOverflow: 0 m_VerticalOverflow: 0 m_LineSpacing: 1 m_Text: Weather Enabled --- !u!1 &2161695231544300088 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2161695231544300095} - component: {fileID: 2161695231544300093} - component: {fileID: 2161695231544300094} m_Layer: 0 m_Name: Title m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2161695231544300095 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695231544300088} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 6359801898852124506} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 1} m_AnchorMax: {x: 0, y: 1} m_AnchoredPosition: {x: 10, y: -10} m_SizeDelta: {x: 160, y: 30} m_Pivot: {x: 0, y: 1} --- !u!222 &2161695231544300093 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695231544300088} m_CullTransparentMesh: 0 --- !u!114 &2161695231544300094 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695231544300088} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.8773585, g: 0.8773585, b: 0.8773585, a: 1} m_RaycastTarget: 1 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 18 m_FontStyle: 0 m_BestFit: 0 m_MinSize: 1 m_MaxSize: 40 m_Alignment: 0 m_AlignByGeometry: 0 m_RichText: 1 m_HorizontalOverflow: 0 m_VerticalOverflow: 0 m_LineSpacing: 1 m_Text: Weather Menu --- !u!1 &2161695231671899667 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2161695231671899666} - component: {fileID: 2161695231671899664} - component: {fileID: 2161695231671899665} m_Layer: 0 m_Name: Background m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2161695231671899666 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695231671899667} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 2161695232929706358} m_Father: {fileID: 2161695232377047715} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 1} m_AnchorMax: {x: 0, y: 1} m_AnchoredPosition: {x: 10, y: -10} m_SizeDelta: {x: 20, y: 20} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &2161695231671899664 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695231671899667} m_CullTransparentMesh: 0 --- !u!114 &2161695231671899665 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695231671899667} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 m_FillAmount: 1 m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 m_PixelsPerUnitMultiplier: 1 --- !u!1 &2161695232377047644 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2161695232377047715} - component: {fileID: 2161695232377047714} m_Layer: 0 m_Name: WeatherEnabled m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2161695232377047715 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232377047644} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 2161695231671899666} - {fileID: 2161695231079865697} m_Father: {fileID: 6359801898852124506} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 1} m_AnchorMax: {x: 0, y: 1} m_AnchoredPosition: {x: 18, y: -80} m_SizeDelta: {x: 160, y: 20} m_Pivot: {x: 0, y: 1} --- !u!114 &2161695232377047714 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232377047644} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 9085046f02f69544eb97fd06b6048fe2, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: m_Mode: 3 m_SelectOnUp: {fileID: 0} m_SelectOnDown: {fileID: 0} m_SelectOnLeft: {fileID: 0} m_SelectOnRight: {fileID: 0} m_Transition: 1 m_Colors: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed m_SelectedTrigger: Selected m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 2161695231671899665} toggleTransition: 1 graphic: {fileID: 2161695232929706357} m_Group: {fileID: 0} onValueChanged: m_PersistentCalls: m_Calls: [] m_IsOn: 1 --- !u!1 &2161695232485480279 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2161695232485480278} - component: {fileID: 2161695232485480276} - component: {fileID: 2161695232485480277} m_Layer: 0 m_Name: Description m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2161695232485480278 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232485480279} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 6359801898852124506} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 1} m_AnchorMax: {x: 0, y: 1} m_AnchoredPosition: {x: 18, y: -35} m_SizeDelta: {x: 238.19766, y: 37.109642} m_Pivot: {x: 0, y: 1} --- !u!222 &2161695232485480276 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232485480279} m_CullTransparentMesh: 0 --- !u!114 &2161695232485480277 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232485480279} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.8773585, g: 0.8773585, b: 0.8773585, a: 1} m_RaycastTarget: 1 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 m_FontStyle: 0 m_BestFit: 0 m_MinSize: 1 m_MaxSize: 40 m_Alignment: 0 m_AlignByGeometry: 0 m_RichText: 1 m_HorizontalOverflow: 0 m_VerticalOverflow: 0 m_LineSpacing: 1 m_Text: 'Weather Intensity & Road Conditions (Currently only supports snow.)' --- !u!1 &2161695232802282896 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2161695232802282903} - component: {fileID: 6567637587224048157} m_Layer: 0 m_Name: WeatherHUD m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2161695232802282903 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232802282896} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 6359801898852124506} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 1} m_AnchorMax: {x: 0, y: 1} m_AnchoredPosition: {x: 30, y: -15} m_SizeDelta: {x: 270, y: 200} m_Pivot: {x: 0, y: 1} --- !u!114 &6567637587224048157 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232802282896} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 44f4876707839e24eaf880eac55bc38e, type: 3} m_Name: m_EditorClassIdentifier: rootPanel: {fileID: 6359801898852124506} weatherEnabledToggle: {fileID: 2161695232377047714} snowSlider: {fileID: 7557342846883258847} --- !u!1 &2161695232929706359 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 2161695232929706358} - component: {fileID: 2161695232929706356} - component: {fileID: 2161695232929706357} m_Layer: 0 m_Name: Checkmark m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &2161695232929706358 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232929706359} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 2161695231671899666} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0.5, y: 0.5} m_AnchorMax: {x: 0.5, y: 0.5} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 20, y: 20} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &2161695232929706356 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232929706359} m_CullTransparentMesh: 0 --- !u!114 &2161695232929706357 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 2161695232929706359} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Sprite: {fileID: 10901, guid: 0000000000000000f000000000000000, type: 0} m_Type: 0 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 m_FillAmount: 1 m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 m_PixelsPerUnitMultiplier: 1 --- !u!1 &6420161668560717326 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 6359801898852124506} - component: {fileID: 8982830834916079832} - component: {fileID: 1179458443930169098} m_Layer: 0 m_Name: WeatherPanel m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!224 &6359801898852124506 RectTransform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 6420161668560717326} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 2161695231544300095} - {fileID: 2161695232485480278} - {fileID: 2161695232377047715} - {fileID: 2161695230994594290} m_Father: {fileID: 2161695232802282903} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_AnchorMin: {x: 0, y: 0} m_AnchorMax: {x: 1, y: 1} m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 0, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!222 &8982830834916079832 CanvasRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 6420161668560717326} m_CullTransparentMesh: 0 --- !u!114 &1179458443930169098 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 6420161668560717326} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0, b: 0, a: 0.9019608} m_RaycastTarget: 1 m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 m_FillCenter: 1 m_FillMethod: 4 m_FillAmount: 1 m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 m_PixelsPerUnitMultiplier: 1 --- !u!1001 &3119393161984508666 PrefabInstance: m_ObjectHideFlags: 0 serializedVersion: 2 m_Modification: m_TransformParent: {fileID: 6359801898852124506} m_Modifications: - target: {fileID: 3942248164879046742, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchorMin.x value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164879046742, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchorMax.x value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164879046742, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchorMax.y value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalPosition.x value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalPosition.y value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalPosition.z value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalRotation.w value: 1 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_RootOrder value: 3 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchoredPosition.x value: 18 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchoredPosition.y value: -117.5 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_SizeDelta.x value: 238.19757 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_SizeDelta.y value: 20 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchorMin.x value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchorMin.y value: 1 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchorMax.x value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchorMax.y value: 1 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_Pivot.x value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_Pivot.y value: 1 objectReference: {fileID: 0} - target: {fileID: 3942248164991974153, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_Name value: Snow objectReference: {fileID: 0} - target: {fileID: 3942248165468422358, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchorMax.x value: 0 objectReference: {fileID: 0} - target: {fileID: 3942248165468422358, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} propertyPath: m_AnchorMax.y value: 0 objectReference: {fileID: 0} m_RemovedComponents: [] m_SourcePrefab: {fileID: 100100000, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} --- !u!224 &2161695230994594290 stripped RectTransform: m_CorrespondingSourceObject: {fileID: 3942248164991974152, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} m_PrefabInstance: {fileID: 3119393161984508666} m_PrefabAsset: {fileID: 0} --- !u!114 &7557342846883258847 stripped MonoBehaviour: m_CorrespondingSourceObject: {fileID: 4876093048180597541, guid: 3db70f24b93815f43a8926a9f089c7be, type: 3} m_PrefabInstance: {fileID: 3119393161984508666} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 0} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 2afa4732bf1bb144392906360cad913a, type: 3} m_Name: m_EditorClassIdentifier:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather/UI/WeatherHUD.prefab/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather/UI/WeatherHUD.prefab", "repo_id": "AirSim", "token_count": 11160 }
50
fileFormatVersion: 2 guid: 4f704ae4b4f98ae41a0bce26658850c1 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/Scenes.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/Scenes.meta", "repo_id": "AirSim", "token_count": 71 }
51
fileFormatVersion: 2 guid: d425c5c4cb38fd44f95b13e9f94575c2 NativeFormatImporter: userData: assetBundleName:
AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials/SkyCarBodyGrey.mat.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials/SkyCarBodyGrey.mat.meta", "repo_id": "AirSim", "token_count": 52 }
52
fileFormatVersion: 2 guid: 4061dc322093be74a80d5dd0d25f1dba folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Textures.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Textures.meta", "repo_id": "AirSim", "token_count": 70 }
53
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!159 &1 EditorSettings: m_ObjectHideFlags: 0 serializedVersion: 9 m_ExternalVersionControlSupport: Visible Meta Files m_SerializationMode: 2 m_LineEndingsForNewScripts: 2 m_DefaultBehaviorMode: 0 m_PrefabRegularEnvironment: {fileID: 0} m_PrefabUIEnvironment: {fileID: 0} m_SpritePackerMode: 0 m_SpritePackerPaddingPower: 1 m_EtcTextureCompressorBehavior: 1 m_EtcTextureFastCompressor: 1 m_EtcTextureNormalCompressor: 2 m_EtcTextureBestCompressor: 4 m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmref m_ProjectGenerationRootNamespace: m_CollabEditorSettings: inProgressEnabled: 1 m_EnableTextureStreamingInEditMode: 1 m_EnableTextureStreamingInPlayMode: 1 m_AsyncShaderCompilation: 1 m_EnterPlayModeOptionsEnabled: 0 m_EnterPlayModeOptions: 3 m_ShowLightmapResolutionOverlay: 1 m_UseLegacyProbeSampleCount: 1 m_AssetPipelineMode: 1 m_CacheServerMode: 0 m_CacheServerEndpoint: m_CacheServerNamespacePrefix: default m_CacheServerEnableDownload: 1 m_CacheServerEnableUpload: 1
AirSim/Unity/UnityDemo/ProjectSettings/EditorSettings.asset/0
{ "file_path": "AirSim/Unity/UnityDemo/ProjectSettings/EditorSettings.asset", "repo_id": "AirSim", "token_count": 400 }
54
@echo off REM //---------- copy binaries and include for MavLinkCom in deps ---------- msbuild AirLibWrapper\AirsimWrapper.sln /target:Clean /target:Build /property:Configuration=Release /property:Platform=x64 if ERRORLEVEL 1 goto :buildfailed if NOT EXIST UnityDemo\Assets\Plugins mkdir UnityDemo\Assets\Plugins copy /Y AirLibWrapper\x64\Release\AirsimWrapper.dll UnityDemo\Assets\Plugins REM //---------- done building ---------- exit /b 0 :buildfailed echo( echo #### Build failed - see messages above. 1>&2 exit /b 1
AirSim/Unity/build.cmd/0
{ "file_path": "AirSim/Unity/build.cmd", "repo_id": "AirSim", "token_count": 166 }
55
#! /bin/bash # get path of current script: https://stackoverflow.com/a/39340259/207661 SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" pushd "$SCRIPT_DIR" >/dev/null set -e set -x rsync -a --exclude 'temp' --delete Plugins/AirSim ../../Plugins/ rsync -a --exclude 'temp' --delete Plugins/AirSim/Source/AirLib ../../../ popd >/dev/null set +x
AirSim/Unreal/Environments/Blocks/update_to_git.sh/0
{ "file_path": "AirSim/Unreal/Environments/Blocks/update_to_git.sh", "repo_id": "AirSim", "token_count": 152 }
56
#pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "GameFramework/PlayerInput.h" #include "ManualPoseController.generated.h" UCLASS() class AIRSIM_API UManualPoseController : public UObject { GENERATED_BODY() public: void initializeForPlay(); void setActor(AActor* actor); AActor* getActor() const; void updateActorPose(float dt); void getDeltaPose(FVector& delta_position, FRotator& delta_rotation) const; void resetDelta(); void updateDeltaPosition(float dt); private: void inputManualLeft(float val); void inputManualRight(float val); void inputManualForward(float val); void inputManualBackward(float val); void inputManualMoveUp(float val); void inputManualDown(float val); void inputManualLeftYaw(float val); void inputManualRightYaw(float val); void inputManualLeftRoll(float val); void inputManualRightRoll(float val); void inputManualUpPitch(float val); void inputManualDownPitch(float val); void inputManualSpeedIncrease(float val); void inputManualSpeedDecrease(float val); void setupInputBindings(); void removeInputBindings(); void clearBindings(); private: FInputAxisBinding *left_binding_, *right_binding_, *up_binding_, *down_binding_; FInputAxisBinding *forward_binding_, *backward_binding_, *left_yaw_binding_, *right_yaw_binding_; FInputAxisBinding *up_pitch_binding_, *down_pitch_binding_, *left_roll_binding_, *right_roll_binding_; FInputAxisBinding *inc_speed_binding_, *dec_speed_binding_; FInputAxisKeyMapping left_mapping_, right_mapping_, up_mapping_, down_mapping_; FInputAxisKeyMapping forward_mapping_, backward_mapping_, left_yaw_mapping_, right_yaw_mapping_; FInputAxisKeyMapping up_pitch_mapping_, down_pitch_mapping_, left_roll_mapping_, right_roll_mapping_; FInputAxisKeyMapping inc_speed_mapping_, dec_speed_mapping_; FVector delta_position_; FRotator delta_rotation_; AActor* actor_; float acceleration_ = 0, speed_scaler_ = 1000; FVector input_positive_, inpute_negative_; FVector last_velocity_; };
AirSim/Unreal/Plugins/AirSim/Source/ManualPoseController.h/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/ManualPoseController.h", "repo_id": "AirSim", "token_count": 802 }
57
#pragma once #include "CoreMinimal.h" #include "Engine/TextureRenderTarget2D.h" #include "common/WorkerThread.hpp" #include "Components/SceneCaptureComponent2D.h" #include "Engine/GameViewportClient.h" #include <memory> #include "common/Common.hpp" class RenderRequest : public FRenderCommand { public: struct RenderParams { USceneCaptureComponent2D* const render_component; UTextureRenderTarget2D* render_target; bool pixels_as_float; bool compress; RenderParams(USceneCaptureComponent2D* render_component_val, UTextureRenderTarget2D* render_target_val, bool pixels_as_float_val, bool compress_val) : render_component(render_component_val), render_target(render_target_val), pixels_as_float(pixels_as_float_val), compress(compress_val) { } }; struct RenderResult { TArray<uint8> image_data_uint8; TArray<float> image_data_float; TArray<FColor> bmp; TArray<FFloat16Color> bmp_float; int width; int height; msr::airlib::TTimePoint time_stamp; }; private: static FReadSurfaceDataFlags setupRenderResource(const FTextureRenderTargetResource* rt_resource, const RenderParams* params, RenderResult* result, FIntPoint& size); std::shared_ptr<RenderParams>* params_; std::shared_ptr<RenderResult>* results_; unsigned int req_size_; std::shared_ptr<msr::airlib::WorkerThreadSignal> wait_signal_; bool saved_DisableWorldRendering_ = false; UGameViewportClient* const game_viewport_; FDelegateHandle end_draw_handle_; std::function<void()> query_camera_pose_cb_; public: RenderRequest(UGameViewportClient* game_viewport, std::function<void()>&& query_camera_pose_cb); ~RenderRequest(); void DoTask(ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) { ExecuteTask(); } FORCEINLINE TStatId GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(RenderRequest, STATGROUP_RenderThreadCommands); } // read pixels from render target using render thread, then compress the result into PNG // argument on the thread that calls this method. void getScreenshot( std::shared_ptr<RenderParams> params[], std::vector<std::shared_ptr<RenderResult>>& results, unsigned int req_size, bool use_safe_method); void ExecuteTask(); };
AirSim/Unreal/Plugins/AirSim/Source/RenderRequest.h/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/RenderRequest.h", "repo_id": "AirSim", "token_count": 906 }
58
#include "UnrealImageCapture.h" #include "Engine/World.h" #include "ImageUtils.h" #include "RenderRequest.h" #include "common/ClockFactory.hpp" UnrealImageCapture::UnrealImageCapture(const common_utils::UniqueValueMap<std::string, APIPCamera*>* cameras) : cameras_(cameras) { //TODO: explore screenshot option //addScreenCaptureHandler(camera->GetWorld()); } UnrealImageCapture::~UnrealImageCapture() { } void UnrealImageCapture::getImages(const std::vector<msr::airlib::ImageCaptureBase::ImageRequest>& requests, std::vector<msr::airlib::ImageCaptureBase::ImageResponse>& responses) const { if (cameras_->valsSize() == 0) { for (unsigned int i = 0; i < requests.size(); ++i) { responses.push_back(ImageResponse()); responses[responses.size() - 1].message = "camera is not set"; } } else getSceneCaptureImage(requests, responses, false); } void UnrealImageCapture::getSceneCaptureImage(const std::vector<msr::airlib::ImageCaptureBase::ImageRequest>& requests, std::vector<msr::airlib::ImageCaptureBase::ImageResponse>& responses, bool use_safe_method) const { std::vector<std::shared_ptr<RenderRequest::RenderParams>> render_params; std::vector<std::shared_ptr<RenderRequest::RenderResult>> render_results; bool visibilityChanged = false; for (unsigned int i = 0; i < requests.size(); ++i) { APIPCamera* camera = cameras_->at(requests.at(i).camera_name); //TODO: may be we should have these methods non-const? visibilityChanged = const_cast<UnrealImageCapture*>(this)->updateCameraVisibility(camera, requests[i]) || visibilityChanged; } if (use_safe_method && visibilityChanged) { // We don't do game/render thread synchronization for safe method. // We just blindly sleep for 200ms (the old way) std::this_thread::sleep_for(std::chrono::duration<double>(0.2)); } UGameViewportClient* gameViewport = nullptr; for (unsigned int i = 0; i < requests.size(); ++i) { APIPCamera* camera = cameras_->at(requests.at(i).camera_name); if (gameViewport == nullptr) { gameViewport = camera->GetWorld()->GetGameViewport(); } responses.push_back(ImageResponse()); ImageResponse& response = responses.at(i); UTextureRenderTarget2D* textureTarget = nullptr; USceneCaptureComponent2D* capture = camera->getCaptureComponent(requests[i].image_type, false); if (capture == nullptr) { response.message = "Can't take screenshot because none camera type is not active"; } else if (capture->TextureTarget == nullptr) { response.message = "Can't take screenshot because texture target is null"; } else textureTarget = capture->TextureTarget; render_params.push_back(std::make_shared<RenderRequest::RenderParams>(capture, textureTarget, requests[i].pixels_as_float, requests[i].compress)); } if (nullptr == gameViewport) { return; } auto query_camera_pose_cb = [this, &requests, &responses]() { size_t count = requests.size(); for (size_t i = 0; i < count; i++) { const ImageRequest& request = requests.at(i); APIPCamera* camera = cameras_->at(request.camera_name); ImageResponse& response = responses.at(i); auto camera_pose = camera->getPose(); response.camera_position = camera_pose.position; response.camera_orientation = camera_pose.orientation; } }; RenderRequest render_request{ gameViewport, std::move(query_camera_pose_cb) }; render_request.getScreenshot(render_params.data(), render_results, render_params.size(), use_safe_method); for (unsigned int i = 0; i < requests.size(); ++i) { const ImageRequest& request = requests.at(i); ImageResponse& response = responses.at(i); response.camera_name = request.camera_name; response.time_stamp = render_results[i]->time_stamp; response.image_data_uint8 = std::vector<uint8_t>(render_results[i]->image_data_uint8.GetData(), render_results[i]->image_data_uint8.GetData() + render_results[i]->image_data_uint8.Num()); response.image_data_float = std::vector<float>(render_results[i]->image_data_float.GetData(), render_results[i]->image_data_float.GetData() + render_results[i]->image_data_float.Num()); if (use_safe_method) { // Currently, we don't have a way to synthronize image capturing and camera pose when safe method is used, APIPCamera* camera = cameras_->at(request.camera_name); msr::airlib::Pose pose = camera->getPose(); response.camera_position = pose.position; response.camera_orientation = pose.orientation; } response.pixels_as_float = request.pixels_as_float; response.compress = request.compress; response.width = render_results[i]->width; response.height = render_results[i]->height; response.image_type = request.image_type; } } bool UnrealImageCapture::updateCameraVisibility(APIPCamera* camera, const msr::airlib::ImageCaptureBase::ImageRequest& request) { bool visibilityChanged = false; if (!camera->getCameraTypeEnabled(request.image_type)) { camera->setCameraTypeEnabled(request.image_type, true); visibilityChanged = true; } return visibilityChanged; } bool UnrealImageCapture::getScreenshotScreen(ImageType image_type, std::vector<uint8_t>& compressedPng) { FScreenshotRequest::RequestScreenshot(false); // This is an async operation return true; } void UnrealImageCapture::addScreenCaptureHandler(UWorld* world) { static bool is_installed = false; if (!is_installed) { UGameViewportClient* ViewportClient = world->GetGameViewport(); ViewportClient->OnScreenshotCaptured().Clear(); ViewportClient->OnScreenshotCaptured().AddLambda( [this](int32 SizeX, int32 SizeY, const TArray<FColor>& Bitmap) { // Make sure that all alpha values are opaque. TArray<FColor>& RefBitmap = const_cast<TArray<FColor>&>(Bitmap); for (auto& Color : RefBitmap) Color.A = 255; TArray<uint8_t> last_compressed_png; FImageUtils::CompressImageArray(SizeX, SizeY, RefBitmap, last_compressed_png); last_compressed_png_ = std::vector<uint8_t>(last_compressed_png.GetData(), last_compressed_png.GetData() + last_compressed_png.Num()); }); is_installed = true; } }
AirSim/Unreal/Plugins/AirSim/Source/UnrealImageCapture.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/UnrealImageCapture.cpp", "repo_id": "AirSim", "token_count": 2633 }
59
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "CarWheelRear.h" #include "TireConfig.h" #include "UObject/ConstructorHelpers.h" UCarWheelRear::UCarWheelRear() { ShapeRadius = 18.f; ShapeWidth = 15.0f; bAffectedByHandbrake = true; SteerAngle = 0.f; // Setup suspension forces SuspensionForceOffset = -0.0f; SuspensionMaxRaise = 10.0f; SuspensionMaxDrop = 10.0f; SuspensionNaturalFrequency = 9.0f; SuspensionDampingRatio = 1.05f; // Find the tire object and set the data for it static ConstructorHelpers::FObjectFinder<UTireConfig> TireData(TEXT("/AirSim/VehicleAdv/Vehicle/WheelData/Vehicle_BackTireConfig.Vehicle_BackTireConfig")); TireConfig = TireData.Object; }
AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarWheelRear.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarWheelRear.cpp", "repo_id": "AirSim", "token_count": 286 }
60
// Fill out your copyright notice in the Description page of Project Settings. #include "WeatherLib.h" #include "Materials/MaterialParameterCollection.h" #include "Runtime/Engine/Classes/Kismet/GameplayStatics.h" #include "Blueprint/UserWidget.h" #include "Blueprint/WidgetBlueprintLibrary.h" AExponentialHeightFog* UWeatherLib::weather_fog_ = nullptr; UMaterialParameterCollectionInstance* UWeatherLib::getWeatherMaterialCollectionInstance(UWorld* World) { //UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull); if (World) { UMaterialParameterCollection* WeatherParameterCollection = Cast<UMaterialParameterCollection>(StaticLoadObject(UMaterialParameterCollection::StaticClass(), NULL, getWeatherParamsObjectPath())); //UWorld* World = GetWorld(); if (WeatherParameterCollection) { UMaterialParameterCollectionInstance* Instance = World->GetParameterCollectionInstance(WeatherParameterCollection); if (Instance) { return Instance; } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI could NOT get WeatherParameterCollectionInstance1!")); } } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI could NOT get WeatherParameterCollection1!")); } } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI could NOT get World!")); } return NULL; } void UWeatherLib::initWeather(UWorld* World, TArray<AActor*> ActorsToAttachTo) { //UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull); if (World) { UClass* WeatherActorClass = getWeatherActorPath().TryLoadClass<AActor>(); if (WeatherActorClass) { for (int32 i = 0; i < ActorsToAttachTo.Num(); i++) { const FVector Location = ActorsToAttachTo[i]->GetActorLocation(); const FRotator Rotation = ActorsToAttachTo[i]->GetActorRotation(); FActorSpawnParameters WeatherActorSpawnInfo; WeatherActorSpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; AActor* SpawnedWeatherActor = World->SpawnActor(WeatherActorClass, &Location, &Rotation, WeatherActorSpawnInfo); SpawnedWeatherActor->AttachToActor(ActorsToAttachTo[i], FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true)); } } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI got invalid weather actor class!")); } // still need the menu class for f10 UClass* MenuActorClass = getWeatherMenuObjectPath().TryLoadClass<AActor>(); if (MenuActorClass) { //UClass* Class, FTransform const* Transform, const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters() const FVector Location = FVector(0, 0, 0); const FRotator Rotation = FRotator(0.0f, 0.0f, 0.0f); FActorSpawnParameters SpawnInfo; SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; World->SpawnActor(MenuActorClass, &Location, &Rotation, SpawnInfo); } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI got invalid menu actor class!")); } } //showWeatherMenu(WorldContextObject); } void UWeatherLib::setWeatherParamScalar(UWorld* World, EWeatherParamScalar Param, float Amount) { UMaterialParameterCollectionInstance* WeatherMaterialCollectionInstance = UWeatherLib::getWeatherMaterialCollectionInstance(World); if (WeatherMaterialCollectionInstance) { FName ParamName = GetWeatherParamScalarName(Param); if (ParamName == TEXT("")) { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI got invalid paramname!")); } WeatherMaterialCollectionInstance->SetScalarParameterValue(ParamName, Amount); // if weather is not enabled, dont allow any weather values to be set // must be called after SetScalarParam, because WeatherEnabled is a scalar param // and must be set to true or false before this. // WeatherEnabled will always be false // NOTE: weather enabled must be set first, before other params for this to work if (!getIsWeatherEnabled(World)) { WeatherMaterialCollectionInstance->SetScalarParameterValue(ParamName, 0.0f); } if (weather_fog_) { weather_fog_->GetRootComponent()->SetVisibility(true); } } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI could NOT get MaterialCollectionInstance!")); } } float UWeatherLib::getWeatherParamScalar(UWorld* World, EWeatherParamScalar Param) { UMaterialParameterCollectionInstance* WeatherMaterialCollectionInstance = UWeatherLib::getWeatherMaterialCollectionInstance(World); if (WeatherMaterialCollectionInstance) { FName ParamName = GetWeatherParamScalarName(Param); if (ParamName == TEXT("")) { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI got invalid paramname!")); } float Amount; WeatherMaterialCollectionInstance->GetScalarParameterValue(ParamName, Amount); //SetScalarParameterValue(ParamName, Amount); return Amount; } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI could NOT get MaterialCollectionInstance!")); } return 0.0f; } FVector UWeatherLib::getWeatherWindDirection(UWorld* World) { UMaterialParameterCollectionInstance* WeatherMaterialCollectionInstance = UWeatherLib::getWeatherMaterialCollectionInstance(World); if (WeatherMaterialCollectionInstance) { FName ParamName = GetWeatherParamVectorName(EWeatherParamVector::WEATHER_PARAM_VECTOR_WIND); if (ParamName == TEXT("")) { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI got invalid paramname!")); } FLinearColor Direction; WeatherMaterialCollectionInstance->GetVectorParameterValue(ParamName, Direction); //SetScalarParameterValue(ParamName, Amount); return FVector(Direction); } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI could NOT get MaterialCollectionInstance!")); } return FVector(0, 0, 0); } void UWeatherLib::setWeatherWindDirection(UWorld* World, FVector NewWind) { UMaterialParameterCollectionInstance* WeatherMaterialCollectionInstance = UWeatherLib::getWeatherMaterialCollectionInstance(World); if (WeatherMaterialCollectionInstance) { FName ParamName = GetWeatherParamVectorName(EWeatherParamVector::WEATHER_PARAM_VECTOR_WIND); if (ParamName == TEXT("")) { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI got invalid paramname!")); } WeatherMaterialCollectionInstance->SetVectorParameterValue(ParamName, NewWind); } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI could NOT get MaterialCollectionInstance!")); } } bool UWeatherLib::getIsWeatherEnabled(UWorld* World) { if (getWeatherParamScalar(World, EWeatherParamScalar::WEATHER_PARAM_SCALAR_WEATHERENABLED) == 1.0f) { return true; } return false; } void UWeatherLib::setWeatherEnabled(UWorld* World, bool bEnabled) { float Value = 0; if (bEnabled) { Value = 1; } setWeatherParamScalar(World, EWeatherParamScalar::WEATHER_PARAM_SCALAR_WEATHERENABLED, Value); } void UWeatherLib::showWeatherMenu(UWorld* World) { //UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull); if (UClass* MenuWidgetClass = getWeatherMenuWidgetClass().TryLoadClass<UUserWidget>()) { UUserWidget* MenuWidget = CreateWidget<UUserWidget>(World, MenuWidgetClass); if (MenuWidget) { MenuWidget->AddToViewport(); } APlayerController* PC = UGameplayStatics::GetPlayerController(World, 0); if (PC) { PC->bShowMouseCursor = true; PC->DisableInput(PC); } } else { UE_LOG(LogTemp, Warning, TEXT("Warning, WeatherAPI could not load weather widget!")); } } void UWeatherLib::hideWeatherMenu(UWorld* World) { //UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull); UClass* MenuWidgetClass = getWeatherMenuWidgetClass().TryLoadClass<UUserWidget>(); if (World && MenuWidgetClass) { // get all menu actors, if any TArray<UUserWidget*> FoundWidgets; UWidgetBlueprintLibrary::GetAllWidgetsOfClass(World, FoundWidgets, UUserWidget::StaticClass()); UE_LOG(LogTemp, Warning, TEXT("%s Warning, WeatherAPI"), *MenuWidgetClass->GetClass()->GetFName().ToString()); if (FoundWidgets.Num() > 0) { for (int32 i = 0; i < FoundWidgets.Num(); i++) { // hacky test to make sure we are getting the right class. for some reason cast above doesn't work, so we use this instead to test for class if (FoundWidgets[i] && FoundWidgets[i]->GetClass()->GetFName().ToString() == getWeatherMenuClassName()) { FoundWidgets[i]->RemoveFromParent(); FoundWidgets[i]->RemoveFromViewport(); } } APlayerController* PC = UGameplayStatics::GetPlayerController(World, 0); if (PC) { PC->bShowMouseCursor = false; PC->EnableInput(PC); } } } } bool UWeatherLib::isMenuVisible(UWorld* World) { //UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull); UClass* MenuWidgetClass = getWeatherMenuWidgetClass().TryLoadClass<UUserWidget>(); if (World && MenuWidgetClass) { // get all menu actors, if any TArray<UUserWidget*> FoundWidgets; UWidgetBlueprintLibrary::GetAllWidgetsOfClass(World, FoundWidgets, UUserWidget::StaticClass()); UE_LOG(LogTemp, Warning, TEXT("%s Warning, WeatherAPI"), *MenuWidgetClass->GetClass()->GetFName().ToString()); if (FoundWidgets.Num() > 0) { for (int32 i = 0; i < FoundWidgets.Num(); i++) { // hacky test to make sure we are getting the right class. for some reason cast above doesn't work, so we use this instead to test for class if (FoundWidgets[i] && FoundWidgets[i]->GetClass()->GetFName().ToString() == getWeatherMenuClassName()) { return true; } } } } // get all menu actors, if any, then hide the menu return false; } void UWeatherLib::toggleWeatherMenu(UWorld* World) { if (isMenuVisible(World)) { hideWeatherMenu(World); } else { showWeatherMenu(World); } } UWorld* UWeatherLib::widgetGetWorld(UUserWidget* Widget) { if (Widget) { return Widget->GetWorld(); } return NULL; } UWorld* UWeatherLib::actorGetWorld(AActor* Actor) { if (Actor) { return Actor->GetWorld(); } return NULL; } void UWeatherLib::setWeatherFog(AExponentialHeightFog* fog) { weather_fog_ = fog; }
AirSim/Unreal/Plugins/AirSim/Source/Weather/WeatherLib.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/Weather/WeatherLib.cpp", "repo_id": "AirSim", "token_count": 4267 }
61
#!/bin/bash AIRSIM_EXECUTABLE=/home/airsim_user/Blocks/Blocks.sh echo Starting AirSim binary... $AIRSIM_EXECUTABLE & echo Waiting 10 seconds before starting app... sleep 10 echo Starting Python app python3.6 /home/airsim_user/app/multirotor.py
AirSim/azure/docker/docker-entrypoint.sh/0
{ "file_path": "AirSim/azure/docker/docker-entrypoint.sh", "repo_id": "AirSim", "token_count": 83 }
62
# Contributing ## Quick Start - Please read our [short and sweet coding guidelines](coding_guidelines.md). - For big changes such as adding new feature or refactoring, [file an issue first](https://github.com/Microsoft/AirSim/issues). - Use our [recommended development workflow](dev_workflow.md) to make changes and test it. - Use [usual steps](https://www.dataschool.io/how-to-contribute-on-github/) to make contributions just like other GitHub projects. If you are not familiar with Git Branch-Rebase-Merge workflow, please [read this first](https://git-rebase.io/). ## Checklist - Use same style and formatting as rest of code even if it's not your preferred one. - Change any documentation that goes with code changes. - Do not include OS specific header files or new 3rd party dependencies. - Keep your pull request small, ideally under 10 files. - Make sure you don't include large binary files. - When adding new includes, make dependency is absolutely necessary. - Rebase your branch frequently with main (once every 2-3 days is ideal). - Make sure your code would compile on Windows, Linux and OSX.
AirSim/docs/CONTRIBUTING.md/0
{ "file_path": "AirSim/docs/CONTRIBUTING.md", "repo_id": "AirSim", "token_count": 281 }
63
# Code Structure ## AirLib Majority of the code is located in AirLib. This is a self-contained library that you should be able to compile with any C++11 compiler. AirLib consists of the following components: 1. [*Physics engine:*](https://github.com/microsoft/AirSim/tree/main/AirLib/include/physics) This is header-only physics engine. It is designed to be fast and extensible to implement different vehicles. 2. [*Sensor models:*](https://github.com/microsoft/AirSim/tree/main/AirLib/include/sensors) This is header-only models for Barometer, IMU, GPS and Magnetometer. 3. [*Vehicle models:*](https://github.com/microsoft/AirSim/tree/main/AirLib/include/vehiclesr) This is header-only models for vehicle configurations and models. Currently we have implemented model for a MultiRotor and a configuration for PX4 QuadRotor in the X config. There are several different Multirotor models defined in MultiRotorParams.hpp including a hexacopter as well. 4. [*API-related files:*](https://github.com/microsoft/AirSim/tree/main/AirLib/include/api) This part of AirLib provides abstract base class for our APIs and concrete implementation for specific vehicle platforms such as MavLink. It also has classes for the RPC client and server. Apart from these, all common utilities are defined in [`common/`](https://github.com/microsoft/AirSim/tree/main/AirLib/include/common) subfolder. One important file here is [AirSimSettings.hpp](https://github.com/microsoft/AirSim/blob/main/AirLib/include/common/AirSimSettings.hpp) which should be modified if any new fields are to be added in `settings.json`. AirSim supports different firmwares for Multirotor such as its own SimpleFlight, PX4 and ArduPilot, files for communicating with each firmware are placed in their respective subfolders in [`multirotor/firmwares`](https://github.com/microsoft/AirSim/tree/main/AirLib/include/vehicles/multirotor/firmwares). The vehicle-specific APIs are defined in the `api/` subfolder, along-with required structs. The [`AirLib/src/`](https://github.com/microsoft/AirSim/tree/main/AirLib/src) contains .cpp files with implementations of various mehtods defined in the .hpp files. For e.g. [MultirotorApiBase.cpp](https://github.com/microsoft/AirSim/blob/main/AirLib/src/vehicles/multirotor/api/MultirotorApiBase.cpp) contains the base implementation of the multirotor APIs, which can also be overridden in the specific firmware files if required. ## Unreal/Plugins/AirSim This is the only portion of project which is dependent on Unreal engine. We have kept it isolated so we can implement simulator for other platforms as well, as has been done for [Unity](https://microsoft.github.io/AirSim/Unity.html). The Unreal code takes advantage of its UObject based classes including Blueprints. The `Source/` folder contains the C++ files, while the `Content/` folder has the blueprints and assets. Some main components are described below: 1. *SimMode_ classes*: The SimMode classes help implement many different modes, such as pure Computer Vision mode, where there is no vehicle or simulation for a specific vehicle (currently car and multirotor). The vehicle classes are located in [`Vehicles/`](https://github.com/microsoft/AirSim/tree/main/Unreal/Plugins/AirSim/Source/Vehicles) 2. *PawnSimApi*: This is the [base class](https://github.com/microsoft/AirSim/blob/main/Unreal/Plugins/AirSim/Source/PawnSimApi.cpp) for all vehicle pawn visualizations. Each vehicle has their own child (Multirotor|Car|ComputerVision)Pawn class. 3. [UnrealSensors](https://github.com/microsoft/AirSim/tree/main/Unreal/Plugins/AirSim/Source/UnrealSensors): Contains implementation of Distance and Lidar sensors. 4. *WorldSimApi*: Implements most of the environment and vehicle-agnostic APIs Apart from these, [`PIPCamera`](https://github.com/microsoft/AirSim/blob/main/Unreal/Plugins/AirSim/Source/PIPCamera.cpp) contains the camera initialization, and [`UnrealImageCapture`](https://github.com/microsoft/AirSim/blob/main/Unreal/Plugins/AirSim/Source/UnrealImageCapture.cpp) & [`RenderRequest`](https://github.com/microsoft/AirSim/blob/main/Unreal/Plugins/AirSim/Source/RenderRequest.cpp) the image rendering code. [`AirBlueprintLib`](https://github.com/microsoft/AirSim/blob/main/Unreal/Plugins/AirSim/Source/AirBlueprintLib.cpp) has a lot of utility and wrapper methods used to interface with the UE4 engine. ## MavLinkCom This is the library developed by our own team member [Chris Lovett](https://github.com/lovettchris) that provides C++ classes to talk to the MavLink devices. This library is stand alone and can be used in any project. See [MavLinkCom](mavlinkcom.md) for more info. ## Sample Programs We have created a few sample programs to demonstrate how to use the API. See HelloDrone and DroneShell. DroneShell demonstrates how to connect to the simulator using UDP. The simulator is running a server (similar to DroneServer). ## PythonClient [PythonClient](https://github.com/microsoft/AirSim/tree/main/PythonClient) contains Python API wrapper files and sample programs demonstrating their uses. ## Contributing See [Contribution Guidelines](CONTRIBUTING.md) ## Unreal Framework The following picture illustrates how AirSim is loaded and invoked by the Unreal Game Engine: ![AirSimConstruction](images/airsim_startup.png)
AirSim/docs/code_structure.md/0
{ "file_path": "AirSim/docs/code_structure.md", "repo_id": "AirSim", "token_count": 1464 }
64
# Image APIs Please read [general API doc](apis.md) first if you are not familiar with AirSim APIs. ## Getting a Single Image Here's a sample code to get a single image from camera named "0". The returned value is bytes of png format image. To get uncompressed and other format as well as available cameras please see next sections. ### Python ```python import airsim #pip install airsim # for car use CarClient() client = airsim.MultirotorClient() png_image = client.simGetImage("0", airsim.ImageType.Scene) # do something with image ``` ### C++ ```cpp #include "vehicles/multirotor/api/MultirotorRpcLibClient.hpp" int getOneImage() { using namespace msr::airlib; // for car use CarRpcLibClient MultirotorRpcLibClient client; std::vector<uint8_t> png_image = client.simGetImage("0", VehicleCameraBase::ImageType::Scene); // do something with images } ``` ## Getting Images with More Flexibility The `simGetImages` API which is slightly more complex to use than `simGetImage` API, for example, you can get left camera view, right camera view and depth image from left camera in a single API call. The `simGetImages` API also allows you to get uncompressed images as well as floating point single channel images (instead of 3 channel (RGB), each 8 bit). ### Python ```python import airsim #pip install airsim # for car use CarClient() client = airsim.MultirotorClient() responses = client.simGetImages([ # png format airsim.ImageRequest(0, airsim.ImageType.Scene), # uncompressed RGB array bytes airsim.ImageRequest(1, airsim.ImageType.Scene, False, False), # floating point uncompressed image airsim.ImageRequest(1, airsim.ImageType.DepthPlanar, True)]) # do something with response which contains image data, pose, timestamp etc ``` #### Using AirSim Images with NumPy If you plan to use numpy for image manipulation, you should get uncompressed RGB image and then convert to numpy like this: ```python responses = client.simGetImages([airsim.ImageRequest("0", airsim.ImageType.Scene, False, False)]) response = responses[0] # get numpy array img1d = np.fromstring(response.image_data_uint8, dtype=np.uint8) # reshape array to 4 channel image array H X W X 4 img_rgb = img1d.reshape(response.height, response.width, 3) # original image is fliped vertically img_rgb = np.flipud(img_rgb) # write to png airsim.write_png(os.path.normpath(filename + '.png'), img_rgb) ``` #### Quick Tips - The API `simGetImage` returns `binary string literal` which means you can simply dump it in binary file to create a .png file. However if you want to process it in any other way than you can handy function `airsim.string_to_uint8_array`. This converts binary string literal to NumPy uint8 array. - The API `simGetImages` can accept request for multiple image types from any cameras in single call. You can specify if image is png compressed, RGB uncompressed or float array. For png compressed images, you get `binary string literal`. For float array you get Python list of float64. You can convert this float array to NumPy 2D array using ``` airsim.list_to_2d_float_array(response.image_data_float, response.width, response.height) ``` You can also save float array to .pfm file (Portable Float Map format) using `airsim.write_pfm()` function. - If you are looking to query position and orientation information in sync with a call to one of the image APIs, you can use `client.simPause(True)` and `client.simPause(False)` to pause the simulation while calling the image API and querying the desired physics state, ensuring that the physics state remains the same immediately after the image API call. ### C++ ```cpp int getStereoAndDepthImages() { using namespace msr::airlib; typedef VehicleCameraBase::ImageRequest ImageRequest; typedef VehicleCameraBase::ImageResponse ImageResponse; typedef VehicleCameraBase::ImageType ImageType; // for car use // CarRpcLibClient client; MultirotorRpcLibClient client; // get right, left and depth images. First two as png, second as float16. std::vector<ImageRequest> request = { //png format ImageRequest("0", ImageType::Scene), //uncompressed RGB array bytes ImageRequest("1", ImageType::Scene, false, false), //floating point uncompressed image ImageRequest("1", ImageType::DepthPlanar, true) }; const std::vector<ImageResponse>& response = client.simGetImages(request); // do something with response which contains image data, pose, timestamp etc } ``` ## Ready to Run Complete Examples ### Python For a more complete ready to run sample code please see [sample code in AirSimClient project](https://github.com/Microsoft/AirSim/tree/main/PythonClient//multirotor/hello_drone.py) for multirotors or [HelloCar sample](https://github.com/Microsoft/AirSim/tree/main/PythonClient//car/hello_car.py). This code also demonstrates simple activities such as saving images in files or using `numpy` to manipulate images. ### C++ For a more complete ready to run sample code please see [sample code in HelloDrone project](https://github.com/Microsoft/AirSim/tree/main/HelloDrone//main.cpp) for multirotors or [HelloCar project](https://github.com/Microsoft/AirSim/tree/main/HelloCar//main.cpp). See also [other example code](https://github.com/Microsoft/AirSim/tree/main/Examples/DataCollection/StereoImageGenerator.hpp) that generates specified number of stereo images along with ground truth depth and disparity and saving it to [pfm format](pfm.md). ## Available Cameras These are the default cameras already available in each vehicle. Apart from these, you can add more cameras to the vehicles and external cameras which are not attached to any vehicle through the [settings](settings.md). ### Car The cameras on car can be accessed by following names in API calls: `front_center`, `front_right`, `front_left`, `fpv` and `back_center`. Here FPV camera is driver's head position in the car. ### Multirotor The cameras on the drone can be accessed by following names in API calls: `front_center`, `front_right`, `front_left`, `bottom_center` and `back_center`. ### Computer Vision Mode Camera names are same as in multirotor. ### Backward compatibility for camera names Before AirSim v1.2, cameras were accessed using ID numbers instead of names. For backward compatibility you can still use following ID numbers for above camera names in same order as above: `"0"`, `"1"`, `"2"`, `"3"`, `"4"`. In addition, camera name `""` is also available to access the default camera which is generally the camera `"0"`. ## "Computer Vision" Mode You can use AirSim in so-called "Computer Vision" mode. In this mode, physics engine is disabled and there is no vehicle, just cameras (If you want to have the vehicle but without its kinematics, you can use the Multirotor mode with the Physics Engine [ExternalPhysicsEngine](settings.md##physicsenginename)). You can move around using keyboard (use F1 to see help on keys). You can press Record button to continuously generate images. Or you can call APIs to move cameras around and take images. To active this mode, edit [settings.json](settings.md) that you can find in your `Documents\AirSim` folder (or `~/Documents/AirSim` on Linux) and make sure following values exist at root level: ```json { "SettingsVersion": 1.2, "SimMode": "ComputerVision" } ``` [Here's the Python code example](https://github.com/Microsoft/AirSim/tree/main/PythonClient//computer_vision/cv_mode.py) to move camera around and capture images. This mode was inspired from [UnrealCV project](http://unrealcv.org/). ### Setting Pose in Computer Vision Mode To move around the environment using APIs you can use `simSetVehiclePose` API. This API takes position and orientation and sets that on the invisible vehicle where the front-center camera is located. All rest of the cameras move along keeping the relative position. If you don't want to change position (or orientation) then just set components of position (or orientation) to floating point nan values. The `simGetVehiclePose` allows to retrieve the current pose. You can also use `simGetGroundTruthKinematics` to get the quantities kinematics quantities for the movement. Many other non-vehicle specific APIs are also available such as segmentation APIs, collision APIs and camera APIs. ## Camera APIs The `simGetCameraInfo` returns the pose (in world frame, NED coordinates, SI units) and FOV (in degrees) for the specified camera. Please see [example usage](https://github.com/Microsoft/AirSim/tree/main/PythonClient//computer_vision/cv_mode.py). The `simSetCameraPose` sets the pose for the specified camera while taking an input pose as a combination of relative position and a quaternion in NED frame. The handy `airsim.to_quaternion()` function allows to convert pitch, roll, yaw to quaternion. For example, to set camera-0 to 15-degree pitch while maintaining the same position, you can use: ``` camera_pose = airsim.Pose(airsim.Vector3r(0, 0, 0), airsim.to_quaternion(0.261799, 0, 0)) #PRY in radians client.simSetCameraPose(0, camera_pose); ``` - `simSetCameraFov` allows changing the Field-of-View of the camera at runtime. - `simSetDistortionParams`, `simGetDistortionParams` allow setting and fetching the distortion parameters K1, K2, K3, P1, P2 All Camera APIs take in 3 common parameters apart from the API-specific ones, `camera_name`(str), `vehicle_name`(str) and `external`(bool, to indicate [External Camera](settings.md#external-cameras)). Camera and vehicle name is used to get the specific camera, if `external` is set to `true`, then the vehicle name is ignored. Also see [external_camera.py](https://github.com/microsoft/AirSim/blob/main/PythonClient/computer_vision/external_camera.py) for example usage of these APIs. ### Gimbal You can set stabilization for pitch, roll or yaw for any camera [using settings](settings.md#gimbal). Please see [example usage](https://github.com/Microsoft/AirSim/tree/main/PythonClient//computer_vision/cv_mode.py). ## Changing Resolution and Camera Parameters To change resolution, FOV etc, you can use [settings.json](settings.md). For example, below addition in settings.json sets parameters for scene capture and uses "Computer Vision" mode described above. If you omit any setting then below default values will be used. For more information see [settings doc](settings.md). If you are using stereo camera, currently the distance between left and right is fixed at 25 cm. ```json { "SettingsVersion": 1.2, "CameraDefaults": { "CaptureSettings": [ { "ImageType": 0, "Width": 256, "Height": 144, "FOV_Degrees": 90, "AutoExposureSpeed": 100, "MotionBlurAmount": 0 } ] }, "SimMode": "ComputerVision" } ``` ## What Does Pixel Values Mean in Different Image Types? ### Available ImageType Values ```cpp Scene = 0, DepthPlanar = 1, DepthPerspective = 2, DepthVis = 3, DisparityNormalized = 4, Segmentation = 5, SurfaceNormals = 6, Infrared = 7, OpticalFlow = 8, OpticalFlowVis = 9 ``` ### DepthPlanar and DepthPerspective You normally want to retrieve the depth image as float (i.e. set `pixels_as_float = true`) and specify `ImageType = DepthPlanar` or `ImageType = DepthPerspective` in `ImageRequest`. For `ImageType = DepthPlanar`, you get depth in camera plane, i.e., all points that are plane-parallel to the camera have same depth. For `ImageType = DepthPerspective`, you get depth from camera using a projection ray that hits that pixel. Depending on your use case, planner depth or perspective depth may be the ground truth image that you want. For example, you may be able to feed perspective depth to ROS package such as `depth_image_proc` to generate a point cloud. Or planner depth may be more compatible with estimated depth image generated by stereo algorithms such as SGM. ### DepthVis When you specify `ImageType = DepthVis` in `ImageRequest`, you get an image that helps depth visualization. In this case, each pixel value is interpolated from black to white depending on depth in camera plane in meters. The pixels with pure white means depth of 100m or more while pure black means depth of 0 meters. ### DisparityNormalized You normally want to retrieve disparity image as float (i.e. set `pixels_as_float = true` and specify `ImageType = DisparityNormalized` in `ImageRequest`) in which case each pixel is `(Xl - Xr)/Xmax`, which is thereby normalized to values between 0 to 1. ### Segmentation When you specify `ImageType = Segmentation` in `ImageRequest`, you get an image that gives you ground truth segmentation of the scene. At the startup, AirSim assigns value 0 to 255 to each mesh available in environment. This value is then mapped to a specific color in [the pallet](https://github.com/microsoft/AirSim/blob/main/Unreal/Plugins/AirSim/Content/HUDAssets/seg_color_palette.png). The RGB values for each object ID can be found in [this file](seg_rgbs.txt). You can assign a specific value (limited to the range 0-255) to a specific mesh using APIs. For example, below Python code sets the object ID for the mesh called "Ground" to 20 in Blocks environment and hence changes its color in Segmentation view: ```python success = client.simSetSegmentationObjectID("Ground", 20); ``` The return value is a boolean type that lets you know if the mesh was found. Notice that typical Unreal environments, like Blocks, usually have many other meshes that comprises of same object, for example, "Ground_2", "Ground_3" and so on. As it is tedious to set object ID for all of these meshes, AirSim also supports regular expressions. For example, the code below sets all meshes which have names starting with "ground" (ignoring case) to 21 with just one line: ```python success = client.simSetSegmentationObjectID("ground[\w]*", 21, True); ``` The return value is true if at least one mesh was found using regular expression matching. It is recommended that you request uncompressed image using this API to ensure you get precise RGB values for segmentation image: ```python responses = client.simGetImages([ImageRequest(0, AirSimImageType.Segmentation, False, False)]) img1d = np.fromstring(response.image_data_uint8, dtype=np.uint8) #get numpy array img_rgb = img1d.reshape(response.height, response.width, 3) #reshape array to 3 channel image array H X W X 3 img_rgb = np.flipud(img_rgb) #original image is fliped vertically #find unique colors print(np.unique(img_rgb[:,:,0], return_counts=True)) #red print(np.unique(img_rgb[:,:,1], return_counts=True)) #green print(np.unique(img_rgb[:,:,2], return_counts=True)) #blue ``` A complete ready-to-run example can be found in [segmentation.py](https://github.com/Microsoft/AirSim/tree/main/PythonClient//computer_vision/segmentation.py). #### Unsetting object ID An object's ID can be set to -1 to make it not show up on the segmentation image. #### How to Find Mesh Names? To get desired ground truth segmentation you will need to know the names of the meshes in your Unreal environment. To do this, you will need to open up Unreal Environment in Unreal Editor and then inspect the names of the meshes you are interested in using the World Outliner. For example, below we see the mesh names for the ground in Blocks environment in right panel in the editor: ![record screenshot](images/unreal_editor_blocks.png) If you don't know how to open Unreal Environment in Unreal Editor then try following the guide for [building from source](build_windows.md). Once you decide on the meshes you are interested, note down their names and use above API to set their object IDs. There are [few settings](settings.md#segmentation-settings) available to change object ID generation behavior. #### Changing Colors for Object IDs At present the color for each object ID is fixed as in [this pallet](https://github.com/microsoft/AirSim/blob/main/Unreal/Plugins/AirSim/Content/HUDAssets/seg_color_palette.png). We will be adding ability to change colors for object IDs to desired values shortly. In the meantime you can open the segmentation image in your favorite image editor and get the RGB values you are interested in. #### Startup Object IDs At the start, AirSim assigns object ID to each object found in environment of type `UStaticMeshComponent` or `ALandscapeProxy`. It then either uses mesh name or owner name (depending on settings), lower cases it, removes any chars below ASCII 97 to remove numbers and some punctuations, sums int value of all chars and modulo 255 to generate the object ID. In other words, all object with same alphabet chars would get same object ID. This heuristic is simple and effective for many Unreal environments but may not be what you want. In that case, please use above APIs to change object IDs to your desired values. There are [few settings](settings.md#segmentation-settings) available to change this behavior. #### Getting Object ID for Mesh The `simGetSegmentationObjectID` API allows you get object ID for given mesh name. ### Infrared Currently this is just a map from object ID to grey scale 0-255. So any mesh with object ID 42 shows up with color (42, 42, 42). Please see [segmentation section](#segmentation) for more details on how to set object IDs. Typically noise setting can be applied for this image type to get slightly more realistic effect. We are still working on adding other infrared artifacts and any contributions are welcome. ### OpticalFlow and OpticalFlowVis These image types return information about motion perceived by the point of view of the camera. OpticalFlow returns a 2-channel image where the channels correspond to vx and vy respectively. OpticalFlowVis is similar to OpticalFlow but converts flow data to RGB for a more 'visual' output. ## Example Code A complete example of setting vehicle positions at random locations and orientations and then taking images can be found in [GenerateImageGenerator.hpp](https://github.com/Microsoft/AirSim/tree/main/Examples/DataCollection/StereoImageGenerator.hpp). This example generates specified number of stereo images and ground truth disparity image and saving it to [pfm format](pfm.md).
AirSim/docs/image_apis.md/0
{ "file_path": "AirSim/docs/image_apis.md", "repo_id": "AirSim", "token_count": 5055 }
65
# Welcome to MavLinkMoCap This folder contains the MavLinkMoCap library which connects to a OptiTrack camera system for accurate indoor location. ## Dependencies: * [OptiTrack Motive](http://www.optitrack.com/products/motive/). * [MavLinkCom](mavlinkcom.md). ### Setup RigidBody First you need to define a RigidBody named 'Quadrocopter' using Motive. See [Rigid_Body_Tracking](http://wiki.optitrack.com/index.php?title=Rigid_Body_Tracking). ### MavLinkTest Use MavLinkTest to talk to your PX4 drone, with "-server:addr:port", for example, when connected to drone wifi use: MavLinkMoCap -server:10.42.0.228:14590 "-project:D:\OptiTrack\Motive Project 2016-12-19 04.09.42 PM.ttp" This publishes the ATT_POS_MOCAP messages and you can proxy those through to the PX4 by running MavLinkTest on the dronebrain using: MavLinkTest -serial:/dev/ttyACM0,115200 -proxy:10.42.0.228:14590 Now the drone will get the ATT_POS_MOCAP and you should see the light turn green meaning it is now has a home position and is ready to fly.
AirSim/docs/mavlinkcom_mocap.md/0
{ "file_path": "AirSim/docs/mavlinkcom_mocap.md", "repo_id": "AirSim", "token_count": 348 }
66
# Sensors in AirSim AirSim currently supports the following sensors. Each sensor is associated with a integer enum specifying its sensor type. * Camera * Barometer = 1 * Imu = 2 * Gps = 3 * Magnetometer = 4 * Distance Sensor = 5 * Lidar = 6 **Note** : Cameras are configured differently than the other sensors and do not have an enum associated with them. Look at [general settings](settings.md) and [image API](image_apis.md) for camera config and API. ## Default sensors If no sensors are specified in the `settings.json`, then the following sensors are enabled by default based on the sim mode. ### Multirotor * Imu * Magnetometer * Gps * Barometer ### Car * Gps ### ComputerVision * None Behind the scenes, `createDefaultSensorSettings` method in [AirSimSettings.hpp](https://github.com/Microsoft/AirSim/blob/main/AirLib/include/common/AirSimSettings.hpp) sets up the above sensors with their default parameters, depending on the sim mode specified in the `settings.json` file. ## Configuring the default sensor list The default sensor list can be configured in settings json: ```json "DefaultSensors": { "Barometer": { "SensorType": 1, "Enabled" : true, "PressureFactorSigma": 0.001825, "PressureFactorTau": 3600, "UncorrelatedNoiseSigma": 2.7, "UpdateLatency": 0, "UpdateFrequency": 50, "StartupDelay": 0 }, "Imu": { "SensorType": 2, "Enabled" : true, "AngularRandomWalk": 0.3, "GyroBiasStabilityTau": 500, "GyroBiasStability": 4.6, "VelocityRandomWalk": 0.24, "AccelBiasStabilityTau": 800, "AccelBiasStability": 36 }, "Gps": { "SensorType": 3, "Enabled" : true, "EphTimeConstant": 0.9, "EpvTimeConstant": 0.9, "EphInitial": 25, "EpvInitial": 25, "EphFinal": 0.1, "EpvFinal": 0.1, "EphMin3d": 3, "EphMin2d": 4, "UpdateLatency": 0.2, "UpdateFrequency": 50, "StartupDelay": 1 }, "Magnetometer": { "SensorType": 4, "Enabled" : true, "NoiseSigma": 0.005, "ScaleFactor": 1, "NoiseBias": 0, "UpdateLatency": 0, "UpdateFrequency": 50, "StartupDelay": 0 }, "Distance": { "SensorType": 5, "Enabled" : true, "MinDistance": 0.2, "MaxDistance": 40, "X": 0, "Y": 0, "Z": -1, "Yaw": 0, "Pitch": 0, "Roll": 0, "DrawDebugPoints": false }, "Lidar2": { "SensorType": 6, "Enabled" : true, "NumberOfChannels": 16, "RotationsPerSecond": 10, "PointsPerSecond": 100000, "X": 0, "Y": 0, "Z": -1, "Roll": 0, "Pitch": 0, "Yaw" : 0, "VerticalFOVUpper": -15, "VerticalFOVLower": -25, "HorizontalFOVStart": -20, "HorizontalFOVEnd": 20, "DrawDebugPoints": true, "DataFrame": "SensorLocalFrame" } }, ``` ## Configuring vehicle-specific sensor list A vehicle can override a subset of the default sensors listed above. A Lidar and Distance sensor are not added to a vehicle by default, so those you need to add this way. Each sensor must have a valid "SensorType" and a subset of the properties can be defined that override the default values shown above and you can set Enabled to false to disable a specific type of sensor. ```json "Vehicles": { "Drone1": { "VehicleType": "SimpleFlight", "AutoCreate": true, ... "Sensors": { "Barometer":{ "SensorType": 1, "Enabled": true, "PressureFactorSigma": 0.0001825 }, "MyLidar1": { "SensorType": 6, "Enabled" : true, "NumberOfChannels": 16, "PointsPerSecond": 10000, "X": 0, "Y": 0, "Z": -1, "DrawDebugPoints": true }, "MyLidar2": { "SensorType": 6, "Enabled" : true, "NumberOfChannels": 4, "PointsPerSecond": 10000, "X": 0, "Y": 0, "Z": -1, "DrawDebugPoints": true } } } } ``` ### Sensor specific settings For detailed information on the meaning of these sensor settings see the following pages: - [Lidar sensor settings](lidar.md) - [Distance sensor settings](distance_sensor.md) ##### Server side visualization for debugging Be default, the points hit by distance sensor are not drawn on the viewport. To enable the drawing of hit points on the viewport, please enable setting `DrawDebugPoints` via settings json. E.g. - ```json "Distance": { "SensorType": 5, "Enabled" : true, ... "DrawDebugPoints": true } ``` ## Sensor APIs Jump straight to [`hello_drone.py`](https://github.com/Microsoft/AirSim/blob/main/PythonClient/multirotor/hello_drone.py) or [`hello_drone.cpp`](https://github.com/Microsoft/AirSim/blob/main/HelloDrone/main.cpp) for example usage, or see follow below for the full API. ### Barometer ```cpp msr::airlib::BarometerBase::Output getBarometerData(const std::string& barometer_name, const std::string& vehicle_name); ``` ```python barometer_data = client.getBarometerData(barometer_name = "", vehicle_name = "") ``` ### IMU ```cpp msr::airlib::ImuBase::Output getImuData(const std::string& imu_name = "", const std::string& vehicle_name = ""); ``` ```python imu_data = client.getImuData(imu_name = "", vehicle_name = "") ``` ### GPS ```cpp msr::airlib::GpsBase::Output getGpsData(const std::string& gps_name = "", const std::string& vehicle_name = ""); ``` ```python gps_data = client.getGpsData(gps_name = "", vehicle_name = "") ``` ### Magnetometer ```cpp msr::airlib::MagnetometerBase::Output getMagnetometerData(const std::string& magnetometer_name = "", const std::string& vehicle_name = ""); ``` ```python magnetometer_data = client.getMagnetometerData(magnetometer_name = "", vehicle_name = "") ``` ### Distance sensor ```cpp msr::airlib::DistanceSensorData getDistanceSensorData(const std::string& distance_sensor_name = "", const std::string& vehicle_name = ""); ``` ```python distance_sensor_data = client.getDistanceSensorData(distance_sensor_name = "", vehicle_name = "") ``` ### Lidar See the [lidar page](lidar.md) for Lidar API.
AirSim/docs/sensors.md/0
{ "file_path": "AirSim/docs/sensors.md", "repo_id": "AirSim", "token_count": 2720 }
67
# XBox Controller To use an XBox controller with AirSim follow these steps: 1. Connect XBox controller so it shows up in your PC Game Controllers: ![Gamecontrollers](images/game_controllers.png) 2. Launch QGroundControl and you should see a new Joystick tab under settings: ![Gamecontrollers](images/qgc_joystick.png) Now calibrate the radio, and setup some handy button actions. For example, I set mine so that the 'A' button arms the drone, 'B' put it in manual flight mode, 'X' puts it in altitude hold mode and 'Y' puts it in position hold mode. I also prefer the feel of the controller when I check the box labelled "Use exponential curve on roll,pitch, yaw" because this gives me more sensitivity for small movements. QGroundControl will find your Pixhawk via the UDP proxy port 14550 setup by MavLinkTest above. AirSim will find your Pixhawk via the other UDP server port 14570 also setup by MavLinkTest above. You can also use all the QGroundControl controls for autonomous flying at this point too. 3. Connect to Pixhawk serial port using MavLinkTest.exe like this: ``` MavLinkTest.exe -serial:*,115200 -proxy:127.0.0.1:14550 -server:127.0.0.1:14570 ``` 4. Run AirSim Unreal simulator with these `~/Documents/AirSim/settings.json` settings: ``` "Vehicles": { "PX4": { "VehicleType": "PX4Multirotor", "SitlIp": "", "SitlPort": 14560, "UdpIp": "127.0.0.1", "UdpPort": 14570, "UseSerial": false } } ``` ## Advanced If the Joystick tab doesn't show up in QGroundControl then Click on the purple "Q" icon on left in tool bar to reveal the Preferences panel. Go to General tab and check the Virtual Joystick checkbox. Go back to settings screen (gears icon), click on Parameters tab, type `COM_RC_IN_MODE` in search box and change its value to either `Joystick/No RC Checks` or `Virtual RC by Joystick`. ### Other Options See [remote controller options](remote_control.md)
AirSim/docs/xbox_controller.md/0
{ "file_path": "AirSim/docs/xbox_controller.md", "repo_id": "AirSim", "token_count": 616 }
68
<launch> <!-- AirSim ROS Wrapper --> <include file="$(find airsim_ros_pkgs)/launch/airsim_node.launch"/> <!-- Vehicle Dynamic Constraints --> <include file="$(find airsim_ros_pkgs)/launch/dynamic_constraints.launch"/> <!-- Simple PID Position Controller --> <include file="$(find airsim_ros_pkgs)/launch/position_controller_simple.launch"/> </launch>
AirSim/ros/src/airsim_ros_pkgs/launch/airsim_with_simple_PD_position_controller.launch/0
{ "file_path": "AirSim/ros/src/airsim_ros_pkgs/launch/airsim_with_simple_PD_position_controller.launch", "repo_id": "AirSim", "token_count": 117 }
69
#!/usr/bin/env python #capture joystick events using ROS and convert to AirSim Car API commands #to enable: # rosrun joy joy_node import rospy import threading import sensor_msgs import sensor_msgs.msg import airsim_ros_pkgs as air import airsim_ros_pkgs.msg class CarCommandTranslator(object): def __init__(self): self.lock = threading.Lock() self.last_forward_btn = 0 self.last_reverse_btn = 0 self.last_neutral_btn = 0 self.last_park_btn = 0 self.last_shift_down_btn = 0 self.last_shift_up_btn = 0 self.parked = True self.last_gear = 0 self.shift_mode_manual = True update_rate_hz = rospy.get_param('~update_rate_hz', 20.0) self.max_curvature = rospy.get_param('~max_curvature', 0.75) self.steer_sign = rospy.get_param('~steer_sign', -1) self.throttle_brake_sign = rospy.get_param('~throttle_brake_sign', 1) self.auto_gear_max = rospy.get_param('~auto_gear_max', 5) self.manual_transmission = rospy.get_param('~manual_transmission', True) self.forward_btn_index = rospy.get_param('~forward_button_index', 0) self.reverse_btn_index = rospy.get_param('~reverse_button_index', 1) # Below was an earlier typo, written like this for compatibility self.neutral_btn_index = rospy.get_param('~neutral_button_index', rospy.get_param('~nuetral_button_index', 2)) self.park_btn_index = rospy.get_param('~park_button_index', 3) self.shift_down_btn_index = rospy.get_param('~shift_down_index', 4) self.shift_up_btn_index = rospy.get_param('~shift_up_index', 5) car_control_topic = rospy.get_param('~car_control_topic', '/airsim_node/drone_1/car_cmd') self.joy_msg = None self.joy_sub = rospy.Subscriber( 'joy', sensor_msgs.msg.Joy, self.handle_joy) self.command_pub = rospy.Publisher( car_control_topic, air.msg.CarControls, queue_size=0 ) self.update_time = rospy.Timer( rospy.Duration(1.0/update_rate_hz), self.handle_update_timer ) def handle_joy(self, msg): with self.lock: self.joy_msg = msg def handle_update_timer(self, ignored): joy = None with self.lock: joy = self.joy_msg if joy is None: return controls = airsim_ros_pkgs.msg.CarControls() controls.steering = self.steer_sign * self.max_curvature * joy.axes[2] u = joy.axes[1] * self.throttle_brake_sign if u > 0.0: controls.throttle = abs(u) controls.brake = 0.0 else: controls.throttle = 0.0 controls.brake = abs(u) forward_btn = joy.buttons[self.forward_btn_index] reverse_btn = joy.buttons[self.reverse_btn_index] neutral_btn = joy.buttons[self.neutral_btn_index] park_btn = joy.buttons[self.park_btn_index] shift_up_btn = joy.buttons[self.shift_up_btn_index] shift_down_btn = joy.buttons[self.shift_down_btn_index] # gearing: -1 reverse, 0 N, >= 1 drive controls.manual = True #set to False for automatic transmission along with manual_gear > 1 if not self.last_neutral_btn and neutral_btn: self.last_gear = 0 self.parked = False controls.manual = True elif not self.last_forward_btn and forward_btn: if self.manual_transmission: self.last_gear = 1 self.shift_mode_manual = True else: self.shift_mode_manual = False self.last_gear = self.auto_gear_max self.parked = False elif not self.last_reverse_btn and reverse_btn: self.last_gear = -1 self.parked = False self.shift_mode_manual = True elif not self.last_park_btn and park_btn: self.parked = True elif not self.last_shift_down_btn and shift_down_btn and self.last_gear > 1 and self.manual_transmission: self.last_gear-=1 self.parked = False self.shift_mode_manual = True elif not self.last_shift_up_btn and shift_up_btn and self.last_gear >= 1 and self.manual_transmission: self.last_gear+=1 self.parked = False self.shift_mode_manual = True if self.parked: self.last_gear = 0 self.shift_mode_manual = True controls.handbrake = True else: controls.handbrake = False controls.manual_gear = self.last_gear controls.manual = self.shift_mode_manual now = rospy.Time.now() controls.header.stamp = now controls.gear_immediate = True self.last_neutral_btn = neutral_btn self.last_forward_btn = forward_btn self.last_reverse_btn = reverse_btn self.last_park_btn = park_btn self.last_shift_down_btn = shift_down_btn self.last_shift_up_btn = shift_up_btn self.command_pub.publish(controls) def run(self): rospy.spin() if __name__ == '__main__': rospy.init_node('car_joy') node = CarCommandTranslator() node.run()
AirSim/ros/src/airsim_ros_pkgs/scripts/car_joy.py/0
{ "file_path": "AirSim/ros/src/airsim_ros_pkgs/scripts/car_joy.py", "repo_id": "AirSim", "token_count": 2576 }
70
<launch> <!-- docs: https://wiki.ros.org/nodelet/Tutorials/Running%20a%20nodelet --> <!-- docs: http://wiki.ros.org/depth_image_proc --> <!-- docs: https://wiki.ros.org/openni_launch --> <!-- docs: https://gist.github.com/bhaskara/2400165 --> <!-- Nodelet manager --> <node pkg="nodelet" type="nodelet" args="manager" name="depth_to_pointcloud_manager" output="screen"/> <!-- Nodelets! --> <!-- Convert it into a point cloud --> <node pkg="nodelet" type="nodelet" name="airsim_depth2cloud" args="load depth_image_proc/point_cloud_xyzrgb depth_to_pointcloud_manager" output="screen"> <remap from="depth_registered/image_rect" to="/airsim_node/drone_1/front_left_custom/DepthPlanar"/> <remap from="depth_registered/points" to="/airsim_node/drone_1/front_left_custom/DepthPlanar/registered/points"/> <remap from="rgb/image_rect_color" to="/airsim_node/drone_1/front_left_custom/Scene"/> <remap from="rgb/camera_info" to="/airsim_node/drone_1/front_left_custom/Scene/camera_info"/> </node> </launch>
AirSim/ros/src/airsim_tutorial_pkgs/launch/front_stereo_and_center_mono/depth_to_pointcloud.launch/0
{ "file_path": "AirSim/ros/src/airsim_tutorial_pkgs/launch/front_stereo_and_center_mono/depth_to_pointcloud.launch", "repo_id": "AirSim", "token_count": 376 }
71
std_msgs/Header header string camera_name string vehicle_name float64 roll float64 pitch float64 yaw
AirSim/ros2/src/airsim_interfaces/msg/GimbalAngleEulerCmd.msg/0
{ "file_path": "AirSim/ros2/src/airsim_interfaces/msg/GimbalAngleEulerCmd.msg", "repo_id": "AirSim", "token_count": 30 }
72
// full credits to https://github.com/ethz-asl/geodetic_utils // todo add as external lib #ifndef GEODETIC_CONVERTER_H_ #define GEODETIC_CONVERTER_H_ #include "math.h" #include <Eigen/Dense> namespace geodetic_converter { // Geodetic system parameters static double kSemimajorAxis = 6378137; static double kSemiminorAxis = 6356752.3142; static double kFirstEccentricitySquared = 6.69437999014 * 0.001; static double kSecondEccentricitySquared = 6.73949674228 * 0.001; static double kFlattening = 1 / 298.257223563; class GeodeticConverter { public: GeodeticConverter() { haveReference_ = false; } ~GeodeticConverter() { } // Default copy constructor and assignment operator are OK. bool isInitialised() { return haveReference_; } void getReference(double* latitude, double* longitude, double* altitude) { *latitude = initial_latitude_; *longitude = initial_longitude_; *altitude = initial_altitude_; } void initialiseReference(const double latitude, const double longitude, const double altitude) { // Save NED origin initial_latitude_ = deg2Rad(latitude); initial_longitude_ = deg2Rad(longitude); initial_altitude_ = altitude; // Compute ECEF of NED origin geodetic2Ecef(latitude, longitude, altitude, &initial_ecef_x_, &initial_ecef_y_, &initial_ecef_z_); // Compute ECEF to NED and NED to ECEF matrices double phiP = atan2(initial_ecef_z_, sqrt(pow(initial_ecef_x_, 2) + pow(initial_ecef_y_, 2))); ecef_to_ned_matrix_ = nRe(phiP, initial_longitude_); ned_to_ecef_matrix_ = nRe(initial_latitude_, initial_longitude_).transpose(); haveReference_ = true; } void geodetic2Ecef(const double latitude, const double longitude, const double altitude, double* x, double* y, double* z) { // Convert geodetic coordinates to ECEF. // http://code.google.com/p/pysatel/source/browse/trunk/coord.py?r=22 double lat_rad = deg2Rad(latitude); double lon_rad = deg2Rad(longitude); double xi = sqrt(1 - kFirstEccentricitySquared * sin(lat_rad) * sin(lat_rad)); *x = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * cos(lon_rad); *y = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * sin(lon_rad); *z = (kSemimajorAxis / xi * (1 - kFirstEccentricitySquared) + altitude) * sin(lat_rad); } void ecef2Geodetic(const double x, const double y, const double z, double* latitude, double* longitude, double* altitude) { // Convert ECEF coordinates to geodetic coordinates. // J. Zhu, "Conversion of Earth-centered Earth-fixed coordinates // to geodetic coordinates," IEEE Transactions on Aerospace and // Electronic Systems, vol. 30, pp. 957-961, 1994. double r = sqrt(x * x + y * y); double Esq = kSemimajorAxis * kSemimajorAxis - kSemiminorAxis * kSemiminorAxis; double F = 54 * kSemiminorAxis * kSemiminorAxis * z * z; double G = r * r + (1 - kFirstEccentricitySquared) * z * z - kFirstEccentricitySquared * Esq; double C = (kFirstEccentricitySquared * kFirstEccentricitySquared * F * r * r) / pow(G, 3); double S = cbrt(1 + C + sqrt(C * C + 2 * C)); double P = F / (3 * pow((S + 1 / S + 1), 2) * G * G); double Q = sqrt(1 + 2 * kFirstEccentricitySquared * kFirstEccentricitySquared * P); double r_0 = -(P * kFirstEccentricitySquared * r) / (1 + Q) + sqrt( 0.5 * kSemimajorAxis * kSemimajorAxis * (1 + 1.0 / Q) - P * (1 - kFirstEccentricitySquared) * z * z / (Q * (1 + Q)) - 0.5 * P * r * r); double U = sqrt(pow((r - kFirstEccentricitySquared * r_0), 2) + z * z); double V = sqrt( pow((r - kFirstEccentricitySquared * r_0), 2) + (1 - kFirstEccentricitySquared) * z * z); double Z_0 = kSemiminorAxis * kSemiminorAxis * z / (kSemimajorAxis * V); *altitude = U * (1 - kSemiminorAxis * kSemiminorAxis / (kSemimajorAxis * V)); *latitude = rad2Deg(atan((z + kSecondEccentricitySquared * Z_0) / r)); *longitude = rad2Deg(atan2(y, x)); } void ecef2Ned(const double x, const double y, const double z, double* north, double* east, double* down) { // Converts ECEF coordinate position into local-tangent-plane NED. // Coordinates relative to given ECEF coordinate frame. Eigen::Vector3d vect, ret; vect(0) = x - initial_ecef_x_; vect(1) = y - initial_ecef_y_; vect(2) = z - initial_ecef_z_; ret = ecef_to_ned_matrix_ * vect; *north = ret(0); *east = ret(1); *down = -ret(2); } void ned2Ecef(const double north, const double east, const double down, double* x, double* y, double* z) { // NED (north/east/down) to ECEF coordinates Eigen::Vector3d ned, ret; ned(0) = north; ned(1) = east; ned(2) = -down; ret = ned_to_ecef_matrix_ * ned; *x = ret(0) + initial_ecef_x_; *y = ret(1) + initial_ecef_y_; *z = ret(2) + initial_ecef_z_; } void geodetic2Ned(const double latitude, const double longitude, const double altitude, double* north, double* east, double* down) { // Geodetic position to local NED frame double x, y, z; geodetic2Ecef(latitude, longitude, altitude, &x, &y, &z); ecef2Ned(x, y, z, north, east, down); } void ned2Geodetic(const double north, const double east, const double down, double* latitude, double* longitude, double* altitude) { // Local NED position to geodetic coordinates double x, y, z; ned2Ecef(north, east, down, &x, &y, &z); ecef2Geodetic(x, y, z, latitude, longitude, altitude); } void geodetic2Enu(const double latitude, const double longitude, const double altitude, double* east, double* north, double* up) { // Geodetic position to local ENU frame double x, y, z; geodetic2Ecef(latitude, longitude, altitude, &x, &y, &z); double aux_north, aux_east, aux_down; ecef2Ned(x, y, z, &aux_north, &aux_east, &aux_down); *east = aux_east; *north = aux_north; *up = -aux_down; } void enu2Geodetic(const double east, const double north, const double up, double* latitude, double* longitude, double* altitude) { // Local ENU position to geodetic coordinates const double aux_north = north; const double aux_east = east; const double aux_down = -up; double x, y, z; ned2Ecef(aux_north, aux_east, aux_down, &x, &y, &z); ecef2Geodetic(x, y, z, latitude, longitude, altitude); } private: inline Eigen::Matrix3d nRe(const double lat_radians, const double lon_radians) { const double sLat = sin(lat_radians); const double sLon = sin(lon_radians); const double cLat = cos(lat_radians); const double cLon = cos(lon_radians); Eigen::Matrix3d ret; ret(0, 0) = -sLat * cLon; ret(0, 1) = -sLat * sLon; ret(0, 2) = cLat; ret(1, 0) = -sLon; ret(1, 1) = cLon; ret(1, 2) = 0.0; ret(2, 0) = cLat * cLon; ret(2, 1) = cLat * sLon; ret(2, 2) = sLat; return ret; } inline double rad2Deg(const double radians) { return (radians / M_PI) * 180.0; } inline double deg2Rad(const double degrees) { return (degrees / 180.0) * M_PI; } double initial_latitude_; double initial_longitude_; double initial_altitude_; double initial_ecef_x_; double initial_ecef_y_; double initial_ecef_z_; Eigen::Matrix3d ecef_to_ned_matrix_; Eigen::Matrix3d ned_to_ecef_matrix_; bool haveReference_; }; // class GeodeticConverter }; // namespace geodetic_conv #endif // GEODETIC_CONVERTER_H_
AirSim/ros2/src/airsim_ros_pkgs/include/geodetic_conv.hpp/0
{ "file_path": "AirSim/ros2/src/airsim_ros_pkgs/include/geodetic_conv.hpp", "repo_id": "AirSim", "token_count": 3844 }
73
#include "pd_position_controller_simple.h" using namespace std::placeholders; bool PIDParams::load_from_rosparams(const std::shared_ptr<rclcpp::Node> nh) { bool found = true; found = found && nh->get_parameter("kp_x", kp_x); found = found && nh->get_parameter("kp_y", kp_y); found = found && nh->get_parameter("kp_z", kp_z); found = found && nh->get_parameter("kp_yaw", kp_yaw); found = found && nh->get_parameter("kd_x", kd_x); found = found && nh->get_parameter("kd_y", kd_y); found = found && nh->get_parameter("kd_z", kd_z); found = found && nh->get_parameter("kd_yaw", kd_yaw); found = found && nh->get_parameter("reached_thresh_xyz", reached_thresh_xyz); found = found && nh->get_parameter("reached_yaw_degrees", reached_yaw_degrees); return found; } bool DynamicConstraints::load_from_rosparams(const std::shared_ptr<rclcpp::Node> nh) { bool found = true; found = found && nh->get_parameter("max_vel_horz_abs", max_vel_horz_abs); found = found && nh->get_parameter("max_vel_vert_abs", max_vel_vert_abs); found = found && nh->get_parameter("max_yaw_rate_degree", max_yaw_rate_degree); return found; } PIDPositionController::PIDPositionController(const std::shared_ptr<rclcpp::Node> nh) : use_eth_lib_for_geodetic_conv_(true), nh_(nh), has_home_geo_(false), reached_goal_(false), has_goal_(false), has_odom_(false), got_goal_once_(false) { params_.load_from_rosparams(nh_); constraints_.load_from_rosparams(nh_); initialize_ros(); reset_errors(); } void PIDPositionController::reset_errors() { prev_error_.x = 0.0; prev_error_.y = 0.0; prev_error_.z = 0.0; prev_error_.yaw = 0.0; } void PIDPositionController::initialize_ros() { vel_cmd_ = airsim_interfaces::msg::VelCmd(); // ROS params double update_control_every_n_sec; nh_->get_parameter("update_control_every_n_sec", update_control_every_n_sec); auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(nh_, "/airsim_node"); while (!parameters_client->wait_for_service(std::chrono::seconds(1))) { if (!rclcpp::ok()) { RCLCPP_ERROR(nh_->get_logger(), "Interrupted while waiting for the service. Exiting."); rclcpp::shutdown(); } RCLCPP_INFO(nh_->get_logger(), "service not available, waiting again..."); } std::string vehicle_name; while (vehicle_name == "") { vehicle_name = parameters_client->get_parameter("vehicle_name", vehicle_name); RCLCPP_INFO_STREAM(nh_->get_logger(), "Waiting vehicle name"); } // ROS publishers airsim_vel_cmd_world_frame_pub_ = nh_->create_publisher<airsim_interfaces::msg::VelCmd>("/airsim_node/" + vehicle_name + "/vel_cmd_world_frame", 1); // ROS subscribers airsim_odom_sub_ = nh_->create_subscription<nav_msgs::msg::Odometry>("/airsim_node/" + vehicle_name + "/odom_local_ned", 50, std::bind(&PIDPositionController::airsim_odom_cb, this, _1)); home_geopoint_sub_ = nh_->create_subscription<airsim_interfaces::msg::GPSYaw>("/airsim_node/home_geo_point", 50, std::bind(&PIDPositionController::home_geopoint_cb, this, _1)); // todo publish this under global nodehandle / "airsim node" and hide it from user local_position_goal_srvr_ = nh_->create_service<airsim_interfaces::srv::SetLocalPosition>("/airsim_node/local_position_goal", std::bind(&PIDPositionController::local_position_goal_srv_cb, this, _1, _2)); local_position_goal_override_srvr_ = nh_->create_service<airsim_interfaces::srv::SetLocalPosition>("/airsim_node/local_position_goal/override", std::bind(&PIDPositionController::local_position_goal_srv_override_cb, this, _1, _2)); gps_goal_srvr_ = nh_->create_service<airsim_interfaces::srv::SetGPSPosition>("/airsim_node/gps_goal", std::bind(&PIDPositionController::gps_goal_srv_cb, this, _1, _2)); gps_goal_override_srvr_ = nh_->create_service<airsim_interfaces::srv::SetGPSPosition>("/airsim_node/gps_goal/override", std::bind(&PIDPositionController::gps_goal_srv_override_cb, this, _1, _2)); // ROS timers update_control_cmd_timer_ = nh_->create_wall_timer(std::chrono::duration<double>(update_control_every_n_sec), std::bind(&PIDPositionController::update_control_cmd_timer_cb, this)); } void PIDPositionController::airsim_odom_cb(const nav_msgs::msg::Odometry::SharedPtr odom_msg) { has_odom_ = true; curr_odom_ = *odom_msg; curr_position_.x = odom_msg->pose.pose.position.x; curr_position_.y = odom_msg->pose.pose.position.y; curr_position_.z = odom_msg->pose.pose.position.z; curr_position_.yaw = utils::get_yaw_from_quat_msg(odom_msg->pose.pose.orientation); } // todo maintain internal representation as eigen vec? // todo check if low velocity if within thresh? // todo maintain separate errors for XY and Z void PIDPositionController::check_reached_goal() { double diff_xyz = sqrt((target_position_.x - curr_position_.x) * (target_position_.x - curr_position_.x) + (target_position_.y - curr_position_.y) * (target_position_.y - curr_position_.y) + (target_position_.z - curr_position_.z) * (target_position_.z - curr_position_.z)); double diff_yaw = math_common::angular_dist(target_position_.yaw, curr_position_.yaw); // todo save this in degrees somewhere to avoid repeated conversion if (diff_xyz < params_.reached_thresh_xyz && diff_yaw < math_common::deg2rad(params_.reached_yaw_degrees)) reached_goal_ = true; } bool PIDPositionController::local_position_goal_srv_cb(const std::shared_ptr<airsim_interfaces::srv::SetLocalPosition::Request> request, std::shared_ptr<airsim_interfaces::srv::SetLocalPosition::Response> response) { unused(response); // this tells the update timer callback to not do active hovering if (!got_goal_once_) got_goal_once_ = true; if (has_goal_ && !reached_goal_) { // todo maintain array of position goals RCLCPP_ERROR_STREAM(nh_->get_logger(), "denying position goal request-> I am still following the previous goal"); return false; } if (!has_goal_) { target_position_.x = request->x; target_position_.y = request->y; target_position_.z = request->z; target_position_.yaw = request->yaw; RCLCPP_INFO_STREAM(nh_->get_logger(), "got goal: x=" << target_position_.x << " y=" << target_position_.y << " z=" << target_position_.z << " yaw=" << target_position_.yaw); // todo error checks // todo fill response has_goal_ = true; reached_goal_ = false; reset_errors(); // todo return true; } // Already have goal, and have reached it RCLCPP_INFO_STREAM(nh_->get_logger(), "Already have goal and have reached it"); return false; } bool PIDPositionController::local_position_goal_srv_override_cb(const std::shared_ptr<airsim_interfaces::srv::SetLocalPosition::Request> request, std::shared_ptr<airsim_interfaces::srv::SetLocalPosition::Response> response) { unused(response); // this tells the update timer callback to not do active hovering if (!got_goal_once_) got_goal_once_ = true; target_position_.x = request->x; target_position_.y = request->y; target_position_.z = request->z; target_position_.yaw = request->yaw; RCLCPP_INFO_STREAM(nh_->get_logger(), "got goal: x=" << target_position_.x << " y=" << target_position_.y << " z=" << target_position_.z << " yaw=" << target_position_.yaw); // todo error checks // todo fill response has_goal_ = true; reached_goal_ = false; reset_errors(); // todo return true; } void PIDPositionController::home_geopoint_cb(const airsim_interfaces::msg::GPSYaw::SharedPtr gps_msg) { if (has_home_geo_) return; gps_home_msg_ = *gps_msg; has_home_geo_ = true; RCLCPP_INFO_STREAM(nh_->get_logger(), "GPS reference initializing " << gps_msg->latitude << ", " << gps_msg->longitude << ", " << gps_msg->altitude); geodetic_converter_.initialiseReference(gps_msg->latitude, gps_msg->longitude, gps_msg->altitude); } // todo do relative altitude, or add an option for the same? bool PIDPositionController::gps_goal_srv_cb(const std::shared_ptr<airsim_interfaces::srv::SetGPSPosition::Request> request, std::shared_ptr<airsim_interfaces::srv::SetGPSPosition::Response> response) { if (!has_home_geo_) { RCLCPP_ERROR_STREAM(nh_->get_logger(), "I don't have home GPS coord. Can't go to GPS goal!"); response->success = false; } // convert GPS goal to NED goal if (!has_goal_) { msr::airlib::GeoPoint goal_gps_point(request->latitude, request->longitude, request->altitude); msr::airlib::GeoPoint gps_home(gps_home_msg_.latitude, gps_home_msg_.longitude, gps_home_msg_.altitude); if (use_eth_lib_for_geodetic_conv_) { double initial_latitude, initial_longitude, initial_altitude; geodetic_converter_.getReference(&initial_latitude, &initial_longitude, &initial_altitude); double n, e, d; geodetic_converter_.geodetic2Ned(request->latitude, request->longitude, request->altitude, &n, &e, &d); // RCLCPP_INFO_STREAM("geodetic_converter_ GPS reference initialized correctly (lat long in radians) " << initial_latitude << ", "<< initial_longitude << ", " << initial_altitude); target_position_.x = n; target_position_.y = e; target_position_.z = d; } else // use airlib::GeodeticToNedFast { RCLCPP_INFO_STREAM(nh_->get_logger(), "home geopoint: lat=" << gps_home.latitude << " long=" << gps_home.longitude << " alt=" << gps_home.altitude << " yaw=" << "todo"); msr::airlib::Vector3r ned_goal = msr::airlib::EarthUtils::GeodeticToNedFast(goal_gps_point, gps_home); target_position_.x = ned_goal[0]; target_position_.y = ned_goal[1]; target_position_.z = ned_goal[2]; } target_position_.yaw = request->yaw; // todo RCLCPP_INFO_STREAM(nh_->get_logger(), "got GPS goal: lat=" << goal_gps_point.latitude << " long=" << goal_gps_point.longitude << " alt=" << goal_gps_point.altitude << " yaw=" << target_position_.yaw); RCLCPP_INFO_STREAM(nh_->get_logger(), "converted NED goal is: x=" << target_position_.x << " y=" << target_position_.y << " z=" << target_position_.z << " yaw=" << target_position_.yaw); // todo error checks // todo fill response has_goal_ = true; reached_goal_ = false; reset_errors(); // todo return true; } // Already have goal, this shouldn't happen RCLCPP_INFO_STREAM(nh_->get_logger(), "Goal already received, ignoring!"); return false; } // todo do relative altitude, or add an option for the same? bool PIDPositionController::gps_goal_srv_override_cb(const std::shared_ptr<airsim_interfaces::srv::SetGPSPosition::Request> request, std::shared_ptr<airsim_interfaces::srv::SetGPSPosition::Response> response) { if (!has_home_geo_) { RCLCPP_ERROR_STREAM(nh_->get_logger(), "I don't have home GPS coord. Can't go to GPS goal!"); response->success = false; } // convert GPS goal to NED goal msr::airlib::GeoPoint goal_gps_point(request->latitude, request->longitude, request->altitude); msr::airlib::GeoPoint gps_home(gps_home_msg_.latitude, gps_home_msg_.longitude, gps_home_msg_.altitude); if (use_eth_lib_for_geodetic_conv_) { double initial_latitude, initial_longitude, initial_altitude; geodetic_converter_.getReference(&initial_latitude, &initial_longitude, &initial_altitude); double n, e, d; geodetic_converter_.geodetic2Ned(request->latitude, request->longitude, request->altitude, &n, &e, &d); // RCLCPP_INFO_STREAM("geodetic_converter_ GPS reference initialized correctly (lat long in radians) " << initial_latitude << ", "<< initial_longitude << ", " << initial_altitude); target_position_.x = n; target_position_.y = e; target_position_.z = d; } else // use airlib::GeodeticToNedFast { RCLCPP_INFO_STREAM(nh_->get_logger(), "home geopoint: lat=" << gps_home.latitude << " long=" << gps_home.longitude << " alt=" << gps_home.altitude << " yaw=" << "todo"); msr::airlib::Vector3r ned_goal = msr::airlib::EarthUtils::GeodeticToNedFast(goal_gps_point, gps_home); target_position_.x = ned_goal[0]; target_position_.y = ned_goal[1]; target_position_.z = ned_goal[2]; } target_position_.yaw = request->yaw; // todo RCLCPP_INFO_STREAM(nh_->get_logger(), "got GPS goal: lat=" << goal_gps_point.latitude << " long=" << goal_gps_point.longitude << " alt=" << goal_gps_point.altitude << " yaw=" << target_position_.yaw); RCLCPP_INFO_STREAM(nh_->get_logger(), "converted NED goal is: x=" << target_position_.x << " y=" << target_position_.y << " z=" << target_position_.z << " yaw=" << target_position_.yaw); // todo error checks // todo fill response has_goal_ = true; reached_goal_ = false; reset_errors(); // todo return true; } void PIDPositionController::update_control_cmd_timer_cb() { // todo check if odometry is too old!! // if no odom, don't do anything. if (!has_odom_) { RCLCPP_ERROR_STREAM(nh_->get_logger(), "Waiting for odometry!"); return; } if (has_goal_) { check_reached_goal(); if (reached_goal_) { RCLCPP_INFO_STREAM(nh_->get_logger(), "Reached goal! Hovering at position."); has_goal_ = false; // dear future self, this function doesn't return coz we need to keep on actively hovering at last goal pose. don't act smart } else { RCLCPP_INFO_STREAM(nh_->get_logger(), "Moving to goal."); } } // only compute and send control commands for hovering / moving to pose, if we received a goal at least once in the past if (got_goal_once_) { compute_control_cmd(); enforce_dynamic_constraints(); publish_control_cmd(); } } void PIDPositionController::compute_control_cmd() { curr_error_.x = target_position_.x - curr_position_.x; curr_error_.y = target_position_.y - curr_position_.y; curr_error_.z = target_position_.z - curr_position_.z; curr_error_.yaw = math_common::angular_dist(curr_position_.yaw, target_position_.yaw); double p_term_x = params_.kp_x * curr_error_.x; double p_term_y = params_.kp_y * curr_error_.y; double p_term_z = params_.kp_z * curr_error_.z; double p_term_yaw = params_.kp_yaw * curr_error_.yaw; double d_term_x = params_.kd_x * prev_error_.x; double d_term_y = params_.kd_y * prev_error_.y; double d_term_z = params_.kd_z * prev_error_.z; double d_term_yaw = params_.kp_yaw * prev_error_.yaw; prev_error_ = curr_error_; vel_cmd_.twist.linear.x = p_term_x + d_term_x; vel_cmd_.twist.linear.y = p_term_y + d_term_y; vel_cmd_.twist.linear.z = p_term_z + d_term_z; vel_cmd_.twist.angular.z = p_term_yaw + d_term_yaw; // todo } void PIDPositionController::enforce_dynamic_constraints() { double vel_norm_horz = sqrt((vel_cmd_.twist.linear.x * vel_cmd_.twist.linear.x) + (vel_cmd_.twist.linear.y * vel_cmd_.twist.linear.y)); if (vel_norm_horz > constraints_.max_vel_horz_abs) { vel_cmd_.twist.linear.x = (vel_cmd_.twist.linear.x / vel_norm_horz) * constraints_.max_vel_horz_abs; vel_cmd_.twist.linear.y = (vel_cmd_.twist.linear.y / vel_norm_horz) * constraints_.max_vel_horz_abs; } if (std::fabs(vel_cmd_.twist.linear.z) > constraints_.max_vel_vert_abs) { // todo just add a sgn funciton in common utils? return double to be safe. // template <typename T> double sgn(T val) { return (T(0) < val) - (val < T(0)); } vel_cmd_.twist.linear.z = (vel_cmd_.twist.linear.z / std::fabs(vel_cmd_.twist.linear.z)) * constraints_.max_vel_vert_abs; } // todo yaw limits if (std::fabs(vel_cmd_.twist.linear.z) > constraints_.max_yaw_rate_degree) { // todo just add a sgn funciton in common utils? return double to be safe. // template <typename T> double sgn(T val) { return (T(0) < val) - (val < T(0)); } vel_cmd_.twist.linear.z = (vel_cmd_.twist.linear.z / std::fabs(vel_cmd_.twist.linear.z)) * constraints_.max_yaw_rate_degree; } } void PIDPositionController::publish_control_cmd() { airsim_vel_cmd_world_frame_pub_->publish(vel_cmd_); }
AirSim/ros2/src/airsim_ros_pkgs/src/pd_position_controller_simple.cpp/0
{ "file_path": "AirSim/ros2/src/airsim_ros_pkgs/src/pd_position_controller_simple.cpp", "repo_id": "AirSim", "token_count": 6926 }
74
// OutBuffer.cs namespace SevenZip.Buffer { public class OutBuffer { byte[] m_Buffer; uint m_Pos; uint m_BufferSize; System.IO.Stream m_Stream; ulong m_ProcessedSize; public OutBuffer(uint bufferSize) { m_Buffer = new byte[bufferSize]; m_BufferSize = bufferSize; } public void SetStream(System.IO.Stream stream) { m_Stream = stream; } public void FlushStream() { m_Stream.Flush(); } public void CloseStream() { m_Stream.Close(); } public void ReleaseStream() { m_Stream = null; } public void Init() { m_ProcessedSize = 0; m_Pos = 0; } public void WriteByte(byte b) { m_Buffer[m_Pos++] = b; if (m_Pos >= m_BufferSize) FlushData(); } public void FlushData() { if (m_Pos == 0) return; m_Stream.Write(m_Buffer, 0, (int)m_Pos); m_Pos = 0; } public ulong GetProcessedSize() { return m_ProcessedSize + m_Pos; } } }
AssetStudio/AssetStudio/7zip/Common/OutBuffer.cs/0
{ "file_path": "AssetStudio/AssetStudio/7zip/Common/OutBuffer.cs", "repo_id": "AssetStudio", "token_count": 386 }
75
/* Copyright 2015 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ namespace Org.Brotli.Dec { /// <summary> /// <see cref="System.IO.Stream"/> /// decorator that decompresses brotli data. /// <p> Not thread-safe. /// </summary> public class BrotliInputStream : System.IO.Stream { public const int DefaultInternalBufferSize = 16384; /// <summary>Internal buffer used for efficient byte-by-byte reading.</summary> private byte[] buffer; /// <summary>Number of decoded but still unused bytes in internal buffer.</summary> private int remainingBufferBytes; /// <summary>Next unused byte offset.</summary> private int bufferOffset; /// <summary>Decoder state.</summary> private readonly Org.Brotli.Dec.State state = new Org.Brotli.Dec.State(); /// <summary> /// Creates a /// <see cref="System.IO.Stream"/> /// wrapper that decompresses brotli data. /// <p> For byte-by-byte reading ( /// <see cref="ReadByte()"/> /// ) internal buffer with /// <see cref="DefaultInternalBufferSize"/> /// size is allocated and used. /// <p> Will block the thread until first kilobyte of data of source is available. /// </summary> /// <param name="source">underlying data source</param> /// <exception cref="System.IO.IOException">in case of corrupted data or source stream problems</exception> public BrotliInputStream(System.IO.Stream source) : this(source, DefaultInternalBufferSize, null) { } /// <summary> /// Creates a /// <see cref="System.IO.Stream"/> /// wrapper that decompresses brotli data. /// <p> For byte-by-byte reading ( /// <see cref="ReadByte()"/> /// ) internal buffer of specified size is /// allocated and used. /// <p> Will block the thread until first kilobyte of data of source is available. /// </summary> /// <param name="source">compressed data source</param> /// <param name="byteReadBufferSize"> /// size of internal buffer used in case of /// byte-by-byte reading /// </param> /// <exception cref="System.IO.IOException">in case of corrupted data or source stream problems</exception> public BrotliInputStream(System.IO.Stream source, int byteReadBufferSize) : this(source, byteReadBufferSize, null) { } /// <summary> /// Creates a /// <see cref="System.IO.Stream"/> /// wrapper that decompresses brotli data. /// <p> For byte-by-byte reading ( /// <see cref="ReadByte()"/> /// ) internal buffer of specified size is /// allocated and used. /// <p> Will block the thread until first kilobyte of data of source is available. /// </summary> /// <param name="source">compressed data source</param> /// <param name="byteReadBufferSize"> /// size of internal buffer used in case of /// byte-by-byte reading /// </param> /// <param name="customDictionary"> /// custom dictionary data; /// <see langword="null"/> /// if not used /// </param> /// <exception cref="System.IO.IOException">in case of corrupted data or source stream problems</exception> public BrotliInputStream(System.IO.Stream source, int byteReadBufferSize, byte[] customDictionary) { if (byteReadBufferSize <= 0) { throw new System.ArgumentException("Bad buffer size:" + byteReadBufferSize); } else if (source == null) { throw new System.ArgumentException("source is null"); } this.buffer = new byte[byteReadBufferSize]; this.remainingBufferBytes = 0; this.bufferOffset = 0; try { Org.Brotli.Dec.State.SetInput(state, source); } catch (Org.Brotli.Dec.BrotliRuntimeException ex) { throw new System.IO.IOException("Brotli decoder initialization failed", ex); } if (customDictionary != null) { Org.Brotli.Dec.Decode.SetCustomDictionary(state, customDictionary); } } /// <summary><inheritDoc/></summary> /// <exception cref="System.IO.IOException"/> public override void Close() { Org.Brotli.Dec.State.Close(state); } /// <summary><inheritDoc/></summary> /// <exception cref="System.IO.IOException"/> public override int ReadByte() { if (bufferOffset >= remainingBufferBytes) { remainingBufferBytes = Read(buffer, 0, buffer.Length); bufferOffset = 0; if (remainingBufferBytes == -1) { return -1; } } return buffer[bufferOffset++] & unchecked((int)(0xFF)); } /// <summary><inheritDoc/></summary> /// <exception cref="System.IO.IOException"/> public override int Read(byte[] destBuffer, int destOffset, int destLen) { if (destOffset < 0) { throw new System.ArgumentException("Bad offset: " + destOffset); } else if (destLen < 0) { throw new System.ArgumentException("Bad length: " + destLen); } else if (destOffset + destLen > destBuffer.Length) { throw new System.ArgumentException("Buffer overflow: " + (destOffset + destLen) + " > " + destBuffer.Length); } else if (destLen == 0) { return 0; } int copyLen = System.Math.Max(remainingBufferBytes - bufferOffset, 0); if (copyLen != 0) { copyLen = System.Math.Min(copyLen, destLen); System.Array.Copy(buffer, bufferOffset, destBuffer, destOffset, copyLen); bufferOffset += copyLen; destOffset += copyLen; destLen -= copyLen; if (destLen == 0) { return copyLen; } } try { state.output = destBuffer; state.outputOffset = destOffset; state.outputLength = destLen; state.outputUsed = 0; Org.Brotli.Dec.Decode.Decompress(state); if (state.outputUsed == 0) { return 0; } return state.outputUsed + copyLen; } catch (Org.Brotli.Dec.BrotliRuntimeException ex) { throw new System.IO.IOException("Brotli stream decoding failed", ex); } } // <{[INJECTED CODE]}> public override bool CanRead { get {return true;} } public override bool CanSeek { get {return false;} } public override long Length { get {throw new System.NotSupportedException();} } public override long Position { get {throw new System.NotSupportedException();} set {throw new System.NotSupportedException();} } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new System.NotSupportedException(); } public override void SetLength(long value){ throw new System.NotSupportedException(); } public override bool CanWrite{get{return false;}} public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw new System.NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new System.NotSupportedException(); } public override void Flush() {} } }
AssetStudio/AssetStudio/Brotli/BrotliInputStream.cs/0
{ "file_path": "AssetStudio/AssetStudio/Brotli/BrotliInputStream.cs", "repo_id": "AssetStudio", "token_count": 2413 }
76
using K4os.Compression.LZ4; using System; using System.IO; using System.Linq; namespace AssetStudio { [Flags] public enum ArchiveFlags { CompressionTypeMask = 0x3f, BlocksAndDirectoryInfoCombined = 0x40, BlocksInfoAtTheEnd = 0x80, OldWebPluginCompatibility = 0x100, BlockInfoNeedPaddingAtStart = 0x200 } [Flags] public enum StorageBlockFlags { CompressionTypeMask = 0x3f, Streamed = 0x40 } public enum CompressionType { None, Lzma, Lz4, Lz4HC, Lzham } public class BundleFile { public class Header { public string signature; public uint version; public string unityVersion; public string unityRevision; public long size; public uint compressedBlocksInfoSize; public uint uncompressedBlocksInfoSize; public ArchiveFlags flags; } public class StorageBlock { public uint compressedSize; public uint uncompressedSize; public StorageBlockFlags flags; } public class Node { public long offset; public long size; public uint flags; public string path; } public Header m_Header; private StorageBlock[] m_BlocksInfo; private Node[] m_DirectoryInfo; public StreamFile[] fileList; public BundleFile(FileReader reader) { m_Header = new Header(); m_Header.signature = reader.ReadStringToNull(); m_Header.version = reader.ReadUInt32(); m_Header.unityVersion = reader.ReadStringToNull(); m_Header.unityRevision = reader.ReadStringToNull(); switch (m_Header.signature) { case "UnityArchive": break; //TODO case "UnityWeb": case "UnityRaw": if (m_Header.version == 6) { goto case "UnityFS"; } ReadHeaderAndBlocksInfo(reader); using (var blocksStream = CreateBlocksStream(reader.FullPath)) { ReadBlocksAndDirectory(reader, blocksStream); ReadFiles(blocksStream, reader.FullPath); } break; case "UnityFS": ReadHeader(reader); ReadBlocksInfoAndDirectory(reader); using (var blocksStream = CreateBlocksStream(reader.FullPath)) { ReadBlocks(reader, blocksStream); ReadFiles(blocksStream, reader.FullPath); } break; } } private void ReadHeaderAndBlocksInfo(EndianBinaryReader reader) { if (m_Header.version >= 4) { var hash = reader.ReadBytes(16); var crc = reader.ReadUInt32(); } var minimumStreamedBytes = reader.ReadUInt32(); m_Header.size = reader.ReadUInt32(); var numberOfLevelsToDownloadBeforeStreaming = reader.ReadUInt32(); var levelCount = reader.ReadInt32(); m_BlocksInfo = new StorageBlock[1]; for (int i = 0; i < levelCount; i++) { var storageBlock = new StorageBlock() { compressedSize = reader.ReadUInt32(), uncompressedSize = reader.ReadUInt32(), }; if (i == levelCount - 1) { m_BlocksInfo[0] = storageBlock; } } if (m_Header.version >= 2) { var completeFileSize = reader.ReadUInt32(); } if (m_Header.version >= 3) { var fileInfoHeaderSize = reader.ReadUInt32(); } reader.Position = m_Header.size; } private Stream CreateBlocksStream(string path) { Stream blocksStream; var uncompressedSizeSum = m_BlocksInfo.Sum(x => x.uncompressedSize); if (uncompressedSizeSum >= int.MaxValue) { /*var memoryMappedFile = MemoryMappedFile.CreateNew(null, uncompressedSizeSum); assetsDataStream = memoryMappedFile.CreateViewStream();*/ blocksStream = new FileStream(path + ".temp", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.DeleteOnClose); } else { blocksStream = new MemoryStream((int)uncompressedSizeSum); } return blocksStream; } private void ReadBlocksAndDirectory(EndianBinaryReader reader, Stream blocksStream) { var isCompressed = m_Header.signature == "UnityWeb"; foreach (var blockInfo in m_BlocksInfo) { var uncompressedBytes = reader.ReadBytes((int)blockInfo.compressedSize); if (isCompressed) { using (var memoryStream = new MemoryStream(uncompressedBytes)) { using (var decompressStream = SevenZipHelper.StreamDecompress(memoryStream)) { uncompressedBytes = decompressStream.ToArray(); } } } blocksStream.Write(uncompressedBytes, 0, uncompressedBytes.Length); } blocksStream.Position = 0; var blocksReader = new EndianBinaryReader(blocksStream); var nodesCount = blocksReader.ReadInt32(); m_DirectoryInfo = new Node[nodesCount]; for (int i = 0; i < nodesCount; i++) { m_DirectoryInfo[i] = new Node { path = blocksReader.ReadStringToNull(), offset = blocksReader.ReadUInt32(), size = blocksReader.ReadUInt32() }; } } public void ReadFiles(Stream blocksStream, string path) { fileList = new StreamFile[m_DirectoryInfo.Length]; for (int i = 0; i < m_DirectoryInfo.Length; i++) { var node = m_DirectoryInfo[i]; var file = new StreamFile(); fileList[i] = file; file.path = node.path; file.fileName = Path.GetFileName(node.path); if (node.size >= int.MaxValue) { /*var memoryMappedFile = MemoryMappedFile.CreateNew(null, entryinfo_size); file.stream = memoryMappedFile.CreateViewStream();*/ var extractPath = path + "_unpacked" + Path.DirectorySeparatorChar; Directory.CreateDirectory(extractPath); file.stream = new FileStream(extractPath + file.fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); } else { file.stream = new MemoryStream((int)node.size); } blocksStream.Position = node.offset; blocksStream.CopyTo(file.stream, node.size); file.stream.Position = 0; } } private void ReadHeader(EndianBinaryReader reader) { m_Header.size = reader.ReadInt64(); m_Header.compressedBlocksInfoSize = reader.ReadUInt32(); m_Header.uncompressedBlocksInfoSize = reader.ReadUInt32(); m_Header.flags = (ArchiveFlags)reader.ReadUInt32(); if (m_Header.signature != "UnityFS") { reader.ReadByte(); } } private void ReadBlocksInfoAndDirectory(EndianBinaryReader reader) { byte[] blocksInfoBytes; if (m_Header.version >= 7) { reader.AlignStream(16); } if ((m_Header.flags & ArchiveFlags.BlocksInfoAtTheEnd) != 0) { var position = reader.Position; reader.Position = reader.BaseStream.Length - m_Header.compressedBlocksInfoSize; blocksInfoBytes = reader.ReadBytes((int)m_Header.compressedBlocksInfoSize); reader.Position = position; } else //0x40 BlocksAndDirectoryInfoCombined { blocksInfoBytes = reader.ReadBytes((int)m_Header.compressedBlocksInfoSize); } MemoryStream blocksInfoUncompresseddStream; var uncompressedSize = m_Header.uncompressedBlocksInfoSize; var compressionType = (CompressionType)(m_Header.flags & ArchiveFlags.CompressionTypeMask); switch (compressionType) { case CompressionType.None: { blocksInfoUncompresseddStream = new MemoryStream(blocksInfoBytes); break; } case CompressionType.Lzma: { blocksInfoUncompresseddStream = new MemoryStream((int)(uncompressedSize)); using (var blocksInfoCompressedStream = new MemoryStream(blocksInfoBytes)) { SevenZipHelper.StreamDecompress(blocksInfoCompressedStream, blocksInfoUncompresseddStream, m_Header.compressedBlocksInfoSize, m_Header.uncompressedBlocksInfoSize); } blocksInfoUncompresseddStream.Position = 0; break; } case CompressionType.Lz4: case CompressionType.Lz4HC: { var uncompressedBytes = new byte[uncompressedSize]; var numWrite = LZ4Codec.Decode(blocksInfoBytes, uncompressedBytes); if (numWrite != uncompressedSize) { throw new IOException($"Lz4 decompression error, write {numWrite} bytes but expected {uncompressedSize} bytes"); } blocksInfoUncompresseddStream = new MemoryStream(uncompressedBytes); break; } default: throw new IOException($"Unsupported compression type {compressionType}"); } using (var blocksInfoReader = new EndianBinaryReader(blocksInfoUncompresseddStream)) { var uncompressedDataHash = blocksInfoReader.ReadBytes(16); var blocksInfoCount = blocksInfoReader.ReadInt32(); m_BlocksInfo = new StorageBlock[blocksInfoCount]; for (int i = 0; i < blocksInfoCount; i++) { m_BlocksInfo[i] = new StorageBlock { uncompressedSize = blocksInfoReader.ReadUInt32(), compressedSize = blocksInfoReader.ReadUInt32(), flags = (StorageBlockFlags)blocksInfoReader.ReadUInt16() }; } var nodesCount = blocksInfoReader.ReadInt32(); m_DirectoryInfo = new Node[nodesCount]; for (int i = 0; i < nodesCount; i++) { m_DirectoryInfo[i] = new Node { offset = blocksInfoReader.ReadInt64(), size = blocksInfoReader.ReadInt64(), flags = blocksInfoReader.ReadUInt32(), path = blocksInfoReader.ReadStringToNull(), }; } } if ((m_Header.flags & ArchiveFlags.BlockInfoNeedPaddingAtStart) != 0) { reader.AlignStream(16); } } private void ReadBlocks(EndianBinaryReader reader, Stream blocksStream) { foreach (var blockInfo in m_BlocksInfo) { var compressionType = (CompressionType)(blockInfo.flags & StorageBlockFlags.CompressionTypeMask); switch (compressionType) { case CompressionType.None: { reader.BaseStream.CopyTo(blocksStream, blockInfo.compressedSize); break; } case CompressionType.Lzma: { SevenZipHelper.StreamDecompress(reader.BaseStream, blocksStream, blockInfo.compressedSize, blockInfo.uncompressedSize); break; } case CompressionType.Lz4: case CompressionType.Lz4HC: { var compressedSize = (int)blockInfo.compressedSize; var compressedBytes = BigArrayPool<byte>.Shared.Rent(compressedSize); reader.Read(compressedBytes, 0, compressedSize); var uncompressedSize = (int)blockInfo.uncompressedSize; var uncompressedBytes = BigArrayPool<byte>.Shared.Rent(uncompressedSize); var numWrite = LZ4Codec.Decode(compressedBytes, 0, compressedSize, uncompressedBytes, 0, uncompressedSize); if (numWrite != uncompressedSize) { throw new IOException($"Lz4 decompression error, write {numWrite} bytes but expected {uncompressedSize} bytes"); } blocksStream.Write(uncompressedBytes, 0, uncompressedSize); BigArrayPool<byte>.Shared.Return(compressedBytes); BigArrayPool<byte>.Shared.Return(uncompressedBytes); break; } default: throw new IOException($"Unsupported compression type {compressionType}"); } } blocksStream.Position = 0; } } }
AssetStudio/AssetStudio/BundleFile.cs/0
{ "file_path": "AssetStudio/AssetStudio/BundleFile.cs", "repo_id": "AssetStudio", "token_count": 7781 }
77
using System.Collections.Generic; namespace AssetStudio { public class UnityTexEnv { public PPtr<Texture> m_Texture; public Vector2 m_Scale; public Vector2 m_Offset; public UnityTexEnv(ObjectReader reader) { m_Texture = new PPtr<Texture>(reader); m_Scale = reader.ReadVector2(); m_Offset = reader.ReadVector2(); } } public class UnityPropertySheet { public KeyValuePair<string, UnityTexEnv>[] m_TexEnvs; public KeyValuePair<string, int>[] m_Ints; public KeyValuePair<string, float>[] m_Floats; public KeyValuePair<string, Color>[] m_Colors; public UnityPropertySheet(ObjectReader reader) { var version = reader.version; int m_TexEnvsSize = reader.ReadInt32(); m_TexEnvs = new KeyValuePair<string, UnityTexEnv>[m_TexEnvsSize]; for (int i = 0; i < m_TexEnvsSize; i++) { m_TexEnvs[i] = new KeyValuePair<string, UnityTexEnv>(reader.ReadAlignedString(), new UnityTexEnv(reader)); } if (version[0] >= 2021) //2021.1 and up { int m_IntsSize = reader.ReadInt32(); m_Ints = new KeyValuePair<string, int>[m_IntsSize]; for (int i = 0; i < m_IntsSize; i++) { m_Ints[i] = new KeyValuePair<string, int>(reader.ReadAlignedString(), reader.ReadInt32()); } } int m_FloatsSize = reader.ReadInt32(); m_Floats = new KeyValuePair<string, float>[m_FloatsSize]; for (int i = 0; i < m_FloatsSize; i++) { m_Floats[i] = new KeyValuePair<string, float>(reader.ReadAlignedString(), reader.ReadSingle()); } int m_ColorsSize = reader.ReadInt32(); m_Colors = new KeyValuePair<string, Color>[m_ColorsSize]; for (int i = 0; i < m_ColorsSize; i++) { m_Colors[i] = new KeyValuePair<string, Color>(reader.ReadAlignedString(), reader.ReadColor4()); } } } public sealed class Material : NamedObject { public PPtr<Shader> m_Shader; public UnityPropertySheet m_SavedProperties; public Material(ObjectReader reader) : base(reader) { m_Shader = new PPtr<Shader>(reader); if (version[0] == 4 && version[1] >= 1) //4.x { var m_ShaderKeywords = reader.ReadStringArray(); } if (version[0] > 2021 || (version[0] == 2021 && version[1] >= 3)) //2021.3 and up { var m_ValidKeywords = reader.ReadStringArray(); var m_InvalidKeywords = reader.ReadStringArray(); } else if (version[0] >= 5) //5.0 ~ 2021.2 { var m_ShaderKeywords = reader.ReadAlignedString(); } if (version[0] >= 5) //5.0 and up { var m_LightmapFlags = reader.ReadUInt32(); } if (version[0] > 5 || (version[0] == 5 && version[1] >= 6)) //5.6 and up { var m_EnableInstancingVariants = reader.ReadBoolean(); //var m_DoubleSidedGI = a_Stream.ReadBoolean(); //2017 and up reader.AlignStream(); } if (version[0] > 4 || (version[0] == 4 && version[1] >= 3)) //4.3 and up { var m_CustomRenderQueue = reader.ReadInt32(); } if (version[0] > 5 || (version[0] == 5 && version[1] >= 1)) //5.1 and up { var stringTagMapSize = reader.ReadInt32(); for (int i = 0; i < stringTagMapSize; i++) { var first = reader.ReadAlignedString(); var second = reader.ReadAlignedString(); } } if (version[0] > 5 || (version[0] == 5 && version[1] >= 6)) //5.6 and up { var disabledShaderPasses = reader.ReadStringArray(); } m_SavedProperties = new UnityPropertySheet(reader); //vector m_BuildTextureStacks 2020 and up } } }
AssetStudio/AssetStudio/Classes/Material.cs/0
{ "file_path": "AssetStudio/AssetStudio/Classes/Material.cs", "repo_id": "AssetStudio", "token_count": 2233 }
78
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public sealed class SkinnedMeshRenderer : Renderer { public PPtr<Mesh> m_Mesh; public PPtr<Transform>[] m_Bones; public float[] m_BlendShapeWeights; public SkinnedMeshRenderer(ObjectReader reader) : base(reader) { int m_Quality = reader.ReadInt32(); var m_UpdateWhenOffscreen = reader.ReadBoolean(); var m_SkinNormals = reader.ReadBoolean(); //3.1.0 and below reader.AlignStream(); if (version[0] == 2 && version[1] < 6) //2.6 down { var m_DisableAnimationWhenOffscreen = new PPtr<Animation>(reader); } m_Mesh = new PPtr<Mesh>(reader); m_Bones = new PPtr<Transform>[reader.ReadInt32()]; for (int b = 0; b < m_Bones.Length; b++) { m_Bones[b] = new PPtr<Transform>(reader); } if (version[0] > 4 || (version[0] == 4 && version[1] >= 3)) //4.3 and up { m_BlendShapeWeights = reader.ReadSingleArray(); } } } }
AssetStudio/AssetStudio/Classes/SkinnedMeshRenderer.cs/0
{ "file_path": "AssetStudio/AssetStudio/Classes/SkinnedMeshRenderer.cs", "repo_id": "AssetStudio", "token_count": 597 }
79
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AssetStudio { public enum FileType { AssetsFile, BundleFile, WebFile, ResourceFile, GZipFile, BrotliFile, ZipFile } }
AssetStudio/AssetStudio/FileType.cs/0
{ "file_path": "AssetStudio/AssetStudio/FileType.cs", "repo_id": "AssetStudio", "token_count": 146 }
80
using System; namespace AssetStudio { public static class Progress { public static IProgress<int> Default = new Progress<int>(); private static int preValue; public static void Reset() { preValue = 0; Default.Report(0); } public static void Report(int current, int total) { var value = (int)(current * 100f / total); Report(value); } private static void Report(int value) { if (value > preValue) { preValue = value; Default.Report(value); } } } }
AssetStudio/AssetStudio/Progress.cs/0
{ "file_path": "AssetStudio/AssetStudio/Progress.cs", "repo_id": "AssetStudio", "token_count": 338 }
81
#pragma once #include "dllexport.h" #include "bool32_t.h" namespace fbxsdk { class FbxNode; class FbxFileTexture; template<typename T, const int Alignment = 16> class FbxArray; class FbxCluster; class FbxMesh; class FbxSurfacePhong; } struct AsFbxContext; struct AsFbxSkinContext; struct AsFbxAnimContext; struct AsFbxMorphContext; AS_API(void) AsUtilQuaternionToEuler(float qx, float qy, float qz, float qw, float* vx, float* vy, float* vz); AS_API(void) AsUtilEulerToQuaternion(float vx, float vy, float vz, float* qx, float* qy, float* qz, float* qw); // All strings ([const] char *) in this header are UTF-8 strings. AS_API(AsFbxContext*) AsFbxCreateContext(); // Do not free pErrMsg AS_API(bool32_t) AsFbxInitializeContext(AsFbxContext* pContext, const char* pFileName, float scaleFactor, int32_t versionIndex, bool32_t isAscii, bool32_t is60Fps, const char** pErrMsg); AS_API(void) AsFbxDisposeContext(AsFbxContext** ppContext); AS_API(void) AsFbxSetFramePaths(AsFbxContext* pContext, const char* ppPaths[], int32_t count); AS_API(void) AsFbxExportScene(AsFbxContext* pContext); AS_API(fbxsdk::FbxNode*) AsFbxGetSceneRootNode(AsFbxContext* pContext); AS_API(fbxsdk::FbxNode*) AsFbxExportSingleFrame(AsFbxContext* pContext, fbxsdk::FbxNode* pParentNode, const char* pFramePath, const char* pFrameName, float localPositionX, float localPositionY, float localPositionZ, float localRotationX, float localRotationY, float localRotationZ, float localScaleX, float localScaleY, float localScaleZ); AS_API(void) AsFbxSetJointsNode_CastToBone(AsFbxContext* pContext, fbxsdk::FbxNode* pNode, float boneSize); AS_API(void) AsFbxSetJointsNode_BoneInPath(AsFbxContext* pContext, fbxsdk::FbxNode* pNode, float boneSize); AS_API(void) AsFbxSetJointsNode_Generic(AsFbxContext* pContext, fbxsdk::FbxNode* pNode); AS_API(void) AsFbxPrepareMaterials(AsFbxContext* pContext, int32_t materialCount, int32_t textureCount); AS_API(fbxsdk::FbxFileTexture*) AsFbxCreateTexture(AsFbxContext* pContext, const char* pMatTexName); AS_API(void) AsFbxLinkTexture(int32_t dest, fbxsdk::FbxFileTexture* pTexture, fbxsdk::FbxSurfacePhong* pMaterial, float offsetX, float offsetY, float scaleX, float scaleY); AS_API(fbxsdk::FbxArray<fbxsdk::FbxCluster*>*) AsFbxMeshCreateClusterArray(int32_t boneCount); AS_API(void) AsFbxMeshDisposeClusterArray(fbxsdk::FbxArray<fbxsdk::FbxCluster*>** ppArray); AS_API(fbxsdk::FbxCluster*) AsFbxMeshCreateCluster(AsFbxContext* pContext, fbxsdk::FbxNode* pBoneNode); AS_API(void) AsFbxMeshAddCluster(fbxsdk::FbxArray<fbxsdk::FbxCluster*>* pArray, /* CanBeNull */ fbxsdk::FbxCluster* pCluster); AS_API(fbxsdk::FbxMesh*) AsFbxMeshCreateMesh(AsFbxContext* pContext, fbxsdk::FbxNode* pFrameNode); AS_API(void) AsFbxMeshInitControlPoints(fbxsdk::FbxMesh* pMesh, int32_t vertexCount); AS_API(void) AsFbxMeshCreateElementNormal(fbxsdk::FbxMesh* pMesh); AS_API(void) AsFbxMeshCreateDiffuseUV(fbxsdk::FbxMesh* pMesh, int32_t uv); AS_API(void) AsFbxMeshCreateNormalMapUV(fbxsdk::FbxMesh* pMesh, int32_t uv); AS_API(void) AsFbxMeshCreateElementTangent(fbxsdk::FbxMesh* pMesh); AS_API(void) AsFbxMeshCreateElementVertexColor(fbxsdk::FbxMesh* pMesh); AS_API(void) AsFbxMeshCreateElementMaterial(fbxsdk::FbxMesh* pMesh); AS_API(fbxsdk::FbxSurfacePhong*) AsFbxCreateMaterial(AsFbxContext* pContext, const char* pMatName, float diffuseR, float diffuseG, float diffuseB, float ambientR, float ambientG, float ambientB, float emissiveR, float emissiveG, float emissiveB, float specularR, float specularG, float specularB, float reflectR, float reflectG, float reflectB, float shininess, float transparency); AS_API(int32_t) AsFbxAddMaterialToFrame(fbxsdk::FbxNode* pFrameNode, fbxsdk::FbxSurfacePhong* pMaterial); AS_API(void) AsFbxSetFrameShadingModeToTextureShading(fbxsdk::FbxNode* pFrameNode); AS_API(void) AsFbxMeshSetControlPoint(fbxsdk::FbxMesh* pMesh, int32_t index, float x, float y, float z); AS_API(void) AsFbxMeshAddPolygon(fbxsdk::FbxMesh* pMesh, int32_t materialIndex, int32_t index0, int32_t index1, int32_t index2); AS_API(void) AsFbxMeshElementNormalAdd(fbxsdk::FbxMesh* pMesh, int32_t elementIndex, float x, float y, float z); AS_API(void) AsFbxMeshElementUVAdd(fbxsdk::FbxMesh* pMesh, int32_t elementIndex, float u, float v); AS_API(void) AsFbxMeshElementTangentAdd(fbxsdk::FbxMesh* pMesh, int32_t elementIndex, float x, float y, float z, float w); AS_API(void) AsFbxMeshElementVertexColorAdd(fbxsdk::FbxMesh* pMesh, int32_t elementIndex, float r, float g, float b, float a); AS_API(void) AsFbxMeshSetBoneWeight(fbxsdk::FbxArray<fbxsdk::FbxCluster*>* pClusterArray, int32_t boneIndex, int32_t vertexIndex, float weight); AS_API(AsFbxSkinContext*) AsFbxMeshCreateSkinContext(AsFbxContext* pContext, fbxsdk::FbxNode* pFrameNode); AS_API(void) AsFbxMeshDisposeSkinContext(AsFbxSkinContext** ppSkinContext); AS_API(bool32_t) FbxClusterArray_HasItemAt(fbxsdk::FbxArray<fbxsdk::FbxCluster*>* pClusterArray, int32_t index); AS_API(void) AsFbxMeshSkinAddCluster(AsFbxSkinContext* pSkinContext, fbxsdk::FbxArray<fbxsdk::FbxCluster*>* pClusterArray, int32_t index, float pBoneMatrix[16]); AS_API(void) AsFbxMeshAddDeformer(AsFbxSkinContext* pSkinContext, fbxsdk::FbxMesh* pMesh); AS_API(AsFbxAnimContext*) AsFbxAnimCreateContext(bool32_t eulerFilter); AS_API(void) AsFbxAnimDisposeContext(AsFbxAnimContext** ppAnimContext); AS_API(void) AsFbxAnimPrepareStackAndLayer(AsFbxContext* pContext, AsFbxAnimContext* pAnimContext, const char* pTakeName); AS_API(void) AsFbxAnimLoadCurves(fbxsdk::FbxNode* pNode, AsFbxAnimContext* pAnimContext); AS_API(void) AsFbxAnimBeginKeyModify(AsFbxAnimContext* pAnimContext); AS_API(void) AsFbxAnimEndKeyModify(AsFbxAnimContext* pAnimContext); AS_API(void) AsFbxAnimAddScalingKey(AsFbxAnimContext* pAnimContext, float time, float x, float y, float z); AS_API(void) AsFbxAnimAddRotationKey(AsFbxAnimContext* pAnimContext, float time, float x, float y, float z); AS_API(void) AsFbxAnimAddTranslationKey(AsFbxAnimContext* pAnimContext, float time, float x, float y, float z); AS_API(void) AsFbxAnimApplyEulerFilter(AsFbxAnimContext* pAnimContext, float filterPrecision); AS_API(int32_t) AsFbxAnimGetCurrentBlendShapeChannelCount(AsFbxAnimContext* pAnimContext, fbxsdk::FbxNode* pNode); AS_API(bool32_t) AsFbxAnimIsBlendShapeChannelMatch(AsFbxAnimContext* pAnimContext, int32_t channelIndex, const char* channelName); AS_API(void) AsFbxAnimBeginBlendShapeAnimCurve(AsFbxAnimContext* pAnimContext, int32_t channelIndex); AS_API(void) AsFbxAnimEndBlendShapeAnimCurve(AsFbxAnimContext* pAnimContext); AS_API(void) AsFbxAnimAddBlendShapeKeyframe(AsFbxAnimContext* pAnimContext, float time, float value); AS_API(AsFbxMorphContext*) AsFbxMorphCreateContext(); AS_API(void) AsFbxMorphInitializeContext(AsFbxContext* pContext, AsFbxMorphContext* pMorphContext, fbxsdk::FbxNode* pNode); AS_API(void) AsFbxMorphDisposeContext(AsFbxMorphContext** ppMorphContext); AS_API(void) AsFbxMorphAddBlendShapeChannel(AsFbxContext* pContext, AsFbxMorphContext* pMorphContext, const char* channelName); AS_API(void) AsFbxMorphAddBlendShapeChannelShape(AsFbxContext* pContext, AsFbxMorphContext* pMorphContext, float weight, const char* shapeName); AS_API(void) AsFbxMorphCopyBlendShapeControlPoints(AsFbxMorphContext* pMorphContext); AS_API(void) AsFbxMorphSetBlendShapeVertex(AsFbxMorphContext* pMorphContext, uint32_t index, float x, float y, float z); AS_API(void) AsFbxMorphCopyBlendShapeControlPointsNormal(AsFbxMorphContext* pMorphContext); AS_API(void) AsFbxMorphSetBlendShapeVertexNormal(AsFbxMorphContext* pMorphContext, uint32_t index, float x, float y, float z);
AssetStudio/AssetStudioFBXNative/api.h/0
{ "file_path": "AssetStudio/AssetStudioFBXNative/api.h", "repo_id": "AssetStudio", "token_count": 3131 }
82
using System.Runtime.InteropServices; using AssetStudio.FbxInterop; namespace AssetStudio { partial class Fbx { [DllImport(FbxDll.DllName, CallingConvention = CallingConvention.Winapi)] private static extern void AsUtilQuaternionToEuler(float qx, float qy, float qz, float qw, out float vx, out float vy, out float vz); [DllImport(FbxDll.DllName, CallingConvention = CallingConvention.Winapi)] private static extern void AsUtilEulerToQuaternion(float vx, float vy, float vz, out float qx, out float qy, out float qz, out float qw); } }
AssetStudio/AssetStudioFBXWrapper/Fbx.PInvoke.cs/0
{ "file_path": "AssetStudio/AssetStudioFBXWrapper/Fbx.PInvoke.cs", "repo_id": "AssetStudio", "token_count": 230 }
83
namespace AssetStudioGUI { partial class ExportOptions { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.OKbutton = new System.Windows.Forms.Button(); this.Cancel = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.openAfterExport = new System.Windows.Forms.CheckBox(); this.restoreExtensionName = new System.Windows.Forms.CheckBox(); this.assetGroupOptions = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.convertAudio = new System.Windows.Forms.CheckBox(); this.panel1 = new System.Windows.Forms.Panel(); this.totga = new System.Windows.Forms.RadioButton(); this.tojpg = new System.Windows.Forms.RadioButton(); this.topng = new System.Windows.Forms.RadioButton(); this.tobmp = new System.Windows.Forms.RadioButton(); this.converttexture = new System.Windows.Forms.CheckBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.exportAllUvsAsDiffuseMaps = new System.Windows.Forms.CheckBox(); this.exportBlendShape = new System.Windows.Forms.CheckBox(); this.exportAnimations = new System.Windows.Forms.CheckBox(); this.scaleFactor = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.fbxFormat = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.fbxVersion = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.boneSize = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.exportSkins = new System.Windows.Forms.CheckBox(); this.label1 = new System.Windows.Forms.Label(); this.filterPrecision = new System.Windows.Forms.NumericUpDown(); this.castToBone = new System.Windows.Forms.CheckBox(); this.exportAllNodes = new System.Windows.Forms.CheckBox(); this.eulerFilter = new System.Windows.Forms.CheckBox(); this.exportUvsTooltip = new System.Windows.Forms.ToolTip(this.components); this.groupBox1.SuspendLayout(); this.panel1.SuspendLayout(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.scaleFactor)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.boneSize)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.filterPrecision)).BeginInit(); this.SuspendLayout(); // // OKbutton // this.OKbutton.Location = new System.Drawing.Point(318, 351); this.OKbutton.Name = "OKbutton"; this.OKbutton.Size = new System.Drawing.Size(75, 21); this.OKbutton.TabIndex = 6; this.OKbutton.Text = "OK"; this.OKbutton.UseVisualStyleBackColor = true; this.OKbutton.Click += new System.EventHandler(this.OKbutton_Click); // // Cancel // this.Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.Cancel.Location = new System.Drawing.Point(399, 351); this.Cancel.Name = "Cancel"; this.Cancel.Size = new System.Drawing.Size(75, 21); this.Cancel.TabIndex = 7; this.Cancel.Text = "Cancel"; this.Cancel.UseVisualStyleBackColor = true; this.Cancel.Click += new System.EventHandler(this.Cancel_Click); // // groupBox1 // this.groupBox1.AutoSize = true; this.groupBox1.Controls.Add(this.openAfterExport); this.groupBox1.Controls.Add(this.restoreExtensionName); this.groupBox1.Controls.Add(this.assetGroupOptions); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.convertAudio); this.groupBox1.Controls.Add(this.panel1); this.groupBox1.Controls.Add(this.converttexture); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(232, 334); this.groupBox1.TabIndex = 9; this.groupBox1.TabStop = false; this.groupBox1.Text = "Export"; // // openAfterExport // this.openAfterExport.AutoSize = true; this.openAfterExport.Checked = true; this.openAfterExport.CheckState = System.Windows.Forms.CheckState.Checked; this.openAfterExport.Location = new System.Drawing.Point(6, 160); this.openAfterExport.Name = "openAfterExport"; this.openAfterExport.Size = new System.Drawing.Size(168, 16); this.openAfterExport.TabIndex = 10; this.openAfterExport.Text = "Open folder after export"; this.openAfterExport.UseVisualStyleBackColor = true; // // restoreExtensionName // this.restoreExtensionName.AutoSize = true; this.restoreExtensionName.Checked = true; this.restoreExtensionName.CheckState = System.Windows.Forms.CheckState.Checked; this.restoreExtensionName.Location = new System.Drawing.Point(6, 58); this.restoreExtensionName.Name = "restoreExtensionName"; this.restoreExtensionName.Size = new System.Drawing.Size(216, 16); this.restoreExtensionName.TabIndex = 9; this.restoreExtensionName.Text = "Restore TextAsset extension name"; this.restoreExtensionName.UseVisualStyleBackColor = true; // // assetGroupOptions // this.assetGroupOptions.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.assetGroupOptions.FormattingEnabled = true; this.assetGroupOptions.Items.AddRange(new object[] { "type name", "container path", "source file name", "do not group"}); this.assetGroupOptions.Location = new System.Drawing.Point(6, 32); this.assetGroupOptions.Name = "assetGroupOptions"; this.assetGroupOptions.Size = new System.Drawing.Size(149, 20); this.assetGroupOptions.TabIndex = 8; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(6, 17); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(149, 12); this.label6.TabIndex = 7; this.label6.Text = "Group exported assets by"; // // convertAudio // this.convertAudio.AutoSize = true; this.convertAudio.Checked = true; this.convertAudio.CheckState = System.Windows.Forms.CheckState.Checked; this.convertAudio.Location = new System.Drawing.Point(6, 138); this.convertAudio.Name = "convertAudio"; this.convertAudio.Size = new System.Drawing.Size(198, 16); this.convertAudio.TabIndex = 6; this.convertAudio.Text = "Convert AudioClip to WAV(PCM)"; this.convertAudio.UseVisualStyleBackColor = true; // // panel1 // this.panel1.Controls.Add(this.totga); this.panel1.Controls.Add(this.tojpg); this.panel1.Controls.Add(this.topng); this.panel1.Controls.Add(this.tobmp); this.panel1.Location = new System.Drawing.Point(20, 102); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(202, 30); this.panel1.TabIndex = 5; // // totga // this.totga.AutoSize = true; this.totga.Location = new System.Drawing.Point(150, 6); this.totga.Name = "totga"; this.totga.Size = new System.Drawing.Size(41, 16); this.totga.TabIndex = 2; this.totga.Text = "Tga"; this.totga.UseVisualStyleBackColor = true; // // tojpg // this.tojpg.AutoSize = true; this.tojpg.Location = new System.Drawing.Point(97, 6); this.tojpg.Name = "tojpg"; this.tojpg.Size = new System.Drawing.Size(47, 16); this.tojpg.TabIndex = 4; this.tojpg.Text = "Jpeg"; this.tojpg.UseVisualStyleBackColor = true; // // topng // this.topng.AutoSize = true; this.topng.Checked = true; this.topng.Location = new System.Drawing.Point(50, 6); this.topng.Name = "topng"; this.topng.Size = new System.Drawing.Size(41, 16); this.topng.TabIndex = 3; this.topng.TabStop = true; this.topng.Text = "Png"; this.topng.UseVisualStyleBackColor = true; // // tobmp // this.tobmp.AutoSize = true; this.tobmp.Location = new System.Drawing.Point(3, 6); this.tobmp.Name = "tobmp"; this.tobmp.Size = new System.Drawing.Size(41, 16); this.tobmp.TabIndex = 2; this.tobmp.Text = "Bmp"; this.tobmp.UseVisualStyleBackColor = true; // // converttexture // this.converttexture.AutoSize = true; this.converttexture.Checked = true; this.converttexture.CheckState = System.Windows.Forms.CheckState.Checked; this.converttexture.Location = new System.Drawing.Point(6, 80); this.converttexture.Name = "converttexture"; this.converttexture.Size = new System.Drawing.Size(126, 16); this.converttexture.TabIndex = 1; this.converttexture.Text = "Convert Texture2D"; this.converttexture.UseVisualStyleBackColor = true; // // groupBox2 // this.groupBox2.AutoSize = true; this.groupBox2.Controls.Add(this.exportAllUvsAsDiffuseMaps); this.groupBox2.Controls.Add(this.exportBlendShape); this.groupBox2.Controls.Add(this.exportAnimations); this.groupBox2.Controls.Add(this.scaleFactor); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.fbxFormat); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.fbxVersion); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.boneSize); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.exportSkins); this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.filterPrecision); this.groupBox2.Controls.Add(this.castToBone); this.groupBox2.Controls.Add(this.exportAllNodes); this.groupBox2.Controls.Add(this.eulerFilter); this.groupBox2.Location = new System.Drawing.Point(250, 12); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(224, 334); this.groupBox2.TabIndex = 11; this.groupBox2.TabStop = false; this.groupBox2.Text = "Fbx"; // // exportAllUvsAsDiffuseMaps // this.exportAllUvsAsDiffuseMaps.AccessibleDescription = ""; this.exportAllUvsAsDiffuseMaps.AutoSize = true; this.exportAllUvsAsDiffuseMaps.Location = new System.Drawing.Point(6, 171); this.exportAllUvsAsDiffuseMaps.Name = "exportAllUvsAsDiffuseMaps"; this.exportAllUvsAsDiffuseMaps.Size = new System.Drawing.Size(204, 16); this.exportAllUvsAsDiffuseMaps.TabIndex = 23; this.exportAllUvsAsDiffuseMaps.Text = "Export all UVs as diffuse maps"; this.exportUvsTooltip.SetToolTip(this.exportAllUvsAsDiffuseMaps, "Unchecked: UV1 exported as normal map. Check this if your export is missing a UV " + "map."); this.exportAllUvsAsDiffuseMaps.UseVisualStyleBackColor = true; // // exportBlendShape // this.exportBlendShape.AutoSize = true; this.exportBlendShape.Checked = true; this.exportBlendShape.CheckState = System.Windows.Forms.CheckState.Checked; this.exportBlendShape.Location = new System.Drawing.Point(6, 127); this.exportBlendShape.Name = "exportBlendShape"; this.exportBlendShape.Size = new System.Drawing.Size(126, 16); this.exportBlendShape.TabIndex = 22; this.exportBlendShape.Text = "Export blendshape"; this.exportBlendShape.UseVisualStyleBackColor = true; // // exportAnimations // this.exportAnimations.AutoSize = true; this.exportAnimations.Checked = true; this.exportAnimations.CheckState = System.Windows.Forms.CheckState.Checked; this.exportAnimations.Location = new System.Drawing.Point(6, 105); this.exportAnimations.Name = "exportAnimations"; this.exportAnimations.Size = new System.Drawing.Size(126, 16); this.exportAnimations.TabIndex = 21; this.exportAnimations.Text = "Export animations"; this.exportAnimations.UseVisualStyleBackColor = true; // // scaleFactor // this.scaleFactor.DecimalPlaces = 2; this.scaleFactor.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.scaleFactor.Location = new System.Drawing.Point(83, 224); this.scaleFactor.Name = "scaleFactor"; this.scaleFactor.Size = new System.Drawing.Size(60, 21); this.scaleFactor.TabIndex = 20; this.scaleFactor.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.scaleFactor.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(6, 226); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(71, 12); this.label5.TabIndex = 19; this.label5.Text = "ScaleFactor"; // // fbxFormat // this.fbxFormat.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.fbxFormat.FormattingEnabled = true; this.fbxFormat.Items.AddRange(new object[] { "Binary", "Ascii"}); this.fbxFormat.Location = new System.Drawing.Point(77, 254); this.fbxFormat.Name = "fbxFormat"; this.fbxFormat.Size = new System.Drawing.Size(61, 20); this.fbxFormat.TabIndex = 18; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 258); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(59, 12); this.label4.TabIndex = 17; this.label4.Text = "FBXFormat"; // // fbxVersion // this.fbxVersion.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.fbxVersion.FormattingEnabled = true; this.fbxVersion.Items.AddRange(new object[] { "6.1", "7.1", "7.2", "7.3", "7.4", "7.5"}); this.fbxVersion.Location = new System.Drawing.Point(77, 284); this.fbxVersion.Name = "fbxVersion"; this.fbxVersion.Size = new System.Drawing.Size(47, 20); this.fbxVersion.TabIndex = 16; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 287); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(65, 12); this.label3.TabIndex = 15; this.label3.Text = "FBXVersion"; // // boneSize // this.boneSize.Location = new System.Drawing.Point(65, 197); this.boneSize.Name = "boneSize"; this.boneSize.Size = new System.Drawing.Size(46, 21); this.boneSize.TabIndex = 11; this.boneSize.Value = new decimal(new int[] { 10, 0, 0, 0}); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 199); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(53, 12); this.label2.TabIndex = 10; this.label2.Text = "BoneSize"; // // exportSkins // this.exportSkins.AutoSize = true; this.exportSkins.Checked = true; this.exportSkins.CheckState = System.Windows.Forms.CheckState.Checked; this.exportSkins.Location = new System.Drawing.Point(6, 83); this.exportSkins.Name = "exportSkins"; this.exportSkins.Size = new System.Drawing.Size(96, 16); this.exportSkins.TabIndex = 8; this.exportSkins.Text = "Export skins"; this.exportSkins.UseVisualStyleBackColor = true; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(26, 39); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(95, 12); this.label1.TabIndex = 7; this.label1.Text = "FilterPrecision"; // // filterPrecision // this.filterPrecision.DecimalPlaces = 2; this.filterPrecision.Increment = new decimal(new int[] { 1, 0, 0, 131072}); this.filterPrecision.Location = new System.Drawing.Point(127, 37); this.filterPrecision.Name = "filterPrecision"; this.filterPrecision.Size = new System.Drawing.Size(51, 21); this.filterPrecision.TabIndex = 6; this.filterPrecision.Value = new decimal(new int[] { 25, 0, 0, 131072}); // // castToBone // this.castToBone.AutoSize = true; this.castToBone.Location = new System.Drawing.Point(6, 149); this.castToBone.Name = "castToBone"; this.castToBone.Size = new System.Drawing.Size(156, 16); this.castToBone.TabIndex = 5; this.castToBone.Text = "All nodes cast to bone"; this.castToBone.UseVisualStyleBackColor = true; // // exportAllNodes // this.exportAllNodes.AutoSize = true; this.exportAllNodes.Checked = true; this.exportAllNodes.CheckState = System.Windows.Forms.CheckState.Checked; this.exportAllNodes.Location = new System.Drawing.Point(6, 61); this.exportAllNodes.Name = "exportAllNodes"; this.exportAllNodes.Size = new System.Drawing.Size(120, 16); this.exportAllNodes.TabIndex = 4; this.exportAllNodes.Text = "Export all nodes"; this.exportAllNodes.UseVisualStyleBackColor = true; // // eulerFilter // this.eulerFilter.AutoSize = true; this.eulerFilter.Checked = true; this.eulerFilter.CheckState = System.Windows.Forms.CheckState.Checked; this.eulerFilter.Location = new System.Drawing.Point(6, 20); this.eulerFilter.Name = "eulerFilter"; this.eulerFilter.Size = new System.Drawing.Size(90, 16); this.eulerFilter.TabIndex = 3; this.eulerFilter.Text = "EulerFilter"; this.eulerFilter.UseVisualStyleBackColor = true; // // ExportOptions // this.AcceptButton = this.OKbutton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.Cancel; this.ClientSize = new System.Drawing.Size(486, 384); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.Cancel); this.Controls.Add(this.OKbutton); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ExportOptions"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Export options"; this.TopMost = true; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.scaleFactor)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.boneSize)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.filterPrecision)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button OKbutton; private System.Windows.Forms.Button Cancel; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.CheckBox converttexture; private System.Windows.Forms.RadioButton tojpg; private System.Windows.Forms.RadioButton topng; private System.Windows.Forms.RadioButton tobmp; private System.Windows.Forms.RadioButton totga; private System.Windows.Forms.CheckBox convertAudio; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.NumericUpDown boneSize; private System.Windows.Forms.Label label2; private System.Windows.Forms.CheckBox exportSkins; private System.Windows.Forms.Label label1; private System.Windows.Forms.NumericUpDown filterPrecision; private System.Windows.Forms.CheckBox castToBone; private System.Windows.Forms.CheckBox exportAllNodes; private System.Windows.Forms.CheckBox eulerFilter; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox fbxVersion; private System.Windows.Forms.ComboBox fbxFormat; private System.Windows.Forms.Label label4; private System.Windows.Forms.NumericUpDown scaleFactor; private System.Windows.Forms.Label label5; private System.Windows.Forms.CheckBox exportBlendShape; private System.Windows.Forms.CheckBox exportAnimations; private System.Windows.Forms.ComboBox assetGroupOptions; private System.Windows.Forms.Label label6; private System.Windows.Forms.CheckBox restoreExtensionName; private System.Windows.Forms.CheckBox openAfterExport; private System.Windows.Forms.CheckBox exportAllUvsAsDiffuseMaps; private System.Windows.Forms.ToolTip exportUvsTooltip; } }
AssetStudio/AssetStudioGUI/ExportOptions.Designer.cs/0
{ "file_path": "AssetStudio/AssetStudioGUI/ExportOptions.Designer.cs", "repo_id": "AssetStudio", "token_count": 12184 }
84
using Mono.Cecil; using System.Collections.Generic; using System.IO; namespace AssetStudio { public class AssemblyLoader { public bool Loaded; private Dictionary<string, ModuleDefinition> moduleDic = new Dictionary<string, ModuleDefinition>(); public void Load(string path) { var files = Directory.GetFiles(path, "*.dll"); var resolver = new MyAssemblyResolver(); var readerParameters = new ReaderParameters(); readerParameters.AssemblyResolver = resolver; foreach (var file in files) { try { var assembly = AssemblyDefinition.ReadAssembly(file, readerParameters); resolver.Register(assembly); moduleDic.Add(assembly.MainModule.Name, assembly.MainModule); } catch { // ignored } } Loaded = true; } public TypeDefinition GetTypeDefinition(string assemblyName, string fullName) { if (moduleDic.TryGetValue(assemblyName, out var module)) { var typeDef = module.GetType(fullName); if (typeDef == null && assemblyName == "UnityEngine.dll") { foreach (var pair in moduleDic) { typeDef = pair.Value.GetType(fullName); if (typeDef != null) { break; } } } return typeDef; } return null; } public void Clear() { foreach (var pair in moduleDic) { pair.Value.Dispose(); } moduleDic.Clear(); Loaded = false; } } }
AssetStudio/AssetStudioUtility/AssemblyLoader.cs/0
{ "file_path": "AssetStudio/AssetStudioUtility/AssemblyLoader.cs", "repo_id": "AssetStudio", "token_count": 1083 }
85
using Mono.Cecil; using System; using System.Collections.Generic; using System.Linq; using Unity.CecilTools; using Unity.SerializationLogic; namespace AssetStudio { public class TypeDefinitionConverter { private readonly TypeDefinition TypeDef; private readonly TypeResolver TypeResolver; private readonly SerializedTypeHelper Helper; private readonly int Indent; public TypeDefinitionConverter(TypeDefinition typeDef, SerializedTypeHelper helper, int indent) { TypeDef = typeDef; TypeResolver = new TypeResolver(null); Helper = helper; Indent = indent; } public List<TypeTreeNode> ConvertToTypeTreeNodes() { var nodes = new List<TypeTreeNode>(); var baseTypes = new Stack<TypeReference>(); var lastBaseType = TypeDef.BaseType; while (!UnitySerializationLogic.IsNonSerialized(lastBaseType)) { var genericInstanceType = lastBaseType as GenericInstanceType; if (genericInstanceType != null) { TypeResolver.Add(genericInstanceType); } baseTypes.Push(lastBaseType); lastBaseType = lastBaseType.Resolve().BaseType; } while (baseTypes.Count > 0) { var typeReference = baseTypes.Pop(); var typeDefinition = typeReference.Resolve(); foreach (var fieldDefinition in typeDefinition.Fields.Where(WillUnitySerialize)) { if (!IsHiddenByParentClass(baseTypes, fieldDefinition, TypeDef)) { nodes.AddRange(ProcessingFieldRef(ResolveGenericFieldReference(fieldDefinition))); } } var genericInstanceType = typeReference as GenericInstanceType; if (genericInstanceType != null) { TypeResolver.Remove(genericInstanceType); } } foreach (var field in FilteredFields()) { nodes.AddRange(ProcessingFieldRef(field)); } return nodes; } private bool WillUnitySerialize(FieldDefinition fieldDefinition) { try { var resolvedFieldType = TypeResolver.Resolve(fieldDefinition.FieldType); if (UnitySerializationLogic.ShouldNotTryToResolve(resolvedFieldType)) { return false; } if (!UnityEngineTypePredicates.IsUnityEngineObject(resolvedFieldType)) { if (resolvedFieldType.FullName == fieldDefinition.DeclaringType.FullName) { return false; } } return UnitySerializationLogic.WillUnitySerialize(fieldDefinition, TypeResolver); } catch (Exception ex) { throw new Exception(string.Format("Exception while processing {0} {1}, error {2}", fieldDefinition.FieldType.FullName, fieldDefinition.FullName, ex.Message)); } } private static bool IsHiddenByParentClass(IEnumerable<TypeReference> parentTypes, FieldDefinition fieldDefinition, TypeDefinition processingType) { return processingType.Fields.Any(f => f.Name == fieldDefinition.Name) || parentTypes.Any(t => t.Resolve().Fields.Any(f => f.Name == fieldDefinition.Name)); } private IEnumerable<FieldDefinition> FilteredFields() { return TypeDef.Fields.Where(WillUnitySerialize).Where(f => UnitySerializationLogic.IsSupportedCollection(f.FieldType) || !f.FieldType.IsGenericInstance || UnitySerializationLogic.ShouldImplementIDeserializable(f.FieldType.Resolve())); } private FieldReference ResolveGenericFieldReference(FieldReference fieldRef) { var field = new FieldReference(fieldRef.Name, fieldRef.FieldType, ResolveDeclaringType(fieldRef.DeclaringType)); return TypeDef.Module.ImportReference(field); } private TypeReference ResolveDeclaringType(TypeReference declaringType) { var typeDefinition = declaringType.Resolve(); if (typeDefinition == null || !typeDefinition.HasGenericParameters) { return typeDefinition; } var genericInstanceType = new GenericInstanceType(typeDefinition); foreach (var genericParameter in typeDefinition.GenericParameters) { genericInstanceType.GenericArguments.Add(genericParameter); } return TypeResolver.Resolve(genericInstanceType); } private List<TypeTreeNode> ProcessingFieldRef(FieldReference fieldDef) { var typeRef = TypeResolver.Resolve(fieldDef.FieldType); return TypeRefToTypeTreeNodes(typeRef, fieldDef.Name, Indent, false); } private static bool IsStruct(TypeReference typeRef) { return typeRef.IsValueType && !IsEnum(typeRef) && !typeRef.IsPrimitive; } private static bool IsEnum(TypeReference typeRef) { return !typeRef.IsArray && typeRef.Resolve().IsEnum; } private static bool RequiresAlignment(TypeReference typeRef) { switch (typeRef.MetadataType) { case MetadataType.Boolean: case MetadataType.Char: case MetadataType.SByte: case MetadataType.Byte: case MetadataType.Int16: case MetadataType.UInt16: return true; default: return UnitySerializationLogic.IsSupportedCollection(typeRef) && RequiresAlignment(CecilUtils.ElementTypeOfCollection(typeRef)); } } private static bool IsSystemString(TypeReference typeRef) { return typeRef.FullName == "System.String"; } private List<TypeTreeNode> TypeRefToTypeTreeNodes(TypeReference typeRef, string name, int indent, bool isElement) { var align = false; if (!IsStruct(TypeDef) || !UnityEngineTypePredicates.IsUnityEngineValueType(TypeDef)) { if (IsStruct(typeRef) || RequiresAlignment(typeRef)) { align = true; } } var nodes = new List<TypeTreeNode>(); if (typeRef.IsPrimitive) { var primitiveName = typeRef.Name; switch (primitiveName) { case "Boolean": primitiveName = "bool"; break; case "Byte": primitiveName = "UInt8"; break; case "SByte": primitiveName = "SInt8"; break; case "Int16": primitiveName = "SInt16"; break; case "UInt16": primitiveName = "UInt16"; break; case "Int32": primitiveName = "SInt32"; break; case "UInt32": primitiveName = "UInt32"; break; case "Int64": primitiveName = "SInt64"; break; case "UInt64": primitiveName = "UInt64"; break; case "Char": primitiveName = "char"; break; case "Double": primitiveName = "double"; break; case "Single": primitiveName = "float"; break; default: throw new NotSupportedException(); } if (isElement) { align = false; } nodes.Add(new TypeTreeNode(primitiveName, name, indent, align)); } else if (IsSystemString(typeRef)) { Helper.AddString(nodes, name, indent); } else if (IsEnum(typeRef)) { nodes.Add(new TypeTreeNode("SInt32", name, indent, align)); } else if (CecilUtils.IsGenericList(typeRef)) { var elementRef = CecilUtils.ElementTypeOfCollection(typeRef); nodes.Add(new TypeTreeNode(typeRef.Name, name, indent, align)); Helper.AddArray(nodes, indent + 1); nodes.AddRange(TypeRefToTypeTreeNodes(elementRef, "data", indent + 2, true)); } else if (typeRef.IsArray) { var elementRef = typeRef.GetElementType(); nodes.Add(new TypeTreeNode(typeRef.Name, name, indent, align)); Helper.AddArray(nodes, indent + 1); nodes.AddRange(TypeRefToTypeTreeNodes(elementRef, "data", indent + 2, true)); } else if (UnityEngineTypePredicates.IsUnityEngineObject(typeRef)) { Helper.AddPPtr(nodes, typeRef.Name, name, indent); } else if (UnityEngineTypePredicates.IsSerializableUnityClass(typeRef) || UnityEngineTypePredicates.IsSerializableUnityStruct(typeRef)) { switch (typeRef.FullName) { case "UnityEngine.AnimationCurve": Helper.AddAnimationCurve(nodes, name, indent); break; case "UnityEngine.Gradient": Helper.AddGradient(nodes, name, indent); break; case "UnityEngine.GUIStyle": Helper.AddGUIStyle(nodes, name, indent); break; case "UnityEngine.RectOffset": Helper.AddRectOffset(nodes, name, indent); break; case "UnityEngine.Color32": Helper.AddColor32(nodes, name, indent); break; case "UnityEngine.Matrix4x4": Helper.AddMatrix4x4(nodes, name, indent); break; case "UnityEngine.Rendering.SphericalHarmonicsL2": Helper.AddSphericalHarmonicsL2(nodes, name, indent); break; case "UnityEngine.PropertyName": Helper.AddPropertyName(nodes, name, indent); break; } } else { nodes.Add(new TypeTreeNode(typeRef.Name, name, indent, align)); var typeDef = typeRef.Resolve(); var typeDefinitionConverter = new TypeDefinitionConverter(typeDef, Helper, indent + 1); nodes.AddRange(typeDefinitionConverter.ConvertToTypeTreeNodes()); } return nodes; } } }
AssetStudio/AssetStudioUtility/TypeDefinitionConverter.cs/0
{ "file_path": "AssetStudio/AssetStudioUtility/TypeDefinitionConverter.cs", "repo_id": "AssetStudio", "token_count": 6136 }
86
#include "bcn.h" #include "atc.h" #include "color.h" #include <algorithm> static uint8_t expand_quantized(uint8_t v, int bits) { v = v << (8 - bits); return v | (v >> bits); } void decode_atc_block(const uint8_t* _src, uint32_t* _dst) { uint8_t colors[4 * 4]; uint32_t c0 = _src[0] | (_src[1] << 8); uint32_t c1 = _src[2] | (_src[3] << 8); if (0 == (c0 & 0x8000)) { colors[0] = expand_quantized((c0 >> 0) & 0x1f, 5); colors[1] = expand_quantized((c0 >> 5) & 0x1f, 5); colors[2] = expand_quantized((c0 >> 10) & 0x1f, 5); colors[12] = expand_quantized((c1 >> 0) & 0x1f, 5); colors[13] = expand_quantized((c1 >> 5) & 0x3f, 6); colors[14] = expand_quantized((c1 >> 11) & 0x1f, 5); colors[4] = (5 * colors[0] + 3 * colors[12]) / 8; colors[5] = (5 * colors[1] + 3 * colors[13]) / 8; colors[6] = (5 * colors[2] + 3 * colors[14]) / 8; colors[8] = (3 * colors[0] + 5 * colors[12]) / 8; colors[9] = (3 * colors[1] + 5 * colors[13]) / 8; colors[10] = (3 * colors[2] + 5 * colors[14]) / 8; } else { colors[0] = 0; colors[1] = 0; colors[2] = 0; colors[8] = expand_quantized((c0 >> 0) & 0x1f, 5); colors[9] = expand_quantized((c0 >> 5) & 0x1f, 5); colors[10] = expand_quantized((c0 >> 10) & 0x1f, 5); colors[12] = expand_quantized((c1 >> 0) & 0x1f, 5); colors[13] = expand_quantized((c1 >> 5) & 0x3f, 6); colors[14] = expand_quantized((c1 >> 11) & 0x1f, 5); colors[4] = std::max(0, colors[8] - colors[12] / 4); colors[5] = std::max(0, colors[9] - colors[13] / 4); colors[6] = std::max(0, colors[10] - colors[14] / 4); } for (uint32_t i = 0, next = 8 * 4; i < 16; i += 1, next += 2) { int32_t idx = ((_src[next >> 3] >> (next & 7)) & 3) * 4; _dst[i] = color(colors[idx + 2], colors[idx + 1], colors[idx + 0], 255); } } int decode_atc_rgb4(const uint8_t* data, uint32_t m_width, uint32_t m_height, uint32_t* image) { uint32_t m_block_width = 4; uint32_t m_block_height = 4; uint32_t m_blocks_x = (m_width + m_block_width - 1) / m_block_width; uint32_t m_blocks_y = (m_height + m_block_height - 1) / m_block_height; uint32_t buffer[16]; for (uint32_t by = 0; by < m_blocks_y; by++) { for (uint32_t bx = 0; bx < m_blocks_x; bx++, data += 8) { decode_atc_block(data, buffer); copy_block_buffer(bx, by, m_width, m_height, m_block_width, m_block_height, buffer, image); } } return 1; } int decode_atc_rgba8(const uint8_t* data, uint32_t m_width, uint32_t m_height, uint32_t* image) { uint32_t m_block_width = 4; uint32_t m_block_height = 4; uint32_t m_blocks_x = (m_width + m_block_width - 1) / m_block_width; uint32_t m_blocks_y = (m_height + m_block_height - 1) / m_block_height; uint32_t buffer[16]; for (uint32_t by = 0; by < m_blocks_y; by++) { for (uint32_t bx = 0; bx < m_blocks_x; bx++, data += 16) { decode_atc_block(data + 8, buffer); decode_bc3_alpha(data, buffer, 3); copy_block_buffer(bx, by, m_width, m_height, m_block_width, m_block_height, buffer, image); } } return 1; }
AssetStudio/Texture2DDecoderNative/atc.cpp/0
{ "file_path": "AssetStudio/Texture2DDecoderNative/atc.cpp", "repo_id": "AssetStudio", "token_count": 1452 }
87
# Better Coroutine The above article talks about how a string of callbacks is a concurrent process, and obviously writing code this way, adding logic and inserting logic is very error prone. We need to use asynchronous syntax to change the form of this asynchronous callback to a synchronous form, fortunately C# has been designed for us, see the code ```csharp // example2_2 class Program { private static int loopCount = 0; static void Main(string[] args) { OneThreadSynchronizationContext _ = OneThreadSynchronizationContext.Instance; Console.WriteLine($"Main Thread: {Thread.CurrentThread.ManagedThreadId}"); Crontine(); while (true) { OneThreadSynchronizationContext.Instance.Update(); Thread.Sleep(1); ++loopCount; if (loopCount % 10000 == 0) { Console.WriteLine($"loop count: {loopCount}"); } } } private static async void Crontine() { await WaitTimeAsync(5000); Console.WriteLine($"Current thread: {Thread.CurrentThread.ManagedThreadId}, WaitTimeAsync finsih loopCount's value is: {loopCount}"); await WaitTimeAsync(4000); Console.WriteLine($"Current Thread: {Thread.CurrentThread.ManagedThreadId}, WaitTimeAsync finsih The value of loopCount is: {loopCount}"); await WaitTimeAsync(3000); Console.WriteLine($"Current Thread: {Thread.CurrentThread.ManagedThreadId}, WaitTimeAsync finsih The value of loopCount is: {loopCount}"); } private static Task WaitTimeAsync(int waitTime) { TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); Thread thread = new Thread(()=>WaitTime(waitTime, tcs)); thread.Start(); return tcs.Task; } /// <summary> /// Waiting in another thread /// </summary> private static void WaitTime(int waitTime, TaskCompletionSource<bool> tcs) { Thread.Sleep(waitTime); // throw tcs back to the main thread for execution OneThreadSynchronizationContext.Instance.Post(o=>tcs.SetResult(true), null); } } ``` In this code, in the WaitTimeAsync method, we use the TaskCompletionSource class instead of the previously passed Action parameter, and the WaitTimeAsync method returns a Task type result. waitTime we replace action() with tcs. SetResult(true), and the WaitTimeAsync method uses the await keyword in front of it, so that the sequence of callbacks can be changed to a synchronized form. This makes the code look very simple and much easier to develop. Here is another trick, we found that WaitTime needs to throw tcs.SetResult back to the main thread for execution, Microsoft gives us a simple way to set up the synchronization context in the main thread by referring to example2_2_2 ```csharp // example2_2_2 SynchronizationContext.SetSynchronizationContext(OneThreadSynchronizationContext.Instance); ``` SetResult(true) will be called directly in WaitTime, the callback will be automatically thrown to the synchronization context, and the synchronization context we can take out in the main thread to execute the callback, so automatically able to complete the operation back to the main thread ```csharp private static void WaitTime(int waitTime, TaskCompletionSource<bool> tcs) { Thread.Sleep(waitTime); tcs.SetResult(true); } ``` If you do not set the synchronization context, you will find that the printout of the current thread is not the main thread, which is also the use of many third-party libraries and . In fact, I think this design is not necessary, to the library developers to achieve better, especially in the game development, logic is all single-threaded, callback every time you go through the synchronization context is redundant, so the ET framework provides the implementation of ETTask does not use the synchronization context, the code is more concise and efficient, which will be discussed later.
ET/Book/2.2Better Coroutine.md/0
{ "file_path": "ET/Book/2.2Better Coroutine.md", "repo_id": "ET", "token_count": 1516 }
88
Similar to world of warcraft, moba such skills are extremely complex, flexibility requires a very high skill system, must need a set of its flexible numerical structure to match. Numerical structure is well designed, the realization of the skill system will be very simple, otherwise it is a disaster. For example, in World of Warcraft, a character has many numerical attributes, such as movement speed, strength, anger, energy, concentration value, magic value, blood, maximum blood, physical attack, physical defense, spell attack, spell defense, etc. There are dozens of attributes. Attributes and attributes affect each other, buffs will add absolute value to attributes, increase the percentage, or some kind of buff will come back to you after counting all the increased value and doubling it. ## Common practice: The general is to write a value class. ```c# class Numeric { public int Hp; public int MaxHp; public int Speed; // Energy public int Energy; public int MaxEnergy; // Magic public int Mp; public int MaxMp; ..... } ``` On second thought, I'm a thief using energy why should I have a value of Mp? I am a mage using magic why should there be a field for energy? I'm not sure what to do with this, just pretend you didn't see it? I can not, I come to an inheritance? ```C# // Mage values calss MageNumeric: Numeric { // magic public int Mp; public int MaxMp; } // Thief value calss RougeNumeric: Numeric { // Energy public int Energy; public int MaxEnergy; } ```` 10 races, each race 7, 8 kinds of heroes, just these values class inheritance relationship, you have to be confused it. Object-oriented is difficult to adapt to the needs of this flexible and complex. And look at the Numeric class, each value can not just design a field, for example, I have a buff will increase 10 points Speed, and a kind of buff to increase 50% of the speed, then I must add at least three secondary attribute fields ```c# class Numeric { // speed final value public int Speed; // Speed initial value public int SpeedInit; // Speed increase value public int SpeedAdd; // Speed increase percentage value public int SpeedPct; } ``` After SpeedAdd and SpeedPct are changed, a calculation is performed to calculate the final speed value. buff only needs to go to modify SpeedAdd and SpeedPct on the line. ```c# Speed = (SpeedInit + SpeedAdd) * (100 + SpeedPct) / 100 ``` Each property may have several indirect effects on the value, you can think about how large this class is, a rough estimate of more than 100 fields. The trouble is that the formula is basically the same, but just can not be unified into a function, such as MaxHp, also has a buff effect ```c# class Numeric { public int Speed; public int SpeedInit; public int SpeedAdd; public int SpeedPct; public int MaxHp; public int MaxHpInit; public int MaxHpAdd; public int MaxHpPct; } ``` Also have to write a formula for calculating Hp ```c# MaxHp = (MaxHpInit + MaxHpAdd) * (100 + MaxHpPct) / 100 ``` Dozens of properties, you have to write dozens of times, and each secondary property changes to correctly call the corresponding formula calculation. Very troublesome! This design also has a big problem, buff configuration table to fill the corresponding attribute field is not very good to fill, for example, sprint buff (increase speed 50%), how to configure the buff table to make the program simple to find and operate the SpeedPct field? Not a good idea. ## ET framework uses the Key Value form to save the value of the property ```c# Using System.Collections.Generic; Generic; namespace Model Generic; namespace Model { public enum NumericType { Max = 10000, Speed = 1000, SpeedBase = Speed * 10 + 1, SpeedAdd = Speed * 10 + 2, SpeedPct = Speed * 10 + 3, SpeedFinalAdd = Speed * 10 + 4, SpeedFinalPct = Speed * 10 + 5, Hp = 1001, HpBase = Hp * 10 + 1, MaxHp = 1002, MaxHpBase = MaxHp * 10 + 1, MaxHpAdd = MaxHp * 10 + 2, MaxHpPct = MaxHp * 10 + 3, MaxHpFinalAdd = MaxHp * 10 + 4, MaxHpFinalPct = MaxHp * 10 + 5, } public class NumericComponent: Component { public readonly Dictionary<int, int> NumericDic = new Dictionary<int, int>(); public void Awake() { // initialize base value here } public float GetAsFloat(NumericType numericType) { return (float)GetByKey((int)numericType) / 10000; } public int GetAsInt(NumericType numericType) { return GetByKey((int)numericType); } public void Set(NumericType nt, float value) { this[nt] = (int) (value * 10000); } public void Set(NumericType nt, int value) { this[nt] = value; } public int this[NumericType numericType] { get { return this.GetByKey((int) numericType); } set { int v = this.GetByKey((int) numericType); if (v == value) { return; } NumericDic[(int)numericType] = value; Update(numericType); } } private int GetByKey(int key) { int value = 0; This.NumericDic.TryGetValue(key, out value); return value; } public void Update(NumericType numericType) { if (numericType > NumericType.Max) { return; } int final = (int) numericType / 10; int bas = final * 10 + 1; int add = final * 10 + 2; int pct = final * 10 + 3; int finalAdd = final * 10 + 4; int finalPct = final * 10 + 5; // A value may be affected by a variety of circumstances, such as speed, adding a buff may increase the speed of the absolute value of 100, but also some buffs increase the speed of 10%, so a value can be controlled by 5 values of the final result // final = (((base + add) * (100 + pct) / 100) + finalAdd) * (100 + finalPct) / 100; this.NumericDic[final] = ((this.GetByKey(base) + this.GetByKey(add)) * (100 + this.GetByKey(pct)) / 100 + this.GetByKey(finalAdd)) * (100 + this. GetByKey(finalPct)) / 100; Game.EventSystem.Run(EventIdType.NumbericChange, this.Entity.Id, numericType, final); } } } ``` 1. values are saved with key value, key is the type of value, defined by NumericType, value are integers, float type can also be converted to integers, for example, multiply by 1000; key value to save properties will become very flexible, for example, mage no energy properties, then initialize the mage object does not add energy key value It's fine. Thieves do not have mana, no spell damage, etc., the initialization will not need to add these. 2. world of warcraft, a value by 5 values to influence, you can unify the use of a formula. ``` final = (((base + add) * (100 + pct) / 100) + finalAdd) * (100 + finalPct) / 100; ``` For example, the speed value speed, there is an initial value speedbase, there is a buff1 to increase the absolute speed by 10 points, then buff1 will add 10 to speedadd when it is created, buff1 minus 10 to speedadd when it is deleted, buff2 increases the speed by 20%, then buff2 adds to speedpct when it is created The 5 values are changed and the corresponding properties can be recalculated by using the Update function in a unified way. buff configuration is quite simple. If the corresponding NumericType is filled in the buff configuration, the program can easily manipulate the corresponding value. 3. Changes in properties can be uniformly thrown to other modules to subscribe to the event, writing a property change monitor becomes very simple. For example, the achievement module needs to develop an achievement life value over 1000, will get the achievement of longevity master. Then the person developing the achievement module will subscribe to the HP changes as follows. ``` /// Monitor hp value changes [NumericWatcher(NumericType.Hp) public class NumericWatcher_Hp : INumericWatcher { public void Run(long id, int value) { if (value > 1000) { // get achievement longevity master achievement } } } ``` Similarly, recording an exception log for a gold change greater than 10,000 at a time, etc. can be done this way. With this numerical component, a moba skill system can be said to be half complete.
ET/Book/5.6Numerical component design.md/0
{ "file_path": "ET/Book/5.6Numerical component design.md", "repo_id": "ET", "token_count": 2547 }
89
using System; using System.Collections.Generic; using System.IO; namespace ET { [Invoke] public class GetAllConfigBytes: AInvokeHandler<ConfigLoader.GetAllConfigBytes, ETTask<Dictionary<Type, byte[]>>> { public override async ETTask<Dictionary<Type, byte[]>> Handle(ConfigLoader.GetAllConfigBytes args) { Dictionary<Type, byte[]> output = new Dictionary<Type, byte[]>(); List<string> startConfigs = new List<string>() { "StartMachineConfigCategory", "StartProcessConfigCategory", "StartSceneConfigCategory", "StartZoneConfigCategory", }; HashSet<Type> configTypes = CodeTypes.Instance.GetTypes(typeof (ConfigAttribute)); foreach (Type configType in configTypes) { string configFilePath; if (startConfigs.Contains(configType.Name)) { configFilePath = $"../Config/Excel/s/{Options.Instance.StartConfig}/{configType.Name}.bytes"; } else { configFilePath = $"../Config/Excel/s/{configType.Name}.bytes"; } output[configType] = File.ReadAllBytes(configFilePath); } await ETTask.CompletedTask; return output; } } [Invoke] public class GetOneConfigBytes: AInvokeHandler<ConfigLoader.GetOneConfigBytes, byte[]> { public override byte[] Handle(ConfigLoader.GetOneConfigBytes args) { byte[] configBytes = File.ReadAllBytes($"../Config/Excel/s/{args.ConfigName}.bytes"); return configBytes; } } }
ET/DotNet/Loader/ConfigLoaderInvoker.cs/0
{ "file_path": "ET/DotNet/Loader/ConfigLoaderInvoker.cs", "repo_id": "ET", "token_count": 832 }
90
using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace ET.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class ClientClassInServerAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ClientClassInServerAnalyzerRule.Rule); public override void Initialize(AnalysisContext context) { context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); //context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.UsingDirective); } private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { if (!AnalyzerHelper.IsAssemblyNeedAnalyze(context.Compilation.AssemblyName, AnalyzeAssembly.ServerModelHotfix)) { return; } var usingDirective = (UsingDirectiveSyntax)context.Node; var namespaceName = usingDirective.Name.ToString(); if (namespaceName.StartsWith(Definition.ETClientNameSpace) && !context.Node.SyntaxTree.FilePath.Contains(Definition.ClientDirInServer)) { var diagnostic = Diagnostic.Create(ClientClassInServerAnalyzerRule.Rule, usingDirective.GetLocation()); context.ReportDiagnostic(diagnostic); } } } }
ET/Share/Analyzer/Analyzer/ClientClassInServerAnalyzer.cs/0
{ "file_path": "ET/Share/Analyzer/Analyzer/ClientClassInServerAnalyzer.cs", "repo_id": "ET", "token_count": 615 }
91
using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace ET.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class UniqueIdAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>ImmutableArray.Create(UniqueIdRangeAnaluzerRule.Rule,UniqueIdDuplicateAnalyzerRule.Rule); public override void Initialize(AnalysisContext context) { if (!AnalyzerGlobalSetting.EnableAnalyzer) { return; } context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterSymbolAction(this.Analyzer, SymbolKind.NamedType); } private void Analyzer(SymbolAnalysisContext context) { if (!AnalyzerHelper.IsAssemblyNeedAnalyze(context.Compilation.AssemblyName, AnalyzeAssembly.All)) { return; } if (!(context.Symbol is INamedTypeSymbol namedTypeSymbol)) { return; } // 筛选出含有UniqueId标签的类 var attr = namedTypeSymbol.GetFirstAttribute(Definition.UniqueIdAttribute); if (attr==null) { return; } // 获取id 最小值最大值 var minIdValue = attr.ConstructorArguments[0].Value; var maxIdValue = attr.ConstructorArguments[1].Value; if (minIdValue==null || maxIdValue==null) { return; } int minId = (int)minIdValue; int maxId = (int)maxIdValue; HashSet<int> IdSet = new HashSet<int>(); foreach (var member in namedTypeSymbol.GetMembers()) { if (member is IFieldSymbol { IsConst: true, ConstantValue: int id } fieldSymbol) { if (id<minId || id>maxId) { ReportDiagnostic(fieldSymbol,id, UniqueIdRangeAnaluzerRule.Rule); }else if (IdSet.Contains(id)) { ReportDiagnostic(fieldSymbol,id,UniqueIdDuplicateAnalyzerRule.Rule); } else { IdSet.Add(id); } } } void ReportDiagnostic(IFieldSymbol fieldSymbol, int idValue, DiagnosticDescriptor rule) { ET.Analyzer.ClientClassInServerAnalyzer analyzer = new ClientClassInServerAnalyzer(); foreach (var syntaxReference in fieldSymbol.DeclaringSyntaxReferences) { var syntax = syntaxReference.GetSyntax(); Diagnostic diagnostic = Diagnostic.Create(rule, syntax.GetLocation(),namedTypeSymbol.Name,fieldSymbol.Name,idValue.ToString()); context.ReportDiagnostic(diagnostic); } } } } }
ET/Share/Analyzer/Analyzer/UniqueIdAnalyzer.cs/0
{ "file_path": "ET/Share/Analyzer/Analyzer/UniqueIdAnalyzer.cs", "repo_id": "ET", "token_count": 1668 }
92
#include "InvokeHelper.h" #include "DetourNavMesh.h" #include "DetourNavMeshQuery.h" #include <cstring> #include <unordered_map> #include "DetourCommon.h" static const int NAVMESHSET_MAGIC = 'M' << 24 | 'S' << 16 | 'E' << 8 | 'T'; //'MSET'; static const int NAVMESHSET_VERSION = 1; struct NavMeshSetHeader { int magic; int version; int numTiles; dtNavMeshParams params; }; struct NavMeshTileHeader { dtTileRef tileRef; int dataSize; }; int32_t InitNav(const char* buffer, int32_t n, dtNavMesh*& navMesh) { int index = 0; // Read header. NavMeshSetHeader header; int count = sizeof(NavMeshSetHeader); if (index + count > n) { return -1; } memcpy(&header, buffer + index, count); index += count; if (header.magic != NAVMESHSET_MAGIC) { return -2; } if (header.version != NAVMESHSET_VERSION) { return -3; } dtNavMesh* mesh = dtAllocNavMesh(); if (!mesh) { return -4; } dtStatus status = mesh->init(&header.params); if (dtStatusFailed(status)) { return -5; } // Read tiles. for (int i = 0; i < header.numTiles; ++i) { NavMeshTileHeader tileHeader; count = sizeof(NavMeshTileHeader); if (index + count > n) { return -6; } memcpy(&tileHeader, buffer + index, count); index += count; if (!tileHeader.tileRef || !tileHeader.dataSize) break; unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM); if (!data) break; memset(data, 0, tileHeader.dataSize); count = tileHeader.dataSize; if (index + count > n) { return -7; } memcpy(data, buffer + index, count); index += count; mesh->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0); } navMesh = mesh; return 0; } static const int MAX_POLYS = 256; static const int MAX_SMOOTH = 2048; class NavMeshContex { public: dtNavMesh* navMesh; dtNavMeshQuery* navQuery; NavMeshContex() { } int32_t Init(const char* buffer, int32_t n) { int32_t ret = InitNav(buffer, n, navMesh); std::string s; if (ret != 0) { return -1; } navQuery = new dtNavMeshQuery(); navQuery->init(navMesh, 2048); return 0; } ~NavMeshContex() { if (navQuery != nullptr) { dtFreeNavMeshQuery(navQuery); } if (navMesh != nullptr) { dtFreeNavMesh(navMesh); } } }; NavMeshContex* New(const char* buffer, int32_t n) { NavMeshContex* navMeshContex = new NavMeshContex(); int32_t ret = navMeshContex->Init(buffer, n); if (ret != 0) { delete navMeshContex; return nullptr; } return navMeshContex; } NavMeshContex* RecastLoad(const char* buffer, int32_t n) { return New(buffer, n); } void RecastClear(NavMeshContex* navMeshContex) { delete navMeshContex; } int32_t RecastFind(NavMeshContex* navMeshContex, float* extents, float* startPos, float* endPos, float* straightPath) { //FILE* fp = fopen("./test.log", "wb"); if (navMeshContex == nullptr) { return -1; } if (startPos == nullptr) { return -2; } if (endPos == nullptr) { return -3; } if (straightPath == nullptr) { return -4; } if (extents == nullptr) { return -5; } //char ss[200]; //int nn = sprintf(ss, "startPos,%f,%f,%f\n", startPos[0], startPos[1], startPos[2]); //fwrite(ss, nn, 1, fp); //fflush(fp); dtPolyRef startRef = 0; dtPolyRef endRef = 0; float startNearestPt[3]; float endNearestPt[3]; dtQueryFilter filter; filter.setIncludeFlags(0xffff); filter.setExcludeFlags(0); navMeshContex->navQuery->findNearestPoly(startPos, extents, &filter, &startRef, startNearestPt); navMeshContex->navQuery->findNearestPoly(endPos, extents, &filter, &endRef, endNearestPt); dtPolyRef polys[MAX_POLYS]; int npolys; unsigned char straightPathFlags[MAX_POLYS]; dtPolyRef straightPathPolys[MAX_POLYS]; int nstraightPath = 0; navMeshContex->navQuery->findPath(startRef, endRef, startNearestPt, endNearestPt, &filter, polys, &npolys, MAX_POLYS); if (npolys) { float epos1[3]; dtVcopy(epos1, endNearestPt); if (polys[npolys - 1] != endRef) { navMeshContex->navQuery->closestPointOnPoly(polys[npolys - 1], endNearestPt, epos1, 0); } navMeshContex->navQuery->findStraightPath(startNearestPt, endNearestPt, polys, npolys, straightPath, straightPathFlags, straightPathPolys, &nstraightPath, MAX_POLYS, DT_STRAIGHTPATH_ALL_CROSSINGS); } return nstraightPath; } int32_t RecastFindNearestPoint(NavMeshContex* navMeshContex, float* extents, float* startPos, float* nearestPos) { if (navMeshContex == nullptr) { return -1; } if (startPos == nullptr) { return -2; } if (nearestPos == nullptr) { return -3; } if (extents == nullptr) { return -5; } dtPolyRef startRef = 0; dtQueryFilter filter; filter.setIncludeFlags(0xffff); filter.setExcludeFlags(0); navMeshContex->navQuery->findNearestPoly(startPos, extents, &filter, &startRef, nearestPos); return startRef; } static float frand() { // return ((float)(rand() & 0xffff)/(float)0xffff); return (float)rand() / (float)RAND_MAX; } int32_t RecastFindRandomPoint(NavMeshContex* navMeshContex, float* pos) { if (navMeshContex == nullptr) { return -1; } if (pos == nullptr) { return -2; } dtQueryFilter filter; filter.setIncludeFlags(0xffff); filter.setExcludeFlags(0); dtPolyRef startRef = 0; return navMeshContex->navQuery->findRandomPoint(&filter, frand, &startRef, pos); } int32_t RecastFindRandomPointAroundCircle(NavMeshContex* navMeshContex, float* extents, const float* centerPos, const float maxRadius, float* pos) { if (navMeshContex == nullptr) { return -1; } if (pos == nullptr) { return -2; } dtQueryFilter filter; filter.setIncludeFlags(0xffff); filter.setExcludeFlags(0); dtPolyRef startRef = 0; dtPolyRef randomRef = 0; float startNearestPt[3]; navMeshContex->navQuery->findNearestPoly(centerPos, extents, &filter, &startRef, startNearestPt); return navMeshContex->navQuery->findRandomPointAroundCircle(startRef, centerPos, maxRadius, &filter, frand, &randomRef, pos); }
ET/Share/Libs/RecastDll/Source/InvokeHelper.cpp/0
{ "file_path": "ET/Share/Libs/RecastDll/Source/InvokeHelper.cpp", "repo_id": "ET", "token_count": 2473 }
93
using System; using System.Collections.Generic; namespace ET.Generator { public class AttributeTemplate { private Dictionary<string, string> templates = new Dictionary<string, string>(); public AttributeTemplate() { this.templates.Add("EntitySystem", $$""" $attribute$ public class $argsTypesUnderLine$_$methodName$System: $methodName$System<$argsTypes$> { protected override $returnType$ $methodName$($argsTypesVars$) { $return$$argsVars0$.$methodName$($argsVarsWithout0$); } } """); this.templates.Add("LSEntitySystem", $$""" $attribute$ public class $argsTypesUnderLine$_$methodName$System: $methodName$System<$argsTypes$> { protected override void $methodName$($argsTypesVars$) { $argsVars0$.$methodName$($argsVarsWithout0$); } } """); this.templates.Add("MessageHandler", $$""" $attribute$ public class $className$_$methodName$_Handler: MessageHandler<$argsTypesWithout0$> { protected override async ETTask Run($argsTypesVars$) { await $className$.$methodName$($argsVars$); } } """); this.templates.Add("ActorMessageHandler", $$""" $attribute$ public class $className$_$methodName$_Handler: ActorMessageHandler<$argsTypes$> { protected override async ETTask Run($argsTypesVars$) { await $className$.$methodName$($argsVars$); } } """); this.templates.Add("ActorMessageLocationHandler", $$""" $attribute$ public class $className$_$methodName$_Handler: ActorMessageLocationHandler<$argsTypes$> { protected override async ETTask Run($argsTypesVars$) { await $className$.$methodName$($argsVars$); } } """); this.templates.Add("Event", $$""" $attribute$ public class $argsTypes2$_$methodName$: AEvent<$argsTypes$> { protected override async ETTask Run($argsTypesVars$) { await $className$.$methodName$($argsVars$); } } """); } public string Get(string attributeType) { if (!this.templates.TryGetValue(attributeType, out string template)) { throw new Exception($"not config template: {attributeType}"); } if (template == null) { throw new Exception($"not config template: {attributeType}"); } return template; } public bool Contains(string attributeType) { return this.templates.ContainsKey(attributeType); } } }
ET/Share/Share.SourceGenerator/Generator/ETSystemGenerator/AttributeTemplate.cs/0
{ "file_path": "ET/Share/Share.SourceGenerator/Generator/ETSystemGenerator/AttributeTemplate.cs", "repo_id": "ET", "token_count": 2343 }
94
(add-to-list 'load-path "~/.emacs.d/el-get/el-get") (unless (require 'el-get nil t) (url-retrieve "https://raw.github.com/dimitri/el-get/master/el-get-install.el" (lambda (s) (goto-char (point-max)) (eval-print-last-sexp)))) (el-get 'sync) (setq make-backup-files nil) (global-set-key [f5] 'revert-buffer-no-confirm) (defun revert-buffer-no-confirm() "刷新buffer不需要yes no" (interactive) (revert-buffer t t))
ET/Tools/Config/.emacs/0
{ "file_path": "ET/Tools/Config/.emacs", "repo_id": "ET", "token_count": 206 }
95
fileFormatVersion: 2 guid: 1ba6771e5d8abc6449e944314b0c77df NativeFormatImporter: externalObjects: {} mainObjectFileID: 112000000 userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Bundles/Scenes/Map1/LightingData.asset.meta/0
{ "file_path": "ET/Unity/Assets/Bundles/Scenes/Map1/LightingData.asset.meta", "repo_id": "ET", "token_count": 75 }
96
fileFormatVersion: 2 guid: 5cb3b48a2d2a948d6b2564f64624607c PrefabImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Bundles/UI/LockStep/UILSLobby.prefab.meta/0
{ "file_path": "ET/Unity/Assets/Bundles/UI/LockStep/UILSLobby.prefab.meta", "repo_id": "ET", "token_count": 68 }
97
fileFormatVersion: 2 guid: c31b5b5deab839f48b5ec0f69fac286c DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Config/Excel/StartConfig/RouterTest/StartZoneConfig@s.xlsx.meta/0
{ "file_path": "ET/Unity/Assets/Config/Excel/StartConfig/RouterTest/StartZoneConfig@s.xlsx.meta", "repo_id": "ET", "token_count": 66 }
98
fileFormatVersion: 2 guid: edc63a02a9f5538479759737a0011a5b folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Plugins/MongoDB/runtimes/osx/native.meta/0
{ "file_path": "ET/Unity/Assets/Plugins/MongoDB/runtimes/osx/native.meta", "repo_id": "ET", "token_count": 70 }
99
fileFormatVersion: 2 guid: dfc15c633f0d98141920018f79a042a6 timeCreated: 18446744011573954816 ModelImporter: serializedVersion: 21 fileIDToRecycleName: 100000: Bip001 100002: Bip001 Footsteps 100004: Bip001 Head 100006: Bip001 L Calf 100008: Bip001 L Clavicle 100010: Bip001 L Finger0 100012: Bip001 L Finger01 100014: Bip001 L Finger02 100016: Bip001 L Finger1 100018: Bip001 L Finger11 100020: Bip001 L Finger12 100022: Bip001 L Foot 100024: Bip001 L Forearm 100026: Bip001 L Hand 100028: Bip001 L Thigh 100030: Bip001 L Toe0 100032: Bip001 L UpperArm 100034: Bip001 Neck 100036: Bip001 Pelvis 100038: Bip001 Prop1 100040: Bip001 R Calf 100042: Bip001 R Clavicle 100044: Bip001 R Finger0 100046: Bip001 R Finger01 100048: Bip001 R Finger02 100050: Bip001 R Finger1 100052: Bip001 R Finger11 100054: Bip001 R Finger12 100056: Bip001 R Foot 100058: Bip001 R Forearm 100060: Bip001 R Hand 100062: Bip001 R Thigh 100064: Bip001 R Toe0 100066: Bip001 R UpperArm 100068: Bip001 Spine 100070: Bip001 Spine1 100072: Bone001 100074: Object01 100076: Object02 100078: //RootNode 400000: Bip001 400002: Bip001 Footsteps 400004: Bip001 Head 400006: Bip001 L Calf 400008: Bip001 L Clavicle 400010: Bip001 L Finger0 400012: Bip001 L Finger01 400014: Bip001 L Finger02 400016: Bip001 L Finger1 400018: Bip001 L Finger11 400020: Bip001 L Finger12 400022: Bip001 L Foot 400024: Bip001 L Forearm 400026: Bip001 L Hand 400028: Bip001 L Thigh 400030: Bip001 L Toe0 400032: Bip001 L UpperArm 400034: Bip001 Neck 400036: Bip001 Pelvis 400038: Bip001 Prop1 400040: Bip001 R Calf 400042: Bip001 R Clavicle 400044: Bip001 R Finger0 400046: Bip001 R Finger01 400048: Bip001 R Finger02 400050: Bip001 R Finger1 400052: Bip001 R Finger11 400054: Bip001 R Finger12 400056: Bip001 R Foot 400058: Bip001 R Forearm 400060: Bip001 R Hand 400062: Bip001 R Thigh 400064: Bip001 R Toe0 400066: Bip001 R UpperArm 400068: Bip001 Spine 400070: Bip001 Spine1 400072: Bone001 400074: Object01 400076: Object02 400078: //RootNode 4300000: Object02 4300002: Object01 7400000: Take 001 9500000: //RootNode 13700000: Object01 13700002: Object02 materials: importMaterials: 1 materialName: 0 materialSearch: 1 animations: legacyGenerateAnimations: 4 bakeSimulation: 0 resampleCurves: 1 optimizeGameObjects: 0 motionNodeName: rigImportErrors: rigImportWarnings: animationImportErrors: animationImportWarnings: animationRetargetingWarnings: animationDoRetargetingWarnings: 0 animationCompression: 1 animationRotationError: 0.5 animationPositionError: 0.5 animationScaleError: 0.5 animationWrapMode: 0 extraExposedTransformPaths: [] extraUserProperties: [] clipAnimations: [] isReadable: 1 meshes: lODScreenPercentages: [] globalScale: 0.01 meshCompression: 0 addColliders: 0 importVisibility: 0 importBlendShapes: 1 importCameras: 0 importLights: 0 swapUVChannels: 0 generateSecondaryUV: 0 useFileUnits: 1 optimizeMeshForGPU: 1 keepQuads: 0 weldVertices: 1 secondaryUVAngleDistortion: 8 secondaryUVAreaDistortion: 15.000001 secondaryUVHardAngle: 88 secondaryUVPackMargin: 4 useFileScale: 0 tangentSpace: normalSmoothAngle: 60 normalImportMode: 0 tangentImportMode: 4 normalCalculationMode: 0 importAnimation: 1 copyAvatar: 0 humanDescription: serializedVersion: 2 human: [] skeleton: [] armTwist: 0.5 foreArmTwist: 0.5 upperLegTwist: 0.5 legTwist: 0.5 armStretch: 0.05 legStretch: 0.05 feetSpacing: 0 rootMotionBoneName: rootMotionBoneRotation: {x: 0, y: 0, z: 0, w: 1} hasTranslationDoF: 0 hasExtraRoot: 0 skeletonHasParents: 0 lastHumanDescriptionAvatarSource: {instanceID: 0} animationType: 2 humanoidOversampling: 1 additionalBone: 1 userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Res/Unit/Skeleton/Ani/Skeleton@Attack.FBX.meta/0
{ "file_path": "ET/Unity/Assets/Res/Unit/Skeleton/Ani/Skeleton@Attack.FBX.meta", "repo_id": "ET", "token_count": 1846 }
100
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!114 &11400000 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 0} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: de640fe3d0db1804a85f9fc8f5cadab6, type: 3} m_Name: UniversalRenderPipelineAsset_Renderer m_EditorClassIdentifier: debugShaders: debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7, type: 3} m_RendererFeatures: [] m_RendererFeatureMap: m_UseNativeRenderPass: 0 postProcessData: {fileID: 11400000, guid: 41439944d30ece34e96484bdb6645b55, type: 2} shaders: blitPS: {fileID: 4800000, guid: c17132b1f77d20942aa75f8429c0f8bc, type: 3} copyDepthPS: {fileID: 4800000, guid: d6dae50ee9e1bfa4db75f19f99355220, type: 3} screenSpaceShadowPS: {fileID: 4800000, guid: 0f854b35a0cf61a429bd5dcfea30eddd, type: 3} samplingPS: {fileID: 4800000, guid: 04c410c9937594faa893a11dceb85f7e, type: 3} stencilDeferredPS: {fileID: 4800000, guid: e9155b26e1bc55942a41e518703fe304, type: 3} fallbackErrorPS: {fileID: 4800000, guid: e6e9a19c3678ded42a3bc431ebef7dbd, type: 3} materialErrorPS: {fileID: 4800000, guid: 5fd9a8feb75a4b5894c241777f519d4e, type: 3} coreBlitPS: {fileID: 4800000, guid: 93446b5c5339d4f00b85c159e1159b7c, type: 3} coreBlitColorAndDepthPS: {fileID: 4800000, guid: d104b2fc1ca6445babb8e90b0758136b, type: 3} cameraMotionVector: {fileID: 4800000, guid: c56b7e0d4c7cb484e959caeeedae9bbf, type: 3} objectMotionVector: {fileID: 4800000, guid: 7b3ede40266cd49a395def176e1bc486, type: 3} m_AssetVersion: 1 m_OpaqueLayerMask: serializedVersion: 2 m_Bits: 4294967295 m_TransparentLayerMask: serializedVersion: 2 m_Bits: 4294967295 m_DefaultStencilState: overrideStencilState: 0 stencilReference: 0 stencilCompareFunction: 8 passOperation: 2 failOperation: 0 zFailOperation: 0 m_ShadowTransparentReceive: 1 m_RenderingMode: 0 m_DepthPrimingMode: 0 m_AccurateGbufferNormals: 0 m_ClusteredRendering: 0 m_TileSize: 32 m_IntermediateTextureMode: 0
ET/Unity/Assets/Res/UniversalRenderPipelineAsset_Renderer.asset/0
{ "file_path": "ET/Unity/Assets/Res/UniversalRenderPipelineAsset_Renderer.asset", "repo_id": "ET", "token_count": 1022 }
101
fileFormatVersion: 2 guid: 3e17786fd2fafce4f9d9fbdcdbf5b9fc MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Analyzer/ComponentOfAttribute.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Analyzer/ComponentOfAttribute.cs.meta", "repo_id": "ET", "token_count": 98 }
102
fileFormatVersion: 2 guid: 62584bd88ecb9ce439aeaaf2f76605f5 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Analyzer/UniqueIdAttribute.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Analyzer/UniqueIdAttribute.cs.meta", "repo_id": "ET", "token_count": 92 }
103
using System; using System.Collections.Generic; namespace ET { [Code] public class EntitySystemSingleton: Singleton<EntitySystemSingleton>, ISingletonAwake { public TypeSystems TypeSystems { get; private set; } public void Awake() { this.TypeSystems = new TypeSystems(InstanceQueueIndex.Max); foreach (Type type in CodeTypes.Instance.GetTypes(typeof (EntitySystemAttribute))) { SystemObject obj = (SystemObject)Activator.CreateInstance(type); if (obj is ISystemType iSystemType) { TypeSystems.OneTypeSystems oneTypeSystems = this.TypeSystems.GetOrCreateOneTypeSystems(iSystemType.Type()); oneTypeSystems.Map.Add(iSystemType.SystemType(), obj); int index = iSystemType.GetInstanceQueueIndex(); if (index > InstanceQueueIndex.None && index < InstanceQueueIndex.Max) { oneTypeSystems.QueueFlag[index] = true; } } } } public void Serialize(Entity component) { if (component is not ISerialize) { return; } List<SystemObject> iSerializeSystems = this.TypeSystems.GetSystems(component.GetType(), typeof (ISerializeSystem)); if (iSerializeSystems == null) { return; } foreach (ISerializeSystem serializeSystem in iSerializeSystems) { if (serializeSystem == null) { continue; } try { serializeSystem.Run(component); } catch (Exception e) { Log.Error(e); } } } public void Deserialize(Entity component) { if (component is not IDeserialize) { return; } List<SystemObject> iDeserializeSystems = this.TypeSystems.GetSystems(component.GetType(), typeof (IDeserializeSystem)); if (iDeserializeSystems == null) { return; } foreach (IDeserializeSystem deserializeSystem in iDeserializeSystems) { if (deserializeSystem == null) { continue; } try { deserializeSystem.Run(component); } catch (Exception e) { Log.Error(e); } } } // GetComponentSystem public void GetComponentSys(Entity entity, Type type) { List<SystemObject> iGetSystem = this.TypeSystems.GetSystems(entity.GetType(), typeof (IGetComponentSysSystem)); if (iGetSystem == null) { return; } foreach (IGetComponentSysSystem getSystem in iGetSystem) { if (getSystem == null) { continue; } try { getSystem.Run(entity, type); } catch (Exception e) { Log.Error(e); } } } public void Awake(Entity component) { List<SystemObject> iAwakeSystems = this.TypeSystems.GetSystems(component.GetType(), typeof (IAwakeSystem)); if (iAwakeSystems == null) { return; } foreach (IAwakeSystem aAwakeSystem in iAwakeSystems) { if (aAwakeSystem == null) { continue; } try { aAwakeSystem.Run(component); } catch (Exception e) { Log.Error(e); } } } public void Awake<P1>(Entity component, P1 p1) { if (component is not IAwake<P1>) { return; } List<SystemObject> iAwakeSystems = this.TypeSystems.GetSystems(component.GetType(), typeof (IAwakeSystem<P1>)); if (iAwakeSystems == null) { return; } foreach (IAwakeSystem<P1> aAwakeSystem in iAwakeSystems) { if (aAwakeSystem == null) { continue; } try { aAwakeSystem.Run(component, p1); } catch (Exception e) { Log.Error(e); } } } public void Awake<P1, P2>(Entity component, P1 p1, P2 p2) { if (component is not IAwake<P1, P2>) { return; } List<SystemObject> iAwakeSystems = this.TypeSystems.GetSystems(component.GetType(), typeof (IAwakeSystem<P1, P2>)); if (iAwakeSystems == null) { return; } foreach (IAwakeSystem<P1, P2> aAwakeSystem in iAwakeSystems) { if (aAwakeSystem == null) { continue; } try { aAwakeSystem.Run(component, p1, p2); } catch (Exception e) { Log.Error(e); } } } public void Awake<P1, P2, P3>(Entity component, P1 p1, P2 p2, P3 p3) { if (component is not IAwake<P1, P2, P3>) { return; } List<SystemObject> iAwakeSystems = this.TypeSystems.GetSystems(component.GetType(), typeof (IAwakeSystem<P1, P2, P3>)); if (iAwakeSystems == null) { return; } foreach (IAwakeSystem<P1, P2, P3> aAwakeSystem in iAwakeSystems) { if (aAwakeSystem == null) { continue; } try { aAwakeSystem.Run(component, p1, p2, p3); } catch (Exception e) { Log.Error(e); } } } public void Destroy(Entity component) { if (component is not IDestroy) { return; } List<SystemObject> iDestroySystems = this.TypeSystems.GetSystems(component.GetType(), typeof (IDestroySystem)); if (iDestroySystems == null) { return; } foreach (IDestroySystem iDestroySystem in iDestroySystems) { if (iDestroySystem == null) { continue; } try { iDestroySystem.Run(component); } catch (Exception e) { Log.Error(e); } } } } }
ET/Unity/Assets/Scripts/Core/Entity/EntitySystemSingleton.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/EntitySystemSingleton.cs", "repo_id": "ET", "token_count": 4726 }
104
namespace ET { public interface ISerializeToEntity { } }
ET/Unity/Assets/Scripts/Core/Entity/ISerializeToEntity.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/ISerializeToEntity.cs", "repo_id": "ET", "token_count": 25 }
105
fileFormatVersion: 2 guid: ebde9d58b893f434eaf40d782d2ef41a folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Fiber/Module/Navmesh.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Fiber/Module/Navmesh.meta", "repo_id": "ET", "token_count": 69 }
106
namespace ET { public static class ETCancelationTokenHelper { public static async ETTask CancelAfter(this ETCancellationToken self, Fiber fiber, long afterTimeCancel) { if (self.IsCancel()) { return; } await fiber.Root.GetComponent<TimerComponent>().WaitAsync(afterTimeCancel); if (self.IsCancel()) { return; } self.Cancel(); } } }
ET/Unity/Assets/Scripts/Core/Helper/ETCancelationTokenHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Helper/ETCancelationTokenHelper.cs", "repo_id": "ET", "token_count": 285 }
107
using System; using System.Text; namespace ET { public static class StringHashHelper { // bkdr hash public static long GetLongHashCode(this string str) { const uint seed = 1313; // 31 131 1313 13131 131313 etc.. ulong hash = 0; for (int i = 0; i < str.Length; ++i) { char c = str[i]; byte high = (byte)(c >> 8); byte low = (byte)(c & byte.MaxValue); hash = hash * seed + high; hash = hash * seed + low; } return (long)hash; } public static int Mode(this string strText, int mode) { if (mode <= 0) { throw new Exception($"string mode < 0: {strText} {mode}"); } return (int)((ulong)strText.GetLongHashCode() % (uint)mode); } } }
ET/Unity/Assets/Scripts/Core/Helper/StringHashHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Helper/StringHashHelper.cs", "repo_id": "ET", "token_count": 500 }
108
fileFormatVersion: 2 guid: 9c12a0ab646b02a42887ca4fd3b9992e MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/MultiDictionary.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/MultiDictionary.cs.meta", "repo_id": "ET", "token_count": 95 }
109
namespace ET { public interface ILocationMessage: ILocationRequest { } public interface ILocationRequest: IRequest { } public interface ILocationResponse: IResponse { } }
ET/Unity/Assets/Scripts/Core/Network/ILocationMessage.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/ILocationMessage.cs", "repo_id": "ET", "token_count": 77 }
110
namespace ET { public static class OpcodeRangeDefine { public const ushort OuterMinOpcode = 10001; public const ushort OuterMaxOpcode = 20000; // 20001-30000 内网pb public const ushort InnerMinOpcode = 20001; public const ushort InnerMaxOpcode = 40000; public const ushort MaxOpcode = 60000; } }
ET/Unity/Assets/Scripts/Core/Network/OpcodeRangeDefine.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/OpcodeRangeDefine.cs", "repo_id": "ET", "token_count": 166 }
111
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace ET { public class WChannel: AChannel { public HttpListenerWebSocketContext WebSocketContext { get; } private readonly WService Service; private readonly WebSocket webSocket; private readonly Queue<MemoryBuffer> queue = new(); private bool isSending; private bool isConnected; private CancellationTokenSource cancellationTokenSource = new(); public WChannel(long id, HttpListenerWebSocketContext webSocketContext, WService service) { this.Service = service; this.Id = id; this.ChannelType = ChannelType.Accept; this.WebSocketContext = webSocketContext; this.webSocket = webSocketContext.WebSocket; isConnected = true; this.Service.ThreadSynchronizationContext.Post(()=> { this.StartRecv().Coroutine(); this.StartSend().Coroutine(); }); } public WChannel(long id, WebSocket webSocket, IPEndPoint ipEndPoint, WService service) { this.Service = service; this.Id = id; this.ChannelType = ChannelType.Connect; this.webSocket = webSocket; isConnected = false; this.Service.ThreadSynchronizationContext.Post(()=>this.ConnectAsync($"ws://{ipEndPoint}").Coroutine()); } public override void Dispose() { if (this.IsDisposed) { return; } this.cancellationTokenSource.Cancel(); this.cancellationTokenSource.Dispose(); this.cancellationTokenSource = null; this.webSocket.Dispose(); } private async ETTask ConnectAsync(string url) { try { await ((ClientWebSocket) this.webSocket).ConnectAsync(new Uri(url), cancellationTokenSource.Token); isConnected = true; this.StartRecv().Coroutine(); this.StartSend().Coroutine(); } catch (Exception e) { Log.Error(e); this.OnError(ErrorCore.ERR_WebsocketConnectError); } } public void Send(MemoryBuffer memoryBuffer) { this.queue.Enqueue(memoryBuffer); if (this.isConnected) { this.StartSend().Coroutine(); } } private async ETTask StartSend() { if (this.IsDisposed) { return; } try { if (this.isSending) { return; } this.isSending = true; while (true) { if (this.queue.Count == 0) { this.isSending = false; return; } MemoryBuffer stream = this.queue.Dequeue(); try { await this.webSocket.SendAsync(stream.GetMemory(), WebSocketMessageType.Binary, true, cancellationTokenSource.Token); this.Service.Recycle(stream); if (this.IsDisposed) { return; } } catch (TaskCanceledException e) { Log.Warning(e.ToString()); } catch (Exception e) { Log.Error(e); this.OnError(ErrorCore.ERR_WebsocketSendError); return; } } } catch (Exception e) { Log.Error(e); } } private readonly byte[] cache = new byte[ushort.MaxValue]; public async ETTask StartRecv() { if (this.IsDisposed) { return; } try { while (true) { ValueWebSocketReceiveResult receiveResult; int receiveCount = 0; do { receiveResult = await this.webSocket.ReceiveAsync( new Memory<byte>(cache, receiveCount, this.cache.Length - receiveCount), cancellationTokenSource.Token); if (this.IsDisposed) { return; } receiveCount += receiveResult.Count; } while (!receiveResult.EndOfMessage); if (receiveResult.MessageType == WebSocketMessageType.Close) { this.OnError(ErrorCore.ERR_WebsocketPeerReset); return; } if (receiveResult.Count > ushort.MaxValue) { await this.webSocket.CloseAsync(WebSocketCloseStatus.MessageTooBig, $"message too big: {receiveCount}", cancellationTokenSource.Token); this.OnError(ErrorCore.ERR_WebsocketMessageTooBig); return; } MemoryBuffer memoryBuffer = this.Service.Fetch(receiveCount); memoryBuffer.SetLength(receiveCount); memoryBuffer.Seek(0, SeekOrigin.Begin); Array.Copy(this.cache, 0, memoryBuffer.GetBuffer(), 0, receiveCount); this.OnRead(memoryBuffer); } } catch (Exception e) { Log.Error(e); this.OnError(ErrorCore.ERR_WebsocketRecvError); } } private void OnRead(MemoryBuffer memoryStream) { try { this.Service.ReadCallback(this.Id, memoryStream); } catch (Exception e) { Log.Error(e); this.OnError(ErrorCore.ERR_PacketParserError); } } private void OnError(int error) { Log.Info($"WChannel error: {error} {this.RemoteAddress}"); long channelId = this.Id; this.Service.Remove(channelId); this.Service.ErrorCallback(channelId, error); } } }
ET/Unity/Assets/Scripts/Core/Network/WChannel.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/WChannel.cs", "repo_id": "ET", "token_count": 4068 }
112
using System.Collections.Generic; namespace ET { public class UnOrderMultiMapSet<T, K>: Dictionary<T, HashSet<K>> { // 重用HashSet public new HashSet<K> this[T t] { get { HashSet<K> set; if (!this.TryGetValue(t, out set)) { set = new HashSet<K>(); } return set; } } public Dictionary<T, HashSet<K>> GetDictionary() { return this; } public void Add(T t, K k) { HashSet<K> set; this.TryGetValue(t, out set); if (set == null) { set = new HashSet<K>(); base[t] = set; } set.Add(k); } public bool Remove(T t, K k) { HashSet<K> set; this.TryGetValue(t, out set); if (set == null) { return false; } if (!set.Remove(k)) { return false; } if (set.Count == 0) { this.Remove(t); } return true; } public bool Contains(T t, K k) { HashSet<K> set; this.TryGetValue(t, out set); if (set == null) { return false; } return set.Contains(k); } public new int Count { get { int count = 0; foreach (KeyValuePair<T,HashSet<K>> kv in this) { count += kv.Value.Count; } return count; } } } }
ET/Unity/Assets/Scripts/Core/UnOrderMultiMapSet.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/UnOrderMultiMapSet.cs", "repo_id": "ET", "token_count": 1201 }
113
using System; using System.Collections.Generic; namespace ET { public class TypeSystems { public class OneTypeSystems { public OneTypeSystems(int count) { this.QueueFlag = new bool[count]; } public readonly UnOrderMultiMap<Type, SystemObject> Map = new(); // 这里不用hash,数量比较少,直接for循环速度更快 public readonly bool[] QueueFlag; } private readonly int count; public TypeSystems(int count) { this.count = count; } private readonly Dictionary<Type, OneTypeSystems> typeSystemsMap = new(); public OneTypeSystems GetOrCreateOneTypeSystems(Type type) { OneTypeSystems systems = null; this.typeSystemsMap.TryGetValue(type, out systems); if (systems != null) { return systems; } systems = new OneTypeSystems(this.count); this.typeSystemsMap.Add(type, systems); return systems; } public OneTypeSystems GetOneTypeSystems(Type type) { OneTypeSystems systems = null; this.typeSystemsMap.TryGetValue(type, out systems); return systems; } public List<SystemObject> GetSystems(Type type, Type systemType) { OneTypeSystems oneTypeSystems = null; if (!this.typeSystemsMap.TryGetValue(type, out oneTypeSystems)) { return null; } if (!oneTypeSystems.Map.TryGetValue(systemType, out List<SystemObject> systems)) { return null; } return systems; } } }
ET/Unity/Assets/Scripts/Core/World/Module/EventSystem/TypeSystems.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/EventSystem/TypeSystems.cs", "repo_id": "ET", "token_count": 931 }
114
using System; using System.Runtime.InteropServices; using System.Threading; namespace ET { [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct IdStruct { public short Process; // 14bit public uint Time; // 30bit public uint Value; // 20bit public long ToLong() { ulong result = 0; result |= (ushort) this.Process; result <<= 30; result |= this.Time; result <<= 20; result |= this.Value; return (long) result; } public IdStruct(uint time, short process, uint value) { this.Process = process; this.Time = time; this.Value = value; } public IdStruct(long id) { ulong result = (ulong) id; this.Value = (uint) (result & IdGenerater.Mask20bit); result >>= 20; this.Time = (uint) result & IdGenerater.Mask30bit; result >>= 30; this.Process = (short) (result & IdGenerater.Mask14bit); } public override string ToString() { return $"process: {this.Process}, time: {this.Time}, value: {this.Value}"; } } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct InstanceIdStruct { public uint Time; // 32bit public uint Value; // 32bit public long ToLong() { ulong result = 0; result |= this.Time; result <<= 32; result |= this.Value; return (long) result; } public InstanceIdStruct(uint time, uint value) { this.Time = time; this.Value = value; } public InstanceIdStruct(long id) { ulong result = (ulong) id; this.Value = (uint)(result & uint.MaxValue); result >>= 32; this.Time = (uint)(result & uint.MaxValue); } public override string ToString() { return $"time: {this.Time}, value: {this.Value}"; } } public class IdGenerater: Singleton<IdGenerater>, ISingletonAwake { public const int MaxZone = 1024; public const int Mask14bit = 0x3fff; public const int Mask30bit = 0x3fffffff; public const int Mask20bit = 0xfffff; private long epoch2022; private int value; private int instanceIdValue; public void Awake() { long epoch1970tick = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000; this.epoch2022 = new DateTime(2022, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000 - epoch1970tick; } private uint TimeSince2022() { uint a = (uint)((TimeInfo.Instance.FrameTime - this.epoch2022) / 1000); return a; } public long GenerateId() { uint time = TimeSince2022(); int v = 0; // 这里必须加锁 lock (this) { if (++this.value > Mask20bit - 1) { this.value = 0; } v = this.value; } IdStruct idStruct = new(time, (short)Options.Instance.Process, (uint)v); return idStruct.ToLong(); } public long GenerateInstanceId() { uint time = this.TimeSince2022(); uint v = (uint)Interlocked.Add(ref this.instanceIdValue, 1); InstanceIdStruct instanceIdStruct = new(time, v); return instanceIdStruct.ToLong(); } } }
ET/Unity/Assets/Scripts/Core/World/Module/IdGenerater/IdGenerater.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/IdGenerater/IdGenerater.cs", "repo_id": "ET", "token_count": 1947 }
115
fileFormatVersion: 2 guid: 9ffc58538c5a27044afacc18aa82e5b4 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Editor/AssetPostProcessor/OnGenerateCSProjectProcessor.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/AssetPostProcessor/OnGenerateCSProjectProcessor.cs.meta", "repo_id": "ET", "token_count": 94 }
116
using System; using UnityEditor; using UnityEngine; namespace ET { [TypeDrawer] public class BoundsTypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type == typeof (Bounds); } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { return EditorGUILayout.BoundsField(memberName, (Bounds) value); } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/BoundsTypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/BoundsTypeDrawer.cs", "repo_id": "ET", "token_count": 193 }
117
using System; using Unity.Mathematics; using UnityEditor; using UnityEngine; namespace ET { [TypeDrawer] public class Float2TypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type == typeof (float2); } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { Vector2 v = (float2)value; return new float2(EditorGUILayout.Vector2Field(memberName, v)); } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/Float2TypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/Float2TypeDrawer.cs", "repo_id": "ET", "token_count": 223 }
118
using System; using UnityEditor; using UnityEngine; namespace ET { [TypeDrawer] public class RectTypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type == typeof (Rect); } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { return EditorGUILayout.RectField(memberName, (Rect) value); } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/RectTypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/RectTypeDrawer.cs", "repo_id": "ET", "token_count": 189 }
119
fileFormatVersion: 2 guid: 4ee994acc7f02fb42b82587aa7dc42bc MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Editor/GlobalConfigEditor/GlobalConfigEditor.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/GlobalConfigEditor/GlobalConfigEditor.cs.meta", "repo_id": "ET", "token_count": 92 }
120
namespace ET { public static class ToolsEditor { public static void ExcelExporter() { #if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX const string tools = "./Tool"; #else const string tools = ".\\Tool.exe"; #endif ShellHelper.Run($"{tools} --AppType=ExcelExporter --Console=1", "../Bin/"); } public static void Proto2CS() { #if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX const string tools = "./Tool"; #else const string tools = ".\\Tool.exe"; #endif ShellHelper.Run($"{tools} --AppType=Proto2CS --Console=1", "../Bin/"); } } }
ET/Unity/Assets/Scripts/Editor/ToolEditor/ToolsEditor.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ToolEditor/ToolsEditor.cs", "repo_id": "ET", "token_count": 320 }
121
fileFormatVersion: 2 guid: aa372ebdea28c6347a1d74e60f335934 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/ClientSenderComponentSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/ClientSenderComponentSystem.cs.meta", "repo_id": "ET", "token_count": 95 }
122
namespace ET.Client { [MessageHandler(SceneType.Demo)] public class M2C_StartSceneChangeHandler : MessageHandler<Scene, M2C_StartSceneChange> { protected override async ETTask Run(Scene root, M2C_StartSceneChange message) { await SceneChangeHelper.SceneChangeTo(root, message.SceneName, message.SceneInstanceId); } } }
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Scene/M2C_StartSceneChangeHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Scene/M2C_StartSceneChangeHandler.cs", "repo_id": "ET", "token_count": 114 }
123
namespace ET.Client { [MessageHandler(SceneType.NetClient)] public class A2NetClient_MessageHandler: MessageHandler<Scene, A2NetClient_Message> { protected override async ETTask Run(Scene root, A2NetClient_Message message) { root.GetComponent<SessionComponent>().Session.Send(message.MessageObject); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/A2NetClient_MessageHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/A2NetClient_MessageHandler.cs", "repo_id": "ET", "token_count": 155 }
124
using System; using System.IO; using System.Net; using System.Net.Sockets; namespace ET.Client { [EntitySystemOf(typeof(RouterAddressComponent))] [FriendOf(typeof(RouterAddressComponent))] public static partial class RouterAddressComponentSystem { [EntitySystem] private static void Awake(this RouterAddressComponent self, string address, int port) { self.RouterManagerHost = address; self.RouterManagerPort = port; } public static async ETTask Init(this RouterAddressComponent self) { self.RouterManagerIPAddress = NetworkHelper.GetHostAddress(self.RouterManagerHost); await self.GetAllRouter(); } private static async ETTask GetAllRouter(this RouterAddressComponent self) { string url = $"http://{self.RouterManagerHost}:{self.RouterManagerPort}/get_router?v={RandomGenerator.RandUInt32()}"; Log.Debug($"start get router info: {url}"); string routerInfo = await HttpClientHelper.Get(url); Log.Debug($"recv router info: {routerInfo}"); HttpGetRouterResponse httpGetRouterResponse = MongoHelper.FromJson<HttpGetRouterResponse>(routerInfo); self.Info = httpGetRouterResponse; Log.Debug($"start get router info finish: {MongoHelper.ToJson(httpGetRouterResponse)}"); // 打乱顺序 RandomGenerator.BreakRank(self.Info.Routers); self.WaitTenMinGetAllRouter().Coroutine(); } // 等10分钟再获取一次 public static async ETTask WaitTenMinGetAllRouter(this RouterAddressComponent self) { await self.Root().GetComponent<TimerComponent>().WaitAsync(5 * 60 * 1000); if (self.IsDisposed) { return; } await self.GetAllRouter(); } public static IPEndPoint GetAddress(this RouterAddressComponent self) { if (self.Info.Routers.Count == 0) { return null; } string address = self.Info.Routers[self.RouterIndex++ % self.Info.Routers.Count]; Log.Info($"get router address: {self.RouterIndex - 1} {address}"); string[] ss = address.Split(':'); IPAddress ipAddress = IPAddress.Parse(ss[0]); if (self.RouterManagerIPAddress.AddressFamily == AddressFamily.InterNetworkV6) { ipAddress = ipAddress.MapToIPv6(); } return new IPEndPoint(ipAddress, int.Parse(ss[1])); } public static IPEndPoint GetRealmAddress(this RouterAddressComponent self, string account) { int v = account.Mode(self.Info.Realms.Count); string address = self.Info.Realms[v]; string[] ss = address.Split(':'); IPAddress ipAddress = IPAddress.Parse(ss[0]); //if (self.IPAddress.AddressFamily == AddressFamily.InterNetworkV6) //{ // ipAddress = ipAddress.MapToIPv6(); //} return new IPEndPoint(ipAddress, int.Parse(ss[1])); } } }
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Router/RouterAddressComponentSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Router/RouterAddressComponentSystem.cs", "repo_id": "ET", "token_count": 1505 }
125
fileFormatVersion: 2 guid: 46f47e16ad6bc417391e3cdee1b5a851 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/LockStep/LSClientUpdaterSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/LockStep/LSClientUpdaterSystem.cs.meta", "repo_id": "ET", "token_count": 95 }
126
fileFormatVersion: 2 guid: b9b509edbaf46e64f97bb6c4b55ccc7c MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/Module/Message/ClientSessionErrorComponentSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Module/Message/ClientSessionErrorComponentSystem.cs.meta", "repo_id": "ET", "token_count": 97 }
127
using System; namespace ET.Server { [MessageSessionHandler(SceneType.Gate)] public class C2G_PingHandler : MessageSessionHandler<C2G_Ping, G2C_Ping> { protected override async ETTask Run(Session session, C2G_Ping request, G2C_Ping response) { using C2G_Ping _ = request; // 这里用完调用Dispose可以回收到池,不调用的话GC会回收 response.Time = TimeInfo.Instance.ClientNow(); await ETTask.CompletedTask; //response会在函数返回发送完消息回收到池 } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/C2G_PingHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/C2G_PingHandler.cs", "repo_id": "ET", "token_count": 238 }
128
using System; namespace ET.Server { [MessageHandler(SceneType.Gate)] public class R2G_GetLoginKeyHandler : MessageHandler<Scene, R2G_GetLoginKey, G2R_GetLoginKey> { protected override async ETTask Run(Scene scene, R2G_GetLoginKey request, G2R_GetLoginKey response) { long key = RandomGenerator.RandInt64(); scene.GetComponent<GateSessionKeyComponent>().Add(key, request.Account); response.Key = key; response.GateId = scene.Id; await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/R2G_GetLoginKeyHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/R2G_GetLoginKeyHandler.cs", "repo_id": "ET", "token_count": 180 }
129
fileFormatVersion: 2 guid: 3aa2b5e0132eb714ab53a38e8c6f7e10 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Move.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Move.meta", "repo_id": "ET", "token_count": 72 }
130
fileFormatVersion: 2 guid: ec1d8ad3c64cebd42950e0400567e918 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Robot.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Robot.meta", "repo_id": "ET", "token_count": 69 }
131
using System.Collections; using System.Diagnostics; namespace ET.Server { [EntitySystemOf(typeof(WatcherComponent))] [FriendOf(typeof(WatcherComponent))] public static partial class WatcherComponentSystem { [EntitySystem] public static void Awake(this WatcherComponent self) { string[] localIP = NetworkHelper.GetAddressIPs(); var processConfigs = StartProcessConfigCategory.Instance.GetAll(); foreach (StartProcessConfig startProcessConfig in processConfigs.Values) { if (!WatcherHelper.IsThisMachine(startProcessConfig.InnerIP, localIP)) { continue; } System.Diagnostics.Process process = WatcherHelper.StartProcess(startProcessConfig.Id); self.Processes.Add(startProcessConfig.Id, process); } } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Watcher/WatcherComponentSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Watcher/WatcherComponentSystem.cs", "repo_id": "ET", "token_count": 398 }
132
fileFormatVersion: 2 guid: 40bebd1c111464ddb96d36e4d0966070 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map/FrameMessageHandler.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map/FrameMessageHandler.cs.meta", "repo_id": "ET", "token_count": 94 }
133
fileFormatVersion: 2 guid: 8f87c1aa12fde40b5afda6ea778cfdf4 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Room/C2Room_CheckHashHandler.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Room/C2Room_CheckHashHandler.cs.meta", "repo_id": "ET", "token_count": 95 }
134
using System; namespace ET.Server { [EntitySystemOf(typeof(MessageLocationSender))] [FriendOf(typeof(MessageLocationSender))] public static partial class MessageLocationSenderSystem { [EntitySystem] private static void Awake(this MessageLocationSender self) { self.LastSendOrRecvTime = TimeInfo.Instance.ServerNow(); self.ActorId = default; } [EntitySystem] private static void Destroy(this MessageLocationSender self) { Log.Debug($"actor location remove: {self.Id}"); self.LastSendOrRecvTime = 0; self.ActorId = default; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/MessageLocationSenderSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/MessageLocationSenderSystem.cs", "repo_id": "ET", "token_count": 299 }
135
fileFormatVersion: 2 guid: a6633f9840ed3f84c84cd67e5f4912b6 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Module/RobotCase.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/RobotCase.meta", "repo_id": "ET", "token_count": 71 }
136
namespace ET { /// <summary> /// 客户端监视hp数值变化,改变血条值 /// </summary> [NumericWatcher(SceneType.Current, NumericType.Hp)] public class NumericWatcher_Hp_ShowUI : INumericWatcher { public void Run(Unit unit, NumbericChange args) { } } }
ET/Unity/Assets/Scripts/Hotfix/Share/Module/Numeric/NumericWatcher_Hp_ShowUI.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Numeric/NumericWatcher_Hp_ShowUI.cs", "repo_id": "ET", "token_count": 131 }
137
using System; using UnityEngine.SceneManagement; namespace ET.Client { [Event(SceneType.Demo)] public class SceneChangeStart_AddComponent: AEvent<Scene, SceneChangeStart> { protected override async ETTask Run(Scene root, SceneChangeStart args) { try { Scene currentScene = root.CurrentScene(); ResourcesLoaderComponent resourcesLoaderComponent = currentScene.GetComponent<ResourcesLoaderComponent>(); // 加载场景资源 await resourcesLoaderComponent.LoadSceneAsync($"Assets/Bundles/Scenes/{currentScene.Name}.unity", LoadSceneMode.Single); // 切换到map场景 //await SceneManager.LoadSceneAsync(currentScene.Name); currentScene.AddComponent<OperaComponent>(); } catch (Exception e) { Log.Error(e); } } } }
ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Scene/SceneChangeStart_AddComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Scene/SceneChangeStart_AddComponent.cs", "repo_id": "ET", "token_count": 457 }
138
fileFormatVersion: 2 guid: 7d084fb1752020643b7f57ef85ba8223 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILobby/UILobbyEvent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILobby/UILobbyEvent.cs.meta", "repo_id": "ET", "token_count": 92 }
139
fileFormatVersion: 2 guid: 1ac911ac3f20c49c6a05014a9a2ee9d8 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/LSSceneInitFinish_Finish.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/LSSceneInitFinish_Finish.cs.meta", "repo_id": "ET", "token_count": 97 }
140
fileFormatVersion: 2 guid: 10386ffef0f574a478ff5ea8a172f6ec folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSLogin.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSLogin.meta", "repo_id": "ET", "token_count": 68 }
141
using System; using UnityEngine; namespace ET.Client { public static class GameObjectHelper { public static T Get<T>(this GameObject gameObject, string key) where T : class { try { return gameObject.GetComponent<ReferenceCollector>().Get<T>(key); } catch (Exception e) { throw new Exception($"获取{gameObject.name}的ReferenceCollector key失败, key: {key}", e); } } } }
ET/Unity/Assets/Scripts/HotfixView/Client/Module/Resource/GameObjectHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Module/Resource/GameObjectHelper.cs", "repo_id": "ET", "token_count": 164 }
142
{ "name": "Unity.HotfixView", "rootNamespace": "ET", "references": [ "Unity.ThirdParty", "Unity.Core", "Unity.Mathematics", "Unity.Loader", "MemoryPack", "Unity.Model", "Unity.Hotfix", "Unity.ModelView", "YooAsset" ], "includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": true, "overrideReferences": false, "precompiledReferences": [], "autoReferenced": true, "defineConstraints": [ "UNITY_COMPILE || UNITY_EDITOR" ], "versionDefines": [], "noEngineReferences": false }
ET/Unity/Assets/Scripts/HotfixView/Unity.HotfixView.asmdef/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Unity.HotfixView.asmdef", "repo_id": "ET", "token_count": 293 }
143
using System; using UnityEngine; using UnityEngine.Networking; namespace ET { public static class CoroutineHelper { // 有了这个方法,就可以直接await Unity的AsyncOperation了 public static async ETTask GetAwaiter(this AsyncOperation asyncOperation) { ETTask task = ETTask.Create(true); asyncOperation.completed += _ => { task.SetResult(); }; await task; } public static async ETTask<string> HttpGet(string link) { try { UnityWebRequest req = UnityWebRequest.Get(link); await req.SendWebRequest(); return req.downloadHandler.text; } catch (Exception e) { throw new Exception($"http request fail: {link.Substring(0,link.IndexOf('?'))}\n{e}"); } } } }
ET/Unity/Assets/Scripts/Loader/Helper/CoroutineHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/Helper/CoroutineHelper.cs", "repo_id": "ET", "token_count": 452 }
144
fileFormatVersion: 2 guid: 0dc8cc2d1f4fd7149a0a1f13f8f8e54b folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Loader/Resource/StreamingAssetsHelper.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/Resource/StreamingAssetsHelper.meta", "repo_id": "ET", "token_count": 75 }
145
fileFormatVersion: 2 guid: 9cf32cd19c3004b4a8e0651fc3047743 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Client/Demo/AI/XunLuoPathComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/Demo/AI/XunLuoPathComponent.cs.meta", "repo_id": "ET", "token_count": 94 }
146