tex_path = "K:\\W3tup"	







fn Half2Float u=
(

   sign = bit.and ( bit.shift u -15 ) 0x00000001
   exponent = bit.and ( bit.shift u -10 ) 0x0000001F
   mantis = bit.and u 0x000003FF

   if (exponent == 0) then
   (
      if(mantis == 0) then
      (
         return bit.shift sign 31
      )
      else
      (
                        tmp = bit.and mantis 0x00000400
         while ( tmp !=0  ) do
         (
            mantis = bit.shift mantis 1
            exponent -=1
         )
         exponent = exponent +1   
         mantis = bit.and mantis 0x00000400 --> should be ~0x00000400
      )
   )
   if(exponent == 31) then
   (
      if( mantis ==0) then 
         return bit.or (bit.shift sign 31) 0x7F800000
      else
         return bit.or (bit.or (bit.shift sign 31) 0x7F800000 ) (bit.shift mantis 13)
   )   
   
   exponent = exponent + (127-15)
   mantis = bit.shift mantis 13
   
   val = bit.or ( bit.or (bit.shift sign 31) ( bit.shift exponent 23) ) (mantis)   
   
   return (bit.intAsFloat val) 
)


fn ReadUnknowProperty file = (
	back = ftell file
    sizeToGoNext = readlong file #unsigned
	print ("ReadUnknowProperty: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string))
	fseek file (back + sizeToGoNext) #seek_set
	)

fn ReadUInt8Property file = (
	back = ftell file
    sizeToGoNext = readlong file #unsigned
	value = readByte file #unsigned
	fseek file (back + sizeToGoNext) #seek_set
	print ("ReadUInt8Property: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string)  + "	value: " + (value as string))
	return value
	)
	
fn ReadUInt32Property file = (
	back = ftell file
    sizeToGoNext = readlong file #unsigned
	value = readLong file #unsigned
	fseek file (back + sizeToGoNext) #seek_set
	print ("ReadUInt32Property: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string)  + "	value: " + (value as string))
	return value
	)

fn ReadFloatProperty file = (
	back = ftell file
    sizeToGoNext = readlong file #unsigned
	value = readFloat file
	fseek file (back + sizeToGoNext) #seek_set
	print ("ReadFloatPropertyfile: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string)  + "	value: " + (value as string))
	return value
	)
	
fn ReadVector3Property file = (
	back = ftell file
    sizeToGoNext = readlong file #unsigned
	fseek file 1 #seek_cur
	fseek file 4 #seek_cur
	x = ReadFloatProperty file
	fseek file 4 #seek_cur
	y = ReadFloatProperty file
    fseek file 4 #seek_cur
	z = ReadFloatProperty file

    fseek file (back + sizeToGoNext) #seek_set	
	value = [x, y, z]	
	print ("ReadVector3Property: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string)  + "	value: " + (value as string))
	return value
)

fn ReadEMVTProperty file str_array= (
	back = ftell file
    sizeToGoNext = readlong file #unsigned
    enumStringId = readShort file #unsigned
	enumString = str_array[enumStringId + 1]
    vertexType = ""    
    if (enumString == "MVT_SkinnedMesh") then vertexType = "EMVT_SKINNED"
	else vertexType = "EMVT_STATIC"
	print ("ReadEMVTProperty: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string)  + "	enumStringId: " + (enumStringId as string) + "	enumString: " + enumString +"	vertexType:" + vertexType)
    return vertexType
	)



	
	
	
	
	
struct SMaterial (
	public
	diffuse_map = "",
	normal_map = "",
	tex_path = "",
	ambient_map = "",
	
	fn GenerateMaterial = (
		smat = StandardMaterial()
		print("GenerateMaterial:")
		matname = getFilenameFile diffuse_map
		--print("GenerateMaterial: matname:  " + matname)
		
		it = matname.count
		while ((it>0) AND (matname[it] != "_") ) do it = it - 1
		if ( it > 0) do  matname = substring  matname 1 (it - 1) 
		
		print("GenerateMaterial: matname:  " + matname)
		smat.name = matname
		smat.showInViewport = true
		
		--diffuse 
		search_path = tex_path + "\\" + (getFilenamePath diffuse_map) 
		search_name = filenameFromPath  diffuse_map
		print("GenerateMaterial: DiffuseMap: search_path: " + search_path)
		print("GenerateMaterial: DiffuseMap: search_name: " + search_name)
		print("GenerateMaterial: DiffuseMap: exist files: ")
		ex_files = getFiles (search_path + search_name + "*")
		print( ex_files )
		dif_name = ""
		if (ex_files.count > 0) then dif_name = ex_files[1]
		else dif_name = search_path + search_name + "*" + ".DDS"
		smat.diffuseMap = bitmaptexture filename: dif_name name: (filenameFromPath diffuse_map)
		
		
		--normal
		search_path = tex_path + "\\" + (getFilenamePath normal_map) 
		search_name = filenameFromPath  normal_map
		print("GenerateMaterial: NormalMap: search_path: " + search_path)
		print("GenerateMaterial: NormalMap: search_name: " + search_name)
		print("GenerateMaterial: NormalMap: exist files: ")
		ex_files = getFiles (search_path + search_name + "*")
		print( ex_files )
		norm_name = ""
		if (ex_files.count > 0) then norm_name = ex_files[1]
		else norm_name = search_path + search_name + "*" + ".DDS"
		
		smat.bumpMap = Normal_Bump normal_map: (bitmaptexture filename: norm_name  name: (filenameFromPath normal_map) ) 
		smat.bumpMapAmount = 100
		
		
		--smat.diffuseMap = bitmaptexture filename: dif_name name: (filenameFromPath diffuse_map) 
		
		
		return smat
		)
)



struct Meshdata (
	public
    back = 0,
    data2 = #(),
    nModel = 0,
    nMat = #()
)




struct Submesh_data (
	public
    vertype = "EMVT_STATIC",
    dataI = #(),
    dataH  = #()
)




struct SVertexBufferInfos (
	public
	verticesCoordsOffset = 0,
	uvOffset = 0,
	normalsOffset = 0,
	nbVertices = 0
)




struct SMeshInfos (
	public
    firstIndice = 0,
    firstVertex = 0,
    numBonesPerVertex = 0,
    vertexType = "EMVT_STATIC",
    numIndices = 0,
    numVertices = 0,
    materialID = 0    
	)

	
	
	
struct SBufferInfos (
	public
    indicesBufferOffset = 0,
    indicesBufferSize = 0,
    quantizationOffset = [0, 0, 0],
    quantizationScale = [1, 1, 1],
    verticesBufferOffset = 0,
    verticesBufferSize = 0 ,
	verticesBuffer = #()
	)
	
	
	
	
struct W3_DataInfos (
	public
	dataBlockType = 0,
	dataTypeName = "",
	size = 0,
	adress = 0
	)
	
	
	
	
fn W3_CMaterialInstance file infos str_array = (
	print ("W3_CMaterialInstance:")
	mat = SMaterial()	
	fseek file (infos.adress + 1)  #seek_set
	back = ftell file
	print ("W3_CMaterialInstance: back: " + (bit.intAsHex(back) as string) )
	
	while true do (
		print ("W3_CMaterialInstance: offset: " + (bit.intAsHex(ftell file) as string))
		propertyID = readShort file #unsigned
		propertyTypeID = readShort file #unsigned
		print ("W3_CMaterialInstance: propertyID: " + (propertyID as string) + " propertyTypeID: " + (propertyTypeID as string))
		if ((propertyID == 0) OR (propertyTypeID == 0) OR (propertyID + 1> str_array.count) OR (propertyTypeID + 1> str_array.count)) do (
			exit
			)
		property = str_array[propertyID + 1]
		propertyType = str_array[propertyTypeID + 1]
		print ("W3_CMaterialInstance: property: " + property + "     propertyType: " + propertyType)
		if (property == "baseMaterial") then (
            mat = ReadIMaterialProperty file str_array
            exit
			)
        else   ReadUnknowProperty file
		)	
	return mat	
	)
	
	
	
	
fn ReadIMaterialProperty file  str_array = (
	print ("ReadIMaterialProperty:")
	mat = SMaterial()	
	back = ftell file
	print ("ReadIMaterialProperty: back: " + (bit.intAsHex(back) as string) )
	fseek file 10 #seek_cur
	nbProperty = readLong file	
	
	
	textures = #()
	
	for tmp_str in str_array do (
		if ((findString tmp_str ".xbm") != undefined ) do append textures tmp_str
		)
	

	print ("ReadIMaterialProperty: nbProperty: " + (nbProperty as string) )
	
	for i = 1 to nbProperty do (
		back = ftell file
		sizeToGoToNext = readlong file #unsigned
		print ("ReadIMaterialProperty: back: " + (bit.intAsHex(back) as string) + "	sizeToGoToNext: " + (bit.intAsHex(sizeToGoToNext) as string))
		propId = readshort file #unsigned
		propTypeId = readshort file #unsigned
		print ("ReadIMaterialProperty: propId: " + (propId as string) + "	propTypeId: " + (propTypeId as string))
		if (propId < 0) OR ( propId + 1 > str_array.count) do (
			exit
			)
		print("ReadIMaterialProperty: ID:  " + str_array[propId + 1])
		
		if (str_array[propId + 1] == "Diffuse") do (
			texId = readByte file #unsigned
			texId = 255 - texId			
			print("ReadIMaterialProperty: texId:  " + (texId as string))
			if (texId <= textures.count) do (
				print("ReadIMaterialProperty: Diffuse map:  " + textures[texId ])
				mat.diffuse_map = textures[texId ]
				)
			)
			
		if (str_array[propId + 1] == "Normal") do (
			texId = readByte file #unsigned
			texId = 255 - texId			
			print("ReadIMaterialProperty: texId:  " + (texId as string))
			if (texId <= textures.count) do (
				print("ReadIMaterialProperty: Normal map:  " + textures[texId ])
				mat.normal_map = textures[texId ]
				)
			)
			
		if (str_array[propId + 1] == "Ambient") do (
			texId = readByte file #unsigned
			texId = 255 - texId			
			print("ReadIMaterialProperty: texId:  " + (texId as string))
			if (texId <= textures.count) do (
				print("ReadIMaterialProperty: Ambient map:  " + textures[texId ])
				mat.ambient_map = textures[texId ]
				)
			)
		
		fseek file (back + sizeToGoToNext) #seek_set
		)
	
	
	return mat	
	)	
	
	
	
	
	
	
	
	
	
	
	
--  нужна отладка	
fn ReadRenderChunksProperty file bufferInfos =(
	print("ReadRenderChunksProperty:")
	temp_buffer = bufferInfos
	back = ftell file
	sizeToGoNext = readlong file #unsigned
	print ("ReadRenderChunksProperty: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string) )
		
	fseek file 5 #seek_cur
	nbBuffers = readByte file #unsigned
	print ("ReadRenderChunksProperty: nbBuffers: " +  (nbBuffers as string) )
	
	while sizeToGoNext > (( ftell file ) - back ) do (		
        buffInfos = SVertexBufferInfos()
        buffInfos.verticesCoordsOffset = readLong file #unsigned
        buffInfos.uvOffset  = readLong file #unsigned
        buffInfos.normalsOffset =  readLong file #unsigned
		fseek file 14 #seek_cur
		buffInfos.nbVertices = readShort file #unsigned		
		print ("ReadRenderChunksProperty verticesCoordsOffset: " + ((bit.intAsHex(buffInfos.verticesCoordsOffset)) as string) + "    uvOffset: " + ((bit.intAsHex(buffInfos.uvOffset)) as string) + "	normalsOffset: " + ((bit.intAsHex(buffInfos.normalsOffset)) as string) + "	nbVertices: " + ((bit.intAsHex(buffInfos.nbVertices)) as string) )
		fseek file 9 #seek_cur
        append temp_buffer.verticesBuffer buffInfos
		)
	
	
	print("	ReadRenderChunksPropertyEND:")
	fseek file (back + sizeToGoNext) #seek_set
	return temp_buffer
	)	
	

fn ReadSMeshChunkPackedProperty file str_array = (
	print("ReadSMeshChunkPackedProperty:")
	meshes = #()
	meshInfos = SMeshInfos()
	
	back = ftell file
	sizeToGoNext = readlong file #unsigned
	nbChunks = readlong file #unsigned
	print ("ReadSMeshChunkPackedProperty: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string) + "	nbChunks: " + (nbChunks as string))
	fseek file 1 #seek_cur
	chunkId = 0
	
	while true do (
		print ("ReadSMeshChunkPackedProperty: offset: " + (bit.intAsHex(ftell file) as string))
		propertyID = readShort file #unsigned
		propertyTypeID = readShort file #unsigned
		print ("ReadSMeshChunkPackedProperty: propertyID: " + (propertyID as string) + " propertyTypeID: " + (propertyTypeID as string))
		if ((propertyID == 0) OR (propertyTypeID == 0) OR (propertyID + 1> str_array.count) OR (propertyTypeID + 1> str_array.count)) do (
			append meshes meshInfos
			chunkId = chunkId + 1
			if (chunkId >= nbChunks) then exit
			else (
			
				newMeshInfos = SMeshInfos()
                newMeshInfos.vertexType = meshInfos.vertexType
                newMeshInfos.numBonesPerVertex = meshInfos.numBonesPerVertex
                meshInfos = newMeshInfos

                fseek file -1 #seek_cur

                propertyID = readShort file #unsigned
				propertyTypeID = readShort file #unsigned
				)
			)	
			
		property = str_array[propertyID + 1]
		propertyType = str_array[propertyTypeID + 1]
		print ("ReadSMeshChunkPackedProperty: property: " + property + "     propertyType: " + propertyType)

		if (property == "numIndices") then meshInfos.numIndices = ReadUInt32Property file
        else if (property == "numVertices") then meshInfos.numVertices = ReadUInt32Property file
        else if (property == "firstVertex") then meshInfos.firstVertex = ReadUInt32Property file
        else if (property == "firstIndex") then meshInfos.firstIndice = ReadUInt32Property file 
        else if (property == "vertexType") then meshInfos.vertexType = ReadEMVTProperty file str_array
        else if (property == "numBonesPerVertex") then meshInfos.numBonesPerVertex = ReadUInt8Property file
        else if (property == "materialID") then meshInfos.materialID = ReadUInt32Property file
        else ReadUnknowProperty file		
		)	
	print ("	ReadSMeshChunkPackedPropertyEND")
	fseek file (back + sizeToGoNext) #seek_set
	return meshes
	)	

	
	
	
fn ReadSMeshCookedDataProperty file str_array = (
	print("ReadSMeshCookedDataProperty:")	
	back = ftell file
	sizeToGoNext = readlong file #unsigned
	print ("ReadSMeshCookedDataProperty: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string))
	fseek file 1 #seek_cur
	bufferInfos = SBufferInfos()

	
	while true do (
		print ("ReadSMeshCookedDataProperty: offset: " + (bit.intAsHex(ftell file) as string))
		propertyID = readShort file #unsigned
		propertyTypeID = readShort file #unsigned
		print ("ReadSMeshCookedDataProperty: propertyID: " + (propertyID as string) + " propertyTypeID: " + (propertyTypeID as string))		
		if ((propertyID == 0) OR (propertyTypeID == 0) OR ((propertyID + 1)> str_array.count) OR ((propertyTypeID + 1)> str_array.count)) do (
			exit
			)	
	
		property = str_array[propertyID + 1]
		print ("ReadSMeshCookedDataProperty: property: " + property  )

        if (property == "indexBufferSize") then bufferInfos.indicesBufferSize = ReadUInt32Property file 
        else if (property == "indexBufferOffset") then bufferInfos.indicesBufferOffset = ReadUInt32Property file 
		else if (property == "vertexBufferSize") then bufferInfos.verticesBufferSize = ReadUInt32Property file 
        else if (property == "quantizationScale") then bufferInfos.quantizationScale = ReadVector3Property file
        else if (property == "quantizationOffset") then bufferInfos.quantizationOffset = ReadVector3Property file
        else if (property == "renderChunks") then bufferInfos = ReadRenderChunksProperty file bufferInfos
        else ReadUnknowProperty file
		)
	print(bufferInfos)
	print ("	ReadSMeshCookedDataPropertyEND")
	
	fseek file (back + sizeToGoNext) #seek_set
	return bufferInfos
	)
	
	
	
	
fn ReadMaterialsProperty file = (	
	print("ReadMaterialsProperty:")
	back = ftell file
	sizeToGoNext = readlong file #unsigned
	nbChunks = readlong file #unsigned
	print ("ReadMaterialsProperty: back: " + (bit.intAsHex(back) as string) + "	sizeToGoNext: " + (sizeToGoNext as string) + "	nbChunks: " + (nbChunks as string))
	
    for  i = 1  to  nbChunks do (
        value = readlong file #unsigned
		)
    fseek file (back + sizeToGoNext) #seek_set
	print("	ReadMaterialsPropertyEND")	
	)

	
	
	
	
	
	
	
	
	
fn W3_ReadBuffer file file_buffer bufferInfos meshInfos mesh_name mat = (
	print ("W3_ReadBuffer:")
	vert_array = #()
	UV_array = #()
	face_array = #()
	print ("W3_ReadBuffer: bufferInfos")
	print (bufferInfos)
	print ("W3_ReadBuffer: meshInfos")
	print (meshInfos)
	
	
	num_vertices = meshInfos.numVertices
	
	vertexSize = 20;
	if (meshInfos.vertexType == "EMVT_SKINNED") do ( vertexSize = vertexSize + meshInfos.numBonesPerVertex * 2 )
	
	first_vertex = meshInfos.firstVertex
	
	inf = SVertexBufferInfos()
	sum = 0
	
	for i = 1 to bufferInfos.verticesBuffer.count do (
		sum = sum + bufferInfos.verticesBuffer[i].nbVertices;
		if ( sum > meshInfos.firstVertex) do (
			inf = bufferInfos.verticesBuffer[i]
			exit
			)
		)
	print ("W3_ReadBuffer: inf:")
	print (inf)
	
	fseek file_buffer ( inf.verticesCoordsOffset + (meshInfos.firstVertex - (sum - inf.nbVertices)) * vertexSize) #seek_set
	print ("W3_ReadBuffer: vertex offset: 0x" + ((bit.intAsHex(ftell file_buffer)) as string ))
	
	for i = 1 to meshInfos.numVertices do (
		x = readshort file_buffer #unsigned
		y = readshort file_buffer #unsigned
		z = readshort file_buffer #unsigned
		qq = readshort file_buffer #unsigned
		if (meshInfos.vertexType == "EMVT_SKINNED") do ( fseek file_buffer (meshInfos.numBonesPerVertex * 2) #seek_cur)
		--print (((bit.intAsHex(ftell file_buffer)) as string ) + "   " + ((bit.intAsHex(x)) as string ) + "   " + ((bit.intAsHex(y)) as string ) + "   " + ((bit.intAsHex(z)) as string ) )
        append vert_array [ (x * bufferInfos.quantizationScale.X + 65536*bufferInfos.quantizationOffset.X), (y * bufferInfos.quantizationScale.Y + 65536*bufferInfos.quantizationOffset.Y), (z * bufferInfos.quantizationScale.Z + 65536*bufferInfos.quantizationOffset.Z) ]
		--append vert_array [x, y, z]
		)

	fseek file_buffer ( inf.uvOffset + (meshInfos.firstVertex - (sum - inf.nbVertices)) * 4 ) #seek_set
	
	

	print ("W3_ReadBuffer: UV offset: 0x" + ((bit.intAsHex(ftell file_buffer)) as string ))
	
	for i = 1 to meshInfos.numVertices do (
		x = Half2Float( readshort file_buffer)
		y = 1 - Half2Float( readshort file_buffer)		
        append UV_array [ x, y, 0 ]
		)
	
	fseek file_buffer ( bufferInfos.indicesBufferOffset + meshInfos.firstIndice * 2 ) #seek_set
	print ("W3_ReadBuffer: indicies offset: 0x" + ((bit.intAsHex(ftell file_buffer)) as string ))
	
	for i = 1 to (meshInfos.numIndices / 3) do (
		i3 = (readshort f #unsigned ) + 1 
		i2 = (readshort f #unsigned ) + 1
		i1 = (readshort f #unsigned ) + 1		
		append face_array[i1,i2,i3]
		)	
	try(
	msh = mesh name:mesh_name vertices:vert_array faces: face_array
	msh.numTVerts = UV_array.count
	buildTVFaces msh
	for j = 1 to UV_array.count do setTVert msh j UV_array[j]
	for j = 1 to face_array.count do setTVFace msh j face_array[j]
	--print(mat)
	if ( mat == undefined ) then (
		newmat = StandardMaterial()
		msh.material = newmat	
		)
	else (
		
		msh.material = mat.GenerateMaterial()
		)
	)
	catch
	(
	print("##############################################################")
	print("##############################################################")
	print ("		ERROR CREATING MESH")
	print("##############################################################")
	print("##############################################################")
	)
	)	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
fn W3_CMesh file binary_file infos str_array mesh_name Materials  = (
	print("W3_CMesh:")
	bufferInfos = SBufferInfos()
	meshes = #()
	fseek file (infos.adress + 1) #seek_set
	print ("W3_CMesh: base offset: " + (bit.intAsHex(ftell file) as string))
	
	while true do (
		print ("W3_CMesh: offset: " + (bit.intAsHex(ftell file) as string))
		propertyID = readShort file #unsigned
        propertyTypeID = readShort file #unsigned
		print ("W3_CMesh: propertyID: " + (propertyID as string) + " propertyTypeID: " + (propertyTypeID as string))
		if ((propertyID == 0) OR (propertyTypeID == 0) OR ((propertyID + 1)> str_array.count) OR ((propertyTypeID + 1)> str_array.count)) do (
			exit
			)			
		property = str_array[propertyID + 1]
        propertyType = str_array[propertyTypeID + 1]	
		print ("W3_CMesh: property: " + property + "     propertyType: " + propertyType)
		
		if (property == "materials") then	(
            ReadMaterialsProperty file
			)
		else if (property == "chunks") then (
			meshes = ReadSMeshChunkPackedProperty file str_array
			)
		else if (propertyType == "SMeshCookedData") then	(
			bufferInfos = ReadSMeshCookedDataProperty file str_array
			)
		else (
            ReadUnknowProperty file 
			)
		)
	
	
	
	
	print ("W3_CMesh: Generation Mesh")
	print ("W3_CMesh: Meshes")
	print (meshes)
	print ("W3_CMesh: bufferInfos")
	print (bufferInfos)
	
	for i = 1 to meshes.count do (
		--if ((meshes[i].materialID >= 0) AND (meshes[i].materialID <= Materials.count)) then	W3_CMesh fm f meshes[i] str_array mesh_name Materials[meshes[i].materialID]
		--else W3_CMesh fm f meshes[i] str_array mesh_name undefined 
		if ((meshes[i].materialID + 1 > 0) AND (meshes[i].materialID + 1 <= Materials.count)) then W3_ReadBuffer file binary_file bufferInfos meshes[i] mesh_name Materials[meshes[i].materialID + 1]
		else W3_ReadBuffer file binary_file bufferInfos meshes[i] mesh_name undefined
		)
		
	)
	
	
	
	
	
	
















	
	

fname = getOpenFileName \
caption:"Open .w2mesh.1.buffer from Mesh folder" \
types:"Witcher 3 Wild Hunt (*.w2mesh.1.buffer)|*.w2mesh.1.buffer" \
historyCategory:"W#_WHObjectPresets"	

mesh_name = getFilenameFile fname
mesh_name = getFilenameFile mesh_name
mesh_name = getFilenameFile mesh_name
print(mesh_name)



--fnamem = "K:\\w3u\\characters\\models\\geralt\\body\\model\\h_00_mg__geralt.w2mesh"
fnamem = substring fname 1 (fname.count - 9)
f = fopen fname "rb"
fm = fopen fnamem "rb"


print("fname :" + fname)
print("fname :" + fnamem )



fseek fm 0x0000 #seek_set

header = ""
for i = 1 to 4 do (
	header = header + bit.intAsChar (readbyte fm #unsigned)
	)
print ("Header: " + header)

fseek fm 0x0008 #seek_cur


header_data = #()
for i = 1 to 38 do (
	append header_data (readlong fm #unsigned)
	)
print ("Header: " + header)


stringChunkStart = header_data[8];
stringChunkSize = header_data[9];
contentChunkStart = header_data[20];
contentChunkSize = header_data[21];

print ("stringChunkStart: 0x" + ((bit.intAsHex(stringChunkStart)) as string))
print ("stringChunkSize: " + (stringChunkSize as String))
print ("contentChunkStart: 0x" + ((bit.intAsHex(contentChunkStart)) as string))
print ("contentChunkSize: " + (contentChunkSize as String))

Materials = #()
str_array = #()
fseek fm stringChunkStart #seek_set

print("astr")

while ((ftell fm) - stringChunkStart) < stringChunkSize do
	(
	tmp_string = ""
	tmp_char = bit.intAsChar (readbyte fm #unsigned)
	while tmp_char != "" do (
		tmp_string = tmp_string + tmp_char
		tmp_char = bit.intAsChar (readbyte fm #unsigned)
		)	
	append str_array tmp_string
	print (tmp_string)
	)
print("astrEND")
--for i = 1 to contentChunkSize do (
--	)

infos_array = #()
meshes = #()
fseek fm contentChunkStart #seek_set

for i = 1 to contentChunkSize do (
	infos = W3_DataInfos()

	infos.dataBlockType =  readshort fm #unsigned
	infos.dataTypeName = str_array[infos.dataBlockType + 1]
	fseek fm 6 #seek_cur
	infos.size = readlong fm #unsigned
	infos.adress = readlong fm #unsigned
	fseek fm 8 #seek_cur
	if ( infos.dataTypeName == "CMesh" ) do ( append meshes infos)
	if ( infos.dataTypeName == "CMaterialInstance") do
        (
            mat = W3_CMaterialInstance fm infos str_array
			mat.tex_path = tex_path
            append Materials mat
        )
	print (infos)
	)
	
print("GLOBAL: meshes")
print(meshes)
print("GLOBAL: Materials")
print(Materials)

for i = 1 to meshes.count do (

	W3_CMesh fm f meshes[i] str_array mesh_name Materials  
	)