Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Web программирование > HTML и CSS
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 12.11.2024, 16:31   #171
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Многогранные коридоры прямые бэкрумс
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
import os

# Функция для генерации 3D-поля с коридорами
def generate_delaunay_field(shape):
    array = np.zeros(shape, dtype=float)

    # Генерация точек для коридоров
    points = []
    for _ in range(10):
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        points.append([x, y, shape[2] // 2])  # Генерируем точки на фиксированной высоте

    # Генерация коридоров между точками
    for i in range(len(points) - 1):
        start_point = points[i]
        end_point = points[i + 1]

        # Горизонтальный или вертикальный коридор
        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]
            array[new_x, new_y, new_z] = 1.0
            # Делаем коридоры более жирными
            for k in range(-2, 3):
                for l in range(-2, 3):
                    for m in range(-2, 3):
                        x1, y1, z1 = new_x + k, new_y + l, new_z + m
                        if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                            array[x1, y1, z1] = 1.0

        for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
            new_x = end_point[0]
            new_z = end_point[2]
            array[new_x, new_y, new_z] = 1.0
            # Делаем коридоры более жирными
            for k in range(-2, 3):
                for l in range(-2, 3):
                    for m in range(-2, 3):
                        x1, y1, z1 = new_x + k, new_y + l, new_z + m
                        if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                            array[x1, y1, z1] = 1.0

    return array

# Параметры
shape = (128, 128, 128)  # Размеры 3D массива

# Генерация 3D-поля с коридорами
delaunay_field = generate_delaunay_field(shape)

# Создание изосурфейса
verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='r', alpha=0.5)
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 12.11.2024, 16:58   #172
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Бэкрумс но коридоры исключительно от комнаты к комнате
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
from scipy.spatial import Delaunay
import os

# Функция для генерации 3D-поля с триангуляцией Делоне
def generate_delaunay_field(shape):
    array = np.zeros(shape, dtype=float)

    # Генерация кубов на каждом уровне
    points = []
    for level in range(3):
        for _ in range(10):
            x = np.random.randint(10, shape[0] - 10)
            y = np.random.randint(10, shape[1] - 10)
            z = level * (shape[2] // 3) + np.random.randint(10, shape[2] // 3 - 10)
            points.append([x, y, z])
            generate_cube(array, (x, y, z), np.random.randint(4, 8))

    # Генерация линий между кубами на разных уровнях
    for i in range(len(points) - 1):
        dx = points[i+1][0] - points[i][0]
        dy = points[i+1][1] - points[i][1]
        dz = points[i+1][2] - points[i][2]
        length = int(np.sqrt(dx**2 + dy**2 + dz**2))
        for j in range(length):
            new_x = int(points[i][0] + j * dx // length)
            new_y = int(points[i][1] + j * dy // length)
            new_z = int(points[i][2] + j * dz // length)
            if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                array[new_x, new_y, new_z] = 1.0
                # Делаем линии более жирными
                for k in range(-2, 3):
                    for l in range(-2, 3):
                        for m in range(-2, 3):
                            x1, y1, z1 = new_x + k, new_y + l, new_z + m
                            if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                array[x1, y1, z1] = 1.0

    return array

# Функция для генерации куба в заданной точке
def generate_cube(array, point, size):
    x, y, z = int(point[0]), int(point[1]), int(point[2])
    for i in range(-size, size+1):
        for j in range(-size, size+1):
            for k in range(-size, size+1):
                new_x, new_y, new_z = x + i, y + j, z + k
                if 0 <= new_x < array.shape[0] and 0 <= new_y < array.shape[1] and 0 <= new_z < array.shape[2]:
                    array[new_x, new_y, new_z] = 1.0

# Параметры
shape = (128, 128, 128)  # Размеры 3D массива

# Генерация 3D-поля с триангуляцией Делоне
delaunay_field = generate_delaunay_field(shape)

# Создание изосурфейса
verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], faces, verts[:, 2], color='r', alpha=0.5)
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 12.11.2024, 17:16   #173
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Бэкрумс но это ломанная линия коридора по всему чанку
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
import os

# Функция для генерации 3D-поля с коридорами
def generate_delaunay_field(shape):
    array = np.zeros(shape, dtype=float)

    # Генерация стартовых точек для коридоров
    points = []
    for _ in range(10):
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        z = np.random.randint(1, shape[2] - 1)  # Разные высоты
        points.append([x, y, z])

    # Генерация коридоров между точками
    for i in range(len(points) - 1):
        start_point = points[i]
        end_point = points[i + 1]

        # Генерация коридоров с высотами
        dx = end_point[0] - start_point[0]
        dy = end_point[1] - start_point[1]
        dz = end_point[2] - start_point[2]
        length = max(abs(dx), abs(dy), abs(dz))

        for j in range(length + 1):
            new_x = int(start_point[0] + j * dx // length) if length > 0 else start_point[0]
            new_y = int(start_point[1] + j * dy // length) if length > 0 else start_point[1]
            new_z = int(start_point[2] + j * dz // length) if length > 0 else start_point[2]
            if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                array[new_x, new_y, new_z] = 1.0
                # Делаем коридоры более широкими
                for k in range(-1, 2):
                    for l in range(-1, 2):
                        for m in range(-1, 2):
                            x1, y1, z1 = new_x + k, new_y + l, new_z + m
                            if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                array[x1, y1, z1] = 1.0

    return array

# Параметры
shape = (128, 128, 128)  # Размеры 3D массива

# Генерация 3D-поля с коридорами
delaunay_field = generate_delaunay_field(shape)

# Создание изосурфейса
verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='r', alpha=0.5)
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 13.11.2024, 03:29   #174
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Бэкрумс но коридоры без комнат многоэтажные
Код:
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
import os

# Функция для генерации 3D-поля с коридорами
def generate_delaunay_field(shape):
    array = np.zeros(shape, dtype=float)

    # Генерация коридоров на каждом уровне
    points = []
    for level in range(3):  # 3 уровня
        for _ in range(50):  # 50 коридоров
            x = np.random.randint(10, shape[0] - 10)
            y = np.random.randint(10, shape[1] - 10)
            z = level * (shape[2] // 3) + np.random.randint(10, shape[2] // 3 - 10)
            points.append([x, y, z])

    # Генерация коридоров между точками
    for i in range(len(points) - 1):
        start_point = points[i]
        end_point = points[i + 1]

        # Горизонтальный коридор
        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]

            # Делаем коридоры высокими и широкими
            for height_offset in range(-4, 5):  # Высота коридоров
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

        # Вертикальный коридор
        for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
            new_x = end_point[0]
            new_z = end_point[2]

            # Делаем коридоры высокими и широкими
            for height_offset in range(-4, 5):  # Высота коридоров
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

        # Добавление соединений между уровнями
        if start_point[2] != end_point[2]:  # Если уровень изменился
            for new_z in range(min(start_point[2], end_point[2]), max(start_point[2], end_point[2]) + 1):
                if 0 <= start_point[0] < shape[0] and 0 <= start_point[1] < shape[1]:
                    for height_offset in range(-4, 5):  # Высота коридоров
                        array[start_point[0], start_point[1], new_z + height_offset] = 1.0
                        for k in range(-2, 3):  # Ширина по x и y
                            for l in range(-2, 3):
                                if 0 <= start_point[0] + k < shape[0] and 0 <= start_point[1] + l < shape[1]:
                                    array[start_point[0] + k, start_point[1] + l, new_z + height_offset] = 1.0

    return array

# Параметры
shape = (128, 128, 128)  # Размеры 3D массива

# Генерация 3D-поля с коридорами
delaunay_field = generate_delaunay_field(shape)

# Создание изосурфейса
verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='r', alpha=0.5)
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 13.11.2024, 08:38   #175
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Процедурный генератор вспаханного поля
Код:
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
import noise
import os

# Инициализация Pygame
pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)

# Инициализация камеры
gluPerspective(45, (display[0] / display[1]), 0.1, 1000.0)
glTranslatef(0.0, 0.0, -30)
glRotatef(45, 1, 0, 0)  # Повернуть камеру на 45 градусов вокруг оси X

# Генерация шума
def generate_noise_2d(shape, x_offset, z_offset, scale=100.0, octaves=6, persistence=0.5, lacunarity=2.0):
    noise_map = np.zeros(shape)
    for i in range(shape[0]):
        for j in range(shape[1]):
            noise_map[i][j] = noise.pnoise2((i + x_offset) / scale, (j + z_offset) / scale, octaves=octaves,
                                              persistence=persistence, lacunarity=lacunarity, repeatx=1024,
                                              repeaty=1024, base=42)
    return noise_map

# Создание террейна
def create_terrain(width, height, x_offset, z_offset):
    noise_map = generate_noise_2d((width, height), x_offset, z_offset)
    vertices = []
    for i in range(width):
        for j in range(height):
            x = i - width // 2
            z = j - height // 2
            y = noise_map[i][j] * 10
            vertices.append((x, y, z))
    return vertices

# Генерация трубы с сохранением вершин и граней
def create_tube(vertices, radius, slices):
    tube_vertices = []
    tube_faces = []

    for i in range(len(vertices) - 1):
        v1 = np.array(vertices[i])
        v2 = np.array(vertices[i + 1])
        
        # Находим направление и длину между v1 и v2
        direction = v2 - v1
        length = np.linalg.norm(direction)
        direction /= length  # Нормализация

        # Вектор перпендикулярный направлению
        if np.linalg.norm(direction) == 0:
            continue
        perpendicular = np.cross(direction, np.array([0, 1, 0]))
        if np.linalg.norm(perpendicular) == 0:
            perpendicular = np.cross(direction, np.array([1, 0, 0]))
        
        perpendicular /= np.linalg.norm(perpendicular)  # Нормализация

        # Создание вершин и граней трубы
        for j in range(slices + 1):
            angle = 2 * np.pi * j / slices
            offset = radius * (np.cos(angle) * perpendicular + np.sin(angle) * np.cross(direction, perpendicular))
            current_vertex = v1 + offset
            
            tube_vertices.append(current_vertex)

            # Формирование граней
            if i < len(vertices) - 2:  # Проверка, чтобы не выйти за границы
                next_index = (i + 1) * (slices + 1) + j
                current_index = i * (slices + 1) + j
                next_j = (j + 1) % (slices + 1)

                # Создание двух треугольников
                tube_faces.append([current_index, next_index, next_index + 1])
                tube_faces.append([current_index, next_index + 1, current_index + 1])

    return tube_vertices, tube_faces

# Сохранение в OBJ файл
def save_to_obj(vertices, faces, filename):
    with open(filename, "w") as f:
        for vert in vertices:
            f.write(f"v {vert[0]:.4f} {vert[1]:.4f} {vert[2]:.4f}\n")
        for face in faces:
            f.write(f"f {face[0] + 1} {face[1] + 1} {face[2] + 1}\n")
    print(f"Model saved as {filename}")

# Функция для отрисовки трубы
def draw_tube(vertices, radius, slices):
    for i in range(len(vertices) - 1):
        v1 = np.array(vertices[i])
        v2 = np.array(vertices[i + 1])
        
        # Находим направление и длину между v1 и v2
        direction = v2 - v1
        length = np.linalg.norm(direction)
        direction /= length  # Нормализация

        # Вектор перпендикулярный направлению
        if np.linalg.norm(direction) == 0:
            continue
        perpendicular = np.cross(direction, np.array([0, 1, 0]))
        if np.linalg.norm(perpendicular) == 0:
            perpendicular = np.cross(direction, np.array([1, 0, 0]))
        
        perpendicular /= np.linalg.norm(perpendicular)  # Нормализация

        # Отрисовка трубы между v1 и v2
        glBegin(GL_QUAD_STRIP)
        for j in range(slices + 1):
            angle = 2 * np.pi * j / slices
            offset = radius * (np.cos(angle) * perpendicular + np.sin(angle) * np.cross(direction, perpendicular))
            
            glVertex3fv(v1 + offset)  # Вершина 1
            glVertex3fv(v2 + offset)  # Вершина 2
        glEnd()

# Основной цикл
width, height = 20, 20
x_offset = 0
z_offset = 0
clock = pygame.time.Clock()
tube_radius = 0.5
slices = 10

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                z_offset += 5
            if event.key == pygame.K_s:
                z_offset -= 5
            if event.key == pygame.K_a:
                x_offset -= 5
            if event.key == pygame.K_d:
                x_offset += 5
            if event.key == pygame.K_r:  # Сохранение на нажатие R
                desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
                terrain = create_terrain(width, height, x_offset, z_offset)
                tube_vertices, tube_faces = create_tube(terrain, tube_radius, slices)
                filename = os.path.join(desktop_path, "terrain_tube.obj")
                save_to_obj(tube_vertices, tube_faces, filename)

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    vertices = create_terrain(width, height, x_offset, z_offset)
    tube_vertices, _ = create_tube(vertices, tube_radius, slices)  # Создаем данные труб
    draw_tube(vertices, radius=tube_radius, slices=slices)  # Рисуем трубы
    pygame.display.flip()
    clock.tick(60)
MakarovDs вне форума Ответить с цитированием
Старый 13.11.2024, 10:55   #176
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Многоэтажные коридоры бэкрумс по одинаковому размеру
Код:
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
import os

def generate_delaunay_field(shape):
    array = np.zeros(shape, dtype=float)

    points = []
    for _ in range(50):  # 50 коридоров
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        z = shape[2] // 3  # Генерируем точки на фиксированной высоте
        points.append([x, y, z])

    points2 = []
    for _ in range(50):  # 50 коридоров
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        z = 2 * shape[2] // 3  # Генерируем точки на фиксированной высоте
        points2.append([x, y, z])

    points3 = []
    for _ in range(50):  # 50 коридоров
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        z = shape[2] // 6  # Генерируем точки на фиксированной высоте
        points3.append([x, y, z])

    for i in range(len(points) - 1):
        start_point = points[i]
        end_point = points[i + 1]

        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]

            for height_offset in range(-1, 5):  # Высота коридоров
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

        for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
            new_x = end_point[0]
            new_z = end_point[2]

            for height_offset in range(-1, 5):  # Высота коридоров
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

    for i in range(len(points2) - 1):
        start_point = points2[i]
        end_point = points2[i + 1]

        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]

            for height_offset in range(-1, 5):  # Высота коридоров
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

        for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
            new_x = end_point[0]
            new_z = end_point[2]

            for height_offset in range(-1, 5):  # Высота коридоров
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

    for i in range(len(points3) - 1):
        start_point = points3[i]
        end_point = points3[i + 1]

        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]

            for height_offset in range(-1, 5):  # Высота коридоров
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

        for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
            new_x = end_point[0]
            new_z = end_point[2]

            for height_offset in range(-1, 5):  # Высота коридоров
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

    for i in range(len(points)):
        start_point = points[i]
        end_point = points2[i]
        for new_z in range(min(start_point[2], end_point[2]), max(start_point[2], end_point[2]) + 1):
            if 0 <= start_point[0] < shape[0] and 0 <= start_point[1] < shape[1]:
                for height_offset in range(-1, 5):  # Высота коридоров
                    array[start_point[0], start_point[1], new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= start_point[0] + k < shape[0] and 0 <= start_point[1] + l < shape[1]:
                                array[start_point[0] + k, start_point[1] + l, new_z + height_offset] = 1.0

    for i in range(len(points2)):
        start_point = points2[i]
        end_point = points3[i]
        for new_z in range(min(start_point[2], end_point[2]), max(start_point[2], end_point[2]) + 1):
            if 0 <= start_point[0] < shape[0] and 0 <= start_point[1] < shape[1]:
                for height_offset in range(-1, 5):  # Высота коридоров
                    array[start_point[0], start_point[1], new_z + height_offset] = 1.0
                    for k in range(-2, 3):  # Ширина по x и y
                        for l in range(-2, 3):
                            if 0 <= start_point[0] + k < shape[0] and 0 <= start_point[1] + l < shape[1]:
                                array[start_point[0] + k, start_point[1] + l, new_z + height_offset] = 1.0

    return array

shape = (128, 128, 128)  # Размеры 3D массива

delaunay_field = generate_delaunay_field(shape)

verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='r', alpha=0.5)
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 13.11.2024, 12:48   #177
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Ребристые ривы
Код:
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
import noise
import os

pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)

gluPerspective(45, (display[0] / display[1]), 0.1, 1000.0)
glTranslatef(0.0, 0.0, -30)
glRotatef(45, 1, 0, 0)  # Повернуть камеру на 45 градусов вокруг оси X

def generate_noise_2d(shape, x_offset, z_offset, scale=100.0, octaves=6, persistence=0.5, lacunarity=2.0):
    noise_map = np.zeros(shape)
    for i in range(shape[0]):
        for j in range(shape[1]):
            noise_map[i][j] = noise.pnoise2((i + x_offset) / scale, (j + z_offset) / scale, octaves=octaves,
                                              persistence=persistence, lacunarity=lacunarity, repeatx=1024,
                                              repeaty=1024, base=42)
    return noise_map

def create_terrain(width, height, x_offset, z_offset):
    noise_map = generate_noise_2d((width, height), x_offset, z_offset)
    vertices = []
    for i in range(width):
        for j in range(height):
            x = i - width // 2
            z = j - height // 2
            y = noise_map[i][j] * 10
            vertices.append((x, y, z))
    return vertices

def create_tube(vertices, radius, slices):
    tube_vertices = []
    tube_faces = []

    for i in range(len(vertices) - 1):
        v1 = np.array(vertices[i])
        v2 = np.array(vertices[i + 1])

        direction = v2 - v1
        length = np.linalg.norm(direction)
        direction /= length  # Нормализация

        if np.linalg.norm(direction) == 0:
            continue
        perpendicular = np.cross(direction, np.array([0, 1, 0]))
        if np.linalg.norm(perpendicular) == 0:
            perpendicular = np.cross(direction, np.array([1, 0, 0]))
        
        perpendicular /= np.linalg.norm(perpendicular)  # Нормализация

        # Создание вершин и граней трубы
        for j in range(slices + 1):
            angle = 2 * np.pi * j / slices
            offset = radius * (np.cos(angle) * perpendicular + np.sin(angle) * np.cross(direction, perpendicular))
            current_vertex = v1 + offset
            
            tube_vertices.append(current_vertex)

            # Формирование граней
            if i < len(vertices) - 2:  # Проверка, чтобы не выйти за границы
                next_index = (i + 1) * (slices + 1) + j
                current_index = i * (slices + 1) + j
                next_j = (j + 1) % (slices + 1)

                # Создание двух треугольников
                tube_faces.append([current_index, next_index, next_index + 1])
                tube_faces.append([current_index, next_index + 1, current_index + 1])

    return tube_vertices, tube_faces

def save_to_obj(vertices, faces, filename):
    with open(filename, "w") as f:
        for vert in vertices:
            f.write(f"v {vert[0]:.4f} {vert[1]:.4f} {vert[2]:.4f}\n")
        for face in faces:
            f.write(f"f {face[0] + 1} {face[1] + 1} {face[2] + 1}\n")
    print(f"Model saved as {filename}")
    # Функция для отрисовки трубы

def draw_tube(vertices, width, height, radius, slices):
    # Отрисовка труб сверху вниз
    for i in range(width):
        for j in range(height - 1):
            v1 = np.array(vertices[i * height + j])
            v2 = np.array(vertices[i * height + j + 1])

            direction = v2 - v1
            length = np.linalg.norm(direction)
            direction /= length  # Нормализация

            perpendicular = np.cross(direction, np.array([1, 0, 0]))
            if np.linalg.norm(perpendicular) == 0:
                continue
            perpendicular /= np.linalg.norm(perpendicular)  # Нормализация

            # Отрисовка трубы между v1 и v2
            glBegin(GL_QUAD_STRIP)
            for k in range(slices + 1):
                angle = 2 * np.pi * k / slices
                offset = radius * (np.cos(angle) * perpendicular + np.sin(angle) * np.cross(direction, perpendicular))

                glVertex3fv(v1 + offset)  # Вершина 1
                glVertex3fv(v2 + offset)  # Вершина 2
            glEnd()

    # Отрисовка труб справа налево
    for j in range(height):
        for i in range(width - 1, 0, -1):
            v1 = np.array(vertices[j * height + i])
            v2 = np.array(vertices[j * height + i - 1])

            direction = v2 - v1
            length = np.linalg.norm(direction)
            direction /= length  # Нормализация

            perpendicular = np.cross(direction, np.array([0, 1, 0]))
            if np.linalg.norm(perpendicular) == 0:
                continue
            perpendicular /= np.linalg.norm(perpendicular)  # Нормализация

            glBegin(GL_QUAD_STRIP)
            for k in range(slices + 1):
                angle = 2 * np.pi * k / slices
                offset = radius * (np.cos(angle) * perpendicular + np.sin(angle) * np.cross(direction, perpendicular))

                glVertex3fv(v1 + offset)  # Вершина 1
                glVertex3fv(v2 + offset)  # Вершина 2
            glEnd()

width, height = 20, 20
x_offset = 0
z_offset = 0
clock = pygame.time.Clock()
tube_radius = 0.25
slices = 10

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                z_offset += 5
            if event.key == pygame.K_s:
                z_offset -= 5
            if event.key == pygame.K_a:
                x_offset -= 5
            if event.key == pygame.K_d:
                x_offset += 5
            if event.key == pygame.K_r:  # Сохранение на нажатие R
                desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
                terrain = create_terrain(width, height, x_offset, z_offset)
                tube_vertices, tube_faces = create_tube(terrain, tube_radius, slices)
                filename = os.path.join(desktop_path, "terrain_tube.obj")
                save_to_obj(tube_vertices, tube_faces, filename)

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    vertices = create_terrain(width, height, x_offset, z_offset)
    tube_vertices, _ = create_tube(vertices, tube_radius, slices)  # Создаем данные труб
    draw_tube(vertices, width, height, radius=tube_radius, slices=slices)  # Рисуем трубы
    pygame.display.flip()
    clock.tick(60)

Последний раз редактировалось MakarovDs; 14.11.2024 в 07:03.
MakarovDs вне форума Ответить с цитированием
Старый 14.11.2024, 09:11   #178
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Бэкрумс многоэтажный коридорный но между каждым коридором по одному переходу.
Код:
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
import os

def generate_delaunay_field(shape):
    array = np.zeros(shape, dtype=float)

    points = []
    for _ in range(50):  
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        z = shape[2] // 3  
        points.append([x, y, z])

    points2 = []
    for _ in range(50):  
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        z = 2 * shape[2] // 3  
        points2.append([x, y, z])

    points3 = []
    for _ in range(50):  
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        z = shape[2] // 6  
        points3.append([x, y, z])

    for i in range(len(points) - 1):
        start_point = points[i]
        end_point = points[i + 1]

        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]

            for height_offset in range(-1, 5):  
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

        for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
            new_x = end_point[0]
            new_z = end_point[2]

            for height_offset in range(-1, 5):  
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

    for i in range(len(points2) - 1):
        start_point = points2[i]
        end_point = points2[i + 1]

        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]

            for height_offset in range(-1, 5):  
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

        for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
            new_x = end_point[0]
            new_z = end_point[2]

            for height_offset in range(-1, 5):  
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

    for i in range(len(points3) - 1):
        start_point = points3[i]
        end_point = points3[i + 1]

        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]

            for height_offset in range(-1, 5):  
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

        for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
            new_x = end_point[0]
            new_z = end_point[2]

            for height_offset in range(-1, 5):  
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0
                    for k in range(-2, 3):  
                        for l in range(-2, 3):
                            if 0 <= new_x + k < shape[0] and 0 <= new_y + l < shape[1]:
                                array[new_x + k, new_y + l, new_z + height_offset] = 1.0

    for i in range(len(points)):
        start_point = points[i]
        end_point = points2[i]
        if i == 0:  # только для первого соединения
            for new_z in range(min(start_point[2], end_point[2]), max(start_point[2], end_point[2]) + 1):
                if 0 <= start_point[0] < shape[0] and 0 <= start_point[1] < shape[1]:
                    for height_offset in range(-1, 5):  
                        array[start_point[0], start_point[1], new_z + height_offset] = 1.0
                        for k in range(-2, 3):  
                            for l in range(-2, 3):
                                if 0 <= start_point[0] + k < shape[0] and 0 <= start_point[1] + l < shape[1]:
                                    array[start_point[0] + k, start_point[1] + l, new_z + height_offset] = 1.0

    for i in range(len(points2)):
        start_point = points2[i]
        end_point = points3[i]
        if i == 0:  # только для первого соединения
            for new_z in range(min(start_point[2], end_point[2]), max(start_point[2], end_point[2]) + 1):
                if 0 <= start_point[0] < shape[0] and 0 <= start_point[1] < shape[1]:
                    for height_offset in range(-1, 5):  
                        array[start_point[0], start_point[1], new_z + height_offset] = 1.0
                        for k in range(-2, 3):  
                            for l in range(-2, 3):
                                if 0 <= start_point[0] + k < shape[0] and 0 <= start_point[1] + l < shape[1]:
                                    array[start_point[0] + k, start_point[1] + l, new_z + height_offset] = 1.0

    return array

shape = (128, 128, 128)  

delaunay_field = generate_delaunay_field(shape)

verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='r', alpha=0.5)
plt.show()

Последний раз редактировалось MakarovDs; 14.11.2024 в 09:25.
MakarovDs вне форума Ответить с цитированием
Старый 14.11.2024, 13:42   #179
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Плитка жесткая на стену
Код:
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
import trimesh
import os

def generate_delaunay_field(shape):
    array = np.zeros(shape, dtype=float)

    points2 = []
    for _ in range(50):  
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        z = 2 * shape[2] // 3  
        points2.append([x, y, z])

    for i in range(len(points2) - 1):
        start_point = points2[i]
        end_point = points2[i + 1]

        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]

            for height_offset in range(-1, 5):  
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1]:
                    array[new_x, new_y, new_z + height_offset] = 1.0

    return array

shape = (128, 128, 128)  

delaunay_field = generate_delaunay_field(shape)

# Generate a mesh from your array
verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for vert in verts:
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='r', alpha=0.5)
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 15.11.2024, 05:36   #180
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 380
По умолчанию

Палеты
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
import os

def generate_hair(shape, hair_density, direction):
    # Создаем 3D массив для волос
    hair = np.zeros(shape, dtype=float)

    # Генерируем волосы в заданном направлении
    for x in range(shape[0]):
        for y in range(shape[1]):
            if np.random.rand() < hair_density:
                if direction == 'up':
                    hair[x, y, :] = np.linspace(0, 1, shape[2])
                elif direction == 'down':
                    hair[x, y, :] = np.linspace(1, 0, shape[2])
                elif direction == 'left':
                    hair[:, x, y] = np.linspace(0, 1, shape[0])
                elif direction == 'right':
                    hair[:, x, y] = np.linspace(1, 0, shape[0])

    return hair

def generate_floor_surface(shape, floor_z):
    # Создаем 3D массив для пола
    floor = np.zeros(shape, dtype=float)

    # Генерируем пол на заданной высоте
    for x in range(shape[0]):
        for y in range(shape[1]):
            floor[x, y, floor_z] = 1.0

    return floor

# Параметры
shape = (64, 64, 64)  # Размеры 3D массива
hair_density = 0.1  # Плотность волос
floor_z = 0  # Высота пола

# Генерация волос вверх
hair_up = generate_hair(shape, hair_density, 'up')

# Генерация волос вниз
hair_down = generate_hair(shape, hair_density, 'down')

# Генерация волос влево
hair_left = generate_hair(shape, hair_density, 'left')

# Генерация волос вправо
hair_right = generate_hair(shape, hair_density, 'right')

# Генерация пола под волосами
floor = generate_floor_surface(shape, floor_z)

# Объединение волос и пола логическим оператором "или"
hair = np.logical_or(np.logical_or(np.logical_or(hair_up, hair_down), np.logical_or(hair_left, hair_right)), floor).astype(float)

# Создание изосурфейса
verts, faces, _, _ = measure.marching_cubes(hair, level=0.5)

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "hair.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], faces, verts[:, 2], color='r', alpha=0.5)
plt.show()

Последний раз редактировалось MakarovDs; 15.11.2024 в 05:45.
MakarovDs вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
помогите с генератором слов Мой повелитель Общие вопросы C/C++ 6 27.02.2016 23:46
Зарубежные микроконтроллеры с встроенным ШИМ-генератором MyLastHit Компьютерное железо 6 22.10.2013 14:33
написание генератора фракталов Жюлиа kyzmich2370 Visual C++ 1 06.11.2012 09:57
Помогите с генератором чисел на Pascal vadmaruschak Помощь студентам 6 13.09.2009 17:06
Игры фракталов на VB Kail Свободное общение 1 29.05.2009 09:30