Fix broken texture loading for PY 3 builds

The problem was that Python 3 wants a bytes object and not a string.
So we have to encode the string first to make it useable. Python 2 handles
bytes objects as normal strings so the fix should be backwards compatible.

Furthermore this commit adds a massive performance improvement by collecting
all bytes in a list and calling "join" at the end. This is significantly
faster than simply appending each byte to the bytes object one at one.

https://forum.freecadweb.org/viewtopic.php?f=3&t=35032
This commit is contained in:
furti
2019-03-18 21:31:13 +01:00
committed by Yorik van Havre
parent 50c82c2b91
commit a8686cdb88

View File

@@ -616,28 +616,48 @@ def loadTexture(filename,size=None):
img = coin.SoSFImage()
width = size[0]
height = size[1]
bytes = ""
byteList = []
isPy2 = sys.version_info.major < 3
for y in range(height):
#line = width*numcomponents*(height-(y));
for x in range(width):
rgb = p.pixel(x,y)
if numcomponents == 1:
bytes = bytes + chr(QtGui.qGray( rgb ))
if isPy2:
byteList.append(chr(QtGui.qGray( rgb )))
else:
byteList.append(chr(QtGui.qGray( rgb )).encode('latin-1'))
elif numcomponents == 2:
bytes = bytes + chr(QtGui.qGray( rgb ))
bytes = bytes + chr(QtGui.qAlpha( rgb ))
if isPy2:
byteList.append(chr(QtGui.qGray( rgb )))
byteList.append(chr(QtGui.qAlpha( rgb )))
else:
byteList.append(chr(QtGui.qGray( rgb )).encode('latin-1'))
byteList.append(chr(QtGui.qAlpha( rgb )).encode('latin-1'))
elif numcomponents == 3:
bytes = bytes + chr(QtGui.qRed( rgb ))
bytes = bytes + chr(QtGui.qGreen( rgb ))
bytes = bytes + chr(QtGui.qBlue( rgb ))
if isPy2:
byteList.append(chr(QtGui.qRed( rgb )))
byteList.append(chr(QtGui.qGreen( rgb )))
byteList.append(chr(QtGui.qBlue( rgb )))
else:
byteList.append(chr(QtGui.qRed( rgb )).encode('latin-1'))
byteList.append(chr(QtGui.qGreen( rgb )).encode('latin-1'))
byteList.append(chr(QtGui.qBlue( rgb )).encode('latin-1'))
elif numcomponents == 4:
bytes = bytes + chr(QtGui.qRed( rgb ))
bytes = bytes + chr(QtGui.qGreen( rgb ))
bytes = bytes + chr(QtGui.qBlue( rgb ))
bytes = bytes + chr(QtGui.qAlpha( rgb ))
if isPy2:
byteList.append(chr(QtGui.qRed( rgb )))
byteList.append(chr(QtGui.qGreen( rgb )))
byteList.append(chr(QtGui.qBlue( rgb )))
byteList.append(chr(QtGui.qAlpha( rgb )))
else:
byteList.append(chr(QtGui.qRed( rgb )).encode('latin-1'))
byteList.append(chr(QtGui.qGreen( rgb )).encode('latin-1'))
byteList.append(chr(QtGui.qBlue( rgb )).encode('latin-1'))
byteList.append(chr(QtGui.qAlpha( rgb )).encode('latin-1'))
#line += numcomponents
bytes = b"".join(byteList)
img.setValue(size, numcomponents, bytes)
except:
print("Draft: unable to load texture")