본문으로 건너뛰기

레이어와 스타일

이 장은 워크스페이스 없이 지도 뷰와 레이어를 직접 만들어 다루는 방법을 설명합니다. 피처 레이어를 만들어 지도에 더하고, 보이기·불투명도·축척 범위 같은 공통 속성과 그리는 순서를 바꾸고, 레이어를 그룹으로 묶고, 스타일 JSON과 렌더러 정의로 레이어를 칠하고 라벨을 붙이는 순서입니다.

이 장의 코드는 sdk_samples의 layers 예제에서 가져왔습니다. 실행할 때는 데이터 폴더를 첫 인자로, 그림을 남길 폴더를 선택 인자로 줍니다(<실행 파일> <sdk_samples/data 폴더> [<출력 폴더>]). 출력 폴더를 주면 그 폴더에 layers.bmp(640x480, 96 dpi)를 남기고, 주지 않으면 임시 폴더에 썼다가 끝날 때 지웁니다. 예제 데이터 harbor_town.gpkg는 읽기 전용으로 열고, 스타일 파일은 데이터 폴더의 styles 폴더에서 읽기만 합니다. 이 장은 시작하기의 호환성 확인과 공급자 등록이 끝났다고 가정합니다(초기화와 종료).

그리기가 배경에서 일어난다는 것, 프레임을 기다렸다가 복사하는 방법, 지도 뷰의 크기와 범위 맞춤은 7장 워크스페이스와 지도 표시에서 설명했습니다. 이 장은 그 내용을 링크로만 가리킵니다.

레이어 종류

지도 뷰에 올리는 레이어는 모두 공통 기반 클래스 glsMapLayer를 가지며, 종류는 glsMapLayerType 값으로 구분합니다.

값 레이어 C++에서 만드는 함수 C#에서 만드는 방법
Feature 벡터 데이터 소스의 피처 glsCreateFeatureLayer new glsFeatureLayer(source) 또는 glsMapLayer.CreateFeatureLayer(source)
Group 다른 레이어를 묶는 그룹 glsCreateGroupLayer glsGroupLayer.Create(id, name)
Raster 래스터 영상 glsCreateRasterLayer new glsRasterLayer(source)
RangeRaster 수치 래스터(값 구간별 색) glsCreateRangeRasterLayer new glsRangeRasterLayer(source)
ValueRaster 수치 래스터(값별 색) glsCreateValueRasterLayer new glsValueRasterLayer(source)
Tile 타일(Terrain-RGB 고도 타일 포함) glsCreateTileLayer, glsCreateTerrainRgbLayer new glsTileLayer(dataset)
VectorTile 벡터 타일 glsCreateVectorTileLayer 없음
Annotation 주석 glsCreateAnnotationLayer 없음
Overlay 오버레이 glsCreateOverlayLayer 없음
MapImage WMS 같은 지도 이미지 서비스 직접 만드는 함수 없음 없음

이 장은 Feature와 Group만 다룹니다. 래스터, 타일, 고도는 12장에서 다룹니다.

지도 뷰나 그룹에서 레이어를 꺼내면 그 종류에 맞는 래퍼가 돌아옵니다.

GetLayer, GetLayerById가 돌려주는 glsMapLayer*는 실제로는 종류별 클래스(glsFeatureLayer, glsGroupLayer 등)의 객체이므로 dynamic_cast로 바꿔 씁니다. 종류는 GetLayerType으로도 확인할 수 있습니다. 반납은 glsReleaseMapLayer나 종류별 반납 함수(glsReleaseFeatureLayer 등) 어느 쪽으로 해도 됩니다.

만들기와 더하기

지도 뷰. 워크스페이스 없이 지도 뷰를 직접 만들 수 있습니다(C++ glsCreateMapView, C# new glsMapView()). 이렇게 만든 지도 뷰는 호출자가 소유하고 반납합니다(C++ glsReleaseMapView, C# Dispose). 지도 뷰는 크기를 정하기 전에는 그리지 않습니다(크기 맞추기).

피처 레이어. 피처 레이어는 벡터 데이터 소스 하나 위에 만듭니다. 레이어가 데이터 소스를 함께 가지므로, 레이어를 만든 뒤에는 데이터 소스 래퍼를 바로 반납해도 됩니다. 새 피처 레이어의 상태는 다음과 같습니다.

  • id는 빈 문자열이고, 이름은 데이터 소스의 이름입니다.
  • 스타일은 기본 단순 스타일입니다. 점은 테두리가 검은 8픽셀 파란 원, 선은 1.5픽셀 검은 선, 면은 반투명 파랑 채움에 1픽셀 검은 외곽선입니다. 이때 스타일 JSON을 읽으면 규칙이 없는 {"rules":[],"version":1}이 나옵니다(단순 스타일).

지도에 더하기. AddLayer는 레이어를 지도의 맨 위에 더합니다(정확한 자리는 순서에 있습니다). 지도 뷰가 레이어 자체를 가지므로, 더한 뒤에는 레이어 래퍼를 반납해도 지도에서 레이어가 사라지지 않습니다. 필요할 때 id나 번호로 다시 꺼냅니다. 레이어를 더하거나 지우면 지도 뷰가 새 그리기를 예약합니다(그리기는 배경에서 일어난다).

id. AddLayer는 id가 겹치는지 확인하지 않습니다. 같은 id의 레이어를 두 번 더하면(같은 레이어를 두 번 더해도) 지도에 두 개가 들어가고, id로 다루는 호출(찾기, 지우기, 순서 바꾸기)은 그중 하나만 다룹니다. 지도에 더하는 레이어마다 다른 id를 주세요.

찾기와 지우기. id로 찾는 호출은 그룹 안의 레이어까지 찾습니다. RemoveLayer(id)는 지도 맨 위 수준에서 먼저 찾고, 없으면 그룹 안에서 찾아 지웁니다. 지도에 없는 id를 지우면 아무것도 하지 않고 성공을 돌려줍니다.

반납 순서. 다음 순서를 지키세요.

  1. 프레임 준비 콜백을 지웁니다(콜백 규칙).
  2. 레이어 래퍼와 지도 뷰를 반납합니다. 지도 뷰를 반납하면 지도 뷰는 더 이상 레이어를 붙잡지 않습니다.
  3. 데이터셋을 반납합니다. 지도에 그 데이터셋의 레이어가 있는 동안에는 데이터셋을 반납하지 마세요.
  4. 프로세스를 끝낼 때 프로세스 종료 호출을 합니다(종료 순서).

예제는 districts, roads, places 순서로 레이어를 만들고 id와 이름(Districts 등)을 주어 더합니다. 그리는 순서는 districts roads places입니다.

glsCreateFeatureLayer(glsDataSource*, glsFeatureLayer**)로 만들고 glsReleaseFeatureLayer로 반납합니다. AddLayer(glsMapLayer*)는 래퍼를 호출하는 동안만 빌립니다. id로 찾는 GetLayerById는 없는 id에 NotFound를 돌려줍니다. 예제의 succeeded는 실패한 호출의 메시지를 출력하는 작은 도우미입니다.

// glsCreateFeatureLayer makes a layer over a vector data source. The layer
// shares the data source, so the data source wrapper can be released as soon
// as the layer exists. AddLayer borrows the layer wrapper and the map keeps the
// layer, so that wrapper can be released after the call too. A new layer has
// an empty id and the data source's name; give every layer a unique id.
static bool createLayers(GDK::glsDataset& dataset, GDK::glsMapView& view)
{
    const char* const ids[] = {"districts", "roads", "places"};
    const char* const names[] = {"Districts", "Roads", "Places"};
    for (int i = 0; i < 3; ++i) {
        GDK::glsDataSource* rawSource = nullptr;
        if (!succeeded(dataset.OpenVectorDataSourceByName(ids[i], &rawSource))) {
            return false;
        }
        DataSourcePtr source(rawSource);
        GDK::glsFeatureLayer* rawLayer = nullptr;
        if (!succeeded(GDK::glsCreateFeatureLayer(source.get(), &rawLayer))) {
            return false;
        }
        FeatureLayerPtr layer(rawLayer, GDK::glsReleaseFeatureLayer);
        source.reset();  // the layer keeps the data source
        if (i == 0) {
            std::printf("[sample] new layer: id \"%s\", name \"%s\"\n", layerId(*layer).c_str(),
                        layerName(*layer).c_str());
        }
        if (!succeeded(layer->SetId(ids[i])) || !succeeded(layer->SetName(names[i])) ||
            !succeeded(view.AddLayer(layer.get()))) {
            return false;
        }
    }  // each layer wrapper is released here; the map keeps the layers
    int count = 0;
    if (!succeeded(view.GetLayerCount(&count))) {
        return false;
    }
    std::printf("[sample] map layers: %d, draw order: %s\n", count, drawOrder(view).c_str());
    return true;
}

공통 속성

모든 레이어가 다음 속성을 가집니다. 지도에 있는 레이어의 보이기, 불투명도, 축척 범위를 바꾸면 지도 뷰가 새 그리기를 예약합니다.

속성 뜻
id, 이름 id는 지도에서 레이어를 찾는 열쇠이고, 이름은 사람에게 보일 이름입니다. 둘 다 UTF-8 문자열입니다.
보이기 false면 그리지 않습니다.
불투명도 0(투명)~1(불투명). 범위 밖의 값은 가까운 끝으로 맞춰집니다. 예제에서 1.5를 넣으면 1.0이 됩니다.
축척 범위 최소와 최대 두 개의 축척 분모입니다. 0은 그쪽에 제한이 없다는 뜻입니다. 지금 축척 분모가 최소보다 작거나(더 확대) 최대보다 크면(더 축소) 그리지 않습니다. 기본값은 둘 다 0입니다.
종류 glsMapLayerType 값입니다.
범위 레이어 데이터의 범위입니다. 피처 레이어는 데이터 소스의 범위를 데이터 소스의 좌표로 돌려줍니다.

피처 레이어의 불투명도는 피처·라벨·선택 강조 등을 모두 그린 합성 결과에 한 번 적용합니다. 같은 레이어의 불투명한 면들이 겹쳐도 레이어 불투명도가 0.5이면 단독 영역과 겹침 영역 모두 50%입니다. 스타일 색상이나 심볼 자체의 알파는 내부 합성에 유지됩니다. 예를 들어 자체 알파가 0.5인 면 두 개에 레이어 불투명도 0.5를 적용하면 단독 영역은 약 25%, 겹침 영역은 약 37.5%입니다. 중간 프레임과 완성 프레임에 같은 규칙을 적용합니다.

IsVisibleAtScale(scale)은 보이기와 축척 범위를 함께 보고, 주어진 축척 분모에서 레이어를 그릴지 알려 줍니다. 예제는 roads의 축척 범위를 0~100000으로 정한 뒤 1:50000에서 true, 1:200000에서 false를 확인하고 범위를 0, 0으로 되돌립니다.

GetId/SetId, GetName/SetName, GetVisible/SetVisible, GetOpacity/SetOpacity, GetScaleRange/SetScaleRange, GetLayerType, GetExtent를 씁니다. 문자열은 두 번 호출하는 방식으로 읽습니다.

// Every layer kind has these properties. Opacity is clamped to 0..1. The scale
// range holds two scale denominators; 0 means no limit on that side.
static bool layerProperties(GDK::glsMapView& view)
{
    LayerPtr roads = layerById(view, "roads");
    if (!roads) {
        std::printf("[sample] roads not found\n");
        return false;
    }
    GDK::glsMapLayerType type = GDK::glsMapLayerType::Group;
    bool visible = true;
    if (!succeeded(roads->SetVisible(false)) || !succeeded(roads->GetVisible(&visible)) ||
        !succeeded(roads->SetVisible(true)) || !succeeded(roads->GetLayerType(&type))) {
        return false;
    }
    std::printf("[sample] roads: name %s, feature layer: %s, visible after SetVisible(false): %s\n",
                layerName(*roads).c_str(), yesNo(type == GDK::glsMapLayerType::Feature), yesNo(visible));

    float half = 0;
    float clamped = 0;
    if (!succeeded(roads->SetOpacity(0.5f)) || !succeeded(roads->GetOpacity(&half)) ||
        !succeeded(roads->SetOpacity(1.5f)) || !succeeded(roads->GetOpacity(&clamped))) {
        return false;
    }
    std::printf("[sample] opacity 0.5 -> %.2f, 1.5 -> %.2f\n", half, clamped);

    bool atLarge = false;
    bool atSmall = false;
    if (!succeeded(roads->SetScaleRange(0, 100000)) || !succeeded(roads->IsVisibleAtScale(50000, &atLarge)) ||
        !succeeded(roads->IsVisibleAtScale(200000, &atSmall)) || !succeeded(roads->SetScaleRange(0, 0))) {
        return false;
    }
    std::printf("[sample] scale range 0 to 100000: visible at 1:50000 %s, at 1:200000 %s\n", yesNo(atLarge),
                yesNo(atSmall));

    GDK::glsEnvelope e;
    if (!succeeded(roads->GetExtent(&e))) {
        return false;
    }
    std::printf("[sample] roads extent %.3f %.3f %.3f %.3f\n", e.MinX, e.MinY, e.MaxX, e.MaxY);
    return true;
}

순서

레이어는 번호 0부터 그려지므로 번호 0이 맨 아래입니다(지도 뷰 얻기). 순서를 바꾸는 호출은 네 가지이고 모두 id를 받습니다.

호출 하는 일
MoveLayerUp 한 칸 위로(나중에 그려지게)
MoveLayerDown 한 칸 아래로
MoveLayerToFront 맨 위로
MoveLayerToBack 맨 아래로

이미 맨 위나 맨 아래에 있거나 지도에 없는 id면 아무것도 하지 않고 성공을 돌려줍니다. 이 호출들은 지도의 맨 위 수준 레이어만 옮기고, 그룹 안의 순서는 바꾸지 않습니다.

순서 값. 지도 뷰는 레이어를 순서 값(C++ GetZIndex/SetZIndex, C# ZIndex)이 작은 것부터 늘어놓고, 순서 값이 같으면 더한 순서를 지킵니다. 새로 만든 레이어의 순서 값은 0입니다. 위의 호출로 순서가 실제로 바뀌면 지도 뷰가 모든 맨 위 수준 레이어에 아래부터 1, 2, 3, …을 다시 매깁니다. 그래서 순서를 한 번이라도 바꾼 뒤에 순서 값 0인 레이어를 더하면 맨 위가 아니라 맨 아래에 놓입니다. 원하는 자리로 옮기거나 순서 값을 직접 정하세요. 워크스페이스가 만든 기본 레이어는 종류별 순서를 받습니다(데이터셋 더하기).

예제는 districts roads places에서 MoveLayerUp(districts)로 roads districts places, MoveLayerToFront(roads)로 districts places roads, MoveLayerDown(roads)로 다시 districts roads places를 만듭니다.

// Index 0 is drawn first (at the bottom). MoveLayerUp moves a layer one step
// toward the top, MoveLayerToFront to the top. An id that is not on the map
// changes nothing and is not reported as an error.
static bool layerOrder(GDK::glsMapView& view)
{
    if (!succeeded(view.MoveLayerUp("districts"))) {
        return false;
    }
    std::printf("[sample] after MoveLayerUp(districts): %s\n", drawOrder(view).c_str());
    if (!succeeded(view.MoveLayerToFront("roads"))) {
        return false;
    }
    std::printf("[sample] after MoveLayerToFront(roads): %s\n", drawOrder(view).c_str());
    if (!succeeded(view.MoveLayerDown("roads"))) {
        return false;
    }
    std::printf("[sample] after MoveLayerDown(roads): %s\n", drawOrder(view).c_str());
    return true;
}

그룹

그룹 레이어는 다른 레이어를 묶어 하나처럼 다룹니다. 그룹은 id와 이름을 받아 만들고, 자식 레이어를 AddLayer로 넣은 뒤 그룹을 지도에 더합니다. 그룹도 자식 레이어를 함께 가지므로 자식의 래퍼는 넣은 뒤 반납해도 됩니다. 자식은 그룹 안의 목록 순서대로, 지도에서 그룹이 놓인 자리에 그려집니다. 그룹에 그룹 자신이나 자신을 품은 그룹을 넣으면 InvalidArgument로 실패합니다.

  • 보이기와 축척 범위. 그룹을 숨기거나 지금 축척이 그룹의 축척 범위 밖이면 자식을 모두 그리지 않습니다.
  • 불투명도. 각 자식을 자신의 스타일과 불투명도로 그린 다음, 자식들의 합성 결과에 그룹 불투명도를 한 번 적용합니다. 자식의 불투명도 속성값은 바뀌지 않습니다. 자식들을 합성한 결과가 불투명한 영역은 그룹이 0.5일 때 겹친 곳도 50%가 됩니다. 이 결과를 다시 불투명도 0.5인 바깥 그룹에 넣으면 25%가 됩니다. 자식의 합성 결과가 이미 반투명하면 그 알파값에 그룹 불투명도가 추가로 곱해집니다. 그룹이 0이면 그룹의 결과 전체가 투명해집니다.
  • 찾기와 범위 맞춤. id로 찾는 호출은 그룹 안의 자식도 찾습니다. 지도의 레이어 수(GetLayerCount, C# LayerCount)는 맨 위 수준만 셉니다. ZoomToLayer에 그룹의 id를 주면 자식 전체의 범위로 맞춥니다.
  • 지도와 그룹에 함께 넣지 않기. 같은 레이어를 지도와 그룹 양쪽에 넣는 것을 막지 않으므로, 그러면 그 레이어가 두 번 들어갑니다. 지도에 있던 레이어를 그룹으로 옮길 때는 지도에서 먼저 지웁니다.

예제는 roads를 그룹 transport에 넣고 지도에서 roads를 지운 뒤 그룹을 더합니다. 앞에서 순서를 바꿨으므로 그룹은 맨 아래(transport districts places)에 놓이고, MoveLayerUp(transport)로 districts transport places를 만듭니다. 지도의 레이어는 3개, 그룹 안의 레이어는 1개이고, roads는 id로 여전히 찾힙니다.

glsCreateGroupLayer(id, name, &group)로 만들고 glsReleaseGroupLayer로 반납합니다. 그룹의 AddLayer, InsertLayer, RemoveLayer, ClearLayers, SetLayers로 자식을 다루고, GetLayerCount, GetLayer로 읽습니다.

// A group holds other layers and is added to the map like any layer. The
// layer is taken off the map first so that it is not on the map twice. Once a
// move has changed the order, the map's layers carry order values from 1 up,
// and a newly added layer (order value 0) goes to the bottom, so the group
// is moved up one step.
static bool groupLayer(GDK::glsMapView& view)
{
    LayerPtr roads = layerById(view, "roads");
    if (!roads) {
        std::printf("[sample] roads not found\n");
        return false;
    }
    GDK::glsGroupLayer* rawGroup = nullptr;
    if (!succeeded(GDK::glsCreateGroupLayer("transport", "Transport", &rawGroup))) {
        return false;
    }
    GroupLayerPtr group(rawGroup, GDK::glsReleaseGroupLayer);
    if (!succeeded(group->AddLayer(roads.get())) || !succeeded(view.RemoveLayer("roads")) ||
        !succeeded(view.AddLayer(group.get()))) {
        return false;
    }
    std::printf("[sample] after adding the group: %s\n", drawOrder(view).c_str());
    if (!succeeded(view.MoveLayerUp("transport"))) {
        return false;
    }
    std::printf("[sample] after MoveLayerUp(transport): %s\n", drawOrder(view).c_str());
    int mapLayers = 0;
    int children = 0;
    if (!succeeded(view.GetLayerCount(&mapLayers)) || !succeeded(group->GetLayerCount(&children))) {
        return false;
    }
    std::printf("[sample] map layers: %d, layers in the group: %d, roads found by id: %s\n", mapLayers, children,
                yesNo(layerById(view, "roads") != nullptr));
    return true;
}

피처 스타일 JSON

피처 레이어는 피처 스타일로 그립니다. 피처 스타일은 JSON 문자열로 넣고 읽습니다(SetFeatureStyleJson, GetFeatureStyleJson). 예제의 districts 스타일 파일은 다음과 같습니다.

{
  "version": 1,
  "rules": [
    {
      "name": "districts",
      "geometryType": "Polygon",
      "symbolLayers": [
        {
          "type": "Polygon",
          "fill": { "color": "#FFDCE9F5" },
          "outlines": [
            {
              "type": "Line",
              "stroke": {
                "color": "#FF4A6FA5",
                "width": { "value": 1, "unit": "Pixel" }
              }
            }
          ]
        }
      ]
    }
  ]
}

구조는 다음과 같습니다.

  • 최상위. rules는 규칙의 목록입니다. version은 SDK가 스타일을 쓸 때 넣는 형식 번호(1)이며, 읽을 때는 보지 않습니다.
  • 규칙. name은 규칙의 이름, geometryType은 이 규칙을 적용할 피처의 지오메트리 형식입니다. Polygon은 폴리곤과 멀티폴리곤(Z 형식 포함) 피처에, LineString은 선과 멀티선에, Point는 점과 멀티점에 적용됩니다. 생략하거나 Unknown이면 모든 피처에 적용됩니다. symbolLayers는 그 피처를 그릴 기호 레이어의 목록이며 목록 순서대로 그립니다. 한 피처에 맞는 규칙이 여럿이면 모두 그립니다.
  • 기호 레이어. type이 종류를 정합니다. Polygon은 면을 fill로 채우고 outlines(선 기호 레이어의 목록)로 외곽선을 그립니다. Line은 stroke(color, width)로 선을 그립니다.
  • 색. "#AARRGGBB" 형식의 9자 문자열입니다. AA는 알파이며 FF가 불투명입니다.
  • 길이. { "value": 숫자, "unit": 단위 }입니다. 단위 Pixel은 기기 픽셀입니다. 이 밖에 Point(1/72인치, 그릴 때의 DPI로 환산)와 MapUnit(지도 좌표의 단위, 경위도 지도에서는 도)이 있습니다.

roads 스타일은 한 규칙에 선 기호 레이어 두 개를 넣었습니다. 아래에 5픽셀 짙은 회색 선을, 그 위에 3픽셀 흰 선을 그려 테두리가 있는 도로가 됩니다.

{
  "version": 1,
  "rules": [
    {
      "name": "roads",
      "geometryType": "LineString",
      "symbolLayers": [
        {
          "type": "Line",
          "stroke": {
            "color": "#FF555555",
            "width": { "value": 5, "unit": "Pixel" }
          }
        },
        {
          "type": "Line",
          "stroke": {
            "color": "#FFFFFFFF",
            "width": { "value": 3, "unit": "Pixel" }
          }
        }
      ]
    }
  ]
}

빠진 키는 기본값으로 채워집니다. 그래서 GetFeatureStyleJson이 돌려주는 JSON은 넣은 텍스트와 같지 않고, 빠졌던 키의 기본값까지 적힌 한 줄 JSON입니다(예제의 districts는 433자). 들여쓴 형태가 필요하면 pretty 인자를 받는 오버로드를 씁니다.

스타일을 넣는 것만으로 다시 그려집니다. 지도에 있는 레이어의 스타일을 바꾸면 지도 뷰가 새 그리기를 예약하므로 Invalidate()를 따로 부를 필요가 없습니다. 다만 스타일을 바꾼 직후에는 이전 스타일로 그린 완성 프레임도 판정식을 통과하므로, 화면에 보여 줄 때는 알림이 올 때마다 다시 복사해 그립니다(판정식이 알려 주는 것).

지도에서 꺼낸 래퍼를 dynamic_cast<GDK::glsFeatureLayer*>로 바꿔 SetFeatureStyleJson(const char* json)을 부릅니다. JSON은 UTF-8이고 호출하는 동안만 읽힙니다.

// A feature style JSON holds rules; each rule lists symbol layers drawn in
// order. glsValidateFeatureStyleJson reads the JSON the same way the setter
// does, without touching a layer. A layer found by id is returned as a wrapper
// of its own kind, so dynamic_cast gives the feature layer.
static bool applyStyleJson(GDK::glsMapView& view, const std::filesystem::path& styleDir)
{
    const char* const ids[] = {"districts", "roads"};
    const char* const files[] = {"districts_style.json", "roads_style.json"};
    for (int i = 0; i < 2; ++i) {
        std::string json;
        if (!readTextFile(styleDir / files[i], json)) {
            std::printf("[sample] could not read %s\n", files[i]);
            return false;
        }
        if (!GDK::glsValidateFeatureStyleJson(json.c_str()).IsOk()) {
            std::printf("[sample] %s is not valid: %s\n", files[i], GDK::glsGetLastErrorMessage());
            return false;
        }
        LayerPtr layer = layerById(view, ids[i]);
        GDK::glsFeatureLayer* feature = asFeatureLayer(layer, ids[i]);
        if (feature == nullptr || !succeeded(feature->SetFeatureStyleJson(json.c_str()))) {
            return false;
        }
        std::printf("[sample] %s: valid, applied to %s\n", files[i], ids[i]);
    }
    return true;
}

렌더러 정의

렌더러 정의는 스타일을 한 단계 위에서 적는 방법입니다. "모든 피처를 같은 기호로", "필드 값마다 다른 기호로"처럼 적으면 레이어가 이것을 피처 스타일로 바꾸어(컴파일하여) 그립니다. 종류는 최상위 type 문자열로 정하며 반드시 있어야 합니다.

type 그리는 방법
SingleSymbol 모든 피처를 같은 기호로
Categorized 한 필드의 값마다 다른 기호로
Graduated 한 숫자 필드의 값 구간마다 다른 기호로
RuleBased 조건이 붙은 규칙의 목록으로
Heatmap 점의 밀도를 색 면으로(이 장에서는 다루지 않습니다)

예제의 places 렌더러 정의는 Categorized입니다.

{
  "version": 1,
  "type": "Categorized",
  "fieldName": "kind",
  "geometryType": "Point",
  "classes": [
    {
      "label": "Harbor",
      "value": { "type": "String", "value": "harbor" },
      "symbolLayers": [
        {
          "type": "Marker",
          "shape": "Circle",
          "size": { "value": 12, "unit": "Pixel" },
          "fill": { "color": "#FF1F77B4" },
          "outline": { "color": "#FF000000", "width": { "value": 1, "unit": "Pixel" } }
        }
      ]
    },
    {
      "label": "Market",
      "value": { "type": "String", "value": "market" },
      "symbolLayers": [
        {
          "type": "Marker",
          "shape": "Circle",
          "size": { "value": 12, "unit": "Pixel" },
          "fill": { "color": "#FFD62728" },
          "outline": { "color": "#FF000000", "width": { "value": 1, "unit": "Pixel" } }
        }
      ]
    },
    {
      "label": "School",
      "value": { "type": "String", "value": "school" },
      "symbolLayers": [
        {
          "type": "Marker",
          "shape": "Circle",
          "size": { "value": 12, "unit": "Pixel" },
          "fill": { "color": "#FF9467BD" },
          "outline": { "color": "#FF000000", "width": { "value": 1, "unit": "Pixel" } }
        }
      ]
    },
    {
      "label": "Park",
      "value": { "type": "String", "value": "park" },
      "symbolLayers": [
        {
          "type": "Marker",
          "shape": "Circle",
          "size": { "value": 12, "unit": "Pixel" },
          "fill": { "color": "#FF2CA02C" },
          "outline": { "color": "#FF000000", "width": { "value": 1, "unit": "Pixel" } }
        }
      ]
    }
  ],
  "labeling": {
    "label": {
      "enabled": true,
      "fieldName": "name",
      "font": { "family": "Arial", "size": { "value": 12, "unit": "Pixel" } },
      "textColor": "#FF202020",
      "haloColor": "#FFFFFFFF",
      "haloSize": { "value": 2, "unit": "Pixel" },
      "offset": { "x": 0, "y": -14 }
    }
  }
}
  • fieldName은 분류할 필드입니다. 비어 있으면 실패합니다.
  • geometryType은 이 렌더러가 대상으로 하는 지오메트리 형식입니다. 컴파일된 규칙이 이 형식을 받고, 검증이 레이어의 형식과 비교합니다.
  • classes의 항목마다 value(값의 type과 value, 여기서는 String)와 같은 값을 가진 피처를 symbolLayers로 그립니다. label은 분류의 이름입니다. 컴파일하면 분류마다 "필드 = 값" 조건을 가진 규칙이 하나씩 생깁니다.
  • 어느 분류에도 맞지 않는 값의 피처에는 기호가 그려지지 않습니다. Categorized에는 "그 밖의 값"용 기호가 없습니다. 다만 라벨 규칙에는 값 조건이 없으므로 그런 피처에도 라벨은 그려집니다. 예제 데이터의 kind는 네 값 중 하나이므로 모든 장소에 마커가 그려집니다.
  • Marker는 점 기호입니다. shape(모양, 여기서는 Circle), size(크기), fill(채움), outline(테두리 선)을 가집니다.
  • labeling은 라벨입니다.

네 분류의 색은 예제 데이터 폴더의 README.md에 표로 있습니다.

스타일 JSON과의 관계. 레이어는 언제나 피처 스타일로 그립니다.

  • 렌더러 정의를 넣으면(SetFeatureRendererDefinitionJson) 레이어가 그것을 피처 스타일로 컴파일해 쓰고, 정의 자체도 따로 간직합니다. 이때 GetFeatureStyleJson은 컴파일된 스타일을, GetFeatureRendererDefinitionJson은 넣은 정의를 돌려줍니다.
  • 스타일 JSON을 넣으면(SetFeatureStyleJson) 간직하던 렌더러 정의가 지워집니다. 렌더러 정의가 없는 레이어에서 GetFeatureRendererDefinitionJson을 부르면 레이어의 단순 스타일에서 만든 SingleSymbol 정의(히트맵 스타일이면 Heatmap 정의)가 돌아오며, 이것은 넣은 스타일 JSON을 나타내지 않습니다. 레이어에 정의가 있는지 알려면 C++의 GetFeatureRendererDefinition이 NotFound를 돌려주는지 봅니다(형식 있는 스타일 객체).

SetFeatureRendererDefinitionJson(const char* json)을 씁니다. 검증은 glsValidateFeatureRendererDefinitionJsonForGeometry(json, glsGeometryType)입니다.

// A renderer definition describes the style at a higher level (here: one
// symbol per value of the kind field, plus labels); the layer compiles it into
// a feature style. The validation also checks that the renderer fits the
// layer's geometry type, which the setter does not check.
static bool applyRenderer(GDK::glsMapView& view, const std::filesystem::path& styleDir)
{
    std::string json;
    if (!readTextFile(styleDir / "places_renderer.json", json)) {
        std::printf("[sample] could not read places_renderer.json\n");
        return false;
    }
    if (!GDK::glsValidateFeatureRendererDefinitionJsonForGeometry(json.c_str(), GDK::glsGeometryType::Point)
             .IsOk()) {
        std::printf("[sample] places_renderer.json is not valid: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    LayerPtr layer = layerById(view, "places");
    GDK::glsFeatureLayer* places = asFeatureLayer(layer, "places");
    if (places == nullptr || !succeeded(places->SetFeatureRendererDefinitionJson(json.c_str()))) {
        return false;
    }
    std::printf("[sample] places_renderer.json: valid for Point, applied to places\n");
    return true;
}
// GetFeatureStyleJson returns the style the layer draws with. For a layer
// styled by a renderer definition that is the compiled style, where the labels
// are a rule named "Labels"; GetFeatureRendererDefinitionJson returns the
// definition itself.
static bool readBackStyle(GDK::glsMapView& view)
{
    LayerPtr districtsLayer = layerById(view, "districts");
    LayerPtr placesLayer = layerById(view, "places");
    GDK::glsFeatureLayer* districts = asFeatureLayer(districtsLayer, "districts");
    GDK::glsFeatureLayer* places = asFeatureLayer(placesLayer, "places");
    if (districts == nullptr || places == nullptr) {
        return false;
    }
    const std::string districtStyle = featureStyleJson(*districts);
    const std::string placeStyle = districtStyle.empty() ? std::string() : featureStyleJson(*places);
    const std::string placeRenderer = placeStyle.empty() ? std::string() : rendererJson(*places);
    if (placeRenderer.empty()) {
        return false;  // the failing call has been reported
    }
    std::printf("[sample] districts style JSON: %zu characters\n", districtStyle.size());
    std::printf("[sample] places style has a \"Labels\" rule: %s\n",
                yesNo(placeStyle.find("\"name\":\"Labels\"") != std::string::npos));
    std::printf("[sample] places renderer definition is Categorized: %s\n",
                yesNo(placeRenderer.find("\"type\":\"Categorized\"") != std::string::npos));
    return true;
}

라벨

렌더러 정의의 라벨은 labeling 안의 label에 적습니다. 예제 파일에 쓴 키는 다음과 같습니다.

키 뜻
enabled 라벨을 그립니다. 기본값이 false이므로 true로 적어야 합니다.
fieldName 라벨 글자를 가져올 필드입니다.
font 글꼴. family(글꼴 이름)와 size(길이)입니다.
textColor 글자 색입니다.
haloColor, haloSize 글자 둘레의 테두리(후광) 색과 굵기입니다.
offset 라벨을 옮기는 양입니다(x, y, 기기 픽셀). y가 음수면 위로 옮깁니다.

라벨은 enabled가 true이고 필드 이름(또는 식)이 있을 때만 생깁니다. 컴파일된 피처 스타일에서는 이름이 Labels인 규칙의 Text 기호 레이어가 됩니다. 스타일 JSON으로 직접 라벨을 붙이려면 이런 Text 기호 레이어를 규칙에 넣습니다.

예제는 장소 이름(name)을 12픽셀 Arial로, 마커와 겹치지 않게 14픽셀 위에 그립니다. 그림에서 열두 장소의 이름이 모두 마커 위에 보입니다.


검증과 실패

실패한 호출은 스타일을 바꾸지 않습니다. 스타일 JSON이나 렌더러 정의를 넣는 호출은 JSON을 끝까지 읽고 확인한 뒤에야 레이어를 바꿉니다. 실패하면 레이어는 그 전의 스타일(과 렌더러 정의)을 그대로 가집니다. 예제는 중간에서 끊긴 JSON {"rules": [를 districts에 넣어 실패를 확인하고, 넣기 전과 뒤의 스타일 JSON이 같음을 값으로 비교합니다.

넣는 호출이 실패하는 경우는 다음과 같습니다.

  • JSON 문법이 틀렸습니다.
  • 기호 레이어의 type이 모르는 값입니다.
  • 색이 9자 # 문자열인데 16진수가 아닙니다(예: #GG000000).
  • 렌더러 정의에 type이 없거나 모르는 값이거나, 분류 필드 이름이 비어 있는 등 컴파일할 수 없습니다.
  • 키의 값이 기대와 다른 JSON 형식입니다. 예를 들어 "enabled": "true"처럼 참/거짓 자리에 문자열을 쓰면 실패합니다.

위 목록이 전부는 아닙니다. 넣는 호출이 실패하면 메시지로 이유를 확인하세요.

반대로 다음은 실패하지 않으므로 검증으로도 잡히지 않습니다. 결과는 그려 보고 확인하세요.

  • 모르는 키는 무시됩니다(철자가 틀린 키 포함).
  • 빠진 키는 기본값이 됩니다.
  • 9자 #AARRGGBB 형식이 아닌 색 문자열(예: #FF0000)은 오류 없이 그 자리의 기본 색이 됩니다. 이 기본 색은 투명일 수 있습니다.
  • 모르는 길이 단위는 Pixel이 됩니다.
  • 모르는 geometryType 값(철자가 틀린 값 포함)은 Unknown이 되어, 그 규칙이 모든 피처에 적용됩니다.
  • 스타일 규칙의 geometryType이 레이어의 피처와 맞지 않으면 그 규칙은 아무것도 그리지 않습니다.

검증 함수. 레이어에 넣기 전에 JSON을 확인할 수 있습니다.

  • 스타일 JSON의 검증은 넣는 호출과 같은 방식으로 JSON을 읽기만 합니다. 넣는 호출보다 더 잡는 것은 없습니다.
  • 렌더러 정의의 검증은 읽고 컴파일한 뒤, 정의의 geometryType이 주어진 레이어 형식과 맞는지도 확인합니다. 넣는 호출은 이것을 확인하지 않습니다. 점 렌더러를 폴리곤 레이어에 넣어도 성공하지만, 규칙이 점에만 적용되므로 아무것도 그려지지 않습니다. 형식은 점(멀티점), 선(멀티선), 폴리곤(멀티폴리곤) 묶음끼리 맞아야 하고(Z 형식 포함), 어느 한쪽이 Unknown이면 맞는 것으로 봅니다. 예제는 places 렌더러를 Polygon으로 검증해 거부되는 것을 확인합니다.

넣는 호출의 실패는 glsStatus로 돌아옵니다. 문법 오류는 UnknownError이며, 이유는 glsGetLastErrorMessage()로 읽습니다. 검증 함수도 glsStatus를 돌려줍니다.

// A setter that fails leaves the layer's style as it was. Here the style JSON
// is cut short, and the places renderer is checked against a polygon layer.
static bool invalidStyle(GDK::glsMapView& view, const std::filesystem::path& styleDir)
{
    LayerPtr layer = layerById(view, "districts");
    GDK::glsFeatureLayer* districts = asFeatureLayer(layer, "districts");
    if (districts == nullptr) {
        return false;
    }
    const std::string before = featureStyleJson(*districts);
    if (before.empty()) {
        return false;
    }
    if (districts->SetFeatureStyleJson("{\"rules\": [").IsOk()) {
        std::printf("[sample] expected the broken style JSON to be rejected\n");
        return false;
    }
    std::printf("[sample] broken style JSON: the call failed\n");
    const std::string after = featureStyleJson(*districts);
    if (after.empty()) {
        return false;
    }
    if (after != before) {
        std::printf("[sample] the style changed\n");
        return false;
    }
    std::printf("[sample] style unchanged\n");

    std::string renderer;
    if (!readTextFile(styleDir / "places_renderer.json", renderer)) {
        std::printf("[sample] could not read places_renderer.json\n");
        return false;
    }
    if (GDK::glsValidateFeatureRendererDefinitionJsonForGeometry(renderer.c_str(), GDK::glsGeometryType::Polygon)
            .IsOk()) {
        std::printf("[sample] expected the Point renderer to be rejected for Polygon\n");
        return false;
    }
    std::printf("[sample] places renderer checked for a Polygon layer: rejected\n");
    return true;
}

단순 스타일 (C++)

C++에는 JSON 없이 구조체로 칠하는 단순 스타일이 있습니다. glsSimpleFeatureStyle은 점(Point), 선(Line), 면(Polygon)의 기호를 하나씩 가지며, 레이어는 피처의 지오메트리에 맞는 것으로 그립니다. 라벨은 glsSimpleLabelStyle과 필드 이름, 글꼴 이름으로 붙입니다(SetSimpleLabelStyle). 문자열 인자는 호출하는 동안만 읽힙니다. 라벨 구조체의 Enabled 기본값은 false입니다.

주의할 점이 있습니다.

  • 단순 스타일은 스타일 JSON에 담기지 않습니다. 단순 스타일을 쓰는 레이어에서 GetFeatureStyleJson을 부르면 규칙이 없는 {"rules":[],"version":1}이 나옵니다. 단순 스타일은 GetSimpleStyle, GetSimpleLabelStyle 등으로 읽습니다.
  • SetSimpleStyle은 구조체의 Label까지 통째로 바꿉니다. Label의 기본값은 라벨 없음이므로, SetSimpleLabelStyle로 붙인 라벨은 그 뒤에 SetSimpleStyle을 부르면 없어집니다. 라벨은 SetSimpleStyle 다음에 붙이고, 기호만 바꾸려면 라벨을 그대로 두는 SetSimpleSymbolStyle을 쓰세요.
  • SetSimpleStyle은 레이어가 간직한 렌더러 정의를 지우지 않습니다(이전 스타일이 히트맵이었을 때만 지웁니다). 렌더러 정의를 쓰던 레이어에 단순 스타일을 넣으면 그림은 단순 스타일로 바뀌지만 GetFeatureRendererDefinition은 이전 정의를 돌려줍니다.
  • 렌더러 정의가 있는 레이어에서 SetSimpleLabelStyle은 정의의 라벨을 바꾸고 다시 컴파일합니다. 렌더러 정의가 없는 레이어에서는 레이어의 스타일을 단순 스타일로 바꿉니다. 지금 스타일이 단순 스타일이면 거기에 이 라벨을 더하고, 스타일 JSON으로 칠한 레이어라면 기본 단순 스타일에 이 라벨을 더합니다. 그래서 스타일 JSON으로 칠한 레이어에 부르면 JSON의 규칙이 없어집니다.

C#에는 단순 스타일 구조체가 없습니다. 스타일 JSON을 쓰세요.

예제는 districts를 단순 스타일과 라벨로 칠했다가, 스타일 파일을 다시 넣어 처음과 같은 스타일 JSON으로 돌아온 것을 확인합니다.

// The simple style structs set one symbol per geometry kind and an optional
// label. The string arguments are read during the call only. Setting the file
// style again replaces the simple style.
static bool simpleStyle(GDK::glsMapView& view, const std::filesystem::path& styleDir)
{
    LayerPtr layer = layerById(view, "districts");
    GDK::glsFeatureLayer* districts = asFeatureLayer(layer, "districts");
    if (districts == nullptr) {
        return false;
    }
    std::string fileStyle;
    if (!readTextFile(styleDir / "districts_style.json", fileStyle)) {
        std::printf("[sample] could not read districts_style.json\n");
        return false;
    }
    const std::string before = featureStyleJson(*districts);
    if (before.empty()) {
        return false;
    }

    GDK::glsSimpleFeatureStyle simple;
    simple.Polygon.FillColor = 0xFFF5E6C8u;
    simple.Polygon.OutlineColor = 0xFF8A6D3Bu;
    simple.Polygon.OutlineWidth = 2.0f;
    GDK::glsSimpleLabelStyle label;
    label.Enabled = true;
    label.FontSize = 14.0f;
    if (!succeeded(districts->SetSimpleStyle(&simple)) ||
        !succeeded(districts->SetSimpleLabelStyle(&label, "name", "Arial"))) {
        return false;
    }
    std::printf("[sample] simple style and label set on districts\n");

    if (!succeeded(districts->SetFeatureStyleJson(fileStyle.c_str()))) {
        return false;
    }
    const bool same = featureStyleJson(*districts) == before;
    std::printf("[sample] back to the file style: %s\n", yesNo(same));
    return same;
}

형식 있는 스타일 객체 (C++)

C++에는 렌더러 정의와 피처 스타일을 JSON 문자열 대신 객체로 다루는 형식도 있습니다(gdk_dll/glsStyleModel.h).

  • glsFeatureRendererDefinition: glsFeatureRendererDefinitionFromJson(JSON에서) 또는 glsCreateFeatureRendererDefinition(kind)(빈 정의)로 만들고 glsReleaseFeatureRendererDefinition으로 반납합니다. GetKind와 종류별 읽기·쓰기 메서드(예: GetCategorizedClassCount), ToJson이 있습니다. 레이어에는 SetFeatureRendererDefinition으로 넣고, GetFeatureRendererDefinition으로 레이어가 간직한 정의의 사본을 꺼냅니다. 레이어에 정의가 없으면 NotFound입니다.
  • glsFeatureStyle: glsFeatureStyleFromJson 또는 glsCreateFeatureStyle로 만들고 glsReleaseFeatureStyle로 반납합니다. 규칙을 더하고 읽는 메서드와 ToJson이 있습니다. glsFeatureLayer에는 이 객체를 받는 메서드가 없으므로, 레이어에는 ToJson으로 만든 JSON을 SetFeatureStyleJson으로 넣습니다.

C#에는 이 객체들이 없고 JSON 문자열로 같은 일을 합니다.

예제는 렌더러 파일을 객체로 읽어 종류(Categorized)와 분류 수(4)를 출력하고, places 레이어의 정의도 꺼내 종류를 확인합니다.

// glsFeatureRendererDefinitionFromJson reads a renderer definition into an
// object with typed getters and setters. GetFeatureRendererDefinition returns
// a copy of the layer's definition (NotFound when the layer has none).
static bool typedRenderer(GDK::glsMapView& view, const std::filesystem::path& styleDir)
{
    std::string json;
    if (!readTextFile(styleDir / "places_renderer.json", json)) {
        std::printf("[sample] could not read places_renderer.json\n");
        return false;
    }
    GDK::glsFeatureRendererDefinition* raw = nullptr;
    if (!succeeded(GDK::glsFeatureRendererDefinitionFromJson(json.c_str(), &raw))) {
        return false;
    }
    RendererPtr fromFile(raw, GDK::glsReleaseFeatureRendererDefinition);
    GDK::glsRendererKind kind = GDK::glsRendererKind::SingleSymbol;
    int classes = 0;
    if (!succeeded(fromFile->GetKind(&kind)) || !succeeded(fromFile->GetCategorizedClassCount(&classes))) {
        return false;
    }
    std::printf("[sample] typed renderer from the file: %s, %d classes\n", rendererKindName(kind), classes);

    LayerPtr layer = layerById(view, "places");
    GDK::glsFeatureLayer* places = asFeatureLayer(layer, "places");
    raw = nullptr;
    if (places == nullptr || !succeeded(places->GetFeatureRendererDefinition(&raw))) {
        return false;
    }
    RendererPtr fromLayer(raw, GDK::glsReleaseFeatureRendererDefinition);
    if (!succeeded(fromLayer->GetKind(&kind))) {
        return false;
    }
    std::printf("[sample] typed renderer from places: %s\n", rendererKindName(kind));
    return true;
}

그려서 확인하기

예제는 마지막에 640x480, 96 dpi로 크기를 정하고 ZoomToLayer("districts", 0.05)로 구역 전체에 맞춘 뒤, 프레임을 기다려 복사하고 layers.bmp로 씁니다(기다리기와 복사는 7장). 크기가 없는 지도 뷰는 아무것도 그리지 않으므로, 이때 처음 생기는 완성 프레임은 스타일을 모두 바꾼 뒤에 그린 것입니다. 그림에는 연한 하늘색으로 채운 구역, 흰 선에 회색 테두리가 있는 도로, 네 가지 색의 장소 마커와 이름이 보입니다.

그린 결과는 픽셀 값으로도 확인합니다. 불투명한 채움과 마커의 안쪽은 스타일의 색을 그대로 가지므로, 구역 채움색 #FFDCE9F5와 네 마커 색의 픽셀이 각각 하나 이상 있는지 셉니다. 모두 있으면 [sample] colors ok를 출력하고, 하나라도 없으면 실패(종료 코드 1)로 끝납니다.

Note

지도가 글자(라벨, 나침반의 글자 등)를 그리면 SDK가 글꼴 관련 캐시를 만들고, 종료 호출(glsGdkShutdown())이 이를 비웁니다. 글자를 그린 프로그램의 종료와 표준 출력은 초기화와 종료에 있습니다.

// The map view starts with no size: Resize first, then fit the view. Style
// changes on layers that are on the map schedule a new render by themselves.
// The checks look for exact style colors, which opaque fills and the inside of
// the markers keep in the rendered frame.
static bool renderToFile(GDK::glsMapView& view, const std::filesystem::path& folder)
{
    if (!succeeded(view.Resize(kWidth, kHeight, kDpi, kDpi))) {
        return false;
    }
    if (!view.ZoomToLayer("districts", 0.05).IsOk()) {
        std::printf("[sample] zoom failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    if (!sample::waitForFrame(view, kRenderTimeoutMs)) {
        return false;  // waitForFrame has printed why
    }
    std::vector<unsigned char> pixels;
    if (!sample::copyFrame(view, kWidth, kHeight, pixels)) {
        std::printf("[sample] copy frame failed: %s\n", GDK::glsGetLastErrorMessage());
        return false;
    }
    if (!sample::writeBmp((folder / "layers.bmp").u8string(), pixels.data(), kWidth, kHeight)) {
        std::printf("[sample] could not write layers.bmp\n");
        return false;
    }
    std::printf("[sample] wrote layers.bmp\n");

    bool ok = sample::countPixels(pixels.data(), kWidth, kHeight, kDistrictFill) > 0;
    if (!ok) {
        std::printf("[sample] district fill color not found\n");
    }
    for (const MarkerColor& marker : kMarkerColors) {
        if (sample::countPixels(pixels.data(), kWidth, kHeight, marker.argb) == 0) {
            std::printf("[sample] %s marker color not found\n", marker.kind);
            ok = false;
        }
    }
    if (ok) {
        std::printf("[sample] colors ok\n");
    }
    return ok;
}

스타일 카탈로그

스타일 카탈로그(glsStyleCatalog, C++과 C# 모두)는 여러 피처 스타일을 id로 묶어 한 JSON 파일로 읽고 쓰는 객체입니다. 파일에서 읽고(LoadJsonFile) 저장하며(SaveJsonFile), 항목을 더하거나 바꾸고, 항목마다 스타일 JSON을 꺼낼 수 있습니다(C++ GetEntryStyleJsonAt, C# EntryAt(index).StyleJson). 꺼낸 스타일 JSON은 이 장의 방법대로 SetFeatureStyleJson으로 레이어에 넣습니다. 자세한 내용은 C++ API 레퍼런스와 .NET API 레퍼런스의 glsStyleCatalog를 보세요.

이 장은 예제에 나온 키만 설명합니다.

다음 장

다음은 9장 선택입니다. 지도에서 피처를 고르고 선택을 읽고 쓰는 방법을 설명합니다.

관련 .NET API

.NET 시작하기 · 객체 관계와 처리 흐름