summaryrefslogtreecommitdiff
path: root/NW4RTools/ColladaWriter.cs
blob: b2fc5a255748fd4981e1495ed3294981c397d858 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using NW4RTools.Models;
using Collada141;

namespace NW4RTools {
	public class ColladaWriter {
		public static void WriteModel(Stream outputStream, ResFile file, string modelName) {
			new ColladaWriter(file).SaveModel(outputStream, modelName);
		}



		ResFile CurrentFile;
		Models.Model CurrentModel;
		COLLADA Collada;

		library_geometries LibGeometries;
		library_visual_scenes LibVisualScenes;

		private ColladaWriter(ResFile file) {
			CurrentFile = file;
		}

		public void SaveModel(Stream outputStream, string modelName) {
			CurrentModel = CurrentFile.GetGroup<Model>("3DModels(NW4R)")[modelName];
			Collada = new COLLADA();
			
			Collada.asset = new asset();
			
			Collada.asset.contributor = new assetContributor[1];
			Collada.asset.contributor[0] = new assetContributor();
			Collada.asset.contributor[0].authoring_tool = "NW4RTools Collada exporter by Treeki";
			Collada.asset.contributor[0].source_data = "NW4R model: " + modelName;
			Collada.asset.created = DateTime.Now;
			Collada.asset.modified = DateTime.Now;
			Collada.asset.unit = new assetUnit();
			Collada.asset.unit.meter = 1.0;
			Collada.asset.up_axis = UpAxisType.Y_UP;
			
			List<object> ColladaItems = new List<object>();
			
			LibGeometries = new library_geometries();
			ColladaItems.Add(LibGeometries);
			
			var GeometryList = new List<geometry>();
			foreach (var kv in CurrentModel.Shapes) {
				GeometryList.Add(CreateGeometryFromShape(kv.Key, kv.Value));
			}
			
			LibGeometries.geometry = GeometryList.ToArray();

			// SHAPES ARE DONE.
			// Next up: Visual Scenes (I will just create one atm)
			
			LibVisualScenes = new library_visual_scenes();
			ColladaItems.Add(LibVisualScenes);
			
			LibVisualScenes.visual_scene = new visual_scene[1];
			var mainScene = LibVisualScenes.visual_scene[0] = new visual_scene();
			
			// TODO: Change this so it doesn't have the possibility of name collisions with shapes
			mainScene.id = "RootNode";
			mainScene.name = "RootNode";
			var mainSceneNodeList = new List<node>();

			// OK, so here's what's up: first off, we must create a definition for every node
			var NodeDefs = new Dictionary<Node, node>();

			foreach (var kv in CurrentModel.Nodes) {
				string nodeName = kv.Key;
				Node origNode = kv.Value;
				var cNode = new node();

				cNode.id = nodeName;
				cNode.name = nodeName;
				//cNode.type = NodeType.JOINT;
				cNode.node1 = new node[0];

				double cosX = Math.Cos(origNode.Rotation.x / 180 * Math.PI);
				double cosY = Math.Cos(origNode.Rotation.y / 180 * Math.PI);
				double cosZ = Math.Cos(origNode.Rotation.z / 180 * Math.PI);
				double sinX = Math.Sin(origNode.Rotation.x / 180 * Math.PI);
				double sinY = Math.Sin(origNode.Rotation.y / 180 * Math.PI);
				double sinZ = Math.Sin(origNode.Rotation.z / 180 * Math.PI);

				var nodeMatrix = new matrix();
				nodeMatrix.Values = new double[] {
					origNode.Scale.x * cosY * cosZ,
					origNode.Scale.y * (sinX * cosZ * sinY - cosX * sinZ),
					origNode.Scale.z * (sinX * sinZ + cosX * cosZ * sinY),
					origNode.Translation.x,
					origNode.Scale.x * sinZ * cosY,
					origNode.Scale.y * (sinX * sinZ * sinY + cosZ * cosX),
					origNode.Scale.z * (cosX * sinZ * sinY - sinX * cosZ),
					origNode.Translation.y,
					-origNode.Scale.x * sinY,
					origNode.Scale.y * sinX * cosY,
					origNode.Scale.z * cosX * cosY,
					origNode.Translation.z,
					0, 0, 0, 1
				};

				cNode.Items = new object[] { nodeMatrix };
				cNode.ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType2.matrix };

				NodeDefs[origNode] = cNode;
			}

			// Now add them to the hierarchy
			foreach (var kv in NodeDefs) {
				Node origNode = kv.Key;
				node cNode = kv.Value;

				if (origNode.Parent == null) {
					mainSceneNodeList.Add(cNode);
				} else {
					var parentNode = NodeDefs[origNode.Parent];

					// this is stupid, thanks C#
					node[] nodeArrayCopy = parentNode.node1;
					Array.Resize<node>(ref nodeArrayCopy, nodeArrayCopy.Length + 1);
					nodeArrayCopy[nodeArrayCopy.Length - 1] = cNode;
					parentNode.node1 = nodeArrayCopy;
				}
			}

			// Apply shapes to nodes
			foreach (var kv in CurrentModel.Shapes) {
				Shape shape = kv.Value;
				Node origNode = CurrentModel.Nodes[CurrentModel.MatrixIDtoNodeID[shape.MatrixID]];
				node cNode = NodeDefs[origNode];

				var newGeoEntry = new instance_geometry();
				newGeoEntry.name = kv.Key;
				newGeoEntry.url = String.Format("#{0}-lib", kv.Key);

				instance_geometry[] geoArrayCopy = cNode.instance_geometry;
				if (geoArrayCopy == null)
					geoArrayCopy = new instance_geometry[1];
				else
					Array.Resize<instance_geometry>(ref geoArrayCopy, geoArrayCopy.Length + 1);
				geoArrayCopy[geoArrayCopy.Length - 1] = newGeoEntry;
				cNode.instance_geometry = geoArrayCopy;
			}

			/*foreach (var kv in CurrentModel.Shapes) {
				var thisNode = new node();

				thisNode.id = kv.Key;
				thisNode.name = kv.Key;
				thisNode.instance_geometry = new instance_geometry[1];
				thisNode.instance_geometry[0] = new instance_geometry();
				thisNode.instance_geometry[0].url = String.Format("#{0}-lib", kv.Key);

				mainSceneNodeList.Add(thisNode);
			}*/
			
			mainScene.node = mainSceneNodeList.ToArray();

			
			// Finally, create a scene
			Collada.scene = new COLLADAScene();
			Collada.scene.instance_visual_scene = new InstanceWithExtra();
			Collada.scene.instance_visual_scene.url = "#RootNode";
			
			Collada.Items = ColladaItems.ToArray();
			Collada.Save(outputStream);
		}





		private geometry CreateGeometryFromShape(string name, Shape shape) {
			var geo = new geometry();
			
			geo.id = name + "-lib";
			geo.name = name + "Mesh";
			
			var m = new mesh();
			geo.Item = m;
			
			// Vertex settings
			var firstDL = new InputStream(shape.DisplayList1);
			firstDL.Seek(0x0C);
			UInt32 vtxDesc1 = firstDL.ReadUInt32();
			firstDL.Seek(0x12);
			UInt32 vtxDesc2 = firstDL.ReadUInt32();
			firstDL.Seek(0x22);
			UInt32 vtxAttr1 = firstDL.ReadUInt32();
			firstDL.Seek(0x28);
			UInt32 vtxAttr2 = firstDL.ReadUInt32();
			firstDL.Seek(0x2E);
			UInt32 vtxAttr3 = firstDL.ReadUInt32();
			
			var vs = new VertexSettings();
			vs.SetDesc(vtxDesc1, vtxDesc2);
			vs.SetAttrFmt(vtxAttr1, vtxAttr2, vtxAttr3);
			
			// Figure out how many elements we need in the Source array
			// Position data ALWAYS exists
			int sourceCount = 1;
			sourceCount += (shape.NrmData != null) ? 1 : 0;
			for (int i = 0; i < 8; i++)
				sourceCount += (shape.TexCoordData[i] != null) ? 1 : 0;
			
			m.source = new source[sourceCount];
			int currentSource = 0;
			
			// TODO: Refactor this messy code!
			
			int dest;
			
			// Write position data
			var posData = shape.PosData;
			var posSource = new source();
			posSource.id = name + "-lib-Position";
			m.source[currentSource++] = posSource;
			
			var posArray = new float_array();
			posArray.id = name + "-lib-Position-array";
			posArray.count = (ulong)(posData.GetRealCount() * posData.EntryCount);
			posArray.Values = new double[posArray.count];
			
			dest = 0;
			for (int i = 0; i < posData.EntryCount; i++) {
				float[] data = posData.GetEntry(i);
				for (int j = 0; j < data.Length; j++) {
					posArray.Values[dest++] = data[j];
				}
			}
			
			posSource.Item = posArray;
			
			// Write position technique
			posSource.technique_common = new sourceTechnique_common();
			var posAcc = posSource.technique_common.accessor = new accessor();
			posAcc.source = String.Format("#{0}-lib-Position-array", name);
			posAcc.count = posData.EntryCount;
			posAcc.stride = (ulong)posData.GetRealCount();
			
			posAcc.param = new param[posData.GetRealCount()];
			string[] posParamNames = new string[] { "X", "Y", "Z" };
			
			for (int i = 0; i < posAcc.param.Length; i++) {
				posAcc.param[i] = new param();
				posAcc.param[i].name = posParamNames[i];
				posAcc.param[i].type = "float";
			}
			
			
			// Write normal data
			if (shape.NrmData != null) {
				var nrmData = shape.NrmData;
				var nrmSource = new source();
				nrmSource.id = name + "-lib-Normal";
				m.source[currentSource++] = nrmSource;
				
				var nrmArray = new float_array();
				nrmArray.id = name + "-lib-Normal-array";
				nrmArray.count = (ulong)(nrmData.GetRealCount() * nrmData.EntryCount);
				nrmArray.Values = new double[nrmArray.count];
				
				dest = 0;
				for (int i = 0; i < nrmData.EntryCount; i++) {
					float[] data = nrmData.GetEntry(i);
					for (int j = 0; j < data.Length; j++) {
						nrmArray.Values[dest++] = data[j];
					}
				}

				nrmSource.Item = nrmArray;
				
				// Write normal technique
				nrmSource.technique_common = new sourceTechnique_common();
				var nrmAcc = nrmSource.technique_common.accessor = new accessor();
				nrmAcc.source = String.Format("#{0}-lib-Normal-array", name);
				nrmAcc.count = nrmData.EntryCount;
				nrmAcc.stride = (ulong)nrmData.GetRealCount();
				
				nrmAcc.param = new param[nrmData.GetRealCount()];
				string[] nrmParamNames = new string[] { "X", "Y", "Z" };
				
				for (int i = 0; i < nrmAcc.param.Length; i++) {
					nrmAcc.param[i] = new param();
					nrmAcc.param[i].name = nrmParamNames[i];
					nrmAcc.param[i].type = "float";
				}
			}
			
			
			// Write TexCoord data
			for (int tcIndex = 0; tcIndex < 8; tcIndex++) {
				if (shape.TexCoordData[tcIndex] != null) {
					var tcData = shape.TexCoordData[tcIndex];
					var tcSource = new source();
					tcSource.id = String.Format("{0}-lib-TexCoord{1}", name, tcIndex);
					m.source[currentSource++] = tcSource;
					
					var tcArray = new float_array();
					tcArray.id = String.Format("{0}-lib-TexCoord{1}-array", name, tcIndex);
					tcArray.count = (ulong)(tcData.GetRealCount() * tcData.EntryCount);
					tcArray.Values = new double[tcArray.count];
					
					dest = 0;
					for (int i = 0; i < tcData.EntryCount; i++) {
						float[] data = tcData.GetEntry(i);
						for (int j = 0; j < data.Length; j++) {
							tcArray.Values[dest++] = data[j];
						}
					}
					
					tcSource.Item = tcArray;
					
					// Write texcoord technique
					tcSource.technique_common = new sourceTechnique_common();
					var tcAcc = tcSource.technique_common.accessor = new accessor();
					tcAcc.source = String.Format("#{0}-lib-TexCoord{1}-array", name, tcIndex);
					tcAcc.count = tcData.EntryCount;
					tcAcc.stride = (ulong)tcData.GetRealCount();
					
					tcAcc.param = new param[tcData.GetRealCount()];
					string[] tcParamNames = new string[] { "S", "T" };
					
					for (int i = 0; i < tcAcc.param.Length; i++) {
						tcAcc.param[i] = new param();
						tcAcc.param[i].name = tcParamNames[i];
						tcAcc.param[i].type = "float";
					}
				}
			}
			
			
			
			// Ok, we've written all the raw float data, now set up vertices
			// TODO: Vertex colours
			m.vertices = new vertices();
			m.vertices.id = String.Format("{0}-lib-Vertex", name);
			m.vertices.input = new InputLocal[1];
			m.vertices.input[0] = new InputLocal();
			m.vertices.input[0].semantic = "POSITION";
			m.vertices.input[0].source = String.Format("#{0}-lib-Position", name);
			
			// And before we finish, write the polygon data of course
			var dl = new InputStream(shape.DisplayList2);
			
			List<object> meshItems = new List<object>();
			
			// create the Input array -- we can reuse sourceCount!
			var inputArray = new InputLocalOffset[sourceCount];
			currentSource = 0;
			
			var posInput = inputArray[currentSource] = new InputLocalOffset();
			posInput.semantic = "VERTEX";
			posInput.offset = (ulong)currentSource;
			posInput.source = String.Format("#{0}-lib-Vertex", name);
			currentSource++;
			
			if (shape.NrmData != null) {
				var nrmInput = inputArray[currentSource] = new InputLocalOffset();
				nrmInput.semantic = "NORMAL";
				nrmInput.offset = (ulong)currentSource;
				nrmInput.source = String.Format("#{0}-lib-Normal", name);
				currentSource++;
			}
			
			for (int i = 0; i < 8; i++) {
				if (shape.TexCoordData[i] != null) {
					var tcInput = inputArray[currentSource] = new InputLocalOffset();
					tcInput.semantic = "TEXCOORD";
					tcInput.offset = (ulong)currentSource;
					tcInput.@set = (ulong)i;
					tcInput.source = String.Format("#{0}-lib-TexCoord{1}", name, i);
					currentSource++;
				}
			}
			
			
			// Create a list for tristrips beforehand, because they're THE most common
			List<string> triStrips = new List<string>();
			
			
			// Now go through the display list
			while (true) {
				if (dl.AtEnd)
					break;
				
				byte cmd = dl.ReadByte();
				if (cmd == 0)
					break;
				
				PrimitiveType prim = (PrimitiveType)((cmd >> 3) & 7);
				int vtxCount = dl.ReadUInt16();
				
				// first, parse it into a list of vertices
				GXIndexedVertex[] vtxs = new GXIndexedVertex[vtxCount];
				string[] pVtxs = new string[vtxCount];
				
				for (int i = 0; i < vtxCount; i++) {
					vtxs[i].LoadFrom(dl, vs);
					
					pVtxs[i] = vtxs[i].Position.ToString();
					
					if (vs.NormalDesc != VertexSettings.DescType.None)
						pVtxs[i] += " " + vtxs[i].Normal.ToString();
					
					for (int j = 0; j < 8; j++) {
						if (vs.TexCoordDesc[j] != VertexSettings.DescType.None) {
							pVtxs[i] += " " + vtxs[i].TexCoords[j].ToString();
						}
					}
				}
				
				switch (prim) {
				case PrimitiveType.Triangles:
					var pTri = new triangles();
					pTri.count = (ulong)(vtxCount / 3);
					// should be 1? dunno
					pTri.input = inputArray;
					
					StringBuilder pTriData = new StringBuilder();
					
					for (int i = 0; i < vtxCount; i++) {
						pTriData.AppendFormat("{0} ", pVtxs[i]);
					}

					
					pTri.p = pTriData.ToString();
					
					meshItems.Add(pTri);
					break;
				
				case PrimitiveType.TriangleStrip:
					StringBuilder pTriStripData = new StringBuilder();
					
					for (int i = 0; i < vtxCount; i++) {
						pTriStripData.AppendFormat("{0} ", pVtxs[i]);
					}

					
					triStrips.Add(pTriStripData.ToString());
					break;
				default:
					
					
					Console.WriteLine("UNIMPLEMENTED PRIMITIVE TYPE");
					return geo;
				}
			}
			
			
			// If any tristrips were found, add them!
			if (triStrips.Count > 0) {
				var pTriStrips = new tristrips();
				pTriStrips.input = inputArray;
				pTriStrips.count = (ulong)triStrips.Count;
				pTriStrips.p = triStrips.ToArray();
				meshItems.Add(pTriStrips);
			}
			
			
			m.Items = meshItems.ToArray();
			
			// FINALLY DONE!
			return geo;
		}
	}
}