BillboardSet.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/Batch.h"
  26. #include "../Graphics/BillboardSet.h"
  27. #include "../Graphics/Camera.h"
  28. #include "../Graphics/Geometry.h"
  29. #include "../Graphics/Graphics.h"
  30. #include "../Graphics/IndexBuffer.h"
  31. #include "../Graphics/OctreeQuery.h"
  32. #include "../Graphics/VertexBuffer.h"
  33. #include "../IO/MemoryBuffer.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../Scene/Node.h"
  36. #include "../DebugNew.h"
  37. namespace Atomic
  38. {
  39. extern const char* GEOMETRY_CATEGORY;
  40. static const float INV_SQRT_TWO = 1.0f / sqrtf(2.0f);
  41. const char* faceCameraModeNames[] =
  42. {
  43. "None",
  44. "Rotate XYZ",
  45. "Rotate Y",
  46. "LookAt XYZ",
  47. "LookAt Y",
  48. "Direction",
  49. 0
  50. };
  51. inline bool CompareBillboards(Billboard* lhs, Billboard* rhs)
  52. {
  53. return lhs->sortDistance_ > rhs->sortDistance_;
  54. }
  55. BillboardSet::BillboardSet(Context* context) :
  56. Drawable(context, DRAWABLE_GEOMETRY),
  57. animationLodBias_(1.0f),
  58. animationLodTimer_(0.0f),
  59. relative_(true),
  60. scaled_(true),
  61. sorted_(false),
  62. fixedScreenSize_(false),
  63. faceCameraMode_(FC_ROTATE_XYZ),
  64. geometry_(new Geometry(context)),
  65. vertexBuffer_(new VertexBuffer(context_)),
  66. indexBuffer_(new IndexBuffer(context_)),
  67. bufferSizeDirty_(true),
  68. bufferDirty_(true),
  69. forceUpdate_(false),
  70. geometryTypeUpdate_(false),
  71. sortThisFrame_(false),
  72. hasOrthoCamera_(false),
  73. sortFrameNumber_(0),
  74. previousOffset_(Vector3::ZERO)
  75. {
  76. geometry_->SetVertexBuffer(0, vertexBuffer_);
  77. geometry_->SetIndexBuffer(indexBuffer_);
  78. batches_.Resize(1);
  79. batches_[0].geometry_ = geometry_;
  80. batches_[0].geometryType_ = GEOM_BILLBOARD;
  81. batches_[0].worldTransform_ = &transforms_[0];
  82. }
  83. BillboardSet::~BillboardSet()
  84. {
  85. }
  86. void BillboardSet::RegisterObject(Context* context)
  87. {
  88. context->RegisterFactory<BillboardSet>(GEOMETRY_CATEGORY);
  89. ATOMIC_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  90. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
  91. AM_DEFAULT);
  92. ATOMIC_ACCESSOR_ATTRIBUTE("Relative Position", IsRelative, SetRelative, bool, true, AM_DEFAULT);
  93. ATOMIC_ACCESSOR_ATTRIBUTE("Relative Scale", IsScaled, SetScaled, bool, true, AM_DEFAULT);
  94. ATOMIC_ACCESSOR_ATTRIBUTE("Sort By Distance", IsSorted, SetSorted, bool, false, AM_DEFAULT);
  95. ATOMIC_ACCESSOR_ATTRIBUTE("Fixed Screen Size", IsFixedScreenSize, SetFixedScreenSize, bool, false, AM_DEFAULT);
  96. ATOMIC_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  97. ATOMIC_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  98. ATOMIC_ENUM_ACCESSOR_ATTRIBUTE("Face Camera Mode", GetFaceCameraMode, SetFaceCameraMode, FaceCameraMode, faceCameraModeNames, FC_ROTATE_XYZ, AM_DEFAULT);
  99. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  100. ATOMIC_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  101. ATOMIC_ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  102. ATOMIC_COPY_BASE_ATTRIBUTES(Drawable);
  103. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Billboards", GetBillboardsAttr, SetBillboardsAttr, VariantVector, Variant::emptyVariantVector,
  104. AM_FILE);
  105. ATOMIC_ACCESSOR_ATTRIBUTE("Network Billboards", GetNetBillboardsAttr, SetNetBillboardsAttr, PODVector<unsigned char>,
  106. Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  107. }
  108. void BillboardSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  109. {
  110. // If no billboard-level testing, use the Drawable test
  111. if (query.level_ < RAY_TRIANGLE)
  112. {
  113. Drawable::ProcessRayQuery(query, results);
  114. return;
  115. }
  116. // Check ray hit distance to AABB before proceeding with billboard-level tests
  117. if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
  118. return;
  119. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  120. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  121. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  122. for (unsigned i = 0; i < billboards_.Size(); ++i)
  123. {
  124. if (!billboards_[i].enabled_)
  125. continue;
  126. // Approximate the billboards as spheres for raycasting
  127. float size = INV_SQRT_TWO * (billboards_[i].size_.x_ * billboardScale.x_ + billboards_[i].size_.y_ * billboardScale.y_);
  128. if (fixedScreenSize_)
  129. size *= billboards_[i].screenScaleFactor_;
  130. Vector3 center = billboardTransform * billboards_[i].position_;
  131. Sphere billboardSphere(center, size);
  132. float distance = query.ray_.HitDistance(billboardSphere);
  133. if (distance < query.maxDistance_)
  134. {
  135. // If the code reaches here then we have a hit
  136. RayQueryResult result;
  137. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  138. result.normal_ = -query.ray_.direction_;
  139. result.distance_ = distance;
  140. result.drawable_ = this;
  141. result.node_ = node_;
  142. result.subObject_ = i;
  143. results.Push(result);
  144. }
  145. }
  146. }
  147. void BillboardSet::UpdateBatches(const FrameInfo& frame)
  148. {
  149. // If beginning a new frame, assume no sorting first
  150. if (frame.frameNumber_ != sortFrameNumber_)
  151. {
  152. sortThisFrame_ = false;
  153. sortFrameNumber_ = frame.frameNumber_;
  154. }
  155. Vector3 worldPos = node_->GetWorldPosition();
  156. Vector3 offset = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
  157. // Sort if position relative to camera has changed
  158. if (offset != previousOffset_ || frame.camera_->IsOrthographic() != hasOrthoCamera_)
  159. {
  160. if (sorted_)
  161. sortThisFrame_ = true;
  162. if (faceCameraMode_ == FC_DIRECTION)
  163. bufferDirty_ = true;
  164. hasOrthoCamera_ = frame.camera_->IsOrthographic();
  165. // Calculate fixed screen size scale factor for billboards if needed
  166. if (fixedScreenSize_)
  167. CalculateFixedScreenSize(frame);
  168. }
  169. distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
  170. // Calculate scaled distance for animation LOD
  171. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  172. // If there are no billboards, the size becomes zero, and LOD'ed updates no longer happen. Disable LOD in that case
  173. if (scale > M_EPSILON)
  174. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  175. else
  176. lodDistance_ = 0.0f;
  177. batches_[0].distance_ = distance_;
  178. batches_[0].numWorldTransforms_ = 2;
  179. // Billboard positioning
  180. transforms_[0] = relative_ ? node_->GetWorldTransform() : Matrix3x4::IDENTITY;
  181. // Billboard rotation
  182. transforms_[1] = Matrix3x4(Vector3::ZERO, faceCameraMode_ != FC_NONE ? frame.camera_->GetFaceCameraRotation(
  183. node_->GetWorldPosition(), node_->GetWorldRotation(), faceCameraMode_) : node_->GetWorldRotation(), Vector3::ONE);
  184. }
  185. void BillboardSet::UpdateGeometry(const FrameInfo& frame)
  186. {
  187. // If rendering from multiple views and fixed screen size is in use, re-update scale factors before each render
  188. if (fixedScreenSize_ && viewCameras_.Size() > 1)
  189. CalculateFixedScreenSize(frame);
  190. // If using camera facing, re-update the rotation for the current view now
  191. if (faceCameraMode_ != FC_NONE)
  192. {
  193. transforms_[1] = Matrix3x4(Vector3::ZERO, frame.camera_->GetFaceCameraRotation(node_->GetWorldPosition(),
  194. node_->GetWorldRotation(), faceCameraMode_), Vector3::ONE);
  195. }
  196. if (bufferSizeDirty_ || indexBuffer_->IsDataLost())
  197. UpdateBufferSize();
  198. if (bufferDirty_ || sortThisFrame_ || vertexBuffer_->IsDataLost())
  199. UpdateVertexBuffer(frame);
  200. }
  201. UpdateGeometryType BillboardSet::GetUpdateGeometryType()
  202. {
  203. // If using camera facing, always need some kind of geometry update, in case the billboard set is rendered from several views
  204. if (bufferDirty_ || bufferSizeDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost() || sortThisFrame_ ||
  205. faceCameraMode_ != FC_NONE || fixedScreenSize_)
  206. return UPDATE_MAIN_THREAD;
  207. else
  208. return UPDATE_NONE;
  209. }
  210. void BillboardSet::SetMaterial(Material* material)
  211. {
  212. batches_[0].material_ = material;
  213. MarkNetworkUpdate();
  214. }
  215. void BillboardSet::SetNumBillboards(unsigned num)
  216. {
  217. // Prevent negative value being assigned from the editor
  218. if (num > M_MAX_INT)
  219. num = 0;
  220. if (num > MAX_BILLBOARDS)
  221. num = MAX_BILLBOARDS;
  222. unsigned oldNum = billboards_.Size();
  223. if (num == oldNum)
  224. return;
  225. billboards_.Resize(num);
  226. // Set default values to new billboards
  227. for (unsigned i = oldNum; i < num; ++i)
  228. {
  229. billboards_[i].position_ = Vector3::ZERO;
  230. billboards_[i].size_ = Vector2::ONE;
  231. billboards_[i].uv_ = Rect::POSITIVE;
  232. billboards_[i].color_ = Color(1.0f, 1.0f, 1.0f);
  233. billboards_[i].rotation_ = 0.0f;
  234. billboards_[i].direction_ = Vector3::UP;
  235. billboards_[i].enabled_ = false;
  236. billboards_[i].screenScaleFactor_ = 1.0f;
  237. }
  238. bufferSizeDirty_ = true;
  239. Commit();
  240. }
  241. void BillboardSet::SetRelative(bool enable)
  242. {
  243. relative_ = enable;
  244. Commit();
  245. }
  246. void BillboardSet::SetScaled(bool enable)
  247. {
  248. scaled_ = enable;
  249. Commit();
  250. }
  251. void BillboardSet::SetSorted(bool enable)
  252. {
  253. sorted_ = enable;
  254. Commit();
  255. }
  256. void BillboardSet::SetFixedScreenSize(bool enable)
  257. {
  258. fixedScreenSize_ = enable;
  259. Commit();
  260. }
  261. void BillboardSet::SetFaceCameraMode(FaceCameraMode mode)
  262. {
  263. if ((faceCameraMode_ != FC_DIRECTION && mode == FC_DIRECTION) || (faceCameraMode_ == FC_DIRECTION && mode != FC_DIRECTION))
  264. {
  265. faceCameraMode_ = mode;
  266. if (faceCameraMode_ == FC_DIRECTION)
  267. batches_[0].geometryType_ = GEOM_DIRBILLBOARD;
  268. else
  269. batches_[0].geometryType_ = GEOM_BILLBOARD;
  270. geometryTypeUpdate_ = true;
  271. bufferSizeDirty_ = true;
  272. Commit();
  273. }
  274. else
  275. {
  276. faceCameraMode_ = mode;
  277. MarkNetworkUpdate();
  278. }
  279. }
  280. void BillboardSet::SetAnimationLodBias(float bias)
  281. {
  282. animationLodBias_ = Max(bias, 0.0f);
  283. MarkNetworkUpdate();
  284. }
  285. void BillboardSet::Commit()
  286. {
  287. MarkPositionsDirty();
  288. MarkNetworkUpdate();
  289. }
  290. Material* BillboardSet::GetMaterial() const
  291. {
  292. return batches_[0].material_;
  293. }
  294. Billboard* BillboardSet::GetBillboard(unsigned index)
  295. {
  296. return index < billboards_.Size() ? &billboards_[index] : (Billboard*)0;
  297. }
  298. void BillboardSet::SetMaterialAttr(const ResourceRef& value)
  299. {
  300. ResourceCache* cache = GetSubsystem<ResourceCache>();
  301. SetMaterial(cache->GetResource<Material>(value.name_));
  302. }
  303. void BillboardSet::SetBillboardsAttr(const VariantVector& value)
  304. {
  305. unsigned index = 0;
  306. unsigned numBillboards = index < value.Size() ? value[index++].GetUInt() : 0;
  307. SetNumBillboards(numBillboards);
  308. // Dealing with old billboard format
  309. if (value.Size() == billboards_.Size() * 6 + 1)
  310. {
  311. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End() && index < value.Size(); ++i)
  312. {
  313. i->position_ = value[index++].GetVector3();
  314. i->size_ = value[index++].GetVector2();
  315. Vector4 uv = value[index++].GetVector4();
  316. i->uv_ = Rect(uv.x_, uv.y_, uv.z_, uv.w_);
  317. i->color_ = value[index++].GetColor();
  318. i->rotation_ = value[index++].GetFloat();
  319. i->enabled_ = value[index++].GetBool();
  320. }
  321. }
  322. // New billboard format
  323. else
  324. {
  325. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End() && index < value.Size(); ++i)
  326. {
  327. i->position_ = value[index++].GetVector3();
  328. i->size_ = value[index++].GetVector2();
  329. Vector4 uv = value[index++].GetVector4();
  330. i->uv_ = Rect(uv.x_, uv.y_, uv.z_, uv.w_);
  331. i->color_ = value[index++].GetColor();
  332. i->rotation_ = value[index++].GetFloat();
  333. i->direction_ = value[index++].GetVector3();
  334. i->enabled_ = value[index++].GetBool();
  335. }
  336. }
  337. Commit();
  338. }
  339. void BillboardSet::SetNetBillboardsAttr(const PODVector<unsigned char>& value)
  340. {
  341. MemoryBuffer buf(value);
  342. unsigned numBillboards = buf.ReadVLE();
  343. SetNumBillboards(numBillboards);
  344. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  345. {
  346. i->position_ = buf.ReadVector3();
  347. i->size_ = buf.ReadVector2();
  348. i->uv_ = buf.ReadRect();
  349. i->color_ = buf.ReadColor();
  350. i->rotation_ = buf.ReadFloat();
  351. i->direction_ = buf.ReadVector3();
  352. i->enabled_ = buf.ReadBool();
  353. }
  354. Commit();
  355. }
  356. ResourceRef BillboardSet::GetMaterialAttr() const
  357. {
  358. return GetResourceRef(batches_[0].material_, Material::GetTypeStatic());
  359. }
  360. VariantVector BillboardSet::GetBillboardsAttr() const
  361. {
  362. VariantVector ret;
  363. ret.Reserve(billboards_.Size() * 7 + 1);
  364. ret.Push(billboards_.Size());
  365. for (PODVector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  366. {
  367. ret.Push(i->position_);
  368. ret.Push(i->size_);
  369. ret.Push(Vector4(i->uv_.min_.x_, i->uv_.min_.y_, i->uv_.max_.x_, i->uv_.max_.y_));
  370. ret.Push(i->color_);
  371. ret.Push(i->rotation_);
  372. ret.Push(i->direction_);
  373. ret.Push(i->enabled_);
  374. }
  375. return ret;
  376. }
  377. const PODVector<unsigned char>& BillboardSet::GetNetBillboardsAttr() const
  378. {
  379. attrBuffer_.Clear();
  380. attrBuffer_.WriteVLE(billboards_.Size());
  381. for (PODVector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  382. {
  383. attrBuffer_.WriteVector3(i->position_);
  384. attrBuffer_.WriteVector2(i->size_);
  385. attrBuffer_.WriteRect(i->uv_);
  386. attrBuffer_.WriteColor(i->color_);
  387. attrBuffer_.WriteFloat(i->rotation_);
  388. attrBuffer_.WriteVector3(i->direction_);
  389. attrBuffer_.WriteBool(i->enabled_);
  390. }
  391. return attrBuffer_.GetBuffer();
  392. }
  393. void BillboardSet::OnWorldBoundingBoxUpdate()
  394. {
  395. unsigned enabledBillboards = 0;
  396. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  397. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  398. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  399. BoundingBox worldBox;
  400. for (unsigned i = 0; i < billboards_.Size(); ++i)
  401. {
  402. if (!billboards_[i].enabled_)
  403. continue;
  404. float size = INV_SQRT_TWO * (billboards_[i].size_.x_ * billboardScale.x_ + billboards_[i].size_.y_ * billboardScale.y_);
  405. if (fixedScreenSize_)
  406. size *= billboards_[i].screenScaleFactor_;
  407. Vector3 center = billboardTransform * billboards_[i].position_;
  408. Vector3 edge = Vector3::ONE * size;
  409. worldBox.Merge(BoundingBox(center - edge, center + edge));
  410. ++enabledBillboards;
  411. }
  412. // Always merge the node's own position to ensure particle emitter updates continue when the relative mode is switched
  413. worldBox.Merge(node_->GetWorldPosition());
  414. worldBoundingBox_ = worldBox;
  415. }
  416. void BillboardSet::UpdateBufferSize()
  417. {
  418. unsigned numBillboards = billboards_.Size();
  419. if (vertexBuffer_->GetVertexCount() != numBillboards * 4 || geometryTypeUpdate_)
  420. {
  421. if (faceCameraMode_ == FC_DIRECTION)
  422. {
  423. vertexBuffer_->SetSize(numBillboards * 4, MASK_POSITION | MASK_NORMAL | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2, true);
  424. geometry_->SetVertexBuffer(0, vertexBuffer_);
  425. }
  426. else
  427. {
  428. vertexBuffer_->SetSize(numBillboards * 4, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2, true);
  429. geometry_->SetVertexBuffer(0, vertexBuffer_);
  430. }
  431. geometryTypeUpdate_ = false;
  432. }
  433. if (indexBuffer_->GetIndexCount() != numBillboards * 6)
  434. indexBuffer_->SetSize(numBillboards * 6, false);
  435. bufferSizeDirty_ = false;
  436. bufferDirty_ = true;
  437. forceUpdate_ = true;
  438. if (!numBillboards)
  439. return;
  440. // Indices do not change for a given billboard capacity
  441. unsigned short* dest = (unsigned short*)indexBuffer_->Lock(0, numBillboards * 6, true);
  442. if (!dest)
  443. return;
  444. unsigned vertexIndex = 0;
  445. while (numBillboards--)
  446. {
  447. dest[0] = (unsigned short)vertexIndex;
  448. dest[1] = (unsigned short)(vertexIndex + 1);
  449. dest[2] = (unsigned short)(vertexIndex + 2);
  450. dest[3] = (unsigned short)(vertexIndex + 2);
  451. dest[4] = (unsigned short)(vertexIndex + 3);
  452. dest[5] = (unsigned short)vertexIndex;
  453. dest += 6;
  454. vertexIndex += 4;
  455. }
  456. indexBuffer_->Unlock();
  457. indexBuffer_->ClearDataLost();
  458. }
  459. void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame)
  460. {
  461. // If using animation LOD, accumulate time and see if it is time to update
  462. if (animationLodBias_ > 0.0f && lodDistance_ > 0.0f)
  463. {
  464. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * ANIMATION_LOD_BASESCALE;
  465. if (animationLodTimer_ >= lodDistance_)
  466. animationLodTimer_ = fmodf(animationLodTimer_, lodDistance_);
  467. else
  468. {
  469. // No LOD if immediate update forced
  470. if (!forceUpdate_)
  471. return;
  472. }
  473. }
  474. unsigned numBillboards = billboards_.Size();
  475. unsigned enabledBillboards = 0;
  476. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  477. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  478. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  479. // First check number of enabled billboards
  480. for (unsigned i = 0; i < numBillboards; ++i)
  481. {
  482. if (billboards_[i].enabled_)
  483. ++enabledBillboards;
  484. }
  485. sortedBillboards_.Resize(enabledBillboards);
  486. unsigned index = 0;
  487. // Then set initial sort order and distances
  488. for (unsigned i = 0; i < numBillboards; ++i)
  489. {
  490. Billboard& billboard = billboards_[i];
  491. if (billboard.enabled_)
  492. {
  493. sortedBillboards_[index++] = &billboard;
  494. if (sorted_)
  495. billboard.sortDistance_ = frame.camera_->GetDistanceSquared(billboardTransform * billboards_[i].position_);
  496. }
  497. }
  498. batches_[0].geometry_->SetDrawRange(TRIANGLE_LIST, 0, enabledBillboards * 6, false);
  499. bufferDirty_ = false;
  500. forceUpdate_ = false;
  501. if (!enabledBillboards)
  502. return;
  503. if (sorted_)
  504. {
  505. Sort(sortedBillboards_.Begin(), sortedBillboards_.End(), CompareBillboards);
  506. Vector3 worldPos = node_->GetWorldPosition();
  507. // Store the "last sorted position" now
  508. previousOffset_ = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
  509. }
  510. float* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, true);
  511. if (!dest)
  512. return;
  513. if (faceCameraMode_ != FC_DIRECTION)
  514. {
  515. for (unsigned i = 0; i < enabledBillboards; ++i)
  516. {
  517. Billboard& billboard = *sortedBillboards_[i];
  518. Vector2 size(billboard.size_.x_ * billboardScale.x_, billboard.size_.y_ * billboardScale.y_);
  519. unsigned color = billboard.color_.ToUInt();
  520. if (fixedScreenSize_)
  521. size *= billboard.screenScaleFactor_;
  522. float rotationMatrix[2][2];
  523. SinCos(billboard.rotation_, rotationMatrix[0][1], rotationMatrix[0][0]);
  524. rotationMatrix[1][0] = -rotationMatrix[0][1];
  525. rotationMatrix[1][1] = rotationMatrix[0][0];
  526. dest[0] = billboard.position_.x_;
  527. dest[1] = billboard.position_.y_;
  528. dest[2] = billboard.position_.z_;
  529. ((unsigned&)dest[3]) = color;
  530. dest[4] = billboard.uv_.min_.x_;
  531. dest[5] = billboard.uv_.min_.y_;
  532. dest[6] = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  533. dest[7] = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  534. dest[8] = billboard.position_.x_;
  535. dest[9] = billboard.position_.y_;
  536. dest[10] = billboard.position_.z_;
  537. ((unsigned&)dest[11]) = color;
  538. dest[12] = billboard.uv_.max_.x_;
  539. dest[13] = billboard.uv_.min_.y_;
  540. dest[14] = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  541. dest[15] = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  542. dest[16] = billboard.position_.x_;
  543. dest[17] = billboard.position_.y_;
  544. dest[18] = billboard.position_.z_;
  545. ((unsigned&)dest[19]) = color;
  546. dest[20] = billboard.uv_.max_.x_;
  547. dest[21] = billboard.uv_.max_.y_;
  548. dest[22] = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  549. dest[23] = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  550. dest[24] = billboard.position_.x_;
  551. dest[25] = billboard.position_.y_;
  552. dest[26] = billboard.position_.z_;
  553. ((unsigned&)dest[27]) = color;
  554. dest[28] = billboard.uv_.min_.x_;
  555. dest[29] = billboard.uv_.max_.y_;
  556. dest[30] = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  557. dest[31] = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  558. dest += 32;
  559. }
  560. }
  561. else
  562. {
  563. for (unsigned i = 0; i < enabledBillboards; ++i)
  564. {
  565. Billboard& billboard = *sortedBillboards_[i];
  566. Vector2 size(billboard.size_.x_ * billboardScale.x_, billboard.size_.y_ * billboardScale.y_);
  567. unsigned color = billboard.color_.ToUInt();
  568. if (fixedScreenSize_)
  569. size *= billboard.screenScaleFactor_;
  570. float rot2D[2][2];
  571. SinCos(billboard.rotation_, rot2D[0][1], rot2D[0][0]);
  572. rot2D[1][0] = -rot2D[0][1];
  573. rot2D[1][1] = rot2D[0][0];
  574. dest[0] = billboard.position_.x_;
  575. dest[1] = billboard.position_.y_;
  576. dest[2] = billboard.position_.z_;
  577. dest[3] = billboard.direction_.x_;
  578. dest[4] = billboard.direction_.y_;
  579. dest[5] = billboard.direction_.z_;
  580. ((unsigned&)dest[6]) = color;
  581. dest[7] = billboard.uv_.min_.x_;
  582. dest[8] = billboard.uv_.min_.y_;
  583. dest[9] = -size.x_ * rot2D[0][0] + size.y_ * rot2D[0][1];
  584. dest[10] = -size.x_ * rot2D[1][0] + size.y_ * rot2D[1][1];
  585. dest[11] = billboard.position_.x_;
  586. dest[12] = billboard.position_.y_;
  587. dest[13] = billboard.position_.z_;
  588. dest[14] = billboard.direction_.x_;
  589. dest[15] = billboard.direction_.y_;
  590. dest[16] = billboard.direction_.z_;
  591. ((unsigned&)dest[17]) = color;
  592. dest[18] = billboard.uv_.max_.x_;
  593. dest[19] = billboard.uv_.min_.y_;
  594. dest[20] = size.x_ * rot2D[0][0] + size.y_ * rot2D[0][1];
  595. dest[21] = size.x_ * rot2D[1][0] + size.y_ * rot2D[1][1];
  596. dest[22] = billboard.position_.x_;
  597. dest[23] = billboard.position_.y_;
  598. dest[24] = billboard.position_.z_;
  599. dest[25] = billboard.direction_.x_;
  600. dest[26] = billboard.direction_.y_;
  601. dest[27] = billboard.direction_.z_;
  602. ((unsigned&)dest[28]) = color;
  603. dest[29] = billboard.uv_.max_.x_;
  604. dest[30] = billboard.uv_.max_.y_;
  605. dest[31] = size.x_ * rot2D[0][0] - size.y_ * rot2D[0][1];
  606. dest[32] = size.x_ * rot2D[1][0] - size.y_ * rot2D[1][1];
  607. dest[33] = billboard.position_.x_;
  608. dest[34] = billboard.position_.y_;
  609. dest[35] = billboard.position_.z_;
  610. dest[36] = billboard.direction_.x_;
  611. dest[37] = billboard.direction_.y_;
  612. dest[38] = billboard.direction_.z_;
  613. ((unsigned&)dest[39]) = color;
  614. dest[40] = billboard.uv_.min_.x_;
  615. dest[41] = billboard.uv_.max_.y_;
  616. dest[42] = -size.x_ * rot2D[0][0] - size.y_ * rot2D[0][1];
  617. dest[43] = -size.x_ * rot2D[1][0] - size.y_ * rot2D[1][1];
  618. dest += 44;
  619. }
  620. }
  621. vertexBuffer_->Unlock();
  622. vertexBuffer_->ClearDataLost();
  623. }
  624. void BillboardSet::MarkPositionsDirty()
  625. {
  626. Drawable::OnMarkedDirty(node_);
  627. bufferDirty_ = true;
  628. }
  629. void BillboardSet::CalculateFixedScreenSize(const FrameInfo& frame)
  630. {
  631. float invViewHeight = 1.0f / frame.viewSize_.y_;
  632. float halfViewWorldSize = frame.camera_->GetHalfViewSize();
  633. if (!frame.camera_->IsOrthographic())
  634. {
  635. Matrix4 viewProj(frame.camera_->GetProjection(false) * frame.camera_->GetView());
  636. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  637. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  638. for (unsigned i = 0; i < billboards_.Size(); ++i)
  639. {
  640. Vector4 projPos(viewProj * Vector4(billboardTransform * billboards_[i].position_, 1.0f));
  641. billboards_[i].screenScaleFactor_ = invViewHeight * halfViewWorldSize * projPos.w_;
  642. }
  643. }
  644. else
  645. {
  646. for (unsigned i = 0; i < billboards_.Size(); ++i)
  647. billboards_[i].screenScaleFactor_ = invViewHeight * halfViewWorldSize;
  648. }
  649. bufferDirty_ = true;
  650. forceUpdate_ = true;
  651. worldBoundingBoxDirty_ = true;
  652. }
  653. }