358 lines
16 KiB
C#
358 lines
16 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
|
||
[Serializable]
|
||
public class CarCatalogItem
|
||
{
|
||
public string carTitle = "Ibishu Covet 1.5";
|
||
public GameObject carPrefab;
|
||
public float idealPrice = 4500f;
|
||
public int minYear = 1992;
|
||
public int maxYear = 2005;
|
||
public string bodyType = "Хэтчбек";
|
||
}
|
||
|
||
public class CarListing
|
||
{
|
||
public int id;
|
||
public CarCatalogItem catalogItem;
|
||
public int seed;
|
||
public Color bodyColor;
|
||
public string bodyColorName;
|
||
public int year;
|
||
public int mileageKm;
|
||
public int price;
|
||
public DriveType driveType;
|
||
public string sellerName;
|
||
public float sellerRating;
|
||
public string sellerPhone;
|
||
public string sellerDescription;
|
||
public CarDefectsSummary defectsSummary;
|
||
public Sprite photo;
|
||
public bool isMeetingArranged;
|
||
public GameObject spawnedInstance;
|
||
public Vector3 spawnPosition;
|
||
public bool isSold;
|
||
}
|
||
|
||
public class CarMarketManager : MonoBehaviour
|
||
{
|
||
[Header("Каталог префабов машин для продажи")]
|
||
[SerializeField] private CarCatalogItem[] carCatalog;
|
||
|
||
[Header("Точки спавна машин для встречи на карте")]
|
||
[SerializeField] private Transform[] meetingSpawnPoints;
|
||
|
||
[Header("Настройки генерации объявлений")]
|
||
[SerializeField] private int listingsCount = 6;
|
||
[SerializeField] private Color[] possibleBodyColors = new Color[]
|
||
{
|
||
new Color(0.12f, 0.32f, 0.75f), // Синий
|
||
new Color(0.75f, 0.15f, 0.15f), // Красный
|
||
new Color(0.85f, 0.85f, 0.88f), // Белый / Серебро
|
||
new Color(0.18f, 0.20f, 0.22f), // Темно-серый
|
||
new Color(0.15f, 0.48f, 0.25f), // Темно-зеленый
|
||
new Color(0.85f, 0.65f, 0.12f) // Желтый / Золотистый
|
||
};
|
||
|
||
private readonly string[] colorNames = new string[]
|
||
{
|
||
"Синий металлик", "Красный рубин", "Серебристый металлик", "Мокрый асфальт", "Изумрудный перламутр", "Золотистый металлик"
|
||
};
|
||
|
||
private readonly string[] sellerNames = new string[]
|
||
{
|
||
"Алексей Смирнов", "Сергей (Частник)", "Михаил Ремонт", "Дмитрий В.", "Виктор Авто", "Артем Романов", "Владимир", "Елена (муж попросил)"
|
||
};
|
||
|
||
[Header("Настройки ракурса фотостудии")]
|
||
[SerializeField] private Vector3 cameraOffset = new Vector3(-2.6f, 1.35f, 3.4f);
|
||
[SerializeField] private Vector3 lookAtOffset = new Vector3(0f, 0.45f, 0f);
|
||
[SerializeField] private int photoWidth = 640;
|
||
[SerializeField] private int photoHeight = 360;
|
||
|
||
public readonly List<CarListing> Listings = new List<CarListing>();
|
||
public CarListing ActiveMeetingListing { get; private set; }
|
||
|
||
public event Action<CarListing> OnMeetingArranged;
|
||
public event Action OnMeetingCleared;
|
||
public event Action OnListingsUpdated;
|
||
|
||
public CarCatalogItem[] Catalog => carCatalog;
|
||
|
||
/// <summary>Настройка рынка из Editor-автонастройки.</summary>
|
||
public void Configure(CarCatalogItem[] catalog, Transform[] spawnPoints)
|
||
{
|
||
carCatalog = catalog;
|
||
meetingSpawnPoints = spawnPoints;
|
||
}
|
||
|
||
private GameObject photoStudioRoot;
|
||
private Camera photoCamera;
|
||
private RenderTexture photoRT;
|
||
private int lastUsedSpawnPointIndex = -1;
|
||
|
||
private void Start()
|
||
{
|
||
EnsureListingsGenerated();
|
||
}
|
||
|
||
public void EnsureListingsGenerated()
|
||
{
|
||
if (Listings.Count == 0)
|
||
{
|
||
SetupPhotoStudio();
|
||
GenerateListings();
|
||
}
|
||
}
|
||
|
||
private void SetupPhotoStudio()
|
||
{
|
||
if (photoStudioRoot != null) return;
|
||
|
||
// Создаем изолированную студию глубоко под картой
|
||
photoStudioRoot = new GameObject("Offscreen_CarPhotoStudio");
|
||
photoStudioRoot.transform.position = new Vector3(0f, -500f, 0f);
|
||
|
||
// Подиум/асфальт для приятного фона на фотографиях
|
||
GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
|
||
Destroy(floor.GetComponent<Collider>());
|
||
floor.transform.SetParent(photoStudioRoot.transform, false);
|
||
floor.transform.localScale = new Vector3(3f, 1f, 3f);
|
||
Renderer floorRend = floor.GetComponent<Renderer>();
|
||
Material floorMat = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard"));
|
||
floorMat.color = new Color(0.22f, 0.24f, 0.27f);
|
||
floorRend.sharedMaterial = floorMat;
|
||
|
||
// Освещение студии
|
||
GameObject lightObj = new GameObject("StudioLight");
|
||
lightObj.transform.SetParent(photoStudioRoot.transform, false);
|
||
lightObj.transform.localPosition = new Vector3(-3f, 5f, 4f);
|
||
lightObj.transform.localRotation = Quaternion.Euler(45f, 135f, 0f);
|
||
Light studioLight = lightObj.AddComponent<Light>();
|
||
studioLight.type = LightType.Directional;
|
||
studioLight.intensity = 1.4f;
|
||
|
||
// Камера для рендера фото объявления
|
||
GameObject camObj = new GameObject("StudioCamera");
|
||
camObj.transform.SetParent(photoStudioRoot.transform, false);
|
||
photoCamera = camObj.AddComponent<Camera>();
|
||
photoCamera.clearFlags = CameraClearFlags.SolidColor;
|
||
photoCamera.backgroundColor = new Color(0.48f, 0.60f, 0.74f);
|
||
photoCamera.fieldOfView = 40f;
|
||
photoCamera.enabled = false; // Выключена, рендерит только по команде Render()
|
||
|
||
photoRT = new RenderTexture(photoWidth, photoHeight, 24, RenderTextureFormat.ARGB32);
|
||
photoCamera.targetTexture = photoRT;
|
||
}
|
||
|
||
[ContextMenu("Обновить объявления")]
|
||
public void GenerateListings()
|
||
{
|
||
if (carCatalog == null || carCatalog.Length == 0)
|
||
{
|
||
Debug.LogWarning("[CarMarketManager] Добавьте хотя бы один префаб машины в Car Catalog!");
|
||
return;
|
||
}
|
||
|
||
if (photoStudioRoot == null) SetupPhotoStudio();
|
||
|
||
Listings.Clear();
|
||
|
||
for (int i = 0; i < listingsCount; i++)
|
||
{
|
||
CarCatalogItem item = carCatalog[UnityEngine.Random.Range(0, carCatalog.Length)];
|
||
if (item.carPrefab == null) continue;
|
||
|
||
int seed = UnityEngine.Random.Range(10000, 999999);
|
||
int colorIndex = (possibleBodyColors.Length > 0) ? UnityEngine.Random.Range(0, possibleBodyColors.Length) : 0;
|
||
Color color = (possibleBodyColors.Length > 0) ? possibleBodyColors[colorIndex] : Color.blue;
|
||
string colorName = (colorIndex < colorNames.Length) ? colorNames[colorIndex] : "Заводской окрас";
|
||
|
||
int year = UnityEngine.Random.Range(item.minYear, item.maxYear + 1);
|
||
int mileage = (2026 - year) * UnityEngine.Random.Range(9500, 18000);
|
||
|
||
// 1. Временно спавним машину в фотостудии для точного снимка
|
||
GameObject tempCar = Instantiate(item.carPrefab, photoStudioRoot.transform.position, Quaternion.identity);
|
||
|
||
// Отключаем гравитацию в фотобоксе, чтобы машина не падала во время кадра
|
||
Rigidbody rb = tempCar.GetComponent<Rigidbody>();
|
||
if (rb != null) rb.isKinematic = true;
|
||
|
||
CarController ctrl = tempCar.GetComponent<CarController>();
|
||
DriveType drive = ctrl != null ? ctrl.driveType : DriveType.FWD;
|
||
|
||
CarConditionGenerator gen = tempCar.GetComponent<CarConditionGenerator>();
|
||
if (gen == null) gen = tempCar.AddComponent<CarConditionGenerator>();
|
||
|
||
// Применяем состояние по Seed (точно такое же применится при выезде на встречу!)
|
||
gen.ApplyConditionBySeed(seed, color, true, out CarDefectsSummary defects);
|
||
|
||
// 2. Выставляем камеру фотостудии в 3/4 спереди и делаем снимок
|
||
photoCamera.transform.position = tempCar.transform.position + cameraOffset;
|
||
photoCamera.transform.LookAt(tempCar.transform.position + lookAtOffset);
|
||
Sprite capturedPhoto = CaptureStudioPhoto();
|
||
|
||
// 3. Сразу удаляем временную машину, чтобы не нагружать сцену!
|
||
DestroyImmediate(tempCar);
|
||
|
||
// 4. Считаем итоговую цену и генерируем живое описание продавца
|
||
float rawPrice = item.idealPrice - defects.totalPricePenalty - (mileage / 10000f) * 65f;
|
||
int finalPrice = Mathf.RoundToInt(Mathf.Max(item.idealPrice * 0.25f, rawPrice) / 50f) * 50;
|
||
|
||
string sName = sellerNames[UnityEngine.Random.Range(0, sellerNames.Length)];
|
||
float sRating = Mathf.Round(UnityEngine.Random.Range(4.5f, 5.0f) * 10f) / 10f;
|
||
string sPhone = $"+375 ({(UnityEngine.Random.value < 0.5f ? 29 : 33)}) {UnityEngine.Random.Range(100, 999)}-{UnityEngine.Random.Range(10, 99)}-{UnityEngine.Random.Range(10, 99)}";
|
||
|
||
CarListing listing = new CarListing
|
||
{
|
||
id = i + 1,
|
||
catalogItem = item,
|
||
seed = seed,
|
||
bodyColor = color,
|
||
bodyColorName = colorName,
|
||
year = year,
|
||
mileageKm = mileage,
|
||
price = finalPrice,
|
||
driveType = drive,
|
||
sellerName = sName,
|
||
sellerRating = sRating,
|
||
sellerPhone = sPhone,
|
||
sellerDescription = BuildSellerDescription(defects, year, mileage),
|
||
defectsSummary = defects,
|
||
photo = capturedPhoto
|
||
};
|
||
|
||
Listings.Add(listing);
|
||
}
|
||
|
||
OnListingsUpdated?.Invoke();
|
||
}
|
||
|
||
private Sprite CaptureStudioPhoto()
|
||
{
|
||
RenderTexture prev = RenderTexture.active;
|
||
RenderTexture.active = photoRT;
|
||
|
||
photoCamera.Render();
|
||
|
||
Texture2D tex = new Texture2D(photoWidth, photoHeight, TextureFormat.RGB24, false);
|
||
tex.ReadPixels(new Rect(0, 0, photoWidth, photoHeight), 0, 0);
|
||
tex.Apply();
|
||
|
||
RenderTexture.active = prev;
|
||
|
||
return Sprite.Create(tex, new Rect(0, 0, photoWidth, photoHeight), new Vector2(0.5f, 0.5f));
|
||
}
|
||
|
||
private string BuildSellerDescription(CarDefectsSummary d, int year, int mileage)
|
||
{
|
||
List<string> notes = new List<string>();
|
||
|
||
if (d.rustedPartsCount == 0 && d.missingBodyPartsCount == 0 && d.flatTiresCount == 0 && d.missingWheelsCount == 0 && d.lowFluidsCount == 0 && d.engineIssuesCount == 0)
|
||
{
|
||
return $"Отличное состояние для {year} года! Кузов без рыжиков, вся комплектная, родной пробег {mileage:N0} км. Сел и поехал, без вложений. Юридически чистая, торг минимальный.";
|
||
}
|
||
|
||
if (d.rustedPartsCount > 0)
|
||
notes.Add($"по кузову есть возрастные рыжики на кромках ({d.rustedPartsCount} эл.)");
|
||
|
||
if (d.missingBodyPartsCount > 0)
|
||
{
|
||
string missingList = string.Join(", ", d.missingPartNames);
|
||
notes.Add($"сняты некоторые детали ({missingList})");
|
||
}
|
||
|
||
if (d.lowFluidsCount > 0)
|
||
notes.Add("нужно долить технические жидкости под капотом");
|
||
|
||
if (d.startProblems)
|
||
notes.Add("иногда не заводится с первого раза (наверное, аккумулятор подсел)");
|
||
if (d.oilProblems)
|
||
notes.Add("масло давно не менял");
|
||
if (d.overheatProblems)
|
||
notes.Add("летом в пробках бывало грелся");
|
||
if (d.brakeProblems)
|
||
notes.Add("тормоза немного мягкие");
|
||
if (d.dirtAmount > 0.7f)
|
||
notes.Add("стояла под деревом, давно не мыта");
|
||
|
||
if (d.missingWheelsCount > 0)
|
||
notes.Add("стоит на кирпичах (нет одного колеса, приезжайте со своей запаской)");
|
||
else if (d.flatTiresCount > 0)
|
||
notes.Add($"спущено колесо ({d.flatTiresCount} шт.)");
|
||
|
||
string details = string.Join(", ", notes);
|
||
return $"Продаю как есть, под восстановление или перепродажу: {details}. Мотор и коробка живые, хороший торг у капота!";
|
||
}
|
||
|
||
/// <summary>
|
||
/// Вызывается при нажатии кнопки "Договориться о встрече" в приложении телефона.
|
||
/// Спавнит машину на карте с её точным состоянием и активирует GPS навигацию.
|
||
/// </summary>
|
||
public void ArrangeMeeting(CarListing listing)
|
||
{
|
||
if (listing == null || listing.catalogItem == null || listing.catalogItem.carPrefab == null)
|
||
return;
|
||
|
||
// Если машина из этого объявления уже заспавнена — просто активируем метку
|
||
if (listing.isMeetingArranged && listing.spawnedInstance != null)
|
||
{
|
||
ActiveMeetingListing = listing;
|
||
OnMeetingArranged?.Invoke(listing);
|
||
return;
|
||
}
|
||
|
||
Transform spawnPoint = GetNextMeetingSpawnPoint();
|
||
Vector3 pos = spawnPoint != null ? spawnPoint.position : (transform.position + transform.forward * 15f);
|
||
Quaternion rot = spawnPoint != null ? spawnPoint.rotation : Quaternion.identity;
|
||
|
||
GameObject carObj = Instantiate(listing.catalogItem.carPrefab, pos, rot);
|
||
carObj.name = $"MarketCar_{listing.catalogItem.carTitle}_{listing.id}";
|
||
|
||
CarConditionGenerator gen = carObj.GetComponent<CarConditionGenerator>();
|
||
if (gen == null) gen = carObj.AddComponent<CarConditionGenerator>();
|
||
|
||
// Применяем ТОТ ЖЕ САМЫЙ Seed, что был на фотографии в объявлении!
|
||
gen.ApplyConditionBySeed(listing.seed, listing.bodyColor, false, out _);
|
||
|
||
CarOwnership own = carObj.GetComponent<CarOwnership>();
|
||
if (own == null) own = carObj.AddComponent<CarOwnership>();
|
||
own.SetupFromListing(listing);
|
||
own.isOwned = false;
|
||
|
||
listing.isMeetingArranged = true;
|
||
listing.spawnedInstance = carObj;
|
||
listing.spawnPosition = pos;
|
||
ActiveMeetingListing = listing;
|
||
|
||
OnMeetingArranged?.Invoke(listing);
|
||
}
|
||
|
||
/// <summary>Машина куплена: объявление снимается с рынка.</summary>
|
||
public void MarkListingSold(CarListing listing)
|
||
{
|
||
if (listing == null) return;
|
||
listing.isSold = true;
|
||
Listings.Remove(listing);
|
||
if (ActiveMeetingListing == listing) ClearActiveMeeting();
|
||
OnListingsUpdated?.Invoke();
|
||
}
|
||
|
||
public void ClearActiveMeeting()
|
||
{
|
||
if (ActiveMeetingListing != null)
|
||
{
|
||
ActiveMeetingListing = null;
|
||
OnMeetingCleared?.Invoke();
|
||
}
|
||
}
|
||
|
||
private Transform GetNextMeetingSpawnPoint()
|
||
{
|
||
if (meetingSpawnPoints == null || meetingSpawnPoints.Length == 0) return null;
|
||
lastUsedSpawnPointIndex = (lastUsedSpawnPointIndex + 1) % meetingSpawnPoints.Length;
|
||
return meetingSpawnPoints[lastUsedSpawnPointIndex];
|
||
}
|
||
} |