Есть генерация стен, пола, потолка и разбиения мешей на комнаты
This commit is contained in:
1 parent
bb8db47ecc
commit
746cbb2b5e
405 files changed
+24202
-98
No files matched your search
@@ -0,0 +1,92 @@
|
||||
%YAML 1.1
|
||||
%TAG !u! tag:unity3d.com,2011:
|
||||
--- !u!1 &2351983011819804703
|
||||
GameObject:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
serializedVersion: 6
|
||||
m_Component:
|
||||
- component: {fileID: 9198856115946365673}
|
||||
- component: {fileID: 7319817235164270451}
|
||||
- component: {fileID: 8257577605439538500}
|
||||
m_Layer: 0
|
||||
m_Name: Wall_plane
|
||||
m_TagString: Untagged
|
||||
m_Icon: {fileID: 0}
|
||||
m_NavMeshLayer: 0
|
||||
m_StaticEditorFlags: 0
|
||||
m_IsActive: 1
|
||||
--- !u!4 &9198856115946365673
|
||||
Transform:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 2351983011819804703}
|
||||
serializedVersion: 2
|
||||
m_LocalRotation: {x: 0.7071068, y: 0, z: 0, w: 0.7071068}
|
||||
m_LocalPosition: {x: 5, y: 0, z: 5}
|
||||
m_LocalScale: {x: 1, y: 1, z: 1}
|
||||
m_ConstrainProportionsScale: 0
|
||||
m_Children: []
|
||||
m_Father: {fileID: 0}
|
||||
m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0}
|
||||
--- !u!33 &7319817235164270451
|
||||
MeshFilter:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 2351983011819804703}
|
||||
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
|
||||
--- !u!23 &8257577605439538500
|
||||
MeshRenderer:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 2351983011819804703}
|
||||
m_Enabled: 1
|
||||
m_CastShadows: 1
|
||||
m_ReceiveShadows: 1
|
||||
m_DynamicOccludee: 1
|
||||
m_StaticShadowCaster: 0
|
||||
m_MotionVectors: 1
|
||||
m_LightProbeUsage: 1
|
||||
m_ReflectionProbeUsage: 1
|
||||
m_RayTracingMode: 2
|
||||
m_RayTraceProcedural: 0
|
||||
m_RayTracingAccelStructBuildFlagsOverride: 0
|
||||
m_RayTracingAccelStructBuildFlags: 1
|
||||
m_SmallMeshCulling: 1
|
||||
m_ForceMeshLod: -1
|
||||
m_MeshLodSelectionBias: 0
|
||||
m_RenderingLayerMask: 1
|
||||
m_RendererPriority: 0
|
||||
m_Materials:
|
||||
- {fileID: 2100000, guid: 31321ba15b8f8eb4c954353edc038b1d, type: 2}
|
||||
m_StaticBatchInfo:
|
||||
firstSubMesh: 0
|
||||
subMeshCount: 0
|
||||
m_StaticBatchRoot: {fileID: 0}
|
||||
m_ProbeAnchor: {fileID: 0}
|
||||
m_LightProbeVolumeOverride: {fileID: 0}
|
||||
m_ScaleInLightmap: 1
|
||||
m_ReceiveGI: 1
|
||||
m_PreserveUVs: 0
|
||||
m_IgnoreNormalsForChartDetection: 0
|
||||
m_ImportantGI: 0
|
||||
m_StitchLightmapSeams: 1
|
||||
m_SelectedEditorRenderState: 3
|
||||
m_MinimumChartSize: 4
|
||||
m_AutoUVMaxDistance: 0.5
|
||||
m_AutoUVMaxAngle: 89
|
||||
m_LightmapParameters: {fileID: 0}
|
||||
m_GlobalIlluminationMeshLod: 0
|
||||
m_SortingLayerID: 0
|
||||
m_SortingLayer: 0
|
||||
m_SortingOrder: 0
|
||||
m_MaskInteraction: 0
|
||||
m_AdditionalVertexStreams: {fileID: 0}
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d384f0cf68653df499e2ce184bd2459e
|
||||
PrefabImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -30,8 +30,8 @@ namespace _Project.Scripts.LevelGenerating
|
||||
public readonly List<Room> Rooms = new List<Room>();
|
||||
public readonly Dictionary<Room, int> Depth = new Dictionary<Room, int>();
|
||||
|
||||
// Сегменты стен (заполняет ShellBuilder.Build)
|
||||
public readonly List<WallSegment> Walls = new List<WallSegment>();
|
||||
// Отрезки стен (заполняет ShellBuilder.Build)
|
||||
public readonly List<WallRun> Walls = new List<WallRun>();
|
||||
|
||||
public Room Start; // стартовая комната (вход с предыдущего этажа)
|
||||
public Room Lift; // комната с лифтом (выход на следующий этаж)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
[Serializable]
|
||||
public class ThemeEntry
|
||||
{
|
||||
public RoomType type;
|
||||
public RoomTheme theme;
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Для каждой комнаты выбирает тему (по роли комнаты) и генератор, затем запускает его.
|
||||
//
|
||||
// Как добавить особый генератор (например, для лифта):
|
||||
// 1. Написать класс, реализующий IRoomGenerator, с Supports(room) => room.rt == RoomType.Lift.
|
||||
// 2. Добавить его в Awake() ДО ThemedRoomGenerator: берётся первый подходящий.
|
||||
//
|
||||
// НЕ ЗАБЫТЬ: материалы и освещение однозначно определяются темой и ролью комнаты, поэтому
|
||||
// в файл сохранения их можно не класть. Сохранять нужно только случайные решения (предметы).
|
||||
// =====================================================================
|
||||
public class RoomGeneratorRegistry : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private RoomTheme defaultTheme; // если для роли тема не задана
|
||||
[SerializeField] private List<ThemeEntry> themes = new List<ThemeEntry>();
|
||||
|
||||
private readonly List<IRoomGenerator> _generators = new List<IRoomGenerator>();
|
||||
|
||||
void Awake()
|
||||
{
|
||||
// сюда добавлять специальные генераторы, универсальный всегда последний
|
||||
_generators.Add(new ThemedRoomGenerator());
|
||||
}
|
||||
|
||||
public void Run(ShellResult shell, FloorData floor)
|
||||
{
|
||||
foreach (var view in shell.Views)
|
||||
{
|
||||
var theme = ResolveTheme(view.Data.rt);
|
||||
var generator = _generators.FirstOrDefault(g => g.Supports(view.Data));
|
||||
|
||||
if (generator == null)
|
||||
{
|
||||
Debug.LogWarning($"{view.name}: нет подходящего генератора");
|
||||
continue;
|
||||
}
|
||||
generator.Generate(view, floor, theme);
|
||||
}
|
||||
}
|
||||
|
||||
private RoomTheme ResolveTheme(RoomType type)
|
||||
{
|
||||
var entry = themes.FirstOrDefault(e => e.type == type);
|
||||
return entry != null && entry.theme != null ? entry.theme : defaultTheme;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ce465b42a730432fa72090cca5a21514
|
||||
timeCreated: 1791741182
|
||||
@@ -0,0 +1,75 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
// =====================================================================
|
||||
// Генератор, который оформляет одну комнату после того, как построены её меши.
|
||||
// Специальные комнаты (лифт, старт) получают свои реализации,
|
||||
// обычные - универсальный ThemedRoomGenerator.
|
||||
// =====================================================================
|
||||
public interface IRoomGenerator
|
||||
{
|
||||
bool Supports(Room room);
|
||||
void Generate(RoomView view, FloorData floor, RoomTheme theme);
|
||||
}
|
||||
|
||||
// Универсальный генератор: материалы из темы и сетка ламп под потолком.
|
||||
// Позже сюда добавится расстановка предметов по правилам темы.
|
||||
public class ThemedRoomGenerator : IRoomGenerator
|
||||
{
|
||||
public bool Supports(Room room) => true;
|
||||
|
||||
public void Generate(RoomView view, FloorData floor, RoomTheme theme)
|
||||
{
|
||||
if (theme == null)
|
||||
{
|
||||
Debug.LogWarning($"{view.name}: для комнаты не назначена тема");
|
||||
return;
|
||||
}
|
||||
|
||||
ApplyMaterial(view.FloorRenderers, theme.floorMaterial);
|
||||
ApplyMaterial(view.WallRenderers, theme.wallMaterial);
|
||||
ApplyMaterial(view.CeilingRenderers, theme.ceilingMaterial);
|
||||
|
||||
if (theme.createLights) CreateLights(view, theme);
|
||||
}
|
||||
|
||||
private static void ApplyMaterial(System.Collections.Generic.List<Renderer> renderers, Material mat)
|
||||
{
|
||||
if (mat == null) return; // остаётся материал префаба
|
||||
foreach (var r in renderers) r.sharedMaterial = mat;
|
||||
}
|
||||
|
||||
// Сетка ламп: чем больше комната, тем больше ламп (шаг задаёт lightSpacing)
|
||||
private static void CreateLights(RoomView view, RoomTheme theme)
|
||||
{
|
||||
Vector3 size = view.SizeMeters;
|
||||
Vector3 origin = view.OriginMeters;
|
||||
|
||||
int nx = Mathf.Max(1, Mathf.CeilToInt(size.x / theme.lightSpacing));
|
||||
int nz = Mathf.Max(1, Mathf.CeilToInt(size.z / theme.lightSpacing));
|
||||
float y = view.Height - theme.lightDrop;
|
||||
|
||||
var lightsRoot = new GameObject("Lights").transform;
|
||||
lightsRoot.SetParent(view.transform, false);
|
||||
|
||||
for (int ix = 0; ix < nx; ix++)
|
||||
{
|
||||
for (int iz = 0; iz < nz; iz++)
|
||||
{
|
||||
var go = new GameObject($"Light_{ix}_{iz}");
|
||||
go.transform.SetParent(lightsRoot, false);
|
||||
go.transform.position = origin + new Vector3(
|
||||
(ix + 0.5f) / nx * size.x, y, (iz + 0.5f) / nz * size.z);
|
||||
|
||||
var light = go.AddComponent<Light>();
|
||||
light.type = LightType.Point;
|
||||
light.color = theme.lightColor;
|
||||
light.intensity = theme.lightIntensity;
|
||||
light.range = theme.lightRange;
|
||||
light.shadows = theme.lightShadows;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: deb99be7fb324a07aee8dfb48bbcd5c8
|
||||
timeCreated: 1791741221
|
||||
@@ -0,0 +1,29 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
// =====================================================================
|
||||
// Набор оформления комнаты: материалы и освещение.
|
||||
// Создаётся в проекте: ПКМ -> Create -> Level -> Room Theme.
|
||||
// Новая тема - это новые данные, код не меняется.
|
||||
// =====================================================================
|
||||
[CreateAssetMenu(menuName = "Level/Room Theme", fileName = "RoomTheme")]
|
||||
public class RoomTheme : ScriptableObject
|
||||
{
|
||||
[Header("Материалы")]
|
||||
public Material floorMaterial;
|
||||
public Material wallMaterial;
|
||||
public Material ceilingMaterial;
|
||||
|
||||
[Header("Освещение")]
|
||||
public bool createLights = true;
|
||||
public Color lightColor = Color.white;
|
||||
public float lightIntensity = 1.5f;
|
||||
public float lightRange = 8f;
|
||||
[Tooltip("Расстояние между лампами в метрах: большая комната получает сетку ламп")]
|
||||
public float lightSpacing = 6f;
|
||||
[Tooltip("На сколько метров ниже потолка висит лампа")]
|
||||
public float lightDrop = 0.3f;
|
||||
public LightShadows lightShadows = LightShadows.None;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: db0cd7361afa447e84273406c58818df
|
||||
timeCreated: 1791741243
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
// =====================================================================
|
||||
// Объект комнаты в сцене. Создаётся ShellSpawner, потом с ним работают генераторы комнат.
|
||||
// Хранит данные комнаты и ссылки на её меши, чтобы генератор не искал их сам.
|
||||
// =====================================================================
|
||||
public class RoomView : MonoBehaviour
|
||||
{
|
||||
public Room Data;
|
||||
public int Index;
|
||||
public float Height; // высота стен в метрах
|
||||
|
||||
public readonly List<Renderer> FloorRenderers = new List<Renderer>();
|
||||
public readonly List<Renderer> CeilingRenderers = new List<Renderer>();
|
||||
public readonly List<Renderer> WallRenderers = new List<Renderer>();
|
||||
|
||||
// Левый нижний угол комнаты в метрах
|
||||
public Vector3 OriginMeters =>
|
||||
new Vector3(Data.Position.x * LevelGrid.Module, 0f, Data.Position.y * LevelGrid.Module);
|
||||
|
||||
// Размеры комнаты в метрах: x - по X, z - по Z
|
||||
public Vector3 SizeMeters =>
|
||||
new Vector3(Data.Length * LevelGrid.Module, Height, Data.Width * LevelGrid.Module);
|
||||
|
||||
public Vector3 CenterMeters =>
|
||||
OriginMeters + new Vector3(SizeMeters.x / 2f, 0f, SizeMeters.z / 2f);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7907be0cba2c4211b9a9a7aee5ebd3d1
|
||||
timeCreated: 1791741256
|
||||
@@ -3,52 +3,80 @@ using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
public enum SegmentKind { Wall, Corner }
|
||||
// Куда смотрит видимая сторона стены (внутрь комнаты или коридора)
|
||||
public enum WallFacing { XP, XN, ZP, ZN }
|
||||
|
||||
// Куда смотрит видимая сторона сегмента (внутрь комнаты или коридора).
|
||||
// Для Corner - какой это угол комнаты (SW = минимальные X и Z).
|
||||
public enum SegmentFacing { XP, XN, ZP, ZN, CornerSW, CornerSE, CornerNW, CornerNE }
|
||||
|
||||
// Один сегмент стены = одна клетка (1 модуль = 0.5 м) по периметру.
|
||||
// Поля публичные, чтобы потом можно было сохранять в файл.
|
||||
// Прямой отрезок стены по линии сетки (координаты в модулях).
|
||||
// Start - точка на линии сетки, с которой отрезок начинается.
|
||||
// Для ZP/ZN отрезок идёт вдоль +X, для XP/XN - вдоль +Z.
|
||||
// RoomIndex - индекс комнаты в FloorData.Rooms, которой принадлежит стена.
|
||||
// Поля публичные, чтобы потом сохранять в файл.
|
||||
[System.Serializable]
|
||||
public struct WallSegment
|
||||
public struct WallRun
|
||||
{
|
||||
public Vector2Int Cell;
|
||||
public SegmentKind Kind;
|
||||
public SegmentFacing Facing;
|
||||
public Vector2Int Start;
|
||||
public int Length;
|
||||
public WallFacing Facing;
|
||||
public int RoomIndex;
|
||||
|
||||
public WallSegment(Vector2Int cell, SegmentKind kind, SegmentFacing facing)
|
||||
public WallRun(Vector2Int start, int length, WallFacing facing, int roomIndex)
|
||||
{
|
||||
Cell = cell;
|
||||
Kind = kind;
|
||||
Start = start;
|
||||
Length = length;
|
||||
Facing = facing;
|
||||
RoomIndex = roomIndex;
|
||||
}
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Строит сегменты стен из FloorData. Спавна здесь нет, только данные.
|
||||
// Строит отрезки стен из FloorData. Спавна здесь нет, только данные.
|
||||
//
|
||||
// Правила:
|
||||
// - Стены стоят ВНУТРИ прямоугольника комнаты: это внешнее кольцо клеток шириной 1 модуль.
|
||||
// - Стена стоит на границе прямоугольника комнаты (плоскость без толщины).
|
||||
// - У коридора стены только по двум длинным сторонам, торцы открыты.
|
||||
// - Проём в стене комнаты равен ВНУТРЕННЕЙ ширине коридора (ширина коридора минус 2 клетки,
|
||||
// то есть минус по 0.5 м стены с каждой стороны). Иначе проём был бы шире прохода.
|
||||
// - Стык стены коридора со стеной комнаты - Т-образный, угловой элемент там не ставится.
|
||||
//
|
||||
// НЕ ЗАБЫТЬ: ширина коридора должна быть минимум 3 клетки, иначе проёма не будет.
|
||||
// - В стенах комнат вырезаются проёмы шириной ровно с коридор.
|
||||
// - Каждый отрезок помнит комнату-владельца (RoomIndex).
|
||||
// =====================================================================
|
||||
public static class ShellBuilder
|
||||
{
|
||||
private struct Gap
|
||||
{
|
||||
public bool Vertical; // линия x = Line (вертикальная), иначе z = Line
|
||||
public int Line, From, To;
|
||||
}
|
||||
|
||||
public static void Build(FloorData floor)
|
||||
{
|
||||
floor.Walls.Clear();
|
||||
var doors = CollectDoorCells(floor);
|
||||
var gaps = CollectGaps(floor);
|
||||
|
||||
foreach (var r in floor.Rooms)
|
||||
for (int i = 0; i < floor.Rooms.Count; i++)
|
||||
{
|
||||
if (r.rt == RoomType.Corridor) AddCorridorWalls(floor, r);
|
||||
else AddRoomWalls(floor, r, doors);
|
||||
var r = floor.Rooms[i];
|
||||
int x0 = r.Position.x, x1 = x0 + r.Length;
|
||||
int z0 = r.Position.y, z1 = z0 + r.Width;
|
||||
|
||||
if (r.rt == RoomType.Corridor)
|
||||
{
|
||||
// у коридора проёмов нет, его торцы просто открыты
|
||||
if (IsAlongX(r))
|
||||
{
|
||||
AddSide(floor, i, false, z0, x0, x1, WallFacing.ZP, null);
|
||||
AddSide(floor, i, false, z1, x0, x1, WallFacing.ZN, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
AddSide(floor, i, true, x0, z0, z1, WallFacing.XP, null);
|
||||
AddSide(floor, i, true, x1, z0, z1, WallFacing.XN, null);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
AddSide(floor, i, false, z0, x0, x1, WallFacing.ZP, gaps); // южная
|
||||
AddSide(floor, i, false, z1, x0, x1, WallFacing.ZN, gaps); // северная
|
||||
AddSide(floor, i, true, x0, z0, z1, WallFacing.XP, gaps); // западная
|
||||
AddSide(floor, i, true, x1, z0, z1, WallFacing.XN, gaps); // восточная
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,92 +88,59 @@ namespace _Project.Scripts.LevelGenerating
|
||||
return c.Length >= c.Width;
|
||||
}
|
||||
|
||||
// Клетки стен комнат, которые нужно убрать под проёмы коридоров
|
||||
private static HashSet<Vector2Int> CollectDoorCells(FloorData floor)
|
||||
// Места, где коридор упирается в стены комнат
|
||||
private static List<Gap> CollectGaps(FloorData floor)
|
||||
{
|
||||
var set = new HashSet<Vector2Int>();
|
||||
var gaps = new List<Gap>();
|
||||
|
||||
foreach (var c in floor.Corridors)
|
||||
{
|
||||
int x0 = c.Position.x, z0 = c.Position.y;
|
||||
int x0 = c.Position.x, x1 = x0 + c.Length;
|
||||
int z0 = c.Position.y, z1 = z0 + c.Width;
|
||||
|
||||
if (IsAlongX(c))
|
||||
{
|
||||
// слева стена комнаты в колонке x0 - 1, справа в колонке x0 + Length
|
||||
for (int z = z0 + 1; z < z0 + c.Width - 1; z++)
|
||||
{
|
||||
set.Add(new Vector2Int(x0 - 1, z));
|
||||
set.Add(new Vector2Int(x0 + c.Length, z));
|
||||
}
|
||||
gaps.Add(new Gap { Vertical = true, Line = x0, From = z0, To = z1 });
|
||||
gaps.Add(new Gap { Vertical = true, Line = x1, From = z0, To = z1 });
|
||||
}
|
||||
else
|
||||
{
|
||||
// снизу стена комнаты в ряду z0 - 1, сверху в ряду z0 + Width
|
||||
for (int x = x0 + 1; x < x0 + c.Length - 1; x++)
|
||||
{
|
||||
set.Add(new Vector2Int(x, z0 - 1));
|
||||
set.Add(new Vector2Int(x, z0 + c.Width));
|
||||
}
|
||||
gaps.Add(new Gap { Vertical = false, Line = z0, From = x0, To = x1 });
|
||||
gaps.Add(new Gap { Vertical = false, Line = z1, From = x0, To = x1 });
|
||||
}
|
||||
}
|
||||
return set;
|
||||
return gaps;
|
||||
}
|
||||
|
||||
private static void AddRoomWalls(FloorData floor, Room r, HashSet<Vector2Int> doors)
|
||||
// Добавляет сторону [from, to] на линии line, вырезая проёмы
|
||||
private static void AddSide(FloorData floor, int owner, bool vertical, int line, int from, int to,
|
||||
WallFacing facing, List<Gap> gaps)
|
||||
{
|
||||
int x0 = r.Position.x, z0 = r.Position.y;
|
||||
int x1 = x0 + r.Length - 1, z1 = z0 + r.Width - 1;
|
||||
int cursor = from;
|
||||
|
||||
// углы
|
||||
Add(floor, new Vector2Int(x0, z0), SegmentKind.Corner, SegmentFacing.CornerSW);
|
||||
Add(floor, new Vector2Int(x1, z0), SegmentKind.Corner, SegmentFacing.CornerSE);
|
||||
Add(floor, new Vector2Int(x0, z1), SegmentKind.Corner, SegmentFacing.CornerNW);
|
||||
Add(floor, new Vector2Int(x1, z1), SegmentKind.Corner, SegmentFacing.CornerNE);
|
||||
|
||||
// нижняя и верхняя стены (идут вдоль X)
|
||||
for (int x = x0 + 1; x < x1; x++)
|
||||
if (gaps != null)
|
||||
{
|
||||
AddWall(floor, new Vector2Int(x, z0), SegmentFacing.ZP, doors);
|
||||
AddWall(floor, new Vector2Int(x, z1), SegmentFacing.ZN, doors);
|
||||
}
|
||||
var own = new List<Gap>();
|
||||
foreach (var g in gaps)
|
||||
if (g.Vertical == vertical && g.Line == line && g.To > from && g.From < to)
|
||||
own.Add(g);
|
||||
own.Sort((a, b) => a.From.CompareTo(b.From));
|
||||
|
||||
// левая и правая стены (идут вдоль Z)
|
||||
for (int z = z0 + 1; z < z1; z++)
|
||||
{
|
||||
AddWall(floor, new Vector2Int(x0, z), SegmentFacing.XP, doors);
|
||||
AddWall(floor, new Vector2Int(x1, z), SegmentFacing.XN, doors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddCorridorWalls(FloorData floor, Room c)
|
||||
{
|
||||
int x0 = c.Position.x, z0 = c.Position.y;
|
||||
|
||||
if (IsAlongX(c))
|
||||
{
|
||||
for (int x = x0; x < x0 + c.Length; x++)
|
||||
foreach (var g in own)
|
||||
{
|
||||
Add(floor, new Vector2Int(x, z0), SegmentKind.Wall, SegmentFacing.ZP);
|
||||
Add(floor, new Vector2Int(x, z0 + c.Width - 1), SegmentKind.Wall, SegmentFacing.ZN);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int z = z0; z < z0 + c.Width; z++)
|
||||
{
|
||||
Add(floor, new Vector2Int(x0, z), SegmentKind.Wall, SegmentFacing.XP);
|
||||
Add(floor, new Vector2Int(x0 + c.Length - 1, z), SegmentKind.Wall, SegmentFacing.XN);
|
||||
if (g.From > cursor) AddRun(floor, owner, vertical, line, cursor, g.From, facing);
|
||||
cursor = Mathf.Max(cursor, g.To);
|
||||
}
|
||||
}
|
||||
|
||||
if (cursor < to) AddRun(floor, owner, vertical, line, cursor, to, facing);
|
||||
}
|
||||
|
||||
private static void AddWall(FloorData floor, Vector2Int cell, SegmentFacing facing, HashSet<Vector2Int> doors)
|
||||
private static void AddRun(FloorData floor, int owner, bool vertical, int line, int a, int b,
|
||||
WallFacing facing)
|
||||
{
|
||||
if (doors.Contains(cell)) return; // здесь проём
|
||||
Add(floor, cell, SegmentKind.Wall, facing);
|
||||
Vector2Int start = vertical ? new Vector2Int(line, a) : new Vector2Int(a, line);
|
||||
floor.Walls.Add(new WallRun(start, b - a, facing, owner));
|
||||
}
|
||||
|
||||
private static void Add(FloorData floor, Vector2Int cell, SegmentKind kind, SegmentFacing facing) =>
|
||||
floor.Walls.Add(new WallSegment(cell, kind, facing));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.LevelGenerating
|
||||
{
|
||||
public class ShellResult
|
||||
{
|
||||
public Transform Root;
|
||||
public List<RoomView> Views = new List<RoomView>(); // индекс совпадает с FloorData.Rooms
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Спавнит пол, потолок и стены из одного префаба-плоскости.
|
||||
// Для каждой комнаты создаётся объект Room_N_Тип с компонентом RoomView.
|
||||
// Материалы здесь НЕ назначаются: этим занимаются генераторы комнат (RoomTheme).
|
||||
//
|
||||
// Требования к префабу:
|
||||
// - Unity Plane (3D Object -> Plane): лежит в XZ, нормаль +Y, размер 10x10 при scale 1.
|
||||
// Если размер другой (например 1x1), поменяй planeBaseSize. Quad не подойдёт: у него нормаль -Z.
|
||||
// - Меш и Renderer на корне префаба. Коллайдеры на префабе игнорируются и заменяются на Box.
|
||||
//
|
||||
// Все плоскости видны только с одной стороны (внутрь комнаты):
|
||||
// стены смотрят внутрь, пол вверх, потолок вниз.
|
||||
//
|
||||
// НЕ ЗАБЫТЬ: сейчас сюда попадает и комната лифта. Позже у неё будет свой фиксированный префаб.
|
||||
// =====================================================================
|
||||
public class ShellSpawner : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private GameObject planePrefab;
|
||||
[SerializeField] private float planeBaseSize = 10f;
|
||||
[SerializeField] private float wallHeight = 3f;
|
||||
[SerializeField] private float colliderThickness = 0.2f;
|
||||
|
||||
public ShellResult Spawn(FloorData floor)
|
||||
{
|
||||
if (planePrefab == null)
|
||||
{
|
||||
Debug.LogError("ShellSpawner: не назначен planePrefab");
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = new ShellResult
|
||||
{
|
||||
Root = new GameObject($"Floor_{floor.Index}_Shell").transform
|
||||
};
|
||||
|
||||
// 1. Объект на каждую комнату + пол и потолок
|
||||
for (int i = 0; i < floor.Rooms.Count; i++)
|
||||
{
|
||||
var room = floor.Rooms[i];
|
||||
|
||||
var roomGo = new GameObject($"Room_{i}_{room.rt}");
|
||||
roomGo.transform.SetParent(result.Root, false);
|
||||
|
||||
var view = roomGo.AddComponent<RoomView>();
|
||||
view.Data = room;
|
||||
view.Index = i;
|
||||
view.Height = wallHeight;
|
||||
result.Views.Add(view);
|
||||
|
||||
var scale = new Vector3(view.SizeMeters.x / planeBaseSize, 1f, view.SizeMeters.z / planeBaseSize);
|
||||
Vector3 c = view.CenterMeters;
|
||||
|
||||
// пол: нормаль вверх
|
||||
var floorGo = Make(roomGo.transform, "Floor", new Vector3(c.x, 0f, c.z),
|
||||
Quaternion.identity, scale, true);
|
||||
view.FloorRenderers.AddRange(floorGo.GetComponentsInChildren<Renderer>());
|
||||
|
||||
// потолок: перевёрнут, нормаль вниз
|
||||
var ceilingGo = Make(roomGo.transform, "Ceiling", new Vector3(c.x, wallHeight, c.z),
|
||||
Quaternion.Euler(180f, 0f, 0f), scale, false);
|
||||
view.CeilingRenderers.AddRange(ceilingGo.GetComponentsInChildren<Renderer>());
|
||||
}
|
||||
|
||||
// 2. Стены раскладываются по комнатам-владельцам
|
||||
foreach (var run in floor.Walls)
|
||||
{
|
||||
if (run.RoomIndex < 0 || run.RoomIndex >= result.Views.Count)
|
||||
{
|
||||
Debug.LogWarning($"Стена ссылается на несуществующую комнату {run.RoomIndex}");
|
||||
continue;
|
||||
}
|
||||
SpawnWall(result.Views[run.RoomIndex], run);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private void SpawnWall(RoomView view, WallRun run)
|
||||
{
|
||||
float len = run.Length * LevelGrid.Module;
|
||||
float y = wallHeight / 2f;
|
||||
float sx = run.Start.x * LevelGrid.Module;
|
||||
float sz = run.Start.y * LevelGrid.Module;
|
||||
|
||||
Vector3 pos;
|
||||
Quaternion rot;
|
||||
Vector3 scale;
|
||||
|
||||
switch (run.Facing)
|
||||
{
|
||||
case WallFacing.ZP: // идёт вдоль X, нормаль +Z
|
||||
pos = new Vector3(sx + len / 2f, y, sz);
|
||||
rot = Quaternion.Euler(90f, 0f, 0f);
|
||||
scale = new Vector3(len / planeBaseSize, 1f, wallHeight / planeBaseSize);
|
||||
break;
|
||||
case WallFacing.ZN: // идёт вдоль X, нормаль -Z
|
||||
pos = new Vector3(sx + len / 2f, y, sz);
|
||||
rot = Quaternion.Euler(-90f, 0f, 0f);
|
||||
scale = new Vector3(len / planeBaseSize, 1f, wallHeight / planeBaseSize);
|
||||
break;
|
||||
case WallFacing.XP: // идёт вдоль Z, нормаль +X
|
||||
pos = new Vector3(sx, y, sz + len / 2f);
|
||||
rot = Quaternion.Euler(0f, 0f, -90f);
|
||||
scale = new Vector3(wallHeight / planeBaseSize, 1f, len / planeBaseSize);
|
||||
break;
|
||||
default: // XN: идёт вдоль Z, нормаль -X
|
||||
pos = new Vector3(sx, y, sz + len / 2f);
|
||||
rot = Quaternion.Euler(0f, 0f, 90f);
|
||||
scale = new Vector3(wallHeight / planeBaseSize, 1f, len / planeBaseSize);
|
||||
break;
|
||||
}
|
||||
|
||||
var go = Make(view.transform, "Wall", pos, rot, scale, true);
|
||||
view.WallRenderers.AddRange(go.GetComponentsInChildren<Renderer>());
|
||||
}
|
||||
|
||||
private GameObject Make(Transform parent, string name, Vector3 pos, Quaternion rot, Vector3 scale,
|
||||
bool withCollider)
|
||||
{
|
||||
var go = Instantiate(planePrefab, pos, rot, parent);
|
||||
go.name = name;
|
||||
go.transform.localScale = scale;
|
||||
|
||||
// коллайдеры префаба не используем: у плоскости нет толщины
|
||||
foreach (var c in go.GetComponents<Collider>()) Destroy(c);
|
||||
|
||||
if (withCollider)
|
||||
{
|
||||
// Box прячем за видимой стороной (локальный -Y), чтобы он не съедал место внутри комнаты
|
||||
var box = go.AddComponent<BoxCollider>();
|
||||
box.size = new Vector3(planeBaseSize, colliderThickness, planeBaseSize);
|
||||
box.center = new Vector3(0f, -colliderThickness / 2f, 0f);
|
||||
}
|
||||
return go;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 303021be9cf546ac97aa5f705270c305
|
||||
@@ -31,6 +31,8 @@ namespace _Project.Scripts.LevelGenerating
|
||||
[SerializeField] private float _minDistanceStartLift; // метры
|
||||
[SerializeField] private GameObject GameObjectA;
|
||||
[SerializeField] private GameObject GameObjectB;
|
||||
[SerializeField] private ShellSpawner shellSpawner; // если назначен, строит пол, стены и потолок
|
||||
[SerializeField] private RoomGeneratorRegistry roomGenerators; // оформляет комнаты по темам (материалы, свет)
|
||||
|
||||
[Header("Генерация")]
|
||||
[SerializeField] private int maxRooms = 15;
|
||||
@@ -123,9 +125,15 @@ namespace _Project.Scripts.LevelGenerating
|
||||
if (!ok) Debug.LogError("Лифт не помещается: проверь размеры карты, лифта и коридора");
|
||||
|
||||
AssignRoles();
|
||||
ShellBuilder.Build(_data); // сегменты стен (только данные, без спавна)
|
||||
ShellBuilder.Build(_data); // отрезки стен (только данные)
|
||||
|
||||
SpawnMarkers(); // временно
|
||||
if (shellSpawner != null)
|
||||
{
|
||||
var shell = shellSpawner.Spawn(_data); // меши: пол, потолок, стены по комнатам
|
||||
if (shell != null && roomGenerators != null)
|
||||
roomGenerators.Run(shell, _data); // оформление каждой комнаты (материалы, свет)
|
||||
}
|
||||
else SpawnMarkers(); // временно, если спавнер не назначен
|
||||
return _data;
|
||||
}
|
||||
|
||||
@@ -570,12 +578,13 @@ namespace _Project.Scripts.LevelGenerating
|
||||
Gizmos.DrawWireCube(c, new Vector3(r.Length * LevelGrid.Module, 0.1f, r.Width * LevelGrid.Module));
|
||||
}
|
||||
|
||||
// Сегменты стен: чёрные - стена, красные - угол
|
||||
foreach (var s in _data.Walls)
|
||||
// Отрезки стен: чёрные линии на высоте 1 м
|
||||
Gizmos.color = Color.black;
|
||||
foreach (var w in _data.Walls)
|
||||
{
|
||||
Gizmos.color = s.Kind == SegmentKind.Corner ? Color.red : Color.black;
|
||||
Vector3 pos = LevelGrid.ToWorld(new Vector2(s.Cell.x + 0.5f, s.Cell.y + 0.5f), 0.5f);
|
||||
Gizmos.DrawCube(pos, new Vector3(LevelGrid.Module, 1f, LevelGrid.Module) * 0.9f);
|
||||
bool alongX = w.Facing == WallFacing.ZP || w.Facing == WallFacing.ZN;
|
||||
Vector2Int end = w.Start + (alongX ? new Vector2Int(w.Length, 0) : new Vector2Int(0, w.Length));
|
||||
Gizmos.DrawLine(LevelGrid.ToWorld(w.Start, 1f), LevelGrid.ToWorld(end, 1f));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user