Pular para o conteúdo
Skillpedia
Testes15 mil · #11109

create-scenario

O que ela faz

Esta skill escreve um novo cenário de teste de direção para o simulador do CARLA, incluindo seus atores, comportamento e critérios de aprovação. É para desenvolvedores que criam testes personalizados para softwares de direção autônoma.

Quando usar

  • ✓Quando você quer um novo teste em que um carro precisa lidar com uma situação específica da via.
  • ✓Quando você precisa de um arquivo de cenário que o executor de testes encontre e rode pelo nome.
  • ✓Quando você quer que o novo cenário seja verificado quanto a erros antes de rodá-lo no simulador.

Link da skill

https://github.com/carla-simulator/carla/blob/ue58-dev/Skills/scenario-runner/create-scenario/SKILL.md

Copie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.

Como usar

O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.

Mensagem pronta para colar

Use esta skill para me ajudar: https://github.com/carla-simulator/carla/blob/ue58-dev/Skills/scenario-runner/create-scenario/SKILL.md Leia o arquivo SKILL.md desse link e siga as instruções dele na minha tarefa.
Quer que a sua IA encontre skills como esta sozinha?Instale o MCP grátis do Skillpedia: uma linha, e ela pesquisa entre 15.000+ skills antes de cada tarefa.Instalar em 1 minuto →

Exemplo do que pedir para a IA

“Você pode escrever um novo teste do CARLA em que outro carro surge de repente na frente do meu carro, e verificar se ele carrega corretamente?”

5 skills novas por semana. 1 minuto de leitura.

Como funciona

O agente cria um arquivo inicial com a estrutura necessária, preenche os atores, o comportamento e as verificações, e depois roda uma verificação offline rápida. O nome do arquivo precisa corresponder ao nome do cenário, senão o executor de testes não o encontra.

Conteúdo técnico (SKILL.md original)

Texto original do autor, em inglês, direto do GitHub.

Create a scenario

Paths. scripts/… and references/… below are relative to the directory holding this SKILL.md. Your working directory is the user's project, not that directory, so prefix them with its absolute path or the command is not found.

A scenario is two files:

srunner/scenarios/my_scenario.py    the class: actors + behaviour tree + criteria
srunner/examples/MyScenario.xml     the config: town, ego spawn, parameters

ScenarioRunner finds the class by globbing $SCENARIO_RUNNER_ROOT/srunner/scenarios/*.py and matching the config's type attribute against class names in those modules. There is no registration list — dropping the two files in is the whole install. The corollary is that the type in the XML must match the class name exactly, and a typo produces Scenario 'X' not supported.

Instructions

Progress:
- [ ] Step 1: Check prerequisites (bash scripts/check_env.sh)
- [ ] Step 2: Generate the skeleton (scaffold), or copy the closest existing scenario
- [ ] Step 3: Fill in _initialize_actors, _create_behavior, _create_test_criteria
- [ ] Step 4: Validate offline (validate) — imports, class/type match, tree shape
- [ ] Step 5: Run it (run-scenario), iterate with DEBUG=1

Step 2: Scaffold

source scripts/env.sh

# a standalone scenario with a config, in the checkout
python3 scripts/scaffold_scenario.py --name MyCutIn --town Town04 \
    --template follow_leading_vehicle

# somewhere else, to keep the checkout clean (use --additionalScenario to run it)
python3 scripts/scaffold_scenario.py --name MyCutIn --town Town04 --out ~/my_scenarios

python3 scripts/scaffold_scenario.py --list-templates

The scaffold writes both files with the four methods stubbed, the imports that actually exist in this branch, and a CollisionTest criterion so the run reports something. Then edit.

Step 3: The four methods

class MyCutIn(BasicScenario):
    def __init__(self, world, ego_vehicles, config, randomize=False,
                 debug_mode=False, criteria_enable=True, timeout=60):
        self.timeout = timeout
        self._map = CarlaDataProvider.get_map()
        self._reference_waypoint = self._map.get_waypoint(config.trigger_points[0].location)
        # scenario parameters come from the XML, via config.other_parameters
        self._distance = 50
        if "distance" in config.other_parameters:
            self._distance = float(config.other_parameters["distance"]["value"])
        super().__init__("MyCutIn", ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable)

    def _initialize_actors(self, config):
        """Spawn everything the scenario needs. Use CarlaDataProvider, never world.spawn_actor."""
        wp = self._reference_waypoint.next(self._distance)[0]
        actor = CarlaDataProvider.request_new_actor("vehicle.tesla.model3", wp.transform)
        self.other_actors.append(actor)

    def _create_behavior(self):
        """Return the py_trees tree. Composites: Sequence, Parallel; leaves: atomics."""
        root = py_trees.composites.Sequence("MyCutIn")
        root.add_child(InTriggerDistanceToVehicle(self.other_actors[0], self.ego_vehicles[0], 30))
        root.add_child(LaneChange(self.other_actors[0], speed=10, distance_other_lane=30))
        root.add_child(ActorDestroy(self.other_actors[0]))
        return root

    def _create_test_criteria(self):
        """Return a list of criteria. These decide pass/fail."""
        return [CollisionTest(self.ego_vehicles[0])]

Rules that are not obvious and cost the most time:

  • Spawn through CarlaDataProvider.request_new_actor, not world.spawn_actor. Only the provider registers the actor for velocity/transform caching and for cleanup; direct spawns leak between runs and read as not found in atomics.
  • Append to self.other_actors or the actor is never destroyed.
  • _create_behavior must return a tree that terminates. A Sequence whose last child never succeeds hangs until the timeout — which is what an apparently stuck scenario usually is.
  • config.other_parameters is a dict of {name: {attr: value}} built from the XML child elements, and every value is a string. Cast it.
  • self.timeout must be set before super().__init__, because the base class reads it while building the tree.
  • Criteria are attached in parallel with the behaviour and run to the end. An optional=True criterion reports but does not fail the scena
Perguntas frequentes

Preciso do simulador para verificar o novo cenário?

Não. A primeira verificação roda sem ele, então você pega erros de arquivo e de nomenclatura logo no início.

Por que o nome precisa corresponder exatamente?

O executor de testes encontra os cenários pelo nome no arquivo de configuração, então um erro de digitação causa um erro de não suportado.

Posso adicionar um cenário a uma rota inteira?

Sim. Ele pode ser adicionado a uma rota com uma opção extra de cenário.

Detalhes

Descrição original do autor

Writes a new ScenarioRunner scenario — a Python class deriving from BasicScenario with its behaviour tree assembled from srunner atomic behaviours and criteria, plus the XML config that gives it a town, ego spawn and parameters — and registers it so `--scenario MyScenario_1` works. Also covers adding a scenario to a route via --additionalScenario. Generates a working skeleton and validates it without a simulator. Use when the user asks to "create/write a new scenario", "add a custom scenario", "make my own traffic situation", or wants to extend the scenario library.

repo: carla-simulator/carla

Popularidade

Estrelas no GitHub
15 mil
Posição no ranking
#11109
Licença
MIT
Atualizada em
02/11/2026

Essa skill é útil?

0

Entre para votar.

Comentários

  • …

Mais skills deste repositório

Skills parecidas