Esempio n. 1
0
def draw_static(
    root: PlacedObject,
    output_dir: str,
    pixel_size: Tuple[int, int] = (480, 480),
    area=None,
    images=None,
    timeseries=None,
    height_of_stored_images: Optional[int] = None,
    main_robot_name: Optional[str] = None,
) -> Sequence[str]:
    from duckietown_world.world_duckietown import get_sampling_points, ChooseTime

    images = images or {}
    timeseries = timeseries or {}
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    fn_svg = os.path.join(output_dir, "drawing.svg")
    fn_html = os.path.join(output_dir, "drawing.html")

    timestamps = get_sampling_points(root)
    # logger.info(f'timestamps: {timestamps}')
    if len(timestamps) == 0:
        keyframes = SampledSequence[Timestamp]([0], [0])
    else:
        keyframes = SampledSequence[Timestamp](range(len(timestamps)),
                                               timestamps)
    # nkeyframes = len(keyframes)

    if area is None:
        areas = []
        all_keyframes = keyframes.values
        keyframes_for_extent = [all_keyframes[0], all_keyframes[-1]]
        for t in keyframes_for_extent:
            root_t = root.filter_all(ChooseTime(t))
            # print(i, root_t)
            rarea = get_extent_points(root_t)
            areas.append(rarea)
        area = reduce(RectangularArea.join, areas)

    logger.info("area: %s" % area)
    drawing, base = get_basic_upright2(fn_svg, area, pixel_size)
    # drawing.add(drawing.defs())
    gmg = drawing.g()
    base.add(gmg)

    static, dynamic = get_static_and_dynamic(root)

    t0 = keyframes.values[0]
    root_t0 = root.filter_all(ChooseTime(t0))
    g_static = drawing.g()
    g_static.attribs["class"] = "static"

    draw_recursive(drawing, root_t0, g_static, draw_list=static)
    base.add(g_static)

    obs_div = Tag(name="div")
    imagename2div = {}
    for name in images:
        imagename2div[name] = Tag(name="div")
        obs_div.append(imagename2div[name])

    # logger.debug('dynamic: %s' % dynamic)
    for i, t in keyframes:
        g_t = drawing.g()
        g_t.attribs["class"] = "keyframe keyframe%d" % i

        root_t = root.filter_all(ChooseTime(t))

        draw_recursive(drawing, root_t, g_t, draw_list=dynamic)
        base.add(g_t)

        for name, sequence in images.items():
            try:
                obs = sequence.at(t)
                updated = True
            except UndefinedAtTime:
                obs = sequence.at_or_previous(t)
                updated = False

            img = Tag(name="img")
            if isinstance(obs, bytes):
                data = obs
            else:
                data = obs.bytes_contents

            if height_of_stored_images is not None:
                data = get_resized_image(data, height_of_stored_images)
            img.attrs["src"] = data_encoded_for_src(data, "image/jpeg")
            # print('image %s %s: %.4fMB ' % (i, t, len(resized) / (1024 * 1024.0)))
            img.attrs["class"] = "keyframe keyframe%d" % i
            img.attrs["visualize"] = "hide"
            img.attrs["updated"] = int(updated)
            imagename2div[name].append(img)

    other = ""

    # language=html
    visualize_controls = """\
            <style>
            *[visualize_parts=false] {
                display: none;
            }
            </style>

            <p>
            <input id='checkbox-static' type="checkbox"  onclick="hideshow(this);" checked>static data</input>
            <input id='checkbox-textures' type="checkbox"  onclick="hideshow(this);" checked>textures</input>
            <input id='checkbox-axes' type="checkbox"  onclick="hideshow(this);">axes</input>
            <br/>
            <input id='checkbox-lane_segments' type="checkbox"  onclick="hideshow(this);">map lane
            segments</input>
            (<input id='checkbox-lane_segments-control_points' type="checkbox"  onclick="hideshow(
            this);">control
            points</input>)</p>
            </p>


            <p>
            <input id='checkbox-vehicles' type="checkbox"  onclick="hideshow(this);" checked>vehicles</input>
            <input id='checkbox-duckies' type="checkbox"  onclick="hideshow(this);" checked>duckies</input>
            <input id='checkbox-signs' type="checkbox"  onclick="hideshow(this);" checked>signs</input>
            <input id='checkbox-sign-papers' type="checkbox"  onclick="hideshow(this);" checked>signs
            textures</input>
            <input id='checkbox-decorations' type="checkbox"  onclick="hideshow(this);"
            checked>decorations</input>

            </p>
             <p>
            <input id='checkbox-current_lane' type="checkbox"  onclick="hideshow(this);">current lane</input>
            <input id='checkbox-anchors' type="checkbox"  onclick="hideshow(this);">anchor point</input>
            </p>
            <script>
                var checkboxValues = null;
                name2selector = {
                    "checkbox-static": "g.static",
                    "checkbox-textures": "g.static .tile-textures",
                    "checkbox-axes": "g.axes",
                    "checkbox-lane_segments": "g.static .LaneSegment",
                    "checkbox-lane_segments-control_points": " .control-point",
                    "checkbox-current_lane": "g.keyframe .LaneSegment",
                    "checkbox-duckies": ".Duckie",
                    "checkbox-signs": ".Sign",
                    "checkbox-sign-papers": ".Sign .sign-paper",
                    "checkbox-vehicles": ".Vehicle",
                    "checkbox-decorations": ".Decoration",
                    'checkbox-anchors': '.Anchor',
                };
                function hideshow(element) {
                    console.log(element);
                    element_name = element.id;
                    console.log(element_name);
                    selector = name2selector[element_name];
                    checked = element.checked;
                    console.log(selector);
                    console.log(checked);
                    elements = document.querySelectorAll(selector);
                    elements.forEach(_ => _.setAttribute('visualize_parts', checked));
                    checkboxValues[element_name] = checked;
                    try {
                        localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
                    } catch (error) {
                        console.log('cannot save preferences.');
                        console.log(error);
                    }
                }

                function init() {
                    for(var name in name2selector) {
                        console.log(name);
                        element = document.getElementById(name);
                        if(name in checkboxValues) {
                            element.checked = checkboxValues[name];
                        }

                        hideshow(element);
                    }
                }

                document.addEventListener("DOMContentLoaded", function(event) {
                    init();
                });

                try {
                    checkboxValues =  JSON.parse(localStorage.getItem('checkboxValues')) || {};

                } catch (error) {
                    console.log('cannot load preferences.');
                    console.log(error);
                    checkboxValues = {}
                }

                init();
                console.log(checkboxValues);
            </script>
        """

    div_timeseries = str(make_tabs(timeseries))

    obs_div = str(obs_div)
    html = make_html_slider(
        drawing,
        keyframes,
        obs_div=obs_div,
        other=other,
        div_timeseries=div_timeseries,
        visualize_controls=visualize_controls,
    )
    with open(fn_html, "w") as f:
        f.write(html)

    # language=css
    style = """
        .sign-paper {
            display: none;
        }
        g.axes, .LaneSegment {
            display: none;
        }

    """
    drawing.defs.add(drawing.style(style))

    drawing.save(pretty=True)
    logger.info("Written SVG to %s" % fn_svg)
    logger.info("Written HTML to %s" % fn_html)

    return [fn_svg, fn_html]
Esempio n. 2
0
def draw_static(root,
                output_dir,
                pixel_size=(480, 480),
                area=None,
                images=None,
                timeseries=None):
    from duckietown_world.world_duckietown import get_sampling_points, ChooseTime
    images = images or {}
    timeseries = timeseries or {}
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    fn_svg = os.path.join(output_dir, 'drawing.svg')
    fn_html = os.path.join(output_dir, 'drawing.html')

    timestamps = get_sampling_points(root)
    if len(timestamps) == 0:
        keyframes = SampledSequence([0], [0])
    else:
        keyframes = SampledSequence(range(len(timestamps)), timestamps)
    # nkeyframes = len(keyframes)

    if area is None:
        areas = []
        for i, t in keyframes:
            root_t = root.filter_all(ChooseTime(t))
            rarea = get_extent_points(root_t)
            areas.append(rarea)
        area = reduce(RectangularArea.join, areas)

    logger.info('area: %s' % area)
    drawing, base = get_basic_upright2(fn_svg, area, pixel_size)

    gmg = drawing.g()
    base.add(gmg)

    static, dynamic = get_static_and_dynamic(root)

    t0 = keyframes.values[0]
    root_t0 = root.filter_all(ChooseTime(t0))
    g_static = drawing.g()
    g_static.attribs['class'] = 'static'

    draw_recursive(drawing, root_t0, g_static, draw_list=static)
    base.add(g_static)

    obs_div = Tag(name='div')
    imagename2div = {}
    for name in images:
        imagename2div[name] = Tag(name='div')
        obs_div.append(imagename2div[name])

    # logger.debug('dynamic: %s' % dynamic)
    for i, t in keyframes:
        g_t = drawing.g()
        g_t.attribs['class'] = 'keyframe keyframe%d' % i

        root_t = root.filter_all(ChooseTime(t))

        draw_recursive(drawing, root_t, g_t, draw_list=dynamic)
        base.add(g_t)

        for name, sequence in images.items():
            try:
                obs = sequence.at(t)
            except UndefinedAtTime:
                pass
            else:
                img = Tag(name='img')
                resized = get_resized_image(obs.bytes_contents, 200)
                img.attrs['src'] = data_encoded_for_src(resized, 'image/jpeg')
                # print('image %s %s: %.4fMB ' % (i, t, len(resized) / (1024 * 1024.0)))
                img.attrs['class'] = 'keyframe keyframe%d' % i
                img.attrs['visualize'] = 'hide'
                imagename2div[name].append(img)

    other = ""

    # language=html
    visualize_controls = """\
            <style>
            *[visualize_parts=false] {
                display: none;
            }
            </style>
        
            <p>
            <input id='checkbox-static' type="checkbox"  onclick="hideshow(this);" checked>static data</input>
            <input id='checkbox-textures' type="checkbox"  onclick="hideshow(this);" checked>textures</input>
            <input id='checkbox-axes' type="checkbox"  onclick="hideshow(this);">axes</input>
            <br/>
            <input id='checkbox-lane_segments' type="checkbox"  onclick="hideshow(this);">map lane segments</input>
            (<input id='checkbox-lane_segments-control_points' type="checkbox"  onclick="hideshow(this);">control points</input>)</p>
            </p>
           
            
            <p>
            <input id='checkbox-vehicles' type="checkbox"  onclick="hideshow(this);" checked>vehicles</input>
            <input id='checkbox-duckies' type="checkbox"  onclick="hideshow(this);" checked>duckies</input>
            <input id='checkbox-signs' type="checkbox"  onclick="hideshow(this);" checked>signs</input>
            <input id='checkbox-sign-papers' type="checkbox"  onclick="hideshow(this);" checked>signs textures</input>
            <input id='checkbox-decorations' type="checkbox"  onclick="hideshow(this);" checked>decorations</input>
          
            </p>
             <p>
            <input id='checkbox-current_lane' type="checkbox"  onclick="hideshow(this);">current lane</input>
            <input id='checkbox-anchors' type="checkbox"  onclick="hideshow(this);">anchor point</input>
            </p>
            <script>
                var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};
                console.log(checkboxValues);
                name2selector = {
                    "checkbox-static": "g.static",
                    "checkbox-textures": "g.static .tile-textures",
                    "checkbox-axes": "g.axes",
                    "checkbox-lane_segments": "g.static .LaneSegment",
                    "checkbox-lane_segments-control_points": " .control-point",
                    "checkbox-current_lane": "g.keyframe .LaneSegment",
                    "checkbox-duckies": ".Duckie",
                    "checkbox-signs": ".Sign",
                    "checkbox-sign-papers": ".Sign .sign-paper",
                    "checkbox-vehicles": ".Vehicle",
                    "checkbox-decorations": ".Decoration",
                    'checkbox-anchors': '.Anchor',
                };
                function hideshow(element) {
                    console.log(element);
                    element_name = element.id;
                    console.log(element_name);
                    selector = name2selector[element_name];
                    checked = element.checked;
                    console.log(selector);
                    console.log(checked);
                    elements = document.querySelectorAll(selector);
                    elements.forEach(_ => _.setAttribute('visualize_parts', checked));
                    checkboxValues[element_name] = checked;
                    localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
                }
                document.addEventListener("DOMContentLoaded", function(event) {
                    for(var name in name2selector) {
                        console.log(name);
                        element = document.getElementById(name);
                        if(name in checkboxValues) {
                            element.checked = checkboxValues[name];
                        }
                        
                        
                        hideshow(element);
                    } 
                     
                });
            </script>
        """

    div_timeseries = str(make_tabs(timeseries))

    obs_div = str(obs_div)
    html = make_html_slider(drawing,
                            keyframes,
                            obs_div=obs_div,
                            other=other,
                            div_timeseries=div_timeseries,
                            visualize_controls=visualize_controls)
    with open(fn_html, 'w') as f:
        f.write(html)

    # language=css
    style = """
        .sign-paper {
            display: none;
        }
        g.axes, .LaneSegment {
            display: none;
        }
         
    """
    drawing.defs.add(drawing.style(style))

    drawing.save(pretty=True)
    logger.info('Written SVG to %s' % fn_svg)
    logger.info('Written HTML to %s' % fn_html)

    return [fn_svg, fn_html]