示例#1
0
def rasterize_triangle(face, m_matrix=None, light=None, *args, **kwargs):
    vertices = [np.array(v) for v, _ in face]
    normals = [np.array(vn) for _, vn in face]
    # Basic shading
    v_ab = vertices[1] - vertices[0]
    v_ac = vertices[2] - vertices[0]
    # v_n = Vector(np.cross(v_ab, v_ac)).normalized()
    # centroid = np.mean(vertices, axis=0)

    # diffuse_intensity = max(0, v_n.dot(Vector(light - centroid).normalized()))
    diffuse_intensities = [
        max(0,
            Vector(v_n).normalized().dot(Vector(light - v).normalized()))
        for v, v_n in face
    ]

    # projection onto 2D - strip z value
    # vertices = [v[:2] for v in vertices]
    vertices = map(screen.rescale_point, vertices)
    # triangle.draw(vertices, wireframe=True)
    # triangle.draw(vertices, wireframe=False, shading=diffuse_intensity)
    triangle.draw(vertices,
                  normals,
                  wireframe=False,
                  shadings=diffuse_intensities,
                  light_pt=light,
                  *args,
                  **kwargs)
示例#2
0
 def __init__(self, x=0, y=0, amount=FOOD_AMOUNT, random=False):
     self.id = uuid.uuid4()
     self.body = Point(x=x, y=y, color=(0, 255, 0), random=random)
     if random:
         self.position = Vector(self.body.x, self.body.y)
     else:
         self.position = Vector(x, y)
     self.amount = amount
示例#3
0
def test_rotation_matrix_2d():
    y = Vector(1, 0)

    assert close_enough(rotation_2d(deg=90) * y, Vector(0, 1))
    assert close_enough(rotation_2d(deg=-270) * y, Vector(0, 1))
    assert close_enough(rotation_2d(deg=170) * y, rotation_2d(deg=-190) * y)
    assert close_enough(rotation_2d(deg=360) * y, y)
    assert close_enough(rotation_2d(rad=2 * pi) * y, y)
示例#4
0
 def on_key_press(self, symbol, modifiers):
     creatures = self.creature_manager.creatures.values()
     if symbol == key.D:  # right
         vel = Vector(1, 0)
         for creature in creatures:
             creature.move(vel)
     if symbol == key.S:  # down
         vel = Vector(0, -1)
         for creature in creatures:
             creature.move(vel)
     if symbol == key.A:  # left
         vel = Vector(-1, 0)
         for creature in creatures:
             creature.move(vel)
     if symbol == key.W:  # up
         vel = Vector(0, 1)
         for creature in creatures:
             creature.move(vel)
示例#5
0
def specular(v, v_n, view_pt, light_pt, coef=10):
    v_n /= normalize(v_n)
    view_pt = view_pt[0][:3]
    v_i = v - light_pt
    v_i /= normalize(v_i)

    v_reflected = -v_i - 2 * -v_i.dot(v_n) * v_n
    v_viewer = Vector(view_pt - v).normalized().dir
    intensity_specular = max(v_reflected.dot(v_viewer), 0.)
    intensity_specular = pow(intensity_specular, coef)
    return intensity_specular
示例#6
0
    def __call__(self, point):
        a, b, c, d = self.matrix.ravel()

        if isinstance(point, (int, float, complex)):
            if infinite(point):
                return a / c
            else:
                return (a * point + b) / (c * point + d)

        elif isinstance(point, Vector):
            if infinite(point):
                return Vector.from_complex(a / c)
            else:
                qa = Vector.from_complex(a)
                qb = Vector.from_complex(b)
                qc = Vector.from_complex(c)
                qd = Vector.from_complex(d)
                return (qa * point + qb) / (qc * point + qd)

        else:
            raise TypeError("A complex number or a vector is expected.")
示例#7
0
    def walk(self, direction=None):
        self.spend_energy(0.1)

        if direction is None:
            acc = Vector(randint(-MAX_SPEED, MAX_SPEED),
                         randint(-MAX_SPEED, MAX_SPEED))
        else:
            acc = Vector(*direction)
        if self.velocity.x >= MAX_SPEED and acc.x < 0:
            self.velocity.x += acc.x
        elif self.velocity.x <= -MAX_SPEED and acc.x > 0:
            self.velocity.x += acc.x
        if self.velocity.y >= MAX_SPEED and acc.y < 0:
            self.velocity.y += acc.y
        elif self.velocity.y <= -MAX_SPEED and acc.y > 0:
            self.velocity.y += acc.y
        if -MAX_SPEED <= self.velocity.x <= MAX_SPEED:
            self.velocity.x += acc.x
        if -MAX_SPEED <= self.velocity.y <= MAX_SPEED:
            self.velocity.y += acc.y
        self.last_action = [0, acc[0], acc[1]]
        self.move(self.velocity)
示例#8
0
def test_matrix_vector_multiplication():
    result = []
    for i in range(rownum):
        result.append(Vector(A[i]).dot(x))

    y = Vector(result)
    assert A * x == y
    assert x * A == y

    # multiply column by column
    result = Vector.zero(size=rownum)
    AT = tuple(A.transpose().vectorize_rows())
    for i in range(rownum):
        result = result + AT[i] * x.components[i]

    assert result == A * x

    # multiply column by column (using axpy)
    result = Vector.zero(size=rownum)
    AT = tuple(A.transpose().vectorize_rows())
    for i in range(rownum):
        result = axpy(AT[i], x.components[i], result)

    assert result == A * x
示例#9
0
import random
from math import pi

from helpers.comparison import close_enough
from operations.matrix import rotation_2d
from operations.vector import axpy
from primitives import Matrix, Vector

rownum = 10
colnum = 10

rows = [[random.uniform(-100, 100) for i in range(colnum)]
        for j in range(rownum)]
cols = zip(*rows)

x = Vector(random.uniform(-100, 100) for i in range(colnum))
A = Matrix(rows=rows)


def test_creation():
    rows2 = [
        [0, 0, 0],
        [1, 1, 1],
        [2, 2, 2],
        [3, 3, 3],
    ]
    cols2 = [
        [0, 1, 2, 3],
        [0, 1, 2, 3],
        [0, 1, 2, 3],
    ]
示例#10
0
def test_creation():
    assert Vector(1) == Vector((1, )) == Vector([1])
    assert Vector(1, 2, 3) == Vector((1, 2, 3)) == Vector([1, 2, 3])
示例#11
0
def test_subtraction():
    assert a - b == Vector(map(sub, a_coords, b_coords))
    assert a - b == -1 * (b - a)
示例#12
0
def test_multiplication():
    assert a * scalar == Vector(ai * scalar for ai in a.components)
    assert scalar * a == Vector(ai * scalar for ai in a.components)
示例#13
0
def test_getting_subvector():
    assert a[1] == Vector(a.components[1])
    assert a[2:5] == Vector(*a.components[2:5])
    assert a[-4] == Vector(a.components[-4])
示例#14
0
def test_addition():
    assert a + b == Vector(map(add, a_coords, b_coords))
    assert a + b == b + a
示例#15
0
def test_zero_creation():
    assert Vector.zero(2) == Vector(0, 0)
    assert Vector.zero(5) == Vector(0, 0, 0, 0, 0)
示例#16
0
def test_vector_splitting_to_basis_products():
    product_vector = Vector.zero(len(a))
    for i, component in enumerate(a):
        product_vector += Vector.basis(i, len(a)) * component

    assert product_vector == a
示例#17
0
from primitives import Vector, Matrix

if __name__ == '__main__':
    x = Vector(1, -2, 3)
    print(x)

    rows = [
        [0, 0, 0],
        [1, 1, 1],
        [2, 2, 2],
        [3, 3, 3],
    ]
    A = Matrix(rows=rows)
    print(A)

    print(A * x)
示例#18
0
def test_basis_creation():
    assert Vector.basis(0, 2) == Vector(1, 0)
    assert Vector.basis(3, 6) == Vector(0, 0, 0, 1, 0, 0)
示例#19
0
 def zero(cls, m: int, n: int) -> 'Matrix':
     """
     Returns the zero matrix of given dimensions
     """
     return cls(rows=(Vector.zero(n) for _ in range(m)))
示例#20
0
文件: main.py 项目: ramAdam/wolf3D
from pyglet.window import Window
import pyglet
from primitives import Segment, Vector, Point
from view import Fov
import pdb
import math

window = Window(800, 600)
x1, y1 = (400, 300)

# parameters for segment
a = Vector(x1, y1)
length = 100
angle = 45

seg = Segment(a, length, angle)

fieldofview = Fov(a, angle, length)
print(fieldofview.getFov())
nAngle = 45
# seg.rotate(nAngle)


def update(dt):
    global nAngle
    # pdb.set_trace()
    if nAngle == 360:
        nAngle = 45

    seg.rotate(nAngle)
    nAngle += 45
示例#21
0
 def identity(cls, m: int) -> 'Matrix':
     """
     Returns the identity matrix m by m
     """
     return cls(rows=(Vector.basis(i, m) for i in range(m)))
示例#22
0
 def vectorize_rows(self) -> Iterable[Vector]:
     """
     Returns components as iterator where each row is represented by a Vector
     """
     return (Vector(row) for row in self.components)
示例#23
0
 def __mul__(self, other: Vector):
     return Vector(Vector(row).dot(other) for row in self.components)
示例#24
0
import random
from math import sqrt
from operator import add, sub, mul

from helpers.comparison import close_enough
from operations.vector import axpy, linear_combination
from primitives import Vector

# init values, we use random values because the code should work
# for all vector lengths / all kinds of float values

vector_size = 10
a_coords = tuple(random.uniform(-100, 100) for _ in range(vector_size))
b_coords = tuple(random.uniform(-100, 100) for _ in range(vector_size))

a = Vector(*a_coords)
b = Vector(*b_coords)

scalar = random.uniform(-100, 100)


def test_creation():
    assert Vector(1) == Vector((1, )) == Vector([1])
    assert Vector(1, 2, 3) == Vector((1, 2, 3)) == Vector([1, 2, 3])


def test_basis_creation():
    assert Vector.basis(0, 2) == Vector(1, 0)
    assert Vector.basis(3, 6) == Vector(0, 0, 0, 1, 0, 0)

示例#25
0
    def __init__(self,
                 x=0,
                 y=0,
                 random=False,
                 show_vision=False,
                 dna=None,
                 **kwargs):
        self.id = uuid.uuid4()
        self.life = 100
        self._alive = True
        self.genes = 15
        self.age = 0
        self.memory_s = []
        self.memory_a = []
        self.all_memory = None
        if kwargs.get('old_memory', None):
            self.all_memory = [x[:] for x in kwargs['old_memory']]
        if not dna:
            layers = randint(2, 100)
            neurons = randint(2, 100)
            iters = randint(2, 100)
            memorysize = randint(2, 100)
            # [Layers, neurons, iters , memory]
            self.dna = [layers, neurons, iters, memorysize]
        else:
            self.dna = dna

        self._hidden_layers = [self.dna[1] for _ in range(self.dna[0])]
        self._max_memory = self.dna[3]
        self.brain = MLPRegressor(activation='logistic',
                                  alpha=1e-05,
                                  batch_size='auto',
                                  beta_1=0.9,
                                  beta_2=0.999,
                                  early_stopping=False,
                                  epsilon=1e-08,
                                  hidden_layer_sizes=self._hidden_layers,
                                  learning_rate='constant',
                                  learning_rate_init=0.001,
                                  max_iter=self.dna[2] * 100,
                                  momentum=0.9,
                                  nesterovs_momentum=True,
                                  power_t=0.5,
                                  random_state=1,
                                  shuffle=True,
                                  solver='adam',
                                  tol=0.0001,
                                  validation_fraction=0.1,
                                  verbose=False,
                                  warm_start=False)

        if random:
            x = randint(0, WIDTH)
            y = randint(0, HEIGHT)
        self.body = Triangle(x=x, y=y, random=False)
        self.vision = Circle(x=x, y=y, radius=VISION_RADIUS)
        self.show_vision = show_vision
        self.position = Vector(x, y)
        self.velocity = Vector(0, 0)
        self.aceleration = Vector(0, 0)
        self.mass = 10
        self.visible_objects = []
        self.last_action = [0, 0, 0]

        if self.all_memory is None:
            start_sensor = [[randint(-5, 5), randint(-5, 5)]
                            for _ in range(10)]
            start_out = [[randint(0, 1),
                          randint(-5, 5),
                          randint(-5, 5)] for _ in range(10)]
            self.all_memory = [start_sensor, start_out]
        else:
            if np.random.random() < RANDOM_MEMORY:
                # creating some random memories
                self.all_memory[0] += [[randint(-5, 5), randint(-5, 5)]]
                self.all_memory[1] += [[
                    randint(0, 1),
                    randint(-5, 5),
                    randint(-5, 5)
                ]]
            start_sensor = self.all_memory[0]
            start_out = self.all_memory[1]
        try:
            self.brain.fit(start_sensor, start_out)
        except:
            print(start_sensor, start_out)
            raise ValueError