summaryrefslogtreecommitdiff
path: root/platform/darwin/src/MGLOpenGLStyleLayer.mm
blob: 2641369fd13d16f0053deb2923a1c0d2f6c4554f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#import "MGLOpenGLStyleLayer.h"

#import "MGLMapView_Private.h"
#import "MGLStyle_Private.h"
#import "MGLStyleLayer_Private.h"

#include <mbgl/style/layers/custom_layer.hpp>
#include <mbgl/math/wrap.hpp>

class MGLOpenGLStyleLayerContext: public mbgl::style::CustomLayerContext
{
public:
    __weak MGLOpenGLStyleLayer* layer;
    int layerRetainCount;

    MGLOpenGLStyleLayerContext(MGLOpenGLStyleLayer *layer_) :
        mbgl::style::CustomLayerContext(),
        layer(layer_),
        layerRetainCount(0)
    {

    }

    ~MGLOpenGLStyleLayerContext()
    {
        while (layerRetainCount) {
            detach();
        }
    }

    void attach()
    {
        if (!layer) return;

        assert(layerRetainCount >= 0);

        @autoreleasepool {
            CFBridgingRetain(layer);
        }
        layerRetainCount++;

        printf("LayerRetainer %p retained %d", this, layerRetainCount);
    }


    void detach()
    {
        if (!layer) return;

        assert(layerRetainCount > 0);

        layerRetainCount--;

        @autoreleasepool {
            CFBridgingRelease((__bridge CFTypeRef)layer);
        }

        printf("LayerRetainer %p released %d", this, layerRetainCount);
    }

    // Custom stuff

    /**
     Runs the preparation handler block contained in the given context, which is
     implicitly an instance of `MGLOpenGLStyleLayer`.

     */
    void initialize() {
        [layer didMoveToMapView:layer.style.mapView];
    };

    /**
     Runs the drawing handler block contained in the given context, which is
     implicitly an instance of `MGLOpenGLStyleLayer`.

     */
    void render(const mbgl::style::CustomLayerRenderParameters& params) {

        MGLStyleLayerDrawingContext drawingContext = {
            .size = CGSizeMake(params.width, params.height),
            .centerCoordinate = CLLocationCoordinate2DMake(params.latitude, params.longitude),
            .zoomLevel = params.zoom,
            .direction = mbgl::util::wrap(params.bearing, 0., 360.),
            .pitch = static_cast<CGFloat>(params.pitch),
            .fieldOfView = static_cast<CGFloat>(params.fieldOfView),
        };
        [layer drawInMapView:layer.style.mapView withContext:drawingContext];
    };

    /**
     Runs the completion handler block contained in the given context, which is
     implicitly an instance of `MGLOpenGLStyleLayer`.

     */
    void deinitialize() {
        [layer willMoveFromMapView:layer.style.mapView];
    };
};



/**
 An `MGLOpenGLStyleLayer` is a style layer that is rendered by OpenGL code that
 you provide.

 By default, this class does nothing. You can subclass this class to provide
 custom OpenGL drawing code that is run on each frame of the map. Your subclass
 should override the `-didMoveToMapView:`, `-willMoveFromMapView:`, and
 `-drawInMapView:withContext:` methods.

 You can access an existing OpenGL style layer using the
 `-[MGLStyle layerWithIdentifier:]` method if you know its identifier;
 otherwise, find it using the `MGLStyle.layers` property. You can also create a
 new OpenGL style layer and add it to the style using a method such as
 `-[MGLStyle addLayer:]`.

 @warning This API is undocumented and therefore unsupported. It may change at
    any time without notice.
 */
@interface MGLOpenGLStyleLayer ()

@property (nonatomic, readonly) mbgl::style::CustomLayer *rawLayer;

/**
 The style currently containing the layer.

 If the layer is not currently part of any style, this property is
 set to `nil`.
 */
@property (nonatomic, weak, readwrite) MGLStyle *style;

@end

@implementation MGLOpenGLStyleLayer

- (void)dealloc
{
    NSLog(@"MGLOpenGLStyleLayer dealloc %p\n", self);
}

/**
 Returns an OpenGL style layer object initialized with the given identifier.

 After initializing and configuring the style layer, add it to a map view’s
 style using the `-[MGLStyle addLayer:]` or
 `-[MGLStyle insertLayer:belowLayer:]` method.

 @param identifier A string that uniquely identifies the layer in the style to
    which it is added.
 @return An initialized OpenGL style layer.
 */

- (instancetype)initWithIdentifier:(NSString *)identifier {

    NSLog(@"MGLOpenGLStyleLayer init %p\n", self);

    auto context = std::make_unique<MGLOpenGLStyleLayerContext>(self);

    // Note, do not retain self here, otherwise MGLOpenGLStyleLayer will never be dealloc'd
    auto layer = std::make_unique<mbgl::style::CustomLayer>(identifier.UTF8String,
                                                            std::move(context));

    self = [super initWithPendingLayer:std::move(layer)];

    if (self) {
        __weak MGLOpenGLStyleLayer *weakself = self;

        self.rawLayer->onDestruction =^{
            weakself.rawLayer = NULL;
        };
    }

    return self;

}

- (mbgl::style::CustomLayer *)rawLayer {
    return (mbgl::style::CustomLayer *)super.rawLayer;
}

#pragma mark - Adding to and removing from a map view

- (void)setStyle:(MGLStyle *)style {
    if (_style && style) {
        [NSException raise:@"MGLLayerReuseException"
                    format:@"%@ cannot be added to more than one MGLStyle at a time.", self];
    }
    _style = style;
}

- (void)addToStyle:(MGLStyle *)style belowLayer:(MGLStyleLayer *)otherLayer {
    self.style = style;

    // We need to ensure that this layer is retained, so that any references from layer impl's
    // e.g. contexts) are still valid
//    [style addToManagedLayers:self];

    [super addToStyle:style belowLayer:otherLayer];
}

- (void)removeFromStyle:(MGLStyle *)style {
    [super removeFromStyle:style];

    // We need to ensure that this layer is now released (however, if this layer is about to be
    // used by the renderer then it will released once rendering is complete)
//    [style removeFromManagedLayers:self];

    self.style = nil;
}

/**
 Called immediately after a layer is added to a map view’s style.

 This method is intended to be overridden in a subclass. You can use this method
 to perform any setup work before the layer is used to draw a frame. For
 example, you might use this method to compile an OpenGL shader. The default
 implementation of this method does nothing.

 Any resource acquired in this method must be released in
 `-willMoveFromMapView:`.

 @param mapView The map view to whose style the layer has been added.
 */
- (void)didMoveToMapView:(MGLMapView *)mapView {

}

/**
 Called immediately before a layer is removed from a map view’s style.

 This method is intended to be overridden in a subclass. You can use this method
 to perform any teardown work once the layer has drawn its last frame and is
 about to be removed from the style. The default implementation of this method
 does nothing.

 This method may be called even if `-didMoveToMapView:` has not been called.

 @param mapView The map view from whose style the layer is about to be removed.
 */
- (void)willMoveFromMapView:(MGLMapView *)mapView {

}

/**
 Called each time the layer needs to draw a new frame in a map view.

 This method is intended to be overridden in a subclass. You can use this method
 to draw the layer’s content. The default implementation of this method does
 nothing.

 Your implementation should not make any assumptions about the OpenGL state,
 other than that the current OpenGL context is active. It may make changes to
 the OpenGL state. It is not required to reset values such as the depth mask,
 stencil mask, or corresponding test flags to their original values.

 Be sure to draw your fragments with a <var>z</var> value of 1 to take advantage
 of the opaque fragment culling, in case the style contains any opaque layers
 above this layer.

 @param mapView The map view to which the layer draws.
 @param context A context structure with information defining the frame to draw.
 */
- (void)drawInMapView:(MGLMapView *)mapView withContext:(MGLStyleLayerDrawingContext)context {

}

/**
 Forces the map view associated with this style to redraw the receiving layer,
 causing the `-drawInMapView:withContext:` method to be called.
 */
- (void)setNeedsDisplay {
    [self.style.mapView setNeedsGLDisplay];
}

@end