BillboardSet.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Batch.h"
  25. #include "BillboardSet.h"
  26. #include "Camera.h"
  27. #include "Context.h"
  28. #include "Geometry.h"
  29. #include "Graphics.h"
  30. #include "GraphicsImpl.h"
  31. #include "IndexBuffer.h"
  32. #include "Material.h"
  33. #include "MemoryBuffer.h"
  34. #include "Profiler.h"
  35. #include "ResourceCache.h"
  36. #include "Sort.h"
  37. #include "VectorBuffer.h"
  38. #include "VertexBuffer.h"
  39. #include "XMLElement.h"
  40. #include "DebugNew.h"
  41. static const Vector3 dotScale(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  42. inline bool CompareBillboards(Billboard* lhs, Billboard* rhs)
  43. {
  44. return lhs->sortDistance_ > rhs->sortDistance_;
  45. }
  46. OBJECTTYPESTATIC(BillboardSet);
  47. BillboardSet::BillboardSet(Context* context) :
  48. Drawable(context),
  49. geometry_(new Geometry(context_)),
  50. animationLodBias_(1.0f),
  51. animationLodTimer_(0.0f),
  52. relative_(true),
  53. scaled_(true),
  54. sorted_(false),
  55. bufferSizeDirty_(true),
  56. bufferDirty_(true),
  57. forceUpdate_(false),
  58. previousOffset_(Vector3::ZERO),
  59. sortFrameNumber_(0)
  60. {
  61. drawableFlags_ = DRAWABLE_GEOMETRY;
  62. }
  63. BillboardSet::~BillboardSet()
  64. {
  65. }
  66. void BillboardSet::RegisterObject(Context* context)
  67. {
  68. context->RegisterFactory<BillboardSet>();
  69. context->CopyBaseAttributes<Drawable, BillboardSet>();
  70. ATTRIBUTE(BillboardSet, VAR_FLOAT, "Animation LOD Bias", animationLodBias_, 1.0f);
  71. ATTRIBUTE(BillboardSet, VAR_BOOL, "Relative Position", relative_, true);
  72. ATTRIBUTE(BillboardSet, VAR_BOOL, "Relative Scale", scaled_, true);
  73. ATTRIBUTE(BillboardSet, VAR_BOOL, "Sort By Distance", sorted_, false);
  74. ATTRIBUTE(BillboardSet, VAR_RESOURCEREF, "Material", material_, ResourceRef(Material::GetTypeStatic()));
  75. ATTRIBUTE(BillboardSet, VAR_BUFFER, "Billboards", billboards_, Vector<unsigned char>());
  76. }
  77. void BillboardSet::OnSetAttribute(const AttributeInfo& attr, const Variant& value)
  78. {
  79. ResourceCache* cache = GetSubsystem<ResourceCache>();
  80. switch (attr.offset_)
  81. {
  82. case offsetof(BillboardSet, relative_):
  83. SetRelative(value.GetBool());
  84. break;
  85. case offsetof(BillboardSet, scaled_):
  86. SetScaled(value.GetBool());
  87. break;
  88. case offsetof(BillboardSet, sorted_):
  89. SetSorted(value.GetBool());
  90. break;
  91. case offsetof(BillboardSet, material_):
  92. SetMaterial(cache->GetResource<Material>(value.GetResourceRef().id_));
  93. break;
  94. case offsetof(BillboardSet, billboards_):
  95. {
  96. MemoryBuffer buf(value.GetBuffer());
  97. unsigned numBillboards = buf.ReadVLE();
  98. SetNumBillboards(numBillboards);
  99. for (Vector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  100. {
  101. i->position_ = buf.ReadVector3();
  102. i->size_ = buf.ReadVector2();
  103. i->uv_ = buf.ReadRect();
  104. i->color_ = buf.ReadColor();
  105. i->rotation_ = buf.ReadFloat();
  106. i->enabled_ = buf.ReadBool();
  107. }
  108. Updated();
  109. }
  110. break;
  111. default:
  112. Serializable::OnSetAttribute(attr, value);
  113. break;
  114. }
  115. }
  116. Variant BillboardSet::OnGetAttribute(const AttributeInfo& attr)
  117. {
  118. switch (attr.offset_)
  119. {
  120. case offsetof(BillboardSet, material_):
  121. return GetResourceRef(material_, Material::GetTypeStatic());
  122. case offsetof(BillboardSet, billboards_):
  123. {
  124. VectorBuffer buf;
  125. buf.WriteVLE(billboards_.Size());
  126. for (Vector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  127. {
  128. buf.WriteVector3(i->position_);
  129. buf.WriteVector2(i->size_);
  130. buf.WriteRect(i->uv_);
  131. buf.WriteColor(i->color_);
  132. buf.WriteFloat(i->rotation_);
  133. buf.WriteBool(i->enabled_);
  134. }
  135. return buf.GetBuffer();
  136. }
  137. default:
  138. return Serializable::OnGetAttribute(attr);
  139. }
  140. }
  141. void BillboardSet::UpdateDistance(const FrameInfo& frame)
  142. {
  143. // Check if position relative to camera has changed, and re-sort in that case
  144. const Vector3& worldPos = GetWorldPosition();
  145. Vector3 offset = (worldPos - frame.camera_->GetWorldPosition());
  146. if (offset != previousOffset_)
  147. {
  148. previousOffset_ = offset;
  149. if (sorted_)
  150. {
  151. // Sort billboards only once per frame. This means that secondary views will get
  152. // the same sorting as the main view
  153. if (frame.frameNumber_ != sortFrameNumber_)
  154. {
  155. sortFrameNumber_ = frame.frameNumber_;
  156. bufferDirty_ = true;
  157. }
  158. }
  159. }
  160. distance_ = frame.camera_->GetDistance(worldPos);
  161. // Calculate scaled distance for animation LOD
  162. float scale = GetWorldBoundingBox().GetSize().DotProduct(dotScale);
  163. // If there are no billboards, the size becomes zero, and LOD'ed updates no longer happen. Disable LOD in that case
  164. if (scale > M_EPSILON)
  165. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  166. else
  167. lodDistance_ = 0.0f;
  168. }
  169. void BillboardSet::UpdateGeometry(const FrameInfo& frame)
  170. {
  171. if (bufferSizeDirty_)
  172. {
  173. UpdateBufferSize();
  174. forceUpdate_ = true;
  175. }
  176. if (vertexBuffer_->IsDataLost())
  177. {
  178. vertexBuffer_->ClearDataLost();
  179. forceUpdate_ = true;
  180. }
  181. if ((bufferDirty_) || (forceUpdate_))
  182. UpdateVertexBuffer(frame);
  183. }
  184. unsigned BillboardSet::GetNumBatches()
  185. {
  186. return 1;
  187. }
  188. void BillboardSet::GetBatch(const FrameInfo& frame, unsigned batchIndex, Batch& batch)
  189. {
  190. batch.geometry_ = geometry_;
  191. batch.geometryType_ = GEOM_BILLBOARD;
  192. batch.worldTransform_ = &GetWorldTransform();
  193. batch.material_ = material_;
  194. }
  195. void BillboardSet::SetMaterial(Material* material)
  196. {
  197. material_ = material;
  198. }
  199. void BillboardSet::SetNumBillboards(unsigned num)
  200. {
  201. unsigned oldNum = billboards_.Size();
  202. billboards_.Resize(num);
  203. // Set default values to new billboards
  204. for (unsigned i = oldNum; i < num; ++i)
  205. {
  206. billboards_[i].position_ = Vector3::ZERO;
  207. billboards_[i].size_ = Vector2::UNITY;
  208. billboards_[i].uv_ = Rect::POSITIVE;
  209. billboards_[i].color_ = Color(1.0f, 1.0f, 1.0f);
  210. billboards_[i].rotation_ = 0.0f;
  211. billboards_[i].enabled_ = false;
  212. }
  213. bufferSizeDirty_ = true;
  214. MarkPositionsDirty();
  215. }
  216. void BillboardSet::SetRelative(bool enable)
  217. {
  218. relative_ = enable;
  219. MarkPositionsDirty();
  220. }
  221. void BillboardSet::SetScaled(bool enable)
  222. {
  223. scaled_ = enable;
  224. MarkPositionsDirty();
  225. }
  226. void BillboardSet::SetSorted(bool enable)
  227. {
  228. sorted_ = enable;
  229. MarkPositionsDirty();
  230. }
  231. void BillboardSet::SetAnimationLodBias(float bias)
  232. {
  233. animationLodBias_ = Max(bias, 0.0f);
  234. }
  235. void BillboardSet::Updated()
  236. {
  237. MarkPositionsDirty();
  238. }
  239. Billboard* BillboardSet::GetBillboard(unsigned index)
  240. {
  241. return index < billboards_.Size() ? &billboards_[index] : (Billboard*)0;
  242. }
  243. void BillboardSet::OnMarkedDirty(Node* node)
  244. {
  245. if (node == node_)
  246. {
  247. Drawable::OnMarkedDirty(node);
  248. if (relative_)
  249. bufferDirty_ = true;
  250. }
  251. }
  252. void BillboardSet::OnWorldBoundingBoxUpdate()
  253. {
  254. worldBoundingBox_.defined_ = false;
  255. unsigned enabledBillboards = 0;
  256. const Matrix4x3& worldTransform = GetWorldTransform();
  257. const Vector3& worldScale = worldTransform.GetScale();
  258. for (unsigned i = 0; i < billboards_.Size(); ++i)
  259. {
  260. if (!billboards_[i].enabled_)
  261. continue;
  262. float maxSize;
  263. if (!scaled_)
  264. maxSize = Max(billboards_[i].size_.x_, billboards_[i].size_.y_);
  265. else
  266. maxSize = Max(billboards_[i].size_.x_ * worldScale.x_, billboards_[i].size_.y_ * worldScale.y_);
  267. if (!relative_)
  268. worldBoundingBox_.Merge(Sphere(billboards_[i].position_, maxSize));
  269. else
  270. worldBoundingBox_.Merge(Sphere(worldTransform * billboards_[i].position_, maxSize));
  271. ++enabledBillboards;
  272. }
  273. // If no billboards enabled, the bounding box is just the node's world position
  274. if (!enabledBillboards)
  275. worldBoundingBox_.Merge(GetWorldPosition());
  276. }
  277. void BillboardSet::UpdateBufferSize()
  278. {
  279. if ((!vertexBuffer_) || (!indexBuffer_))
  280. {
  281. vertexBuffer_ = new VertexBuffer(context_);
  282. indexBuffer_ = new IndexBuffer(context_);
  283. geometry_->SetVertexBuffer(0, vertexBuffer_, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2);
  284. geometry_->SetIndexBuffer(indexBuffer_);
  285. }
  286. unsigned numBillboards = billboards_.Size();
  287. vertexBuffer_->SetSize(numBillboards * 4, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2, true);
  288. indexBuffer_->SetSize(numBillboards * 6, false);
  289. bufferSizeDirty_ = false;
  290. bufferDirty_ = true;
  291. if (!numBillboards)
  292. return;
  293. // Indices do not change for a given billboard capacity
  294. unsigned short* dest = (unsigned short*)indexBuffer_->Lock(0, numBillboards * 6, LOCK_DISCARD);
  295. if (!dest)
  296. return;
  297. unsigned vertexIndex = 0;
  298. while (numBillboards--)
  299. {
  300. *dest++ = vertexIndex; *dest++ = vertexIndex + 1; *dest++ = vertexIndex + 2;
  301. *dest++ = vertexIndex + 2; *dest++ = vertexIndex + 3; *dest++ = vertexIndex;
  302. vertexIndex += 4;
  303. }
  304. indexBuffer_->Unlock();
  305. }
  306. void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame)
  307. {
  308. // If using animation LOD, accumulate time and see if it is time to update
  309. if ((animationLodBias_ > 0.0f) && (lodDistance_ > 0.0f))
  310. {
  311. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * frame.viewSize_.y_ * ANIMATION_LOD_BASESCALE;
  312. if (animationLodTimer_ >= lodDistance_)
  313. animationLodTimer_ = fmodf(animationLodTimer_, lodDistance_);
  314. else
  315. {
  316. // No LOD if immediate update forced
  317. if (!forceUpdate_)
  318. return;
  319. }
  320. }
  321. PROFILE(UpdateBillboardSet);
  322. unsigned numBillboards = billboards_.Size();
  323. unsigned enabledBillboards = 0;
  324. const Matrix4x3& worldTransform = GetWorldTransform();
  325. // First check number of enabled billboards
  326. for (unsigned i = 0; i < numBillboards; ++i)
  327. {
  328. if (billboards_[i].enabled_)
  329. ++enabledBillboards;
  330. }
  331. sortedBillboards_.Resize(enabledBillboards);
  332. unsigned index = 0;
  333. // Then set initial sort order and distances
  334. for (unsigned i = 0; i < numBillboards; ++i)
  335. {
  336. Billboard& billboard = billboards_[i];
  337. if (billboard.enabled_)
  338. {
  339. sortedBillboards_[index++] = &billboard;
  340. if (sorted_)
  341. {
  342. if (!relative_)
  343. billboard.sortDistance_ = frame.camera_->GetDistanceSquared(billboards_[i].position_);
  344. else
  345. billboard.sortDistance_ = frame.camera_->GetDistanceSquared(worldTransform * billboards_[i].position_);
  346. }
  347. }
  348. }
  349. geometry_->SetDrawRange(TRIANGLE_LIST, 0, enabledBillboards * 6, false);
  350. bufferDirty_ = false;
  351. forceUpdate_ = false;
  352. if (!enabledBillboards)
  353. return;
  354. if (sorted_)
  355. Sort(sortedBillboards_.Begin(), sortedBillboards_.End(), CompareBillboards);
  356. float* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, LOCK_DISCARD);
  357. if (!dest)
  358. return;
  359. const Vector3& worldScale = GetWorldTransform().GetScale();
  360. for (unsigned i = 0; i < enabledBillboards; ++i)
  361. {
  362. Billboard& billboard = *sortedBillboards_[i];
  363. if (!billboard.enabled_)
  364. continue;
  365. Vector3 position;
  366. if (!relative_)
  367. position = billboard.position_;
  368. else
  369. position = worldTransform * billboard.position_;
  370. Vector2 size;
  371. if (!scaled_)
  372. size = billboard.size_;
  373. else
  374. size = Vector2(billboard.size_.x_ * worldScale.x_, billboard.size_.y_ * worldScale.y_);
  375. unsigned color = billboard.color_.ToUInt();
  376. float rotationMatrix[2][2];
  377. float angleRad = billboard.rotation_ * M_DEGTORAD;
  378. rotationMatrix[0][0] = cosf(angleRad);
  379. rotationMatrix[0][1] = sinf(angleRad);
  380. rotationMatrix[1][0] = -rotationMatrix[0][1];
  381. rotationMatrix[1][1] = rotationMatrix[0][0];
  382. *dest++ = position.x_; *dest++ = position.y_; *dest++ = position.z_;
  383. *((unsigned*)dest) = color; dest++;
  384. *dest++ = billboard.uv_.min_.x_; *dest++ = billboard.uv_.max_.y_;
  385. *dest++ = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  386. *dest++ = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  387. *dest++ = position.x_; *dest++ = position.y_; *dest++ = position.z_;
  388. *((unsigned*)dest) = color; dest++;
  389. *dest++ = billboard.uv_.max_.x_; *dest++ = billboard.uv_.max_.y_;
  390. *dest++ = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  391. *dest++ = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  392. *dest++ = position.x_; *dest++ = position.y_; *dest++ = position.z_;
  393. *((unsigned*)dest) = color; dest++;
  394. *dest++ = billboard.uv_.max_.x_; *dest++ = billboard.uv_.min_.y_;
  395. *dest++ = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  396. *dest++ = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  397. *dest++ = position.x_; *dest++ = position.y_; *dest++ = position.z_;
  398. *((unsigned*)dest) = color; dest++;
  399. *dest++ = billboard.uv_.min_.x_; *dest++ = billboard.uv_.min_.y_;
  400. *dest++ = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  401. *dest++ = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  402. }
  403. vertexBuffer_->Unlock();
  404. }
  405. void BillboardSet::MarkPositionsDirty()
  406. {
  407. Drawable::OnMarkedDirty(node_);
  408. bufferDirty_ = true;
  409. }