Last active
August 20, 2019 07:04
-
-
Save denegny/b8d7855a3dd51bb7ebec6b9649eda941 to your computer and use it in GitHub Desktop.
AutonomousCar ## lib/scenes/environment.ex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule AutonomousCar.Scene.Environment do | |
| use Scenic.Scene | |
| require Logger | |
| alias AutonomousCar.Math.Vector2 | |
| alias Scenic.Graph | |
| alias Scenic.ViewPort | |
| import Scenic.Primitives | |
| @spec init(any, nil | keyword | map) :: | |
| {:ok, | |
| %{ | |
| graph: Scenic.Graph.t(), | |
| objects: %{car: map}, | |
| viewport: atom | pid, | |
| viewport_height: number, | |
| viewport_width: number | |
| }, [{:push, map}, ...]} | |
| defp draw_objects(graph, object_map) do | |
| Enum.reduce(object_map, graph, fn {object_type, object_data}, graph -> | |
| draw_object(graph, object_type, object_data) | |
| end) | |
| end | |
| defp draw_object(graph, :car, data) do | |
| {sensor_center_x, sensor_center_y} = data.sensor.center | |
| {sensor_right_x, sensor_right_y} = data.sensor.right | |
| {sensor_left_x, sensor_left_y} = data.sensor.left | |
| %{width: width, height: height} = data.dimension | |
| {x, y} = data.coords | |
| angle_radians = data.angle |> Vector2.degrees_to_radians() | |
| new_graph = | |
| graph | |
| |> group( | |
| fn g -> | |
| g | |
| |> rect({width, height}, fill: :white, translate: {x, y}) | |
| |> circle(4, fill: :red, translate: {x + 22, y - 5}, id: :sensor_left) | |
| |> circle(4, fill: :green, translate: {x + 28, y + 5}, id: :sensor_center) | |
| |> circle(4, fill: :blue, translate: {x + 22, y + 15}, id: :sensor_right) | |
| end, | |
| rotate: angle_radians, | |
| pin: {x, y}, | |
| id: :car | |
| ) | |
| end | |
| def init(_arg, opts) do | |
| ## Initialize environment | |
| # PID da ViewPort | |
| viewport = opts[:viewport] | |
| # Initialize the graph | |
| graph = Graph.build(theme: :dark) | |
| # Calculate ViewPort width and height | |
| {:ok, %ViewPort.Status{size: {viewport_width, viewport_height}}} = ViewPort.info(viewport) | |
| # Initial car pos | |
| {pos_x, pos_y} = {trunc(viewport_width / 2), trunc(viewport_height / 2)} | |
| state = %{ | |
| viewport: viewport, | |
| viewport_width: viewport_width, | |
| viewport_height: viewport_height, | |
| graph: graph, | |
| objects: %{ | |
| car: %{ | |
| dimension: %{width: 20, height: 10}, | |
| coords: {pos_x, pos_y}, | |
| velocity: {1, 0}, | |
| angle: 0, | |
| sensor: %{ | |
| left: {0, 0}, | |
| center: {0, 0}, | |
| right: {0, 0} | |
| } | |
| } | |
| } | |
| } | |
| graph = draw_objects(graph, state.objects) | |
| {:ok, state, push: graph} | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment