comparison engine/core/view/layercache.cpp @ 482:16c2b3ee59ce

* Merged the view performance branch back into trunk. fixes[ticket:419]
author helios2000@33b003aa-7bff-0310-803a-e67f0ece8222
date Thu, 29 Apr 2010 13:51:45 +0000
parents
children f45e3e2995e0
comparison
equal deleted inserted replaced
481:1f37adc9a685 482:16c2b3ee59ce
1 /***************************************************************************
2 * Copyright (C) 2005-2008 by the FIFE team *
3 * http://www.fifengine.de *
4 * This file is part of FIFE. *
5 * *
6 * FIFE is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Lesser General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2.1 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
14 * Lesser General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Lesser General Public *
17 * License along with this library; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
20 ***************************************************************************/
21
22 // Standard C++ library includes
23
24 // 3rd party library includes
25 #include <SDL.h>
26
27 // FIFE includes
28 // These includes are split up in two parts, separated by one empty line
29 // First block: files included from the FIFE root src directory
30 // Second block: files included from the same folder
31
32 #include "model/metamodel/grids/cellgrid.h"
33 #include "model/metamodel/action.h"
34 #include "model/structures/layer.h"
35 #include "model/structures/instance.h"
36 #include "model/structures/location.h"
37 #include "util/base/exception.h"
38 #include "util/log/logger.h"
39 #include "util/math/fife_math.h"
40 #include "util/math/angles.h"
41 #include "video/renderbackend.h"
42 #include "video/image.h"
43 #include "video/imagepool.h"
44 #include "video/animation.h"
45 #include "video/animationpool.h"
46
47 #include "camera.h"
48 #include "layercache.h"
49 #include "visual.h"
50
51
52 namespace FIFE {
53 static Logger _log(LM_CAMERA);
54
55 class CacheLayerChangeListener : public LayerChangeListener {
56 public:
57 CacheLayerChangeListener(LayerCache* cache)
58 {
59 m_cache = cache;
60 }
61 virtual ~CacheLayerChangeListener() {};
62
63 virtual void onLayerChanged(Layer* layer, std::vector<Instance*>& instances)
64 {
65 for(std::vector<Instance*>::iterator i = instances.begin();
66 i != instances.end(); ++i) {
67 m_cache->updateInstance(*i);
68 }
69 }
70
71 virtual void onInstanceCreate(Layer* layer, Instance* instance)
72 {
73 m_cache->addInstance(instance);
74 }
75
76 virtual void onInstanceDelete(Layer* layer, Instance* instance)
77 {
78 m_cache->removeInstance(instance);
79 }
80 private:
81 LayerCache* m_cache;
82 };
83
84 LayerCache::LayerCache(Camera* camera, ImagePool* image_pool, AnimationPool* animation_pool) {
85 m_camera = camera;
86 m_image_pool = image_pool;
87 m_animation_pool = animation_pool;
88 m_layer = 0;
89 m_tree = 0;
90 }
91
92 LayerCache::~LayerCache() {
93 m_layer->removeChangeListener(m_layer_observer);
94 delete m_layer_observer;
95 delete m_tree;
96 }
97
98 void LayerCache::setLayer(Layer* layer) {
99 m_layer = layer;
100 m_layer_observer = new CacheLayerChangeListener(this);
101 layer->addChangeListener(m_layer_observer);
102 reset();
103 }
104
105 void LayerCache::reset() {
106 m_instances.clear();
107 delete m_tree;
108 m_tree = new CacheTree;
109 const std::vector<Instance*>& instances = m_layer->getInstances();
110 for(std::vector<Instance*>::const_iterator i = instances.begin();
111 i != instances.end(); ++i) {
112 addInstance(*i);
113 }
114 }
115
116 void LayerCache::addInstance(Instance* instance) {
117 if(m_instance_map.find(instance)!=m_instance_map.end()) {
118 throw new Duplicate(instance->getId());
119 }
120
121 RenderItem item;
122 Entry entry;
123 item.instance = instance;
124 m_instances.push_back(item);
125 m_instance_map[instance] = m_instances.size() - 1;
126
127 entry.node = 0;
128 entry.instance_index = m_instances.size() - 1;
129 entry.entry_index = m_entries.size();
130 m_entries.push_back(entry);
131 updateEntry(m_entries.back());
132 }
133
134 void LayerCache::removeInstance(Instance* instance) {
135 // FIXME
136 // The way LayerCache stores it's data
137 // it's pretty much impossible to cleanly remove
138 // added instances.
139
140 // This has to get fixed.
141 if(m_instance_map.find(instance) == m_instance_map.end()) {
142 throw new NotFound(instance->getId());
143 }
144 Entry& item = m_entries[m_instance_map[instance]];
145 assert(item.instance_index == m_instance_map[instance]);
146
147 if(item.node)
148 item.node->data().erase(item.entry_index);
149 item.node = 0;
150 item.instance_index = unsigned(-1);
151 m_instance_map.erase(instance);
152 }
153
154 void LayerCache::updateInstance(Instance* instance) {
155 Entry& entry = m_entries[m_instance_map[instance]];
156 updateEntry(entry);
157 }
158
159 void LayerCache::updateEntry(LayerCache::Entry& item) {
160 if(item.instance_index == unsigned(-1)) {
161 return;
162 }
163 if(item.node) {
164 item.node->data().erase(item.entry_index);
165 }
166 RenderItem& render_item = m_instances[item.instance_index];
167 Instance* instance = render_item.instance;
168
169 DoublePoint3D screen_position = m_camera->toVirtualScreenCoordinates(instance->getLocationRef().getMapCoordinates());
170
171 render_item.facing_angle = getAngleBetween(instance->getLocationRef(), instance->getFacingLocation());
172 int angle = m_camera->getRotation() + render_item.facing_angle + instance->getRotation();
173
174 Image* image = NULL;
175 Action* action = instance->getCurrentAction();
176 int w = 0;
177 int h = 0;
178 int xshift = 0;
179 int yshift = 0;
180
181 if(!action) {
182 // Try static images then default action.
183 int image_id = render_item.getStaticImageIndexByAngle(angle, instance);
184 if(image_id == Pool::INVALID_ID) {
185 action = instance->getObject()->getDefaultAction();
186 } else {
187 image = &m_image_pool->getImage(image_id);
188 }
189 }
190 item.force_update = bool(action);
191
192 if(action) {
193 int animation_id = action->getVisual<ActionVisual>()->getAnimationIndexByAngle(render_item.facing_angle + m_camera->getRotation());
194 Animation& animation = m_animation_pool->getAnimation(animation_id);
195 unsigned animation_time = instance->getActionRuntime() % animation.getDuration();
196 image = animation.getFrameByTimestamp(animation_time);
197
198 int facing_angle = render_item.facing_angle;
199 if (facing_angle < 0){
200 facing_angle += 360;
201 }
202 instance->setRotation(facing_angle);
203 }
204
205 if (image) {
206 w = image->getWidth();
207 h = image->getHeight();
208 xshift = image->getXShift();
209 yshift = image->getYShift();
210 }
211
212 screen_position.x -= w / 2;
213 screen_position.x += xshift;
214 screen_position.y -= h / 2;
215 screen_position.y += yshift;
216
217 render_item.image = image;
218 render_item.screenpoint = screen_position;
219
220 render_item.bbox.x = screen_position.x;
221 render_item.bbox.y = screen_position.y;
222 render_item.bbox.w = w;
223 render_item.bbox.h = h;
224
225 render_item.dimensions.x = screen_position.x;
226 render_item.dimensions.y = screen_position.y;
227 render_item.dimensions.w = w;
228 render_item.dimensions.h = h;
229
230 CacheTree::Node* node = m_tree->find_container(render_item.bbox);
231 item.node = node;
232 node->data().insert(item.entry_index);
233 }
234
235 class CacheTreeCollector {
236 std::vector<int>& m_indices;
237 Rect m_viewport;
238 public:
239 CacheTreeCollector(std::vector<int>& indices, const Rect& _viewport)
240 : m_indices(indices), m_viewport(_viewport) {
241 }
242 bool visit(LayerCache::CacheTree::Node* node, int d = -1);
243 };
244
245 bool CacheTreeCollector::visit(LayerCache::CacheTree::Node* node, int d) {
246 if(!m_viewport.intersects(Rect(node->x(), node->y(),node->size(),node->size())))
247 return false;
248 std::set<int>& list = node->data();
249 for(std::set<int>::iterator i = list.begin(); i!=list.end();++i) {
250 m_indices.push_back(*i);
251 }
252 return true;
253 }
254
255 void LayerCache::collect(const Rect& viewport, std::vector<int>& index_list) {
256 CacheTree::Node * node = m_tree->find_container(viewport);
257 CacheTreeCollector collector(index_list, viewport);
258 node->apply_visitor(collector);
259 node = node->parent();
260 while(node) {
261 collector.visit(node);
262 node = node->parent();
263 }
264 }
265
266 void LayerCache::fullUpdate() {
267 for(unsigned i=0; i!=m_entries.size(); ++i)
268 updateEntry(m_entries[i]);
269 }
270
271 class InstanceDistanceSort {
272 public:
273 inline bool operator()(RenderItem* const & lhs, RenderItem* const & rhs) {
274 if (lhs->screenpoint.z == rhs->screenpoint.z) {
275 InstanceVisual* liv = lhs->instance->getVisual<InstanceVisual>();
276 InstanceVisual* riv = rhs->instance->getVisual<InstanceVisual>();
277 return liv->getStackPosition() < riv->getStackPosition();
278 }
279 return lhs->screenpoint.z < rhs->screenpoint.z;
280 }
281 };
282
283 void LayerCache::update(Camera::Transform transform, RenderList& renderlist) {
284 const double OVERDRAW = 2.5;
285 renderlist.clear();
286 bool isWarped = transform == Camera::WarpedTransform;
287 if( isWarped )
288 fullUpdate();
289
290 Rect viewport = m_camera->getViewPort();
291 Rect screen_viewport = viewport;
292 float zoom = m_camera->getZoom();
293 DoublePoint3D viewport_a = m_camera->screenToVirtualScreen(Point3D(viewport.x, viewport.y));
294 DoublePoint3D viewport_b = m_camera->screenToVirtualScreen(Point3D(viewport.right(), viewport.bottom()));
295 viewport.x = std::min(viewport_a.x, viewport_b.x);
296 viewport.y = std::min(viewport_a.y, viewport_b.y);
297 viewport.w = std::max(viewport_a.x, viewport_b.x) - viewport.x;
298 viewport.h = std::max(viewport_a.y, viewport_b.y) - viewport.y;
299
300 // FL_LOG(_log, LMsg("camera-update viewport") << viewport);
301 std::vector<int> index_list;
302 collect(viewport, index_list);
303 for(unsigned i=0; i!=index_list.size();++i) {
304 Entry& entry = m_entries[index_list[i]];
305 // NOTE
306 // An update is forced if the item has an animation/action.
307 // This update only happens if it is _already_ included in the viewport
308 // Nevertheless: Moving instances - which might move into the viewport will be updated
309 // By the layer change listener.
310 if(entry.force_update)
311 updateEntry(entry);
312
313 RenderItem& item = m_instances[entry.instance_index];
314 if(!item.image)
315 continue;
316
317 Point3D screen_point = m_camera->virtualScreenToScreen(item.screenpoint);
318 // NOTE:
319 // One would expect this to be necessary here,
320 // however it works the same without, sofar
321 // m_camera->calculateZValue(screen_point);
322 // item.screenpoint.z = -screen_point.z;
323
324 item.dimensions.x = screen_point.x;
325 item.dimensions.y = screen_point.y;
326 item.dimensions.w = unsigned(double(item.bbox.w) * zoom + OVERDRAW);
327 item.dimensions.h = unsigned(double(item.bbox.h) * zoom + OVERDRAW);
328
329 if (zoom != 1.0) {
330 // NOTE: Due to image alignment, there is additional additions on image dimensions
331 // There's probabaly some better solution for this, but works "good enough" for now.
332 // In case additions are removed, gaps appear between tiles.
333 item.dimensions.w = unsigned(ceil(double(item.bbox.w) * zoom)) + OVERDRAW;
334 item.dimensions.h = unsigned(ceil(double(item.bbox.h) * zoom)) + OVERDRAW;
335 }
336
337 if(item.dimensions.intersects(screen_viewport))
338 renderlist.push_back(&item);
339 }
340
341 InstanceDistanceSort ids;
342 std::stable_sort(renderlist.begin(), renderlist.end(), ids);
343 // FL_LOG(_log, LMsg("camera-update ") << " N=" <<renderlist.size() << "/" << m_instances.size() << "/" << index_list.size());
344 }
345 }