FIFE  2008.0
 All Classes Namespaces Functions Variables Enumerations Enumerator Pages
layercache.cpp
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 #include <cfloat>
24 
25 // 3rd party library includes
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/animation.h"
44 #include "video/imagemanager.h"
45 
46 #include "camera.h"
47 #include "layercache.h"
48 #include "visual.h"
49 
50 
51 namespace FIFE {
52  static Logger _log(LM_CAMERA);
53 
54  class CacheLayerChangeListener : public LayerChangeListener {
55  public:
56  CacheLayerChangeListener(LayerCache* cache) {
57  m_cache = cache;
58  }
59  virtual ~CacheLayerChangeListener() {};
60 
61  virtual void onLayerChanged(Layer* layer, std::vector<Instance*>& instances) {
62  for(std::vector<Instance*>::iterator i = instances.begin();
63  i != instances.end(); ++i) {
64  m_cache->updateInstance(*i);
65  }
66  }
67 
68  virtual void onInstanceCreate(Layer* layer, Instance* instance) {
69  m_cache->addInstance(instance);
70  }
71 
72  virtual void onInstanceDelete(Layer* layer, Instance* instance) {
73  m_cache->removeInstance(instance);
74  }
75  private:
76  LayerCache* m_cache;
77  };
78 
79  LayerCache::LayerCache(Camera* camera) {
80  m_camera = camera;
81  m_layer = 0;
82  m_tree = 0;
83  m_needupdate = false;
84  m_need_sorting = true;
85 
86  if(RenderBackend::instance()->getName() == "OpenGLe") {
87  m_need_sorting = false;
88  }
89  }
90 
91  LayerCache::~LayerCache() {
92  m_layer->removeChangeListener(m_layer_observer);
93  delete m_layer_observer;
94  delete m_tree;
95  }
96 
97  void LayerCache::setLayer(Layer* layer) {
98  m_layer = layer;
99  m_layer_observer = new CacheLayerChangeListener(this);
100  layer->addChangeListener(m_layer_observer);
101  reset();
102  }
103 
104  void LayerCache::reset() {
105  m_instances.clear();
106  delete m_tree;
107  m_tree = new CacheTree;
108  const std::vector<Instance*>& instances = m_layer->getInstances();
109  for(std::vector<Instance*>::const_iterator i = instances.begin();
110  i != instances.end(); ++i) {
111  addInstance(*i);
112  }
113  m_needupdate = true;
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  m_needupdate = true;
133  }
134 
135  void LayerCache::removeInstance(Instance* instance) {
136  // FIXME
137  // The way LayerCache stores it's data
138  // it's pretty much impossible to cleanly remove
139  // added instances.
140 
141  // This has to get fixed.
142  if(m_instance_map.find(instance) == m_instance_map.end()) {
143  throw new NotFound(instance->getId());
144  }
145  Entry& item = m_entries[m_instance_map[instance]];
146  assert(item.instance_index == m_instance_map[instance]);
147 
148  if(item.node) {
149  item.node->data().erase(item.entry_index);
150  }
151  item.node = 0;
152  item.instance_index = -1;
153  m_instance_map.erase(instance);
154  m_needupdate = true;
155  }
156 
157  void LayerCache::updateInstance(Instance* instance) {
158  Entry& entry = m_entries[m_instance_map[instance]];
159  updateEntry(entry);
160  }
161 
162  void LayerCache::updateEntry(LayerCache::Entry& item) {
163  if(item.instance_index == -1) {
164  return;
165  }
166 
167  RenderItem& render_item = m_instances[item.instance_index];
168  Instance* instance = render_item.instance;
169 
170  ExactModelCoordinate map_coords = instance->getLocationRef().getMapCoordinates();
171  DoublePoint3D screen_position = m_camera->toVirtualScreenCoordinates(map_coords);
172  render_item.instance_z = instance->getLocationRef().getExactLayerCoordinates().z;
173 
174  render_item.facing_angle = getAngleBetween(instance->getLocationRef(), instance->getFacingLocation());
175  int32_t angle = static_cast<int32_t>(m_camera->getRotation()) +
176  render_item.facing_angle + instance->getRotation();
177 
178  ImagePtr image;
179  Action* action = instance->getCurrentAction();
180  int32_t w = 0;
181  int32_t h = 0;
182 
183  if(!action) {
184  // Try static images then default action.
185  int32_t image_id = render_item.getStaticImageIndexByAngle(angle, instance);
186  if(image_id == -1) {
187  if (!instance->getObject()->isStatic()) {
188  action = instance->getObject()->getDefaultAction();
189  }
190  } else {
191  image = ImageManager::instance()->get(image_id);
192  }
193  }
194  item.force_update = (action != 0);
195 
196  if(action) {
197  AnimationPtr animation = action->getVisual<ActionVisual>()->getAnimationByAngle(
198  render_item.facing_angle + static_cast<int32_t>(m_camera->getRotation()));
199  unsigned animation_time = instance->getActionRuntime() % animation->getDuration();
200 
201  image = animation->getFrameByTimestamp(animation_time);
202 
203  int32_t action_frame = animation->getActionFrame();
204  if (action_frame != -1) {
205  if (render_item.image != image) {
206  if (action_frame == animation->getFrameIndex(animation_time)) {
207  instance->callOnActionFrame(action, action_frame);
208  }
209  }
210  }
211 
212  int32_t facing_angle = render_item.facing_angle;
213  if (facing_angle < 0){
214  facing_angle += 360;
215  }
216  instance->setRotation(facing_angle);
217  m_needupdate = true;
218  }
219 
220  if (image) {
221  w = image->getWidth();
222  h = image->getHeight();
223 
224  screen_position.x -= w / 2;
225  screen_position.x += image->getXShift();
226  screen_position.y -= h / 2;
227  screen_position.y += image->getYShift();
228  }
229 
230  render_item.image = image;
231  if (render_item.screenpoint == screen_position) {
232  return;
233  }
234  m_needupdate = true;
235  render_item.screenpoint = screen_position;
236 
237  render_item.bbox.x = static_cast<int32_t>(screen_position.x);
238  render_item.bbox.y = static_cast<int32_t>(screen_position.y);
239  render_item.bbox.w = w;
240  render_item.bbox.h = h;
241 
242  render_item.dimensions = render_item.bbox;
243 
244  CacheTree::Node* node = m_tree->find_container(render_item.bbox);
245  if (node) {
246  if(item.node) {
247  item.node->data().erase(item.entry_index);
248  }
249  item.node = node;
250  node->data().insert(item.entry_index);
251  }
252  }
253 
254  class CacheTreeCollector {
255  std::vector<int32_t>& m_indices;
256  Rect m_viewport;
257  public:
258  CacheTreeCollector(std::vector<int32_t>& indices, const Rect& _viewport)
259  : m_indices(indices), m_viewport(_viewport) {
260  }
261  bool visit(LayerCache::CacheTree::Node* node, int32_t d = -1);
262  };
263 
264  bool CacheTreeCollector::visit(LayerCache::CacheTree::Node* node, int32_t d) {
265  if(!m_viewport.intersects(Rect(node->x(), node->y(),node->size(),node->size()))) {
266  return false;
267  }
268  std::set<int32_t>& list = node->data();
269  for(std::set<int32_t>::iterator i = list.begin(); i!=list.end();++i) {
270  m_indices.push_back(*i);
271  }
272  return true;
273  }
274 
275  void LayerCache::collect(const Rect& viewport, std::vector<int32_t>& index_list) {
276  CacheTree::Node * node = m_tree->find_container(viewport);
277  CacheTreeCollector collector(index_list, viewport);
278  node->apply_visitor(collector);
279  node = node->parent();
280  while(node) {
281  collector.visit(node);
282  node = node->parent();
283  }
284  }
285 
286  void LayerCache::fullUpdate() {
287  for(unsigned i=0; i!=m_entries.size(); ++i) {
288  updateEntry(m_entries[i]);
289  }
290  }
291 
292  class InstanceDistanceSort {
293  public:
294  inline bool operator()(RenderItem* const & lhs, RenderItem* const & rhs) {
295  if (lhs->screenpoint.z == rhs->screenpoint.z) {
296  InstanceVisual* liv = lhs->instance->getVisual<InstanceVisual>();
297  InstanceVisual* riv = rhs->instance->getVisual<InstanceVisual>();
298  return liv->getStackPosition() < riv->getStackPosition();
299  }
300  return lhs->screenpoint.z < rhs->screenpoint.z;
301  }
302  };
303 
304  void LayerCache::update(Camera::Transform transform, RenderList& renderlist) {
305  const double OVERDRAW = 2.5;
306  renderlist.clear();
307  m_needupdate = false;
308  if(!m_layer->areInstancesVisible()) {
309  FL_DBG(_log, "Layer instances hidden");
310  return;
311  }
312  bool isWarped = transform == Camera::WarpedTransform;
313  if( isWarped ) {
314  fullUpdate();
315  }
316 
317  Rect viewport = m_camera->getViewPort();
318  Rect screen_viewport = viewport;
319  double zoom = m_camera->getZoom();
320  DoublePoint3D viewport_a = m_camera->screenToVirtualScreen(Point3D(viewport.x, viewport.y));
321  DoublePoint3D viewport_b = m_camera->screenToVirtualScreen(Point3D(viewport.right(), viewport.bottom()));
322  viewport.x = static_cast<int32_t>(std::min(viewport_a.x, viewport_b.x));
323  viewport.y = static_cast<int32_t>(std::min(viewport_a.y, viewport_b.y));
324  viewport.w = static_cast<int32_t>(std::max(viewport_a.x, viewport_b.x) - viewport.x);
325  viewport.h = static_cast<int32_t>(std::max(viewport_a.y, viewport_b.y) - viewport.y);
326  uint8_t layer_trans = m_layer->getLayerTransparency();
327 
328  double zmin = 0.0, zmax = 0.0;
329 
330  // FL_LOG(_log, LMsg("camera-update viewport") << viewport);
331  std::vector<int32_t> index_list;
332  collect(viewport, index_list);
333  for(unsigned i=0; i!=index_list.size();++i) {
334  Entry& entry = m_entries[index_list[i]];
335  // NOTE
336  // An update is forced if the item has an animation/action.
337  // This update only happens if it is _already_ included in the viewport
338  // Nevertheless: Moving instances - which might move into the viewport will be updated
339  // By the layer change listener.
340  if(entry.force_update || !isWarped) {
341  updateEntry(entry);
342  }
343 
344  RenderItem& item = m_instances[entry.instance_index];
345  InstanceVisual* visual = item.instance->getVisual<InstanceVisual>();
346  bool visible = (visual->isVisible() != 0);
347  uint8_t instance_trans = visual->getTransparency();
348  if(!item.image || !visible || (instance_trans == 255 && layer_trans == 0)
349  || (instance_trans == 0 && layer_trans == 255)) {
350  continue;
351  }
352 
353  if(layer_trans != 0) {
354  if(instance_trans != 0) {
355  uint8_t calc_trans = layer_trans - instance_trans;
356  if(calc_trans >= 0) {
357  instance_trans = calc_trans;
358  } else {
359  instance_trans = 0;
360  }
361  } else {
362  instance_trans = layer_trans;
363  }
364  }
365 
366  Point3D screen_point = m_camera->virtualScreenToScreen(item.screenpoint);
367  // NOTE:
368  // One would expect this to be necessary here,
369  // however it works the same without, sofar
370  // m_camera->calculateZValue(screen_point);
371  // item.screenpoint.z = -screen_point.z;
372 
373  item.dimensions.x = screen_point.x;
374  item.dimensions.y = screen_point.y;
375  item.dimensions.w = item.bbox.w;
376  item.dimensions.h = item.bbox.h;
377 
378  item.transparency = 255 - instance_trans;
379 
380  if (zoom != 1.0) {
381  // NOTE: Due to image alignment, there is additional additions on image dimensions
382  // There's probabaly some better solution for this, but works "good enough" for now.
383  // In case additions are removed, gaps appear between tiles.
384  item.dimensions.w = unsigned(double(item.bbox.w) * zoom + OVERDRAW);
385  item.dimensions.h = unsigned(double(item.bbox.h) * zoom + OVERDRAW);
386  }
387 
388  if (!m_need_sorting) {
389  zmin = std::min(zmin, item.screenpoint.z);
390  zmax = std::max(zmax, item.screenpoint.z);
391  }
392 
393  if(item.dimensions.intersects(screen_viewport)) {
394  renderlist.push_back(&item);
395  }
396  }
397 
398  if (m_need_sorting) {
399  InstanceDistanceSort ids;
400  std::stable_sort(renderlist.begin(), renderlist.end(), ids);
401  } else {
402  zmin -= 0.5;
403  zmax += 0.5;
404 
405  // We want to put every z value in [-10,10] range.
406  // To do it, we simply solve
407  // { y1 = a*x1 + b
408  // { y2 = a*x2 + b
409  // where [y1,y2]' = [-10,10]' is required z range,
410  // and [x1,x2]' is expected min,max z coords.
411  double det = zmin - zmax;
412  if (fabs(det) > FLT_EPSILON) {
413  double det_a = -10.0 - 10.0;
414  double det_b = 10.0 * zmin - (-10.0) * zmax;
415  double a = static_cast<float>(det_a / det);
416  double b = static_cast<float>(det_b / det);
417  float estimate = sqrtf(static_cast<float>(renderlist.size()));
418  float stack_delta = fabs(-10.0f - 10.0f) / estimate * 0.1f;
419 
420  RenderList::iterator it = renderlist.begin();
421  for ( ; it != renderlist.end(); ++it) {
422  double& z = (*it)->screenpoint.z;
423  z = a * z + b;
424  InstanceVisual* vis = (*it)->instance->getVisual<InstanceVisual>();
425  z += vis->getStackPosition() * stack_delta;
426  }
427  }
428  }
429  // FL_LOG(_log, LMsg("camera-update ") << " N=" <<renderlist.size() << "/" << m_instances.size() << "/" << index_list.size());
430  }
431 }