def cylinderSDF(p, h, r): inOutRadius = glm.length(p.xy) - r inOutHeight = glm.abs(p.z) - h / 2.0 insideDistance = glm.min(glm.max(inOutRadius, inOutHeight), 0.0) outsideDistance = glm.length( glm.max(glm.vec2(inOutRadius, inOutHeight), 0.0)) return insideDistance + outsideDistance
def scatter(self, r_in, rec, attenuation, scattered): outward_normal = glm.vec3 reflected = glm.vec3(reflect(r_in.direction, rec.normal)) attenuation = glm.vec3(1.0, 1.0, 1.0) refracted = glm.vec3 if (glm.dot(r_in.direction, rec.normal) > 0): outward_normal = -rec.normal ni_over_nt = self.ref_idx cosine = self.ref_idx * glm.dot( r_in.direction, rec.normal) / glm.length(r_in.direction) else: outward_normal = rec.normal ni_over_nt = 1.0 / self.ref_idx cosine = -glm.dot(r_in.direction, rec.normal) / glm.length( r_in.direction) x, refracted = refract(r_in.direction, outward_normal, ni_over_nt, refracted) if (x == True): reflect_prob = schlick(cosine, self.ref_idx) else: scattered = Ray(rec.p, reflected) reflect_prob = 1.0 if (ran() < reflect_prob): scattered = Ray(rec.p, reflected) else: scattered = Ray(rec.p, refracted) return (True, scattered, attenuation)
def mandelbulbSDF(pos, iterations, power): julia = False juliaC = glm.vec3(0, 0, 0) #(-2, -2, -2) to (2, 2, 2) orbitTrap = glm.vec4(10000) colorIterations = 9 #0 to 100 bailout = 5 #0 to 30 alternateVersion = False rotVector = glm.vec3(1, 1, 1) #(0, 0, 0) to (1, 1, 1) rotAngle = 0 #0 to 180(?) rot = rotationMatrix3(glm.normalize(rotVector), rotAngle) z = pos dr = 1 i = 0 r = glm.length(z) while r < bailout and i < iterations: if alternateVersion: z, dr = powN2(z, r, dr, power) else: z, dr = powN1(z, r, dr, power) z += juliaC if julia else pos r = glm.length(z) z *= rot if i < colorIterations: orbitTrap = min(orbitTrap, abs(glm.vec4(z.x, z.y, z.z, r * r))) i += 1 return 0.5 * numpy.log(r) * r / dr
def processaColisao(self, corpoA, corpoB): #impacto de corpos if corpoA.near(corpoB, 2.0): #calcula a forca forcaA = corpoA.calcForce() forcaB = corpoB.calcForce() amplitudeForcaA = glm.length(forcaA) amplitudeForcaB = glm.length(forcaB) forcaResultante = glm.vec3() if amplitudeForcaA > amplitudeForcaB: forcaResultante = forcaA - forcaB else: forcaResultante = forcaB - forcaA #remove o corpo de menor massa if corpoA.massa >= corpoB.massa: corpoA.massa += corpoB.massa corpoA.impact(forcaResultante) corpoB.enable = False else: corpoB.massa += corpoA.massa corpoB.impact(forcaResultante) corpoA.enable = False
def getTranslationRotationMatricesForCircles(mesh): rms, tms = [], [] v_n0 = glm.vec3(0.0, 1.0, 0.0) # normal vector of first circle area! for i in range(0, n): # 0,... n - 1 (= last position of the pose) p_i = mesh.positions[ i] # each mesh contains the positions p_i of the pose rm, tm = glm.mat4(), glm.mat4() # initialize unit matrices tm = glm.translate(tm, glm.vec3(p_i[0], p_i[1], p_i[2])) # each p_i: [x, y, z] tms.append(tm) # if first pose position: if i == 0: rms.append(rm) # append a unit matrix = no rotation continue # if last pose position: if i == n - 1: # position vector at: i-1 p_i_prev = glm.vec3(mesh.positions[i - 1][0], mesh.positions[i - 1][1], mesh.positions[i - 1][2]) # normalized gradient vector at p_i: v_ni = glm.normalize(p_i - p_i_prev) if v_ni == v_n0: rms.append(rm) # append a unit matrix = no rotation continue angle = glm.acos(glm.length(v_n0 * v_ni)) # get the rotation angle rot_axis = glm.cross(v_n0, v_ni) # get the rotation axis rm = glm.rotate(rm, angle, rot_axis) rms.append(rm) # append the rotation matrix continue # position vector at: i+1 p_i_next = glm.vec3(mesh.positions[i + 1][0], mesh.positions[i + 1][1], mesh.positions[i + 1][2]) # position vector at: i-1 p_i_prev = glm.vec3(mesh.positions[i - 1][0], mesh.positions[i - 1][1], mesh.positions[i - 1][2]) # normalized gradient vector at p_i: v_ni = glm.normalize(p_i_next - p_i_prev) if v_ni == v_n0: rms.append(rm) # append a unit matrix = no rotation continue angle = glm.acos(glm.length(v_n0 * v_ni)) # get the rotation angle rot_axis = glm.cross(v_n0, v_ni) # get the rotation axis rm = glm.rotate(rm, angle, rot_axis) rms.append(rm) # append the rotation matrix return rms, tms
def seekPosition(self, worldOriginPosition, worldDestinationPosition): # positions vector = glm.vec2(worldDestinationPosition[0] - worldOriginPosition[0], worldDestinationPosition[1] - worldOriginPosition[1]) if glm.length(vector) <= self.minSeekDistance: return glm.vec2(0.0, 0.0) direction = vector if glm.length(vector) > 0.0: direction = glm.normalize(vector) acceleration = direction * self.maxLinearVelocity return acceleration
def remove_child(self, child): self.children.remove(child) child_center = glm.vec3(self.M * glm.vec4(child.center, 1)) child_radius = child.radius * glm.length(self.M * glm.vec4(1, 1, 1, 0)) / glm.sqrt(3) if len(self.children) > 1: centers = [self.M * glm.vec4(child.center, 1) for child in self.children] self.min_x = min([center[0] for center in centers]) self.max_x = max([center[0] for center in centers]) self.min_y = min([center[1] for center in centers]) self.max_y = max([center[1] for center in centers]) self.min_z = min([center[2] for center in centers]) self.max_z = max([center[2] for center in centers]) self.center = glm.vec3((self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2, (self.min_z + self.max_z) / 2) self.radius = max([glm.length(self.center - child.center) + child.radius for child in self.children])
def __init__(self, lookfrom, lookat, vup, vfov, aspect): self.theta = vfov * M_PI / 180 self.half_height = math.tan(self.theta / 2) self.half_width = aspect * self.half_height self.origin = lookfrom self.w = glm.vec3( (lookfrom - lookat) / (glm.length(lookfrom - lookat))) self.u = glm.vec3( glm.cross(vup, self.w) / glm.length(glm.cross(vup, self.w))) self.v = glm.cross(self.w, self.u) self.lower_left_corner = glm.vec3(-self.half_width, -self.half_height, -1.0) self.lower_left_corner = self.origin - self.half_width * self.u - self.half_height * self.v - self.w self.horizontal = 2 * self.half_width * self.u self.vertical = 2 * self.half_height * self.v
def calc_distances_exact_superslow(self, max_range=None): if max_range is None: max_range = max(self.size()) mask = [] for z in range(-max_range, max_range+1): #print("%s/%s" % (z, max_range*2+1)) for y in range(-max_range, max_range+1): for x in range(-max_range, max_range+1): mask.append((x,y,z, glm.length((x,y,z)))) mask = sorted(mask, key=lambda m: m[3]) mask = mask[1:] max_dist = mask[-1][3] for z in range(self.depth): print("%s/%s" % (z, self.depth)) for y in range(self.height): #print("%s/%s/%s" % (z, y, self.height)) for x in range(self.width): if self.value(x, y, z): mindist = 0 else: mindist = max_dist for m in mask: if self.value(x+m[0], y+m[1], z+m[2]): d = m[3] #print(m[0], m[1], m[2], d) if d > mindist: break mindist = d if mindist < 1: break #print("------", mindist) self.distances[self.pos_to_index(x, y, z)] = mindist
def _recalc_prediciton(self, world): STEPS = 20 self.prediction = [] rect = self.rectangles[0].clone() start_width = rect.width start_height = rect.height position = self.position * 1 velocity = glm.normalize(self.possible_velocity) length = glm.length(self.possible_velocity) for i in range(0, STEPS): travel = length / STEPS position, velocity = self._simulate_movement( world, [rect], velocity, travel, position) rect.position = position prediction_rect = rect.clone() prediction_rect.width = (start_width / float(STEPS)) * (STEPS - float(i)) prediction_rect.height = (start_height / float(STEPS)) * (STEPS - float(i)) self.prediction.append(prediction_rect)
def IntersectOld(self, ray): position = self.position radius = self.radius ray_origin = ray.origin ray_direction = ray.direction sphere_center = position t = glm.dot(sphere_center - ray_origin, ray_direction) pos = ray.PointAtOffset(t) # ray_direction * t + ray_origin intersection_distance = glm.length(sphere_center - pos) if intersection_distance == radius: intersection_result = IntersectionResult( self, pos, t, glm.normalize(pos - sphere_center)) return intersection_result elif intersection_distance < radius: tHc = math.sqrt(radius * radius - intersection_distance * intersection_distance) ray_collision_offset = t - tHc intersection1 = ray_origin + (ray_direction * ray_collision_offset) intersection_result = IntersectionResult( self, intersection1, ray_collision_offset, glm.normalize(intersection1 - sphere_center)) return intersection_result # ray_collision_offset = t + tHc # intersection2 = ray_origin + (ray_direction * ray_collision_offset) # intersection_result = IntersectionResult(intersection2, ray_collision_offset, glm.normalize(intersection2 - sphere_center)) return None
def move(self): linearVelocity = glm.vec2(0.0, 0.0) if self.followPath == True: mapDestinationPosition = self.pathFollower.getWaypoint() if mapDestinationPosition == None: return glm.vec2(0.0, 0.0) worldDestinationPosition = self.bot.map.getWorldPosition( mapDestinationPosition) vector = glm.vec2( worldDestinationPosition[0] - self.bot.transform.position[0], worldDestinationPosition[1] - self.bot.transform.position[1]) if glm.length(vector) <= self.minSeekDistance: self.pathFollower.increaseWaypoint() mapDestinationPosition = self.pathFollower.getWaypoint() if mapDestinationPosition == None: return glm.vec2(0.0, 0.0) worldDestinationPosition = self.bot.map.getWorldPosition( mapDestinationPosition) linearVelocity = self.seekPosition(self.bot.transform.position, worldDestinationPosition) else: if self.worldDestinationDirection == None: return glm.vec2(0.0, 0.0) linearVelocity = self.seekDirection(self.worldDestinationDirection) return linearVelocity
def update(self, dt): self.vel += self.force if not self.sleeping: if glm.length(self.vel) < .01: self.sleeping = True self.force *= 0 else: self.last_y = self.pos.y self.pos += self.vel * dt self.force *= 0 if self.platform: if self.vel.y > 0: self.platform = None elif self.platform is True: self.pos.y = 0 self.vel.y = 0 else: self.pos.y = self.platform.get_top(self.pos.xz) self.vel.y = 0 self.last_y = self.pos.y elif self.pos.y < 0: self.pos.y = 0 self.set_platform(True)
def rotation(self, orig, dest): identityQuat = glm.quat(1.0, 0.0, 0.0, 0.0) epsilon = 0.00001 cosTheta = glm.dot(orig, dest) if cosTheta >= 1.0 - epsilon: #// orig and dest point in the same direction return identityQuat if cosTheta < -1.0 + epsilon: ''' // special case when vectors in opposite directions : // there is no "ideal" rotation axis // So guess one; any will do as long as it's perpendicular to start // This implementation favors a rotation around the Up axis (Y), // since it's often what you want to do. ''' rotationAxis = glm.cross(glm.vec3(0.0, 0.0, 1.0), orig) if glm.length( rotationAxis ) < epsilon: # // bad luck, they were parallel, try again! rotationAxis = glm.cross(glm.vec3(1.0, 0.0, 0.0), orig) rotationAxis = glm.normalize(rotationAxis) return glm.angleAxis(glm.pi(), rotationAxis) #// Implementation from Stan Melax's Game Programming Gems 1 article rotationAxis = glm.cross(orig, dest) s = math.sqrt((1.0 + cosTheta) * 2.0) invs = 1.0 / s return glm.quat(s * 0.5, rotationAxis.x * invs, rotationAxis.y * invs, rotationAxis.z * invs)
def process(self): for e_id, (ghost_col, report, velocity, animation, light, ghost) in self.world.get_components(com.CollisionComponent, com.CollisionReport, com.Velocity, com.LightAnimation, com.Light, com.Ghost): if self.world.player_object in report.failed: self.world.damage_player() report.failed.clear() if ghost_col.is_colliding_y or ghost_col.is_colliding_x or glm.length( velocity.value) < 1: velocity.value = glm.normalize( glm.vec3(rand.uniform(-1.0, 1.0), rand.uniform(-1.0, 1.0), 0.0)) * GhostSystem.SPEED if light.enabled: if animation.animation_delta > GhostSystem.ANIMATION_DELTA_LIMIT: light.enabled = False animation.enabled = False self.free_light_count += 1 elif self.free_light_count >= 1: if rand.randrange(0, 100) <= GhostSystem.LIGHT_CHANGE: self.free_light_count -= 1 light.enabled = True animation.animation_delta = 0.0 animation.delta_factor = rand.uniform(0.8, 1.4) animation.enabled = True
def mandelboxSDF(pos, scale): orbitTrap = glm.vec4(10000) iterations = 17 #0 to 300 colorIterations = 3 #0 to 300 minRad2 = 0.25 #0.0 to 2.0 scale = glm.vec4(scale, scale, scale, abs(scale)) / minRad2 rotVector = glm.vec3(1, 1, 1) #(0, 0, 0) to (1, 1, 1) rotAngle = 0 #0 to 180(?) rot = rotationMatrix3(glm.normalize(rotVector), rotAngle) absScalem1 = abs(scale - 1) absScaleRaisedTo1mIters = pow(abs(scale), float(1 - iterations)) p = pos w = 1 p0 = p w0 = w for i in range(iterations): p *= rot p = glm.clamp(p, -1, 1) * 2 - p r2 = glm.dot(p, p) if i < colorIterations: orbitTrap = glm.min(orbitTrap, abs(glm.vec4(p, r2))) p *= glm.clamp(glm.max(minRad2 / r2, minRad2), 0, 1) w *= glm.clamp(glm.max(minRad2 / r2, minRad2), 0, 1) p = p * glm.vec3(scale[0], scale[1], scale[2]) + p0 w = w * scale[3] + w0 if r2 > 1000: break return (glm.length(p) - absScalem1[3]) / w - absScaleRaisedTo1mIters[3]
def scatter(self, r_in, rec, attenuation, scattered): reflected = glm.vec3( reflect(r_in.direction / glm.length(r_in.direction), rec.normal)) scattered = Ray(rec.p, reflected + self.fuzz * random_in_unit_sphere()) attenuation = self.albedo return (glm.dot(scattered.direction, rec.normal) > 0, scattered, attenuation)
def update(self, entity, dt): entity.ai_next_fire -= dt if entity.ai_next_fire > 0 or not entity.alive: return entity.ai_next_fire = uniform(self.min_delay, self.max_delay) player = entity.app.state.player if player and player.alive: # print('randomly fire') to_player = player.position - entity.position if BUTTERFLY_MIN_SHOOT_DIST < glm.length(to_player): entity.play_sound("squeak.wav") bu = entity.scene.add( Bullet( entity.app, entity.scene, entity, entity.position, to_player, entity.damage, BULLET_IMAGE_PATH, ENEMY_BULLET_FACTOR * BULLET_SPEED, ))
def distance(self, other:"Transformation") -> float: td = glm.distance(self.translation, other.translation) sd = glm.distance(self.scale, other.scale) qn : glm.Quat = glm.inverse(self.quaternion) # type: ignore qn = qn * other.quaternion if qn.w<0: qn = -qn qd = glm.length(qn - glm.quat()) return td+sd+qd
def power(self, scene): scene_size = glm.vec3( scene.m_aabb[3], scene.m_aabb[4], scene.m_aabb[5]) - glm.vec3( scene.m_aabb[0], scene.m_aabb[1], scene.m_aabb[2]) scene_len = glm.length(scene_size) factor = 1.0 - math.cos(self.m_radian) return 2.0 * math.pi * factor * scene_len * scene_len * self.d_intensity.Intensity( )
def __init__(self, shader, filename=None, material=None, vertices=None, vertices2=None, colors=None, texCoords=None, normals=None, indices=None, draw_mode=GL_TRIANGLES, line_width=1, **kwargs): super().__init__(**kwargs) # Acquire shader is promised if isinstance(shader, str): self.shader = get_shader(shader) else: self.shader = shader self.vao = glGenVertexArrays(1) self.draw_mode = draw_mode self.line_width = line_width self.material = material self.vertices = np.array(vertices, np.float32).reshape( (-1, 3)) if vertices is not None else None self.vertices = np.array(vertices2, np.float32).reshape( (-1, 2)) if vertices2 is not None else self.vertices self.colors = np.array(colors, np.float32).reshape( (-1, 3)) if colors is not None else None self.texCoords = np.array(texCoords, np.float32).reshape( (-1, 2)) if texCoords is not None else None self.normals = np.array(normals, np.float32).reshape( (-1, 3)) if normals is not None else None self.indices = np.array(indices, np.int32).reshape( (-1, 1)) if indices is not None else None if filename is not None: self.parse(filename) elif vertices is not None: self.setupVec3() elif vertices2 is not None: self.setupVec2() min_x = np.min(self.vertices[:, 0]) max_x = np.max(self.vertices[:, 0]) min_y = np.min(self.vertices[:, 1]) max_y = np.max(self.vertices[:, 1]) min_z = np.min(self.vertices[:, 2]) if vertices is not None else 0 max_z = np.max(self.vertices[:, 2]) if vertices is not None else 0 self.center = glm.vec3((min_x + max_x) / 2, (min_y + max_y) / 2, (min_z + max_z) / 2) self.radius = glm.length(glm.vec3(max_x, max_y, max_z) - self.center) self.uniforms = dict()
def setTarget(self, target, interpolate=False): """Use to set a point where the camera should look. Target is expected to be a glm.vec3, interpolate is a bool. Set interpolate to true produces an animated camera movement""" self._desiredTransform.lookAt(target, self.worldUp) self._desiredTargetDistance = glm.length( target - self._desiredTransform.position) if not interpolate: self._currentTransform.orientation = self._desiredTransform.orientation self._currentTargetDistance = self._desiredTargetDistance
def refract(v, n, ni_over_nt, refracted): uv = glm.vec3(v / glm.length(v)) dt = glm.dot(uv, n) discriminant = 1.0 - ni_over_nt * ni_over_nt * (1 - dt * dt) if (discriminant > 0): refracted = ni_over_nt * (uv - n * dt) - n * math.sqrt(discriminant) return (True, refracted) else: refracted = glm.vec3 return (False, refracted)
def from_mat4(self, m:glm.Mat4) -> None: self.translation = glm.vec3([m[3][0], m[3][1], m[3][2]]) rotation = glm.mat3() for i in range(3): v = glm.vec3([m[i][0], m[i][1], m[i][2]]) l = glm.length(v) self.scale[i] = l rotation[i] = v / l # type: ignore pass self.quaternion = quaternion_of_rotation(rotation) pass
def set_matrix(self, M): self.M = M centers = [self.M * glm.vec4(child.center, 1) for child in self.children] self.min_x = min([center[0] for center in centers]) self.max_x = max([center[0] for center in centers]) self.min_y = min([center[1] for center in centers]) self.max_y = max([center[1] for center in centers]) self.min_z = min([center[2] for center in centers]) self.max_z = max([center[2] for center in centers]) self.center = glm.vec3((self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2, (self.min_z + self.max_z) / 2) self.radius = max([glm.length(self.center - child.center) + child.radius for child in self.children])
def rotate(self): if self.autoRotate == True: if glm.length(self.linearVelocity) > 0.0: direction = glm.normalize(self.linearVelocity) self.lookAt((direction.x, direction.y)) if self.worldDestinationRotation == None: return 0.0 angularVelocity = self.align(self.bot.transform.rotation, self.worldDestinationRotation) return angularVelocity
def update(self, entity, dt): if not entity.alive: return player = entity.app.state.player # Assume state is Game dir = player.position - entity.position dir.z = 0 if dir != vec3(0) and length(dir.xy) < self.radius: # Too close, go away entity.velocity = -vec3(normalize(dir.xy), 0) * self.speed else: entity.velocity = vec3(0)
def update(self, bot, input): seenBotInfo = bot.sight.getSeenBotInfo(self.seenBotEntity) if seenBotInfo.transform == None: return vector = glm.vec2( bot.transform.position[0] - seenBotInfo.transform.position[0], bot.transform.position[1] - seenBotInfo.transform.position[1]) direction = vector if glm.length(vector) > 0.0: direction = glm.normalize(vector) bot.agent.goToDirection((direction.x, direction.y)) bot.agent.lookAt((direction.x, direction.y))
def add_child(self, child: Node): child_center = glm.vec3(self.M * glm.vec4(child.center, 1)) child_radius = child.radius * glm.length(self.M * glm.vec4(1, 1, 1, 0)) / glm.sqrt(3) if len(self.children) == 0: self.center = child_center self.radius = child_radius self.min_x = self.max_x = self.center[0] self.min_y = self.max_y = self.center[1] self.min_z = self.max_z = self.center[2] else: self.min_x = min(self.min_x, child_center[0]) self.max_x = max(self.max_x, child_center[0]) self.min_y = min(self.min_y, child_center[1]) self.max_y = max(self.max_y, child_center[1]) self.min_z = min(self.min_z, child_center[2]) self.max_z = max(self.max_z, child_center[2]) new_center = glm.vec3((self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2, (self.min_z + self.max_z) / 2) self.radius += glm.length(self.center - new_center) self.center = new_center self.radius = max(self.radius, glm.length(child_center - self.center) + child_radius) self.children.append(child)
def decompose_matrix( mat: glm.mat4 ) -> Tuple[Optional[glm.vec3], Optional[glm.quat], Optional[glm.vec3]]: sx = glm.length(glm.vec3(mat[0])) sy = glm.length(glm.vec3(mat[1])) sz = glm.length(glm.vec3(mat[2])) if glm.determinant(mat) < 0.0: sx = -sx translation = glm.vec3(mat[3]) scale = glm.vec3(sx, sy, sz) inv_sx = 1.0 / sx inv_sy = 1.0 / sy inv_sz = 1.0 / sz rot_mat = copy.copy(mat) rot_mat[0][0] *= inv_sx rot_mat[0][1] *= inv_sx rot_mat[0][2] *= inv_sx rot_mat[1][0] *= inv_sy rot_mat[1][1] *= inv_sy rot_mat[1][2] *= inv_sy rot_mat[2][0] *= inv_sz rot_mat[2][1] *= inv_sz rot_mat[2][2] *= inv_sz rot_mat[3] = glm.vec4(0.0, 0.0, 0.0, 1.0) rotation = glm.normalize(glm.quat_cast(rot_mat)) if translation == glm.vec3(): translation = None if rotation == glm.quat(): rotation = None if scale == glm.vec3(): scale = None return (translation, rotation, scale)