阴影投射优化 Python

Optimisation of Shadow Casting Python

我一直在为我正在做的一个小型角色扮演游戏开发 Shadow Caster。

我遇到的问题是,当我在我的游戏中使用它时,它只是减慢速度并导致可怕的延迟的方式。

请不要被 post 的长度吓到。它相当简单,但您可以 运行 我也包含所有 Bresenham 算法的代码。

原理如下: - 制作黑色表面 - 定义具有位置和半径的光源。 - 使用 Bresenham 的圆算法获取由该位置和半径定义的圆周上的所有点。 - 对于沿圆周的每个点,使用 Bresenham 的直线算法从光源的位置绘制一条 ligne。 - 然后遍历直线上的点并检查它们是否与屏幕上显示的每个障碍物发生碰撞。 - 如果没有碰撞,绘制一个以该点为中心、半径为 10 像素左右的白色圆圈。 - 如果发生碰撞,则沿圆周移动到下一个点。 - 最后用黑色的透明度值为 100 和白色的完全透明的表面上的所有白色圆圈对表面进行 blit。

到目前为止,我尝试了以下操作: 这确实减少了滞后: - 将障碍物列表限制在屏幕上显示的那些 - 将屏幕边缘视为障碍,以减少不可见区域的迭代。 - 仅围绕圆圈每 3 个点和沿直线的 12 个点进行迭代。 这没有改变任何东西: - 使用从光源到范围边缘或障碍物的椭圆而不是沿线的许多圆圈。问题是我必须为每个椭圆重新绘制表面,然后旋转整个椭圆。

如果您对如何提高效率有任何建议,我很乐意提供。

Bresenham 线算法:

def get_line(start, end):
    """Bresenham's Line Algorithm
    Produces a list of tuples from start and end

    >>> points1 = get_line((0, 0), (3, 4))
    >>> points2 = get_line((3, 4), (0, 0))
    >>> assert(set(points1) == set(points2))
    >>> print points1
    [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
    >>> print points2
    [(3, 4), (2, 3), (1, 2), (1, 1), (0, 0)]
    """
    # Setup initial conditions
    x1, y1 = start
    x2, y2 = end
    dx = x2 - x1
    dy = y2 - y1

    # Determine how steep the line is
    is_steep = abs(dy) > abs(dx)

    # Rotate line
    if is_steep:
        x1, y1 = y1, x1
        x2, y2 = y2, x2

    # Swap start and end points if necessary and store swap state
    swapped = False
    if x1 > x2:
        x1, x2 = x2, x1
        y1, y2 = y2, y1
        swapped = True

    # Recalculate differentials
    dx = x2 - x1
    dy = y2 - y1

    # Calculate error
    error = int(dx / 2.0)
    ystep = 1 if y1 < y2 else -1

    # Iterate over bounding box generating points between start and end
    y = y1
    points = []
    for x in range(x1, x2 + 1):
        coord = (y, x) if is_steep else (x, y)
        points.append(coord)
        error -= abs(dy)
        if error < 0:
            y += ystep
            error += dx

    # Reverse the list if the coordinates were swapped
    if swapped:
        points.reverse()
    return points

Bresenham 圆算法:

def get_circle((dx,dy),radius):
    "Bresenham complete circle algorithm in Python"
    # init vars
    switch = 3 - (2 * radius)
    points = set()
    x = 0
    y = radius
    # first quarter/octant starts clockwise at 12 o'clock
    while x <= y:
        # first quarter first octant
        points.add((x,-y))
        # first quarter 2nd octant
        points.add((y,-x))
        # second quarter 3rd octant
        points.add((y,x))
        # second quarter 4.octant
        points.add((x,y))
        # third quarter 5.octant
        points.add((-x,y))        
        # third quarter 6.octant
        points.add((-y,x))
        # fourth quarter 7.octant
        points.add((-y,-x))
        # fourth quarter 8.octant
        points.add((-x,-y))
        if switch < 0:
            switch = switch + (4 * x) + 6
        else:
            switch = switch + (4 * (x - y)) + 10
            y = y - 1
        x = x + 1
    offset_points = set()
    for pt in points:
        offset_points.add((pt[0]+dx,pt[1]+dy))

    return offset_points

def shadow_gen(shadow_surf,source,cir_pt,obstacles):
    line_points = get_line(source.pos,cir_pt)
    for line_pt in line_points[0::12]:
        for obs in obstacles:
            pygame.draw.circle(shadow_surf, WHITE, line_pt, 20, 0) #radius to 5px and 0 to fill the circle
            if obs.rect.collidepoint(line_pt) or pygame.Rect(0,0,500,500).collidepoint(line_pt) == False:
                return

我的 类 光源、障碍物和阴影掩模:

class Obstacle(object):
    def __init__(self,x,y):
        self.surf = pygame.Surface((150,150))
        self.rect = pygame.Rect((x,y),(150,150))
        self.surf.fill(pygame.color.Color('blue'))

class Light_Source(object):
    def __init__(self,x,y,range_):
        self.range = range_
        self.pos = (x,y)


class Night_Mask(object):
    def __init__(self):
        self.surf = pygame.Surface((500,500)) #Screenwidth and height
        self.alpha = 100
        self.light_sources = []

        '''setting initial alpha and colorkey'''
        self.surf.set_colorkey(WHITE)
        self.surf.set_alpha(self.alpha)


    def apply_shadows(self, obstacles):
        shadow_surf = pygame.Surface((500,500))
        for source in self.light_sources:
            circle_pts = list(get_circle(source.pos,source.range))
            for cir_pt in circle_pts[0::3]:
                shadow_gen(shadow_surf,source,cir_pt,obstacles)
        self.surf.blit(shadow_surf, (0, 0))

阴影生成功能允许我在 Night_Mask class class 的 apply_shadows 方法中不使用异常就可以突破线和障碍物循环:

def shadow_gen(shadow_surf,source,cir_pt,obstacles):
    line_points = get_line(source.pos,cir_pt)
    for line_pt in line_points[0::12]:
        for obs in obstacles:
            pygame.draw.circle(shadow_surf, WHITE, line_pt, 20, 0) #radius to 5px and 0 to fill the circle
            if obs.rect.collidepoint(line_pt) or pygame.Rect(0,0,500,500).collidepoint(line_pt) == False:
                return

最后 pygame 示例循环到 运行 以上所有内容:

pygame.init()
screen = pygame.display.set_mode((500, 500))

bg = pygame.Surface((500,500))
bg.fill(pygame.color.Color('yellow'))

ob_a = Obstacle(75,80)
ls = Light_Source(75,75,300)
night_m = Night_Mask()
night_m.light_sources.extend([ls])

while True:  
    screen.fill(pygame.color.Color('black'))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    ls.pos = pygame.mouse.get_pos()

    night_m.apply_shadows([ob_a])

    screen.blit(bg, (0,  0))
    screen.blit(ob_a.surf,ob_a.rect)
    screen.blit(night_m.surf, (0, 0))

    pygame.display.flip()

以下是从头到尾的完整代码,便于复制粘贴:

import pygame
import sys

WHITE = (255,255,255)
'''FUNCTIONS'''
def get_line(start, end):
    """Bresenham's Line Algorithm
    Produces a list of tuples from start and end

    >>> points1 = get_line((0, 0), (3, 4))
    >>> points2 = get_line((3, 4), (0, 0))
    >>> assert(set(points1) == set(points2))
    >>> print points1
    [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
    >>> print points2
    [(3, 4), (2, 3), (1, 2), (1, 1), (0, 0)]
    """
    # Setup initial conditions
    x1, y1 = start
    x2, y2 = end
    dx = x2 - x1
    dy = y2 - y1

    # Determine how steep the line is
    is_steep = abs(dy) > abs(dx)

    # Rotate line
    if is_steep:
        x1, y1 = y1, x1
        x2, y2 = y2, x2

    # Swap start and end points if necessary and store swap state
    swapped = False
    if x1 > x2:
        x1, x2 = x2, x1
        y1, y2 = y2, y1
        swapped = True

    # Recalculate differentials
    dx = x2 - x1
    dy = y2 - y1

    # Calculate error
    error = int(dx / 2.0)
    ystep = 1 if y1 < y2 else -1

    # Iterate over bounding box generating points between start and end
    y = y1
    points = []
    for x in range(x1, x2 + 1):
        coord = (y, x) if is_steep else (x, y)
        points.append(coord)
        error -= abs(dy)
        if error < 0:
            y += ystep
            error += dx

    # Reverse the list if the coordinates were swapped
    if swapped:
        points.reverse()
    return points

def get_circle((dx,dy),radius):
    "Bresenham complete circle algorithm in Python"
    # init vars
    switch = 3 - (2 * radius)
    points = set()
    x = 0
    y = radius
    # first quarter/octant starts clockwise at 12 o'clock
    while x <= y:
        # first quarter first octant
        points.add((x,-y))
        # first quarter 2nd octant
        points.add((y,-x))
        # second quarter 3rd octant
        points.add((y,x))
        # second quarter 4.octant
        points.add((x,y))
        # third quarter 5.octant
        points.add((-x,y))        
        # third quarter 6.octant
        points.add((-y,x))
        # fourth quarter 7.octant
        points.add((-y,-x))
        # fourth quarter 8.octant
        points.add((-x,-y))
        if switch < 0:
            switch = switch + (4 * x) + 6
        else:
            switch = switch + (4 * (x - y)) + 10
            y = y - 1
        x = x + 1
    offset_points = set()
    for pt in points:
        offset_points.add((pt[0]+dx,pt[1]+dy))

    return offset_points

def shadow_gen(shadow_surf,source,cir_pt,obstacles):
    line_points = get_line(source.pos,cir_pt)
    for line_pt in line_points[0::12]:
        for obs in obstacles:
            pygame.draw.circle(shadow_surf, WHITE, line_pt, 20, 0) #radius to 5px and 0 to fill the circle
            if obs.rect.collidepoint(line_pt) or pygame.Rect(0,0,500,500).collidepoint(line_pt) == False:
                return

'''CLASSES'''                
class Obstacle(object):
    def __init__(self,x,y):
        self.surf = pygame.Surface((150,150))
        self.rect = pygame.Rect((x,y),(150,150))
        self.surf.fill(pygame.color.Color('blue'))

class Light_Source(object):
    def __init__(self,x,y,range_):
        self.range = range_
        self.pos = (x,y)


class Night_Mask(object):
    def __init__(self):
        self.surf = pygame.Surface((500,500)) #Screenwidth and height
        self.alpha = 100
        self.light_sources = []


        '''setting initial alpha and colorkey'''
        self.surf.set_colorkey(WHITE)
        self.surf.set_alpha(self.alpha)


    def apply_shadows(self, obstacles):
        shadow_surf = pygame.Surface((500,500))
        for source in self.light_sources:
            circle_pts = list(get_circle(source.pos,source.range))
            for cir_pt in circle_pts[0::3]:
                shadow_gen(shadow_surf,source,cir_pt,obstacles)
        self.surf.blit(shadow_surf, (0, 0))


'''MAIN GAME'''
pygame.init()
screen = pygame.display.set_mode((500, 500))

bg = pygame.Surface((500,500))
bg.fill(pygame.color.Color('yellow'))

ob_a = Obstacle(75,80)
ls = Light_Source(75,75,300)
night_m = Night_Mask()
night_m.light_sources.extend([ls])

while True:  
    screen.fill(pygame.color.Color('black'))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    ls.pos = pygame.mouse.get_pos()

    night_m.apply_shadows([ob_a])

    screen.blit(bg, (0,  0))
    screen.blit(ob_a.surf,ob_a.rect)
    screen.blit(night_m.surf, (0, 0))

    pygame.display.flip()

您的延迟问题似乎来自方法 Night_Mask.apply_shadows(self, obstacles)。这似乎是由于嵌套 for 循环需要经历的纯迭代次数。

Light_Source(x, y, range_)的构造函数中减小range_的值,通过减少上述方法的迭代次数来减少延迟,但视觉效果更差。我发现在设置变量超过 ~65-70 后,fps 开始真正下降。

有一个 Pygame 图形库,可以很好地处理阴影。

Link到页面:http://pygame.org/project-Pygame+Advanced+Graphics+Library-660-4586.html 直接从站点下载 8.1.1 版:link

这是来自网站的图书馆描述:

This is an all purpose graphics library for easily creating complicated effects quickly, and with a minimum of code. Run the very well commented examples, each less than a page long (not counting comments), and learn how to make complicated effects like shadows and antialiasing.

这是页面中的一张图片,显示了阴影示例。

我下载并测试了这个库,效果很好。我在 Pygame1.9.2a0 上测试了 python 3.4

我相信这是解决您问题的最简单方法,并且应该对您以后的项目也有帮助。希望对您有所帮助。