From d028d8cc80a091e2f6f24655a022e6b83624be4a Mon Sep 17 00:00:00 2001
From: Philip Trettner <Philip.Trettner@rwth-aachen.de>
Date: Wed, 20 Dec 2017 20:08:54 +0100
Subject: [PATCH] Fixed instance count calculation

---
 src/glow/objects/VertexArray.cc | 21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)

diff --git a/src/glow/objects/VertexArray.cc b/src/glow/objects/VertexArray.cc
index 30da214..ae02b6c 100644
--- a/src/glow/objects/VertexArray.cc
+++ b/src/glow/objects/VertexArray.cc
@@ -262,14 +262,22 @@ SharedArrayBuffer VertexArray::getAttributeBuffer(const std::string &name) const
 
 int VertexArray::getInstanceCount() const
 {
-    auto iCnt = 1;
+    auto isInstanced = false;
+    auto iCnt = std::numeric_limits<int>::max();
     for (auto const &a : mAttributes)
     {
         auto eCnt = a.buffer->getElementCount();
         auto const &aa = a.buffer->getAttributes()[a.locationInBuffer];
-        iCnt = std::max(iCnt, (int)(aa.divisor * eCnt));
+
+        if (aa.divisor > 0)
+        {
+            isInstanced = true;
+            // in order to not sample out of bounds:
+            //   at most divisor * |element| instances
+            iCnt = std::min(iCnt, (int)(aa.divisor * eCnt));
+        }
     }
-    return iCnt;
+    return isInstanced ? iCnt : 1;
 }
 
 int VertexArray::getVertexCount() const
@@ -287,6 +295,13 @@ void VertexArray::BoundVertexArray::attach(const SharedArrayBuffer &ab)
     if (!isCurrent())
         return;
 
+    if (!ab)
+    {
+        error() << "Trying to attach nullptr as ArrayBuffer";
+        assert(false);
+        return;
+    }
+
     auto const &attrs = ab->getAttributes();
     for (auto i = 0u; i < attrs.size(); ++i)
     {
-- 
GitLab