diff --git a/source/anorm_dots.h b/source/anorm_dots.h index 21e6853..a368a1e 100644 --- a/source/anorm_dots.h +++ b/source/anorm_dots.h @@ -19,562 +19,578 @@ */ // 0 - { 1.23, 1.30, 1.47, 1.35, 1.56, 1.71, 1.37, 1.38, - 1.59, 1.60, 1.79, 1.97, 1.88, 1.92, 1.79, 1.02, - 0.93, 1.07, 0.82, 0.87, 0.88, 0.94, 0.96, 1.14, - 1.11, 0.82, 0.83, 0.89, 0.89, 0.86, 0.94, 0.91, - 1.00, 1.21, 0.98, 1.48, 1.30, 1.57, 0.96, 1.07, - 1.14, 1.60, 1.61, 1.40, 1.37, 1.72, 1.78, 1.79, - 1.93, 1.99, 1.90, 1.68, 1.71, 1.86, 1.60, 1.68, - 1.78, 1.86, 1.93, 1.99, 1.97, 1.44, 1.22, 1.49, - 0.93, 0.99, 0.99, 1.23, 1.22, 1.44, 1.49, 0.89, - 0.89, 0.97, 0.91, 0.98, 1.19, 0.82, 0.76, 0.82, - 0.71, 0.72, 0.73, 0.76, 0.79, 0.86, 0.83, 0.72, - 0.76, 0.76, 0.89, 0.82, 0.89, 0.82, 0.89, 0.91, - 0.83, 0.96, 1.14, 0.97, 1.40, 1.19, 0.98, 0.94, - 1.00, 1.07, 1.37, 1.21, 1.48, 1.30, 1.57, 1.61, - 1.37, 0.86, 0.83, 0.91, 0.82, 0.82, 0.88, 0.89, - 0.96, 1.14, 0.98, 0.87, 0.93, 0.94, 1.02, 1.30, - 1.07, 1.35, 1.38, 1.11, 1.56, 1.92, 1.79, 1.79, - 1.59, 1.60, 1.72, 1.90, 1.79, 0.80, 0.85, 0.79, - 0.93, 0.80, 0.85, 0.77, 0.74, 0.72, 0.77, 0.74, - 0.72, 0.70, 0.70, 0.71, 0.76, 0.73, 0.79, 0.79, - 0.73, 0.76, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.23, 1.30, 1.47, 1.35, 1.56, 1.71, 1.37, 1.38, + 1.59, 1.60, 1.79, 1.97, 1.88, 1.92, 1.79, 1.02, + 0.93, 1.07, 0.82, 0.87, 0.88, 0.94, 0.96, 1.14, + 1.11, 0.82, 0.83, 0.89, 0.89, 0.86, 0.94, 0.91, + 1.00, 1.21, 0.98, 1.48, 1.30, 1.57, 0.96, 1.07, + 1.14, 1.60, 1.61, 1.40, 1.37, 1.72, 1.78, 1.79, + 1.93, 1.99, 1.90, 1.68, 1.71, 1.86, 1.60, 1.68, + 1.78, 1.86, 1.93, 1.99, 1.97, 1.44, 1.22, 1.49, + 0.93, 0.99, 0.99, 1.23, 1.22, 1.44, 1.49, 0.89, + 0.89, 0.97, 0.91, 0.98, 1.19, 0.82, 0.76, 0.82, + 0.71, 0.72, 0.73, 0.76, 0.79, 0.86, 0.83, 0.72, + 0.76, 0.76, 0.89, 0.82, 0.89, 0.82, 0.89, 0.91, + 0.83, 0.96, 1.14, 0.97, 1.40, 1.19, 0.98, 0.94, + 1.00, 1.07, 1.37, 1.21, 1.48, 1.30, 1.57, 1.61, + 1.37, 0.86, 0.83, 0.91, 0.82, 0.82, 0.88, 0.89, + 0.96, 1.14, 0.98, 0.87, 0.93, 0.94, 1.02, 1.30, + 1.07, 1.35, 1.38, 1.11, 1.56, 1.92, 1.79, 1.79, + 1.59, 1.60, 1.72, 1.90, 1.79, 0.80, 0.85, 0.79, + 0.93, 0.80, 0.85, 0.77, 0.74, 0.72, 0.77, 0.74, + 0.72, 0.70, 0.70, 0.71, 0.76, 0.73, 0.79, 0.79, + 0.73, 0.76, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 1 - { 1.26, 1.26, 1.48, 1.23, 1.50, 1.71, 1.14, 1.19, - 1.38, 1.46, 1.64, 1.94, 1.87, 1.84, 1.71, 1.02, - 0.92, 1.00, 0.79, 0.85, 0.84, 0.91, 0.90, 0.98, - 0.99, 0.77, 0.77, 0.83, 0.82, 0.79, 0.86, 0.84, - 0.92, 0.99, 0.91, 1.24, 1.03, 1.33, 0.88, 0.94, - 0.97, 1.41, 1.39, 1.18, 1.11, 1.51, 1.61, 1.59, - 1.80, 1.91, 1.76, 1.54, 1.65, 1.76, 1.70, 1.70, - 1.85, 1.85, 1.97, 1.99, 1.93, 1.28, 1.09, 1.39, - 0.92, 0.97, 0.99, 1.18, 1.26, 1.52, 1.48, 0.83, - 0.85, 0.90, 0.88, 0.93, 1.00, 0.77, 0.73, 0.78, - 0.72, 0.71, 0.74, 0.75, 0.79, 0.86, 0.81, 0.75, - 0.81, 0.79, 0.96, 0.88, 0.94, 0.86, 0.93, 0.92, - 0.85, 1.08, 1.33, 1.05, 1.55, 1.31, 1.01, 1.05, - 1.27, 1.31, 1.60, 1.47, 1.70, 1.54, 1.76, 1.76, - 1.57, 0.93, 0.90, 0.99, 0.88, 0.88, 0.95, 0.97, - 1.11, 1.39, 1.20, 0.92, 0.97, 1.01, 1.10, 1.39, - 1.22, 1.51, 1.58, 1.32, 1.64, 1.97, 1.85, 1.91, - 1.77, 1.74, 1.88, 1.99, 1.91, 0.79, 0.86, 0.80, - 0.94, 0.84, 0.88, 0.74, 0.74, 0.71, 0.82, 0.77, - 0.76, 0.70, 0.73, 0.72, 0.73, 0.70, 0.74, 0.85, - 0.77, 0.82, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.26, 1.26, 1.48, 1.23, 1.50, 1.71, 1.14, 1.19, + 1.38, 1.46, 1.64, 1.94, 1.87, 1.84, 1.71, 1.02, + 0.92, 1.00, 0.79, 0.85, 0.84, 0.91, 0.90, 0.98, + 0.99, 0.77, 0.77, 0.83, 0.82, 0.79, 0.86, 0.84, + 0.92, 0.99, 0.91, 1.24, 1.03, 1.33, 0.88, 0.94, + 0.97, 1.41, 1.39, 1.18, 1.11, 1.51, 1.61, 1.59, + 1.80, 1.91, 1.76, 1.54, 1.65, 1.76, 1.70, 1.70, + 1.85, 1.85, 1.97, 1.99, 1.93, 1.28, 1.09, 1.39, + 0.92, 0.97, 0.99, 1.18, 1.26, 1.52, 1.48, 0.83, + 0.85, 0.90, 0.88, 0.93, 1.00, 0.77, 0.73, 0.78, + 0.72, 0.71, 0.74, 0.75, 0.79, 0.86, 0.81, 0.75, + 0.81, 0.79, 0.96, 0.88, 0.94, 0.86, 0.93, 0.92, + 0.85, 1.08, 1.33, 1.05, 1.55, 1.31, 1.01, 1.05, + 1.27, 1.31, 1.60, 1.47, 1.70, 1.54, 1.76, 1.76, + 1.57, 0.93, 0.90, 0.99, 0.88, 0.88, 0.95, 0.97, + 1.11, 1.39, 1.20, 0.92, 0.97, 1.01, 1.10, 1.39, + 1.22, 1.51, 1.58, 1.32, 1.64, 1.97, 1.85, 1.91, + 1.77, 1.74, 1.88, 1.99, 1.91, 0.79, 0.86, 0.80, + 0.94, 0.84, 0.88, 0.74, 0.74, 0.71, 0.82, 0.77, + 0.76, 0.70, 0.73, 0.72, 0.73, 0.70, 0.74, 0.85, + 0.77, 0.82, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 2 - { 1.34, 1.27, 1.53, 1.17, 1.46, 1.71, 0.98, 1.05, - 1.20, 1.34, 1.48, 1.86, 1.82, 1.71, 1.62, 1.09, - 0.94, 0.99, 0.79, 0.85, 0.82, 0.90, 0.87, 0.93, - 0.96, 0.76, 0.74, 0.79, 0.76, 0.74, 0.79, 0.78, - 0.85, 0.92, 0.85, 1.00, 0.93, 1.06, 0.81, 0.86, - 0.89, 1.16, 1.12, 0.97, 0.95, 1.28, 1.38, 1.35, - 1.60, 1.77, 1.57, 1.33, 1.50, 1.58, 1.69, 1.63, - 1.82, 1.74, 1.91, 1.92, 1.80, 1.04, 0.97, 1.21, - 0.90, 0.93, 0.97, 1.05, 1.21, 1.48, 1.37, 0.77, - 0.80, 0.84, 0.85, 0.88, 0.92, 0.73, 0.71, 0.74, - 0.74, 0.71, 0.75, 0.73, 0.79, 0.84, 0.78, 0.79, - 0.86, 0.81, 1.05, 0.94, 0.99, 0.90, 0.95, 0.92, - 0.86, 1.24, 1.44, 1.14, 1.59, 1.34, 1.02, 1.27, - 1.50, 1.49, 1.80, 1.69, 1.86, 1.72, 1.87, 1.80, - 1.69, 1.00, 0.98, 1.23, 0.95, 0.96, 1.09, 1.16, - 1.37, 1.63, 1.46, 0.99, 1.10, 1.25, 1.24, 1.51, - 1.41, 1.67, 1.77, 1.55, 1.72, 1.95, 1.89, 1.98, - 1.91, 1.86, 1.97, 1.99, 1.94, 0.81, 0.89, 0.85, - 0.98, 0.90, 0.94, 0.75, 0.78, 0.73, 0.89, 0.83, - 0.82, 0.72, 0.77, 0.76, 0.72, 0.70, 0.71, 0.91, - 0.83, 0.89, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.34, 1.27, 1.53, 1.17, 1.46, 1.71, 0.98, 1.05, + 1.20, 1.34, 1.48, 1.86, 1.82, 1.71, 1.62, 1.09, + 0.94, 0.99, 0.79, 0.85, 0.82, 0.90, 0.87, 0.93, + 0.96, 0.76, 0.74, 0.79, 0.76, 0.74, 0.79, 0.78, + 0.85, 0.92, 0.85, 1.00, 0.93, 1.06, 0.81, 0.86, + 0.89, 1.16, 1.12, 0.97, 0.95, 1.28, 1.38, 1.35, + 1.60, 1.77, 1.57, 1.33, 1.50, 1.58, 1.69, 1.63, + 1.82, 1.74, 1.91, 1.92, 1.80, 1.04, 0.97, 1.21, + 0.90, 0.93, 0.97, 1.05, 1.21, 1.48, 1.37, 0.77, + 0.80, 0.84, 0.85, 0.88, 0.92, 0.73, 0.71, 0.74, + 0.74, 0.71, 0.75, 0.73, 0.79, 0.84, 0.78, 0.79, + 0.86, 0.81, 1.05, 0.94, 0.99, 0.90, 0.95, 0.92, + 0.86, 1.24, 1.44, 1.14, 1.59, 1.34, 1.02, 1.27, + 1.50, 1.49, 1.80, 1.69, 1.86, 1.72, 1.87, 1.80, + 1.69, 1.00, 0.98, 1.23, 0.95, 0.96, 1.09, 1.16, + 1.37, 1.63, 1.46, 0.99, 1.10, 1.25, 1.24, 1.51, + 1.41, 1.67, 1.77, 1.55, 1.72, 1.95, 1.89, 1.98, + 1.91, 1.86, 1.97, 1.99, 1.94, 0.81, 0.89, 0.85, + 0.98, 0.90, 0.94, 0.75, 0.78, 0.73, 0.89, 0.83, + 0.82, 0.72, 0.77, 0.76, 0.72, 0.70, 0.71, 0.91, + 0.83, 0.89, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 3 - { 1.46, 1.34, 1.60, 1.16, 1.46, 1.71, 0.94, 0.99, - 1.05, 1.26, 1.33, 1.74, 1.76, 1.57, 1.54, 1.23, - 0.98, 1.05, 0.83, 0.89, 0.84, 0.92, 0.87, 0.91, - 0.96, 0.78, 0.74, 0.79, 0.72, 0.72, 0.75, 0.76, - 0.80, 0.88, 0.83, 0.94, 0.87, 0.95, 0.76, 0.80, - 0.82, 0.97, 0.96, 0.89, 0.88, 1.08, 1.11, 1.10, - 1.37, 1.59, 1.37, 1.07, 1.27, 1.34, 1.57, 1.45, - 1.69, 1.55, 1.77, 1.79, 1.60, 0.93, 0.90, 0.99, - 0.86, 0.87, 0.93, 0.96, 1.07, 1.35, 1.18, 0.73, - 0.76, 0.77, 0.81, 0.82, 0.85, 0.70, 0.71, 0.72, - 0.78, 0.73, 0.77, 0.73, 0.79, 0.82, 0.76, 0.83, - 0.90, 0.84, 1.18, 0.98, 1.03, 0.92, 0.95, 0.90, - 0.86, 1.32, 1.45, 1.15, 1.53, 1.27, 0.99, 1.42, - 1.65, 1.58, 1.93, 1.83, 1.94, 1.81, 1.88, 1.74, - 1.70, 1.19, 1.17, 1.44, 1.11, 1.15, 1.36, 1.41, - 1.61, 1.81, 1.67, 1.22, 1.34, 1.50, 1.42, 1.65, - 1.61, 1.82, 1.91, 1.75, 1.80, 1.89, 1.89, 1.98, - 1.99, 1.94, 1.98, 1.92, 1.87, 0.86, 0.95, 0.92, - 1.14, 0.98, 1.03, 0.79, 0.84, 0.77, 0.97, 0.90, - 0.89, 0.76, 0.82, 0.82, 0.74, 0.72, 0.71, 0.98, - 0.89, 0.97, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.46, 1.34, 1.60, 1.16, 1.46, 1.71, 0.94, 0.99, + 1.05, 1.26, 1.33, 1.74, 1.76, 1.57, 1.54, 1.23, + 0.98, 1.05, 0.83, 0.89, 0.84, 0.92, 0.87, 0.91, + 0.96, 0.78, 0.74, 0.79, 0.72, 0.72, 0.75, 0.76, + 0.80, 0.88, 0.83, 0.94, 0.87, 0.95, 0.76, 0.80, + 0.82, 0.97, 0.96, 0.89, 0.88, 1.08, 1.11, 1.10, + 1.37, 1.59, 1.37, 1.07, 1.27, 1.34, 1.57, 1.45, + 1.69, 1.55, 1.77, 1.79, 1.60, 0.93, 0.90, 0.99, + 0.86, 0.87, 0.93, 0.96, 1.07, 1.35, 1.18, 0.73, + 0.76, 0.77, 0.81, 0.82, 0.85, 0.70, 0.71, 0.72, + 0.78, 0.73, 0.77, 0.73, 0.79, 0.82, 0.76, 0.83, + 0.90, 0.84, 1.18, 0.98, 1.03, 0.92, 0.95, 0.90, + 0.86, 1.32, 1.45, 1.15, 1.53, 1.27, 0.99, 1.42, + 1.65, 1.58, 1.93, 1.83, 1.94, 1.81, 1.88, 1.74, + 1.70, 1.19, 1.17, 1.44, 1.11, 1.15, 1.36, 1.41, + 1.61, 1.81, 1.67, 1.22, 1.34, 1.50, 1.42, 1.65, + 1.61, 1.82, 1.91, 1.75, 1.80, 1.89, 1.89, 1.98, + 1.99, 1.94, 1.98, 1.92, 1.87, 0.86, 0.95, 0.92, + 1.14, 0.98, 1.03, 0.79, 0.84, 0.77, 0.97, 0.90, + 0.89, 0.76, 0.82, 0.82, 0.74, 0.72, 0.71, 0.98, + 0.89, 0.97, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 4 - { 1.60, 1.44, 1.68, 1.22, 1.49, 1.71, 0.93, 0.99, - 0.99, 1.23, 1.22, 1.60, 1.68, 1.44, 1.49, 1.40, - 1.14, 1.19, 0.89, 0.96, 0.89, 0.97, 0.89, 0.91, - 0.98, 0.82, 0.76, 0.82, 0.71, 0.72, 0.73, 0.76, - 0.79, 0.86, 0.83, 0.91, 0.83, 0.89, 0.72, 0.76, - 0.76, 0.89, 0.89, 0.82, 0.82, 0.98, 0.96, 0.97, - 1.14, 1.40, 1.19, 0.94, 1.00, 1.07, 1.37, 1.21, - 1.48, 1.30, 1.57, 1.61, 1.37, 0.86, 0.83, 0.91, - 0.82, 0.82, 0.88, 0.89, 0.96, 1.14, 0.98, 0.70, - 0.72, 0.73, 0.77, 0.76, 0.79, 0.70, 0.72, 0.71, - 0.82, 0.77, 0.80, 0.74, 0.79, 0.80, 0.74, 0.87, - 0.93, 0.85, 1.23, 1.02, 1.02, 0.93, 0.93, 0.87, - 0.85, 1.30, 1.35, 1.07, 1.38, 1.11, 0.94, 1.47, - 1.71, 1.56, 1.97, 1.88, 1.92, 1.79, 1.79, 1.59, - 1.60, 1.30, 1.35, 1.56, 1.37, 1.38, 1.59, 1.60, - 1.79, 1.92, 1.79, 1.48, 1.57, 1.72, 1.61, 1.78, - 1.79, 1.93, 1.99, 1.90, 1.86, 1.78, 1.86, 1.93, - 1.99, 1.97, 1.90, 1.79, 1.72, 0.94, 1.07, 1.00, - 1.37, 1.21, 1.30, 0.86, 0.91, 0.83, 1.14, 0.98, - 0.96, 0.82, 0.88, 0.89, 0.79, 0.76, 0.73, 1.07, - 0.94, 1.11, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.60, 1.44, 1.68, 1.22, 1.49, 1.71, 0.93, 0.99, + 0.99, 1.23, 1.22, 1.60, 1.68, 1.44, 1.49, 1.40, + 1.14, 1.19, 0.89, 0.96, 0.89, 0.97, 0.89, 0.91, + 0.98, 0.82, 0.76, 0.82, 0.71, 0.72, 0.73, 0.76, + 0.79, 0.86, 0.83, 0.91, 0.83, 0.89, 0.72, 0.76, + 0.76, 0.89, 0.89, 0.82, 0.82, 0.98, 0.96, 0.97, + 1.14, 1.40, 1.19, 0.94, 1.00, 1.07, 1.37, 1.21, + 1.48, 1.30, 1.57, 1.61, 1.37, 0.86, 0.83, 0.91, + 0.82, 0.82, 0.88, 0.89, 0.96, 1.14, 0.98, 0.70, + 0.72, 0.73, 0.77, 0.76, 0.79, 0.70, 0.72, 0.71, + 0.82, 0.77, 0.80, 0.74, 0.79, 0.80, 0.74, 0.87, + 0.93, 0.85, 1.23, 1.02, 1.02, 0.93, 0.93, 0.87, + 0.85, 1.30, 1.35, 1.07, 1.38, 1.11, 0.94, 1.47, + 1.71, 1.56, 1.97, 1.88, 1.92, 1.79, 1.79, 1.59, + 1.60, 1.30, 1.35, 1.56, 1.37, 1.38, 1.59, 1.60, + 1.79, 1.92, 1.79, 1.48, 1.57, 1.72, 1.61, 1.78, + 1.79, 1.93, 1.99, 1.90, 1.86, 1.78, 1.86, 1.93, + 1.99, 1.97, 1.90, 1.79, 1.72, 0.94, 1.07, 1.00, + 1.37, 1.21, 1.30, 0.86, 0.91, 0.83, 1.14, 0.98, + 0.96, 0.82, 0.88, 0.89, 0.79, 0.76, 0.73, 1.07, + 0.94, 1.11, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 5 - { 1.74, 1.57, 1.76, 1.33, 1.54, 1.71, 0.94, 1.05, - 0.99, 1.26, 1.16, 1.46, 1.60, 1.34, 1.46, 1.59, - 1.37, 1.37, 0.97, 1.11, 0.96, 1.10, 0.95, 0.94, - 1.08, 0.89, 0.82, 0.88, 0.72, 0.76, 0.75, 0.80, - 0.80, 0.88, 0.87, 0.91, 0.83, 0.87, 0.72, 0.76, - 0.74, 0.83, 0.84, 0.78, 0.79, 0.96, 0.89, 0.92, - 0.98, 1.23, 1.05, 0.86, 0.92, 0.95, 1.11, 0.98, - 1.22, 1.03, 1.34, 1.42, 1.14, 0.79, 0.77, 0.84, - 0.78, 0.76, 0.82, 0.82, 0.89, 0.97, 0.90, 0.70, - 0.71, 0.71, 0.73, 0.72, 0.74, 0.73, 0.76, 0.72, - 0.86, 0.81, 0.82, 0.76, 0.79, 0.77, 0.73, 0.90, - 0.95, 0.86, 1.18, 1.03, 0.98, 0.92, 0.90, 0.83, - 0.84, 1.19, 1.17, 0.98, 1.15, 0.97, 0.89, 1.42, - 1.65, 1.44, 1.93, 1.83, 1.81, 1.67, 1.61, 1.36, - 1.41, 1.32, 1.45, 1.58, 1.57, 1.53, 1.74, 1.70, - 1.88, 1.94, 1.81, 1.69, 1.77, 1.87, 1.79, 1.89, - 1.92, 1.98, 1.99, 1.98, 1.89, 1.65, 1.80, 1.82, - 1.91, 1.94, 1.75, 1.61, 1.50, 1.07, 1.34, 1.27, - 1.60, 1.45, 1.55, 0.93, 0.99, 0.90, 1.35, 1.18, - 1.07, 0.87, 0.93, 0.96, 0.85, 0.82, 0.77, 1.15, - 0.99, 1.27, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.74, 1.57, 1.76, 1.33, 1.54, 1.71, 0.94, 1.05, + 0.99, 1.26, 1.16, 1.46, 1.60, 1.34, 1.46, 1.59, + 1.37, 1.37, 0.97, 1.11, 0.96, 1.10, 0.95, 0.94, + 1.08, 0.89, 0.82, 0.88, 0.72, 0.76, 0.75, 0.80, + 0.80, 0.88, 0.87, 0.91, 0.83, 0.87, 0.72, 0.76, + 0.74, 0.83, 0.84, 0.78, 0.79, 0.96, 0.89, 0.92, + 0.98, 1.23, 1.05, 0.86, 0.92, 0.95, 1.11, 0.98, + 1.22, 1.03, 1.34, 1.42, 1.14, 0.79, 0.77, 0.84, + 0.78, 0.76, 0.82, 0.82, 0.89, 0.97, 0.90, 0.70, + 0.71, 0.71, 0.73, 0.72, 0.74, 0.73, 0.76, 0.72, + 0.86, 0.81, 0.82, 0.76, 0.79, 0.77, 0.73, 0.90, + 0.95, 0.86, 1.18, 1.03, 0.98, 0.92, 0.90, 0.83, + 0.84, 1.19, 1.17, 0.98, 1.15, 0.97, 0.89, 1.42, + 1.65, 1.44, 1.93, 1.83, 1.81, 1.67, 1.61, 1.36, + 1.41, 1.32, 1.45, 1.58, 1.57, 1.53, 1.74, 1.70, + 1.88, 1.94, 1.81, 1.69, 1.77, 1.87, 1.79, 1.89, + 1.92, 1.98, 1.99, 1.98, 1.89, 1.65, 1.80, 1.82, + 1.91, 1.94, 1.75, 1.61, 1.50, 1.07, 1.34, 1.27, + 1.60, 1.45, 1.55, 0.93, 0.99, 0.90, 1.35, 1.18, + 1.07, 0.87, 0.93, 0.96, 0.85, 0.82, 0.77, 1.15, + 0.99, 1.27, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 6 - { 1.86, 1.71, 1.82, 1.48, 1.62, 1.71, 0.98, 1.20, - 1.05, 1.34, 1.17, 1.34, 1.53, 1.27, 1.46, 1.77, - 1.60, 1.57, 1.16, 1.38, 1.12, 1.35, 1.06, 1.00, - 1.28, 0.97, 0.89, 0.95, 0.76, 0.81, 0.79, 0.86, - 0.85, 0.92, 0.93, 0.93, 0.85, 0.87, 0.74, 0.78, - 0.74, 0.79, 0.82, 0.76, 0.79, 0.96, 0.85, 0.90, - 0.94, 1.09, 0.99, 0.81, 0.85, 0.89, 0.95, 0.90, - 0.99, 0.94, 1.10, 1.24, 0.98, 0.75, 0.73, 0.78, - 0.74, 0.72, 0.77, 0.76, 0.82, 0.89, 0.83, 0.73, - 0.71, 0.71, 0.71, 0.70, 0.72, 0.77, 0.80, 0.74, - 0.90, 0.85, 0.84, 0.78, 0.79, 0.75, 0.73, 0.92, - 0.95, 0.86, 1.05, 0.99, 0.94, 0.90, 0.86, 0.79, - 0.81, 1.00, 0.98, 0.91, 0.96, 0.89, 0.83, 1.27, - 1.50, 1.23, 1.80, 1.69, 1.63, 1.46, 1.37, 1.09, - 1.16, 1.24, 1.44, 1.49, 1.69, 1.59, 1.80, 1.69, - 1.87, 1.86, 1.72, 1.82, 1.91, 1.94, 1.92, 1.95, - 1.99, 1.98, 1.91, 1.97, 1.89, 1.51, 1.72, 1.67, - 1.77, 1.86, 1.55, 1.41, 1.25, 1.33, 1.58, 1.50, - 1.80, 1.63, 1.74, 1.04, 1.21, 0.97, 1.48, 1.37, - 1.21, 0.93, 0.97, 1.05, 0.92, 0.88, 0.84, 1.14, - 1.02, 1.34, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.86, 1.71, 1.82, 1.48, 1.62, 1.71, 0.98, 1.20, + 1.05, 1.34, 1.17, 1.34, 1.53, 1.27, 1.46, 1.77, + 1.60, 1.57, 1.16, 1.38, 1.12, 1.35, 1.06, 1.00, + 1.28, 0.97, 0.89, 0.95, 0.76, 0.81, 0.79, 0.86, + 0.85, 0.92, 0.93, 0.93, 0.85, 0.87, 0.74, 0.78, + 0.74, 0.79, 0.82, 0.76, 0.79, 0.96, 0.85, 0.90, + 0.94, 1.09, 0.99, 0.81, 0.85, 0.89, 0.95, 0.90, + 0.99, 0.94, 1.10, 1.24, 0.98, 0.75, 0.73, 0.78, + 0.74, 0.72, 0.77, 0.76, 0.82, 0.89, 0.83, 0.73, + 0.71, 0.71, 0.71, 0.70, 0.72, 0.77, 0.80, 0.74, + 0.90, 0.85, 0.84, 0.78, 0.79, 0.75, 0.73, 0.92, + 0.95, 0.86, 1.05, 0.99, 0.94, 0.90, 0.86, 0.79, + 0.81, 1.00, 0.98, 0.91, 0.96, 0.89, 0.83, 1.27, + 1.50, 1.23, 1.80, 1.69, 1.63, 1.46, 1.37, 1.09, + 1.16, 1.24, 1.44, 1.49, 1.69, 1.59, 1.80, 1.69, + 1.87, 1.86, 1.72, 1.82, 1.91, 1.94, 1.92, 1.95, + 1.99, 1.98, 1.91, 1.97, 1.89, 1.51, 1.72, 1.67, + 1.77, 1.86, 1.55, 1.41, 1.25, 1.33, 1.58, 1.50, + 1.80, 1.63, 1.74, 1.04, 1.21, 0.97, 1.48, 1.37, + 1.21, 0.93, 0.97, 1.05, 0.92, 0.88, 0.84, 1.14, + 1.02, 1.34, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 7 - { 1.94, 1.84, 1.87, 1.64, 1.71, 1.71, 1.14, 1.38, - 1.19, 1.46, 1.23, 1.26, 1.48, 1.26, 1.50, 1.91, - 1.80, 1.76, 1.41, 1.61, 1.39, 1.59, 1.33, 1.24, - 1.51, 1.18, 0.97, 1.11, 0.82, 0.88, 0.86, 0.94, - 0.92, 0.99, 1.03, 0.98, 0.91, 0.90, 0.79, 0.84, - 0.77, 0.79, 0.84, 0.77, 0.83, 0.99, 0.85, 0.91, - 0.92, 1.02, 1.00, 0.79, 0.80, 0.86, 0.88, 0.84, - 0.92, 0.88, 0.97, 1.10, 0.94, 0.74, 0.71, 0.74, - 0.72, 0.70, 0.73, 0.72, 0.76, 0.82, 0.77, 0.77, - 0.73, 0.74, 0.71, 0.70, 0.73, 0.83, 0.85, 0.78, - 0.92, 0.88, 0.86, 0.81, 0.79, 0.74, 0.75, 0.92, - 0.93, 0.85, 0.96, 0.94, 0.88, 0.86, 0.81, 0.75, - 0.79, 0.93, 0.90, 0.85, 0.88, 0.82, 0.77, 1.05, - 1.27, 0.99, 1.60, 1.47, 1.39, 1.20, 1.11, 0.95, - 0.97, 1.08, 1.33, 1.31, 1.70, 1.55, 1.76, 1.57, - 1.76, 1.70, 1.54, 1.85, 1.97, 1.91, 1.99, 1.97, - 1.99, 1.91, 1.77, 1.88, 1.85, 1.39, 1.64, 1.51, - 1.58, 1.74, 1.32, 1.22, 1.01, 1.54, 1.76, 1.65, - 1.93, 1.70, 1.85, 1.28, 1.39, 1.09, 1.52, 1.48, - 1.26, 0.97, 0.99, 1.18, 1.00, 0.93, 0.90, 1.05, - 1.01, 1.31, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.94, 1.84, 1.87, 1.64, 1.71, 1.71, 1.14, 1.38, + 1.19, 1.46, 1.23, 1.26, 1.48, 1.26, 1.50, 1.91, + 1.80, 1.76, 1.41, 1.61, 1.39, 1.59, 1.33, 1.24, + 1.51, 1.18, 0.97, 1.11, 0.82, 0.88, 0.86, 0.94, + 0.92, 0.99, 1.03, 0.98, 0.91, 0.90, 0.79, 0.84, + 0.77, 0.79, 0.84, 0.77, 0.83, 0.99, 0.85, 0.91, + 0.92, 1.02, 1.00, 0.79, 0.80, 0.86, 0.88, 0.84, + 0.92, 0.88, 0.97, 1.10, 0.94, 0.74, 0.71, 0.74, + 0.72, 0.70, 0.73, 0.72, 0.76, 0.82, 0.77, 0.77, + 0.73, 0.74, 0.71, 0.70, 0.73, 0.83, 0.85, 0.78, + 0.92, 0.88, 0.86, 0.81, 0.79, 0.74, 0.75, 0.92, + 0.93, 0.85, 0.96, 0.94, 0.88, 0.86, 0.81, 0.75, + 0.79, 0.93, 0.90, 0.85, 0.88, 0.82, 0.77, 1.05, + 1.27, 0.99, 1.60, 1.47, 1.39, 1.20, 1.11, 0.95, + 0.97, 1.08, 1.33, 1.31, 1.70, 1.55, 1.76, 1.57, + 1.76, 1.70, 1.54, 1.85, 1.97, 1.91, 1.99, 1.97, + 1.99, 1.91, 1.77, 1.88, 1.85, 1.39, 1.64, 1.51, + 1.58, 1.74, 1.32, 1.22, 1.01, 1.54, 1.76, 1.65, + 1.93, 1.70, 1.85, 1.28, 1.39, 1.09, 1.52, 1.48, + 1.26, 0.97, 0.99, 1.18, 1.00, 0.93, 0.90, 1.05, + 1.01, 1.31, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 8 - { 1.97, 1.92, 1.88, 1.79, 1.79, 1.71, 1.37, 1.59, - 1.38, 1.60, 1.35, 1.23, 1.47, 1.30, 1.56, 1.99, - 1.93, 1.90, 1.60, 1.78, 1.61, 1.79, 1.57, 1.48, - 1.72, 1.40, 1.14, 1.37, 0.89, 0.96, 0.94, 1.07, - 1.00, 1.21, 1.30, 1.14, 0.98, 0.96, 0.86, 0.91, - 0.83, 0.82, 0.88, 0.82, 0.89, 1.11, 0.87, 0.94, - 0.93, 1.02, 1.07, 0.80, 0.79, 0.85, 0.82, 0.80, - 0.87, 0.85, 0.93, 1.02, 0.93, 0.77, 0.72, 0.74, - 0.71, 0.70, 0.70, 0.71, 0.72, 0.77, 0.74, 0.82, - 0.76, 0.79, 0.72, 0.73, 0.76, 0.89, 0.89, 0.82, - 0.93, 0.91, 0.86, 0.83, 0.79, 0.73, 0.76, 0.91, - 0.89, 0.83, 0.89, 0.89, 0.82, 0.82, 0.76, 0.72, - 0.76, 0.86, 0.83, 0.79, 0.82, 0.76, 0.73, 0.94, - 1.00, 0.91, 1.37, 1.21, 1.14, 0.98, 0.96, 0.88, - 0.89, 0.96, 1.14, 1.07, 1.60, 1.40, 1.61, 1.37, - 1.57, 1.48, 1.30, 1.78, 1.93, 1.79, 1.99, 1.92, - 1.90, 1.79, 1.59, 1.72, 1.79, 1.30, 1.56, 1.35, - 1.38, 1.60, 1.11, 1.07, 0.94, 1.68, 1.86, 1.71, - 1.97, 1.68, 1.86, 1.44, 1.49, 1.22, 1.44, 1.49, - 1.22, 0.99, 0.99, 1.23, 1.19, 0.98, 0.97, 0.97, - 0.98, 1.19, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.97, 1.92, 1.88, 1.79, 1.79, 1.71, 1.37, 1.59, + 1.38, 1.60, 1.35, 1.23, 1.47, 1.30, 1.56, 1.99, + 1.93, 1.90, 1.60, 1.78, 1.61, 1.79, 1.57, 1.48, + 1.72, 1.40, 1.14, 1.37, 0.89, 0.96, 0.94, 1.07, + 1.00, 1.21, 1.30, 1.14, 0.98, 0.96, 0.86, 0.91, + 0.83, 0.82, 0.88, 0.82, 0.89, 1.11, 0.87, 0.94, + 0.93, 1.02, 1.07, 0.80, 0.79, 0.85, 0.82, 0.80, + 0.87, 0.85, 0.93, 1.02, 0.93, 0.77, 0.72, 0.74, + 0.71, 0.70, 0.70, 0.71, 0.72, 0.77, 0.74, 0.82, + 0.76, 0.79, 0.72, 0.73, 0.76, 0.89, 0.89, 0.82, + 0.93, 0.91, 0.86, 0.83, 0.79, 0.73, 0.76, 0.91, + 0.89, 0.83, 0.89, 0.89, 0.82, 0.82, 0.76, 0.72, + 0.76, 0.86, 0.83, 0.79, 0.82, 0.76, 0.73, 0.94, + 1.00, 0.91, 1.37, 1.21, 1.14, 0.98, 0.96, 0.88, + 0.89, 0.96, 1.14, 1.07, 1.60, 1.40, 1.61, 1.37, + 1.57, 1.48, 1.30, 1.78, 1.93, 1.79, 1.99, 1.92, + 1.90, 1.79, 1.59, 1.72, 1.79, 1.30, 1.56, 1.35, + 1.38, 1.60, 1.11, 1.07, 0.94, 1.68, 1.86, 1.71, + 1.97, 1.68, 1.86, 1.44, 1.49, 1.22, 1.44, 1.49, + 1.22, 0.99, 0.99, 1.23, 1.19, 0.98, 0.97, 0.97, + 0.98, 1.19, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 9 - { 1.94, 1.97, 1.87, 1.91, 1.85, 1.71, 1.60, 1.77, - 1.58, 1.74, 1.51, 1.26, 1.48, 1.39, 1.64, 1.99, - 1.97, 1.99, 1.70, 1.85, 1.76, 1.91, 1.76, 1.70, - 1.88, 1.55, 1.33, 1.57, 0.96, 1.08, 1.05, 1.31, - 1.27, 1.47, 1.54, 1.39, 1.20, 1.11, 0.93, 0.99, - 0.90, 0.88, 0.95, 0.88, 0.97, 1.32, 0.92, 1.01, - 0.97, 1.10, 1.22, 0.84, 0.80, 0.88, 0.79, 0.79, - 0.85, 0.86, 0.92, 1.02, 0.94, 0.82, 0.76, 0.77, - 0.72, 0.73, 0.70, 0.72, 0.71, 0.74, 0.74, 0.88, - 0.81, 0.85, 0.75, 0.77, 0.82, 0.94, 0.93, 0.86, - 0.92, 0.92, 0.86, 0.85, 0.79, 0.74, 0.79, 0.88, - 0.85, 0.81, 0.82, 0.83, 0.77, 0.78, 0.73, 0.71, - 0.75, 0.79, 0.77, 0.74, 0.77, 0.73, 0.70, 0.86, - 0.92, 0.84, 1.14, 0.99, 0.98, 0.91, 0.90, 0.84, - 0.83, 0.88, 0.97, 0.94, 1.41, 1.18, 1.39, 1.11, - 1.33, 1.24, 1.03, 1.61, 1.80, 1.59, 1.91, 1.84, - 1.76, 1.64, 1.38, 1.51, 1.71, 1.26, 1.50, 1.23, - 1.19, 1.46, 0.99, 1.00, 0.91, 1.70, 1.85, 1.65, - 1.93, 1.54, 1.76, 1.52, 1.48, 1.26, 1.28, 1.39, - 1.09, 0.99, 0.97, 1.18, 1.31, 1.01, 1.05, 0.90, - 0.93, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.94, 1.97, 1.87, 1.91, 1.85, 1.71, 1.60, 1.77, + 1.58, 1.74, 1.51, 1.26, 1.48, 1.39, 1.64, 1.99, + 1.97, 1.99, 1.70, 1.85, 1.76, 1.91, 1.76, 1.70, + 1.88, 1.55, 1.33, 1.57, 0.96, 1.08, 1.05, 1.31, + 1.27, 1.47, 1.54, 1.39, 1.20, 1.11, 0.93, 0.99, + 0.90, 0.88, 0.95, 0.88, 0.97, 1.32, 0.92, 1.01, + 0.97, 1.10, 1.22, 0.84, 0.80, 0.88, 0.79, 0.79, + 0.85, 0.86, 0.92, 1.02, 0.94, 0.82, 0.76, 0.77, + 0.72, 0.73, 0.70, 0.72, 0.71, 0.74, 0.74, 0.88, + 0.81, 0.85, 0.75, 0.77, 0.82, 0.94, 0.93, 0.86, + 0.92, 0.92, 0.86, 0.85, 0.79, 0.74, 0.79, 0.88, + 0.85, 0.81, 0.82, 0.83, 0.77, 0.78, 0.73, 0.71, + 0.75, 0.79, 0.77, 0.74, 0.77, 0.73, 0.70, 0.86, + 0.92, 0.84, 1.14, 0.99, 0.98, 0.91, 0.90, 0.84, + 0.83, 0.88, 0.97, 0.94, 1.41, 1.18, 1.39, 1.11, + 1.33, 1.24, 1.03, 1.61, 1.80, 1.59, 1.91, 1.84, + 1.76, 1.64, 1.38, 1.51, 1.71, 1.26, 1.50, 1.23, + 1.19, 1.46, 0.99, 1.00, 0.91, 1.70, 1.85, 1.65, + 1.93, 1.54, 1.76, 1.52, 1.48, 1.26, 1.28, 1.39, + 1.09, 0.99, 0.97, 1.18, 1.31, 1.01, 1.05, 0.90, + 0.93, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 10 - { 1.86, 1.95, 1.82, 1.98, 1.89, 1.71, 1.80, 1.91, - 1.77, 1.86, 1.67, 1.34, 1.53, 1.51, 1.72, 1.92, - 1.91, 1.99, 1.69, 1.82, 1.80, 1.94, 1.87, 1.86, - 1.97, 1.59, 1.44, 1.69, 1.05, 1.24, 1.27, 1.49, - 1.50, 1.69, 1.72, 1.63, 1.46, 1.37, 1.00, 1.23, - 0.98, 0.95, 1.09, 0.96, 1.16, 1.55, 0.99, 1.25, - 1.10, 1.24, 1.41, 0.90, 0.85, 0.94, 0.79, 0.81, - 0.85, 0.89, 0.94, 1.09, 0.98, 0.89, 0.82, 0.83, - 0.74, 0.77, 0.72, 0.76, 0.73, 0.75, 0.78, 0.94, - 0.86, 0.91, 0.79, 0.83, 0.89, 0.99, 0.95, 0.90, - 0.90, 0.92, 0.84, 0.86, 0.79, 0.75, 0.81, 0.85, - 0.80, 0.78, 0.76, 0.77, 0.73, 0.74, 0.71, 0.71, - 0.73, 0.74, 0.74, 0.71, 0.76, 0.72, 0.70, 0.79, - 0.85, 0.78, 0.98, 0.92, 0.93, 0.85, 0.87, 0.82, - 0.79, 0.81, 0.89, 0.86, 1.16, 0.97, 1.12, 0.95, - 1.06, 1.00, 0.93, 1.38, 1.60, 1.35, 1.77, 1.71, - 1.57, 1.48, 1.20, 1.28, 1.62, 1.27, 1.46, 1.17, - 1.05, 1.34, 0.96, 0.99, 0.90, 1.63, 1.74, 1.50, - 1.80, 1.33, 1.58, 1.48, 1.37, 1.21, 1.04, 1.21, - 0.97, 0.97, 0.93, 1.05, 1.34, 1.02, 1.14, 0.84, - 0.88, 0.92, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.86, 1.95, 1.82, 1.98, 1.89, 1.71, 1.80, 1.91, + 1.77, 1.86, 1.67, 1.34, 1.53, 1.51, 1.72, 1.92, + 1.91, 1.99, 1.69, 1.82, 1.80, 1.94, 1.87, 1.86, + 1.97, 1.59, 1.44, 1.69, 1.05, 1.24, 1.27, 1.49, + 1.50, 1.69, 1.72, 1.63, 1.46, 1.37, 1.00, 1.23, + 0.98, 0.95, 1.09, 0.96, 1.16, 1.55, 0.99, 1.25, + 1.10, 1.24, 1.41, 0.90, 0.85, 0.94, 0.79, 0.81, + 0.85, 0.89, 0.94, 1.09, 0.98, 0.89, 0.82, 0.83, + 0.74, 0.77, 0.72, 0.76, 0.73, 0.75, 0.78, 0.94, + 0.86, 0.91, 0.79, 0.83, 0.89, 0.99, 0.95, 0.90, + 0.90, 0.92, 0.84, 0.86, 0.79, 0.75, 0.81, 0.85, + 0.80, 0.78, 0.76, 0.77, 0.73, 0.74, 0.71, 0.71, + 0.73, 0.74, 0.74, 0.71, 0.76, 0.72, 0.70, 0.79, + 0.85, 0.78, 0.98, 0.92, 0.93, 0.85, 0.87, 0.82, + 0.79, 0.81, 0.89, 0.86, 1.16, 0.97, 1.12, 0.95, + 1.06, 1.00, 0.93, 1.38, 1.60, 1.35, 1.77, 1.71, + 1.57, 1.48, 1.20, 1.28, 1.62, 1.27, 1.46, 1.17, + 1.05, 1.34, 0.96, 0.99, 0.90, 1.63, 1.74, 1.50, + 1.80, 1.33, 1.58, 1.48, 1.37, 1.21, 1.04, 1.21, + 0.97, 0.97, 0.93, 1.05, 1.34, 1.02, 1.14, 0.84, + 0.88, 0.92, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 11 - { 1.74, 1.89, 1.76, 1.98, 1.89, 1.71, 1.93, 1.99, - 1.91, 1.94, 1.82, 1.46, 1.60, 1.65, 1.80, 1.79, - 1.77, 1.92, 1.57, 1.69, 1.74, 1.87, 1.88, 1.94, - 1.98, 1.53, 1.45, 1.70, 1.18, 1.32, 1.42, 1.58, - 1.65, 1.83, 1.81, 1.81, 1.67, 1.61, 1.19, 1.44, - 1.17, 1.11, 1.36, 1.15, 1.41, 1.75, 1.22, 1.50, - 1.34, 1.42, 1.61, 0.98, 0.92, 1.03, 0.83, 0.86, - 0.89, 0.95, 0.98, 1.23, 1.14, 0.97, 0.89, 0.90, - 0.78, 0.82, 0.76, 0.82, 0.77, 0.79, 0.84, 0.98, - 0.90, 0.98, 0.83, 0.89, 0.97, 1.03, 0.95, 0.92, - 0.86, 0.90, 0.82, 0.86, 0.79, 0.77, 0.84, 0.81, - 0.76, 0.76, 0.72, 0.73, 0.70, 0.72, 0.71, 0.73, - 0.73, 0.72, 0.74, 0.71, 0.78, 0.74, 0.72, 0.75, - 0.80, 0.76, 0.94, 0.88, 0.91, 0.83, 0.87, 0.84, - 0.79, 0.76, 0.82, 0.80, 0.97, 0.89, 0.96, 0.88, - 0.95, 0.94, 0.87, 1.11, 1.37, 1.10, 1.59, 1.57, - 1.37, 1.33, 1.05, 1.08, 1.54, 1.34, 1.46, 1.16, - 0.99, 1.26, 0.96, 1.05, 0.92, 1.45, 1.55, 1.27, - 1.60, 1.07, 1.34, 1.35, 1.18, 1.07, 0.93, 0.99, - 0.90, 0.93, 0.87, 0.96, 1.27, 0.99, 1.15, 0.77, - 0.82, 0.85, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.74, 1.89, 1.76, 1.98, 1.89, 1.71, 1.93, 1.99, + 1.91, 1.94, 1.82, 1.46, 1.60, 1.65, 1.80, 1.79, + 1.77, 1.92, 1.57, 1.69, 1.74, 1.87, 1.88, 1.94, + 1.98, 1.53, 1.45, 1.70, 1.18, 1.32, 1.42, 1.58, + 1.65, 1.83, 1.81, 1.81, 1.67, 1.61, 1.19, 1.44, + 1.17, 1.11, 1.36, 1.15, 1.41, 1.75, 1.22, 1.50, + 1.34, 1.42, 1.61, 0.98, 0.92, 1.03, 0.83, 0.86, + 0.89, 0.95, 0.98, 1.23, 1.14, 0.97, 0.89, 0.90, + 0.78, 0.82, 0.76, 0.82, 0.77, 0.79, 0.84, 0.98, + 0.90, 0.98, 0.83, 0.89, 0.97, 1.03, 0.95, 0.92, + 0.86, 0.90, 0.82, 0.86, 0.79, 0.77, 0.84, 0.81, + 0.76, 0.76, 0.72, 0.73, 0.70, 0.72, 0.71, 0.73, + 0.73, 0.72, 0.74, 0.71, 0.78, 0.74, 0.72, 0.75, + 0.80, 0.76, 0.94, 0.88, 0.91, 0.83, 0.87, 0.84, + 0.79, 0.76, 0.82, 0.80, 0.97, 0.89, 0.96, 0.88, + 0.95, 0.94, 0.87, 1.11, 1.37, 1.10, 1.59, 1.57, + 1.37, 1.33, 1.05, 1.08, 1.54, 1.34, 1.46, 1.16, + 0.99, 1.26, 0.96, 1.05, 0.92, 1.45, 1.55, 1.27, + 1.60, 1.07, 1.34, 1.35, 1.18, 1.07, 0.93, 0.99, + 0.90, 0.93, 0.87, 0.96, 1.27, 0.99, 1.15, 0.77, + 0.82, 0.85, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 12 - { 1.60, 1.78, 1.68, 1.93, 1.86, 1.71, 1.97, 1.99, - 1.99, 1.97, 1.93, 1.60, 1.68, 1.78, 1.86, 1.61, - 1.57, 1.79, 1.37, 1.48, 1.59, 1.72, 1.79, 1.92, - 1.90, 1.38, 1.35, 1.60, 1.23, 1.30, 1.47, 1.56, - 1.71, 1.88, 1.79, 1.92, 1.79, 1.79, 1.30, 1.56, - 1.35, 1.37, 1.59, 1.38, 1.60, 1.90, 1.48, 1.72, - 1.57, 1.61, 1.79, 1.21, 1.00, 1.30, 0.89, 0.94, - 0.96, 1.07, 1.14, 1.40, 1.37, 1.14, 0.96, 0.98, - 0.82, 0.88, 0.82, 0.89, 0.83, 0.86, 0.91, 1.02, - 0.93, 1.07, 0.87, 0.94, 1.11, 1.02, 0.93, 0.93, - 0.82, 0.87, 0.80, 0.85, 0.79, 0.80, 0.85, 0.77, - 0.72, 0.74, 0.71, 0.70, 0.70, 0.71, 0.72, 0.77, - 0.74, 0.72, 0.76, 0.73, 0.82, 0.79, 0.76, 0.73, - 0.79, 0.76, 0.93, 0.86, 0.91, 0.83, 0.89, 0.89, - 0.82, 0.72, 0.76, 0.76, 0.89, 0.82, 0.89, 0.82, - 0.89, 0.91, 0.83, 0.96, 1.14, 0.97, 1.40, 1.44, - 1.19, 1.22, 0.99, 0.98, 1.49, 1.44, 1.49, 1.22, - 0.99, 1.23, 0.98, 1.19, 0.97, 1.21, 1.30, 1.00, - 1.37, 0.94, 1.07, 1.14, 0.98, 0.96, 0.86, 0.91, - 0.83, 0.88, 0.82, 0.89, 1.11, 0.94, 1.07, 0.73, - 0.76, 0.79, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.60, 1.78, 1.68, 1.93, 1.86, 1.71, 1.97, 1.99, + 1.99, 1.97, 1.93, 1.60, 1.68, 1.78, 1.86, 1.61, + 1.57, 1.79, 1.37, 1.48, 1.59, 1.72, 1.79, 1.92, + 1.90, 1.38, 1.35, 1.60, 1.23, 1.30, 1.47, 1.56, + 1.71, 1.88, 1.79, 1.92, 1.79, 1.79, 1.30, 1.56, + 1.35, 1.37, 1.59, 1.38, 1.60, 1.90, 1.48, 1.72, + 1.57, 1.61, 1.79, 1.21, 1.00, 1.30, 0.89, 0.94, + 0.96, 1.07, 1.14, 1.40, 1.37, 1.14, 0.96, 0.98, + 0.82, 0.88, 0.82, 0.89, 0.83, 0.86, 0.91, 1.02, + 0.93, 1.07, 0.87, 0.94, 1.11, 1.02, 0.93, 0.93, + 0.82, 0.87, 0.80, 0.85, 0.79, 0.80, 0.85, 0.77, + 0.72, 0.74, 0.71, 0.70, 0.70, 0.71, 0.72, 0.77, + 0.74, 0.72, 0.76, 0.73, 0.82, 0.79, 0.76, 0.73, + 0.79, 0.76, 0.93, 0.86, 0.91, 0.83, 0.89, 0.89, + 0.82, 0.72, 0.76, 0.76, 0.89, 0.82, 0.89, 0.82, + 0.89, 0.91, 0.83, 0.96, 1.14, 0.97, 1.40, 1.44, + 1.19, 1.22, 0.99, 0.98, 1.49, 1.44, 1.49, 1.22, + 0.99, 1.23, 0.98, 1.19, 0.97, 1.21, 1.30, 1.00, + 1.37, 0.94, 1.07, 1.14, 0.98, 0.96, 0.86, 0.91, + 0.83, 0.88, 0.82, 0.89, 1.11, 0.94, 1.07, 0.73, + 0.76, 0.79, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 13 - { 1.46, 1.65, 1.60, 1.82, 1.80, 1.71, 1.93, 1.91, - 1.99, 1.94, 1.98, 1.74, 1.76, 1.89, 1.89, 1.42, - 1.34, 1.61, 1.11, 1.22, 1.36, 1.50, 1.61, 1.81, - 1.75, 1.15, 1.17, 1.41, 1.18, 1.19, 1.42, 1.44, - 1.65, 1.83, 1.67, 1.94, 1.81, 1.88, 1.32, 1.58, - 1.45, 1.57, 1.74, 1.53, 1.70, 1.98, 1.69, 1.87, - 1.77, 1.79, 1.92, 1.45, 1.27, 1.55, 0.97, 1.07, - 1.11, 1.34, 1.37, 1.59, 1.60, 1.35, 1.07, 1.18, - 0.86, 0.93, 0.87, 0.96, 0.90, 0.93, 0.99, 1.03, - 0.95, 1.15, 0.90, 0.99, 1.27, 0.98, 0.90, 0.92, - 0.78, 0.83, 0.77, 0.84, 0.79, 0.82, 0.86, 0.73, - 0.71, 0.73, 0.72, 0.70, 0.73, 0.72, 0.76, 0.81, - 0.76, 0.76, 0.82, 0.77, 0.89, 0.85, 0.82, 0.75, - 0.80, 0.80, 0.94, 0.88, 0.94, 0.87, 0.95, 0.96, - 0.88, 0.72, 0.74, 0.76, 0.83, 0.78, 0.84, 0.79, - 0.87, 0.91, 0.83, 0.89, 0.98, 0.92, 1.23, 1.34, - 1.05, 1.16, 0.99, 0.96, 1.46, 1.57, 1.54, 1.33, - 1.05, 1.26, 1.08, 1.37, 1.10, 0.98, 1.03, 0.92, - 1.14, 0.86, 0.95, 0.97, 0.90, 0.89, 0.79, 0.84, - 0.77, 0.82, 0.76, 0.82, 0.97, 0.89, 0.98, 0.71, - 0.72, 0.74, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.46, 1.65, 1.60, 1.82, 1.80, 1.71, 1.93, 1.91, + 1.99, 1.94, 1.98, 1.74, 1.76, 1.89, 1.89, 1.42, + 1.34, 1.61, 1.11, 1.22, 1.36, 1.50, 1.61, 1.81, + 1.75, 1.15, 1.17, 1.41, 1.18, 1.19, 1.42, 1.44, + 1.65, 1.83, 1.67, 1.94, 1.81, 1.88, 1.32, 1.58, + 1.45, 1.57, 1.74, 1.53, 1.70, 1.98, 1.69, 1.87, + 1.77, 1.79, 1.92, 1.45, 1.27, 1.55, 0.97, 1.07, + 1.11, 1.34, 1.37, 1.59, 1.60, 1.35, 1.07, 1.18, + 0.86, 0.93, 0.87, 0.96, 0.90, 0.93, 0.99, 1.03, + 0.95, 1.15, 0.90, 0.99, 1.27, 0.98, 0.90, 0.92, + 0.78, 0.83, 0.77, 0.84, 0.79, 0.82, 0.86, 0.73, + 0.71, 0.73, 0.72, 0.70, 0.73, 0.72, 0.76, 0.81, + 0.76, 0.76, 0.82, 0.77, 0.89, 0.85, 0.82, 0.75, + 0.80, 0.80, 0.94, 0.88, 0.94, 0.87, 0.95, 0.96, + 0.88, 0.72, 0.74, 0.76, 0.83, 0.78, 0.84, 0.79, + 0.87, 0.91, 0.83, 0.89, 0.98, 0.92, 1.23, 1.34, + 1.05, 1.16, 0.99, 0.96, 1.46, 1.57, 1.54, 1.33, + 1.05, 1.26, 1.08, 1.37, 1.10, 0.98, 1.03, 0.92, + 1.14, 0.86, 0.95, 0.97, 0.90, 0.89, 0.79, 0.84, + 0.77, 0.82, 0.76, 0.82, 0.97, 0.89, 0.98, 0.71, + 0.72, 0.74, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 14 - { 1.34, 1.51, 1.53, 1.67, 1.72, 1.71, 1.80, 1.77, - 1.91, 1.86, 1.98, 1.86, 1.82, 1.95, 1.89, 1.24, - 1.10, 1.41, 0.95, 0.99, 1.09, 1.25, 1.37, 1.63, - 1.55, 0.96, 0.98, 1.16, 1.05, 1.00, 1.27, 1.23, - 1.50, 1.69, 1.46, 1.86, 1.72, 1.87, 1.24, 1.49, - 1.44, 1.69, 1.80, 1.59, 1.69, 1.97, 1.82, 1.94, - 1.91, 1.92, 1.99, 1.63, 1.50, 1.74, 1.16, 1.33, - 1.38, 1.58, 1.60, 1.77, 1.80, 1.48, 1.21, 1.37, - 0.90, 0.97, 0.93, 1.05, 0.97, 1.04, 1.21, 0.99, - 0.95, 1.14, 0.92, 1.02, 1.34, 0.94, 0.86, 0.90, - 0.74, 0.79, 0.75, 0.81, 0.79, 0.84, 0.86, 0.71, - 0.71, 0.73, 0.76, 0.73, 0.77, 0.74, 0.80, 0.85, - 0.78, 0.81, 0.89, 0.84, 0.97, 0.92, 0.88, 0.79, - 0.85, 0.86, 0.98, 0.92, 1.00, 0.93, 1.06, 1.12, - 0.95, 0.74, 0.74, 0.78, 0.79, 0.76, 0.82, 0.79, - 0.87, 0.93, 0.85, 0.85, 0.94, 0.90, 1.09, 1.27, - 0.99, 1.17, 1.05, 0.96, 1.46, 1.71, 1.62, 1.48, - 1.20, 1.34, 1.28, 1.57, 1.35, 0.90, 0.94, 0.85, - 0.98, 0.81, 0.89, 0.89, 0.83, 0.82, 0.75, 0.78, - 0.73, 0.77, 0.72, 0.76, 0.89, 0.83, 0.91, 0.71, - 0.70, 0.72, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - }, +{ + 1.34, 1.51, 1.53, 1.67, 1.72, 1.71, 1.80, 1.77, + 1.91, 1.86, 1.98, 1.86, 1.82, 1.95, 1.89, 1.24, + 1.10, 1.41, 0.95, 0.99, 1.09, 1.25, 1.37, 1.63, + 1.55, 0.96, 0.98, 1.16, 1.05, 1.00, 1.27, 1.23, + 1.50, 1.69, 1.46, 1.86, 1.72, 1.87, 1.24, 1.49, + 1.44, 1.69, 1.80, 1.59, 1.69, 1.97, 1.82, 1.94, + 1.91, 1.92, 1.99, 1.63, 1.50, 1.74, 1.16, 1.33, + 1.38, 1.58, 1.60, 1.77, 1.80, 1.48, 1.21, 1.37, + 0.90, 0.97, 0.93, 1.05, 0.97, 1.04, 1.21, 0.99, + 0.95, 1.14, 0.92, 1.02, 1.34, 0.94, 0.86, 0.90, + 0.74, 0.79, 0.75, 0.81, 0.79, 0.84, 0.86, 0.71, + 0.71, 0.73, 0.76, 0.73, 0.77, 0.74, 0.80, 0.85, + 0.78, 0.81, 0.89, 0.84, 0.97, 0.92, 0.88, 0.79, + 0.85, 0.86, 0.98, 0.92, 1.00, 0.93, 1.06, 1.12, + 0.95, 0.74, 0.74, 0.78, 0.79, 0.76, 0.82, 0.79, + 0.87, 0.93, 0.85, 0.85, 0.94, 0.90, 1.09, 1.27, + 0.99, 1.17, 1.05, 0.96, 1.46, 1.71, 1.62, 1.48, + 1.20, 1.34, 1.28, 1.57, 1.35, 0.90, 0.94, 0.85, + 0.98, 0.81, 0.89, 0.89, 0.83, 0.82, 0.75, 0.78, + 0.73, 0.77, 0.72, 0.76, 0.89, 0.83, 0.91, 0.71, + 0.70, 0.72, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +}, // 15 - { 1.26, 1.39, 1.48, 1.51, 1.64, 1.71, 1.60, 1.58, - 1.77, 1.74, 1.91, 1.94, 1.87, 1.97, 1.85, 1.10, - 0.97, 1.22, 0.88, 0.92, 0.95, 1.01, 1.11, 1.39, - 1.32, 0.88, 0.90, 0.97, 0.96, 0.93, 1.05, 0.99, - 1.27, 1.47, 1.20, 1.70, 1.54, 1.76, 1.08, 1.31, - 1.33, 1.70, 1.76, 1.55, 1.57, 1.88, 1.85, 1.91, - 1.97, 1.99, 1.99, 1.70, 1.65, 1.85, 1.41, 1.54, - 1.61, 1.76, 1.80, 1.91, 1.93, 1.52, 1.26, 1.48, - 0.92, 0.99, 0.97, 1.18, 1.09, 1.28, 1.39, 0.94, - 0.93, 1.05, 0.92, 1.01, 1.31, 0.88, 0.81, 0.86, - 0.72, 0.75, 0.74, 0.79, 0.79, 0.86, 0.85, 0.71, - 0.73, 0.75, 0.82, 0.77, 0.83, 0.78, 0.85, 0.88, - 0.81, 0.88, 0.97, 0.90, 1.18, 1.00, 0.93, 0.86, - 0.92, 0.94, 1.14, 0.99, 1.24, 1.03, 1.33, 1.39, - 1.11, 0.79, 0.77, 0.84, 0.79, 0.77, 0.84, 0.83, - 0.90, 0.98, 0.91, 0.85, 0.92, 0.91, 1.02, 1.26, - 1.00, 1.23, 1.19, 0.99, 1.50, 1.84, 1.71, 1.64, - 1.38, 1.46, 1.51, 1.76, 1.59, 0.84, 0.88, 0.80, - 0.94, 0.79, 0.86, 0.82, 0.77, 0.76, 0.74, 0.74, - 0.71, 0.73, 0.70, 0.72, 0.82, 0.77, 0.85, 0.74, - 0.70, 0.73, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, - 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 - } +{ + 1.26, 1.39, 1.48, 1.51, 1.64, 1.71, 1.60, 1.58, + 1.77, 1.74, 1.91, 1.94, 1.87, 1.97, 1.85, 1.10, + 0.97, 1.22, 0.88, 0.92, 0.95, 1.01, 1.11, 1.39, + 1.32, 0.88, 0.90, 0.97, 0.96, 0.93, 1.05, 0.99, + 1.27, 1.47, 1.20, 1.70, 1.54, 1.76, 1.08, 1.31, + 1.33, 1.70, 1.76, 1.55, 1.57, 1.88, 1.85, 1.91, + 1.97, 1.99, 1.99, 1.70, 1.65, 1.85, 1.41, 1.54, + 1.61, 1.76, 1.80, 1.91, 1.93, 1.52, 1.26, 1.48, + 0.92, 0.99, 0.97, 1.18, 1.09, 1.28, 1.39, 0.94, + 0.93, 1.05, 0.92, 1.01, 1.31, 0.88, 0.81, 0.86, + 0.72, 0.75, 0.74, 0.79, 0.79, 0.86, 0.85, 0.71, + 0.73, 0.75, 0.82, 0.77, 0.83, 0.78, 0.85, 0.88, + 0.81, 0.88, 0.97, 0.90, 1.18, 1.00, 0.93, 0.86, + 0.92, 0.94, 1.14, 0.99, 1.24, 1.03, 1.33, 1.39, + 1.11, 0.79, 0.77, 0.84, 0.79, 0.77, 0.84, 0.83, + 0.90, 0.98, 0.91, 0.85, 0.92, 0.91, 1.02, 1.26, + 1.00, 1.23, 1.19, 0.99, 1.50, 1.84, 1.71, 1.64, + 1.38, 1.46, 1.51, 1.76, 1.59, 0.84, 0.88, 0.80, + 0.94, 0.79, 0.86, 0.82, 0.77, 0.76, 0.74, 0.74, + 0.71, 0.73, 0.70, 0.72, 0.82, 0.77, 0.85, 0.74, + 0.70, 0.73, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, + 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00 +} diff --git a/source/anorms.h b/source/anorms.h index 35a903e..c0edcaf 100644 --- a/source/anorms.h +++ b/source/anorms.h @@ -18,165 +18,165 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ - { -0.525731, 0.000000, 0.850651 }, - { -0.442863, 0.238856, 0.864188 }, - { -0.295242, 0.000000, 0.955423 }, - { -0.309017, 0.500000, 0.809017 }, - { -0.162460, 0.262866, 0.951056 }, - { 0.000000, 0.000000, 1.000000 }, - { 0.000000, 0.850651, 0.525731 }, - { -0.147621, 0.716567, 0.681718 }, - { 0.147621, 0.716567, 0.681718 }, - { 0.000000, 0.525731, 0.850651 }, - { 0.309017, 0.500000, 0.809017 }, - { 0.525731, 0.000000, 0.850651 }, - { 0.295242, 0.000000, 0.955423 }, - { 0.442863, 0.238856, 0.864188 }, - { 0.162460, 0.262866, 0.951056 }, - { -0.681718, 0.147621, 0.716567 }, - { -0.809017, 0.309017, 0.500000 }, - { -0.587785, 0.425325, 0.688191 }, - { -0.850651, 0.525731, 0.000000 }, - { -0.864188, 0.442863, 0.238856 }, - { -0.716567, 0.681718, 0.147621 }, - { -0.688191, 0.587785, 0.425325 }, - { -0.500000, 0.809017, 0.309017 }, - { -0.238856, 0.864188, 0.442863 }, - { -0.425325, 0.688191, 0.587785 }, - { -0.716567, 0.681718, -0.147621 }, - { -0.500000, 0.809017, -0.309017 }, - { -0.525731, 0.850651, 0.000000 }, - { 0.000000, 0.850651, -0.525731 }, - { -0.238856, 0.864188, -0.442863 }, - { 0.000000, 0.955423, -0.295242 }, - { -0.262866, 0.951056, -0.162460 }, - { 0.000000, 1.000000, 0.000000 }, - { 0.000000, 0.955423, 0.295242 }, - { -0.262866, 0.951056, 0.162460 }, - { 0.238856, 0.864188, 0.442863 }, - { 0.262866, 0.951056, 0.162460 }, - { 0.500000, 0.809017, 0.309017 }, - { 0.238856, 0.864188, -0.442863 }, - { 0.262866, 0.951056, -0.162460 }, - { 0.500000, 0.809017, -0.309017 }, - { 0.850651, 0.525731, 0.000000 }, - { 0.716567, 0.681718, 0.147621 }, - { 0.716567, 0.681718, -0.147621 }, - { 0.525731, 0.850651, 0.000000 }, - { 0.425325, 0.688191, 0.587785 }, - { 0.864188, 0.442863, 0.238856 }, - { 0.688191, 0.587785, 0.425325 }, - { 0.809017, 0.309017, 0.500000 }, - { 0.681718, 0.147621, 0.716567 }, - { 0.587785, 0.425325, 0.688191 }, - { 0.955423, 0.295242, 0.000000 }, - { 1.000000, 0.000000, 0.000000 }, - { 0.951056, 0.162460, 0.262866 }, - { 0.850651, -0.525731, 0.000000 }, - { 0.955423, -0.295242, 0.000000 }, - { 0.864188, -0.442863, 0.238856 }, - { 0.951056, -0.162460, 0.262866 }, - { 0.809017, -0.309017, 0.500000 }, - { 0.681718, -0.147621, 0.716567 }, - { 0.850651, 0.000000, 0.525731 }, - { 0.864188, 0.442863, -0.238856 }, - { 0.809017, 0.309017, -0.500000 }, - { 0.951056, 0.162460, -0.262866 }, - { 0.525731, 0.000000, -0.850651 }, - { 0.681718, 0.147621, -0.716567 }, - { 0.681718, -0.147621, -0.716567 }, - { 0.850651, 0.000000, -0.525731 }, - { 0.809017, -0.309017, -0.500000 }, - { 0.864188, -0.442863, -0.238856 }, - { 0.951056, -0.162460, -0.262866 }, - { 0.147621, 0.716567, -0.681718 }, - { 0.309017, 0.500000, -0.809017 }, - { 0.425325, 0.688191, -0.587785 }, - { 0.442863, 0.238856, -0.864188 }, - { 0.587785, 0.425325, -0.688191 }, - { 0.688191, 0.587785, -0.425325 }, - { -0.147621, 0.716567, -0.681718 }, - { -0.309017, 0.500000, -0.809017 }, - { 0.000000, 0.525731, -0.850651 }, - { -0.525731, 0.000000, -0.850651 }, - { -0.442863, 0.238856, -0.864188 }, - { -0.295242, 0.000000, -0.955423 }, - { -0.162460, 0.262866, -0.951056 }, - { 0.000000, 0.000000, -1.000000 }, - { 0.295242, 0.000000, -0.955423 }, - { 0.162460, 0.262866, -0.951056 }, - { -0.442863, -0.238856, -0.864188 }, - { -0.309017, -0.500000, -0.809017 }, - { -0.162460, -0.262866, -0.951056 }, - { 0.000000, -0.850651, -0.525731 }, - { -0.147621, -0.716567, -0.681718 }, - { 0.147621, -0.716567, -0.681718 }, - { 0.000000, -0.525731, -0.850651 }, - { 0.309017, -0.500000, -0.809017 }, - { 0.442863, -0.238856, -0.864188 }, - { 0.162460, -0.262866, -0.951056 }, - { 0.238856, -0.864188, -0.442863 }, - { 0.500000, -0.809017, -0.309017 }, - { 0.425325, -0.688191, -0.587785 }, - { 0.716567, -0.681718, -0.147621 }, - { 0.688191, -0.587785, -0.425325 }, - { 0.587785, -0.425325, -0.688191 }, - { 0.000000, -0.955423, -0.295242 }, - { 0.000000, -1.000000, 0.000000 }, - { 0.262866, -0.951056, -0.162460 }, - { 0.000000, -0.850651, 0.525731 }, - { 0.000000, -0.955423, 0.295242 }, - { 0.238856, -0.864188, 0.442863 }, - { 0.262866, -0.951056, 0.162460 }, - { 0.500000, -0.809017, 0.309017 }, - { 0.716567, -0.681718, 0.147621 }, - { 0.525731, -0.850651, 0.000000 }, - { -0.238856, -0.864188, -0.442863 }, - { -0.500000, -0.809017, -0.309017 }, - { -0.262866, -0.951056, -0.162460 }, - { -0.850651, -0.525731, 0.000000 }, - { -0.716567, -0.681718, -0.147621 }, - { -0.716567, -0.681718, 0.147621 }, - { -0.525731, -0.850651, 0.000000 }, - { -0.500000, -0.809017, 0.309017 }, - { -0.238856, -0.864188, 0.442863 }, - { -0.262866, -0.951056, 0.162460 }, - { -0.864188, -0.442863, 0.238856 }, - { -0.809017, -0.309017, 0.500000 }, - { -0.688191, -0.587785, 0.425325 }, - { -0.681718, -0.147621, 0.716567 }, - { -0.442863, -0.238856, 0.864188 }, - { -0.587785, -0.425325, 0.688191 }, - { -0.309017, -0.500000, 0.809017 }, - { -0.147621, -0.716567, 0.681718 }, - { -0.425325, -0.688191, 0.587785 }, - { -0.162460, -0.262866, 0.951056 }, - { 0.442863, -0.238856, 0.864188 }, - { 0.162460, -0.262866, 0.951056 }, - { 0.309017, -0.500000, 0.809017 }, - { 0.147621, -0.716567, 0.681718 }, - { 0.000000, -0.525731, 0.850651 }, - { 0.425325, -0.688191, 0.587785 }, - { 0.587785, -0.425325, 0.688191 }, - { 0.688191, -0.587785, 0.425325 }, - { -0.955423, 0.295242, 0.000000 }, - { -0.951056, 0.162460, 0.262866 }, - { -1.000000, 0.000000, 0.000000 }, - { -0.850651, 0.000000, 0.525731 }, - { -0.955423, -0.295242, 0.000000 }, - { -0.951056, -0.162460, 0.262866 }, - { -0.864188, 0.442863, -0.238856 }, - { -0.951056, 0.162460, -0.262866 }, - { -0.809017, 0.309017, -0.500000 }, - { -0.864188, -0.442863, -0.238856 }, - { -0.951056, -0.162460, -0.262866 }, - { -0.809017, -0.309017, -0.500000 }, - { -0.681718, 0.147621, -0.716567 }, - { -0.681718, -0.147621, -0.716567 }, - { -0.850651, 0.000000, -0.525731 }, - { -0.688191, 0.587785, -0.425325 }, - { -0.587785, 0.425325, -0.688191 }, - { -0.425325, 0.688191, -0.587785 }, - { -0.425325, -0.688191, -0.587785 }, - { -0.587785, -0.425325, -0.688191 }, - { -0.688191, -0.587785, -0.425325 }, +{ -0.525731, 0.000000, 0.850651 }, +{ -0.442863, 0.238856, 0.864188 }, +{ -0.295242, 0.000000, 0.955423 }, +{ -0.309017, 0.500000, 0.809017 }, +{ -0.162460, 0.262866, 0.951056 }, +{ 0.000000, 0.000000, 1.000000 }, +{ 0.000000, 0.850651, 0.525731 }, +{ -0.147621, 0.716567, 0.681718 }, +{ 0.147621, 0.716567, 0.681718 }, +{ 0.000000, 0.525731, 0.850651 }, +{ 0.309017, 0.500000, 0.809017 }, +{ 0.525731, 0.000000, 0.850651 }, +{ 0.295242, 0.000000, 0.955423 }, +{ 0.442863, 0.238856, 0.864188 }, +{ 0.162460, 0.262866, 0.951056 }, +{ -0.681718, 0.147621, 0.716567 }, +{ -0.809017, 0.309017, 0.500000 }, +{ -0.587785, 0.425325, 0.688191 }, +{ -0.850651, 0.525731, 0.000000 }, +{ -0.864188, 0.442863, 0.238856 }, +{ -0.716567, 0.681718, 0.147621 }, +{ -0.688191, 0.587785, 0.425325 }, +{ -0.500000, 0.809017, 0.309017 }, +{ -0.238856, 0.864188, 0.442863 }, +{ -0.425325, 0.688191, 0.587785 }, +{ -0.716567, 0.681718, -0.147621 }, +{ -0.500000, 0.809017, -0.309017 }, +{ -0.525731, 0.850651, 0.000000 }, +{ 0.000000, 0.850651, -0.525731 }, +{ -0.238856, 0.864188, -0.442863 }, +{ 0.000000, 0.955423, -0.295242 }, +{ -0.262866, 0.951056, -0.162460 }, +{ 0.000000, 1.000000, 0.000000 }, +{ 0.000000, 0.955423, 0.295242 }, +{ -0.262866, 0.951056, 0.162460 }, +{ 0.238856, 0.864188, 0.442863 }, +{ 0.262866, 0.951056, 0.162460 }, +{ 0.500000, 0.809017, 0.309017 }, +{ 0.238856, 0.864188, -0.442863 }, +{ 0.262866, 0.951056, -0.162460 }, +{ 0.500000, 0.809017, -0.309017 }, +{ 0.850651, 0.525731, 0.000000 }, +{ 0.716567, 0.681718, 0.147621 }, +{ 0.716567, 0.681718, -0.147621 }, +{ 0.525731, 0.850651, 0.000000 }, +{ 0.425325, 0.688191, 0.587785 }, +{ 0.864188, 0.442863, 0.238856 }, +{ 0.688191, 0.587785, 0.425325 }, +{ 0.809017, 0.309017, 0.500000 }, +{ 0.681718, 0.147621, 0.716567 }, +{ 0.587785, 0.425325, 0.688191 }, +{ 0.955423, 0.295242, 0.000000 }, +{ 1.000000, 0.000000, 0.000000 }, +{ 0.951056, 0.162460, 0.262866 }, +{ 0.850651, -0.525731, 0.000000 }, +{ 0.955423, -0.295242, 0.000000 }, +{ 0.864188, -0.442863, 0.238856 }, +{ 0.951056, -0.162460, 0.262866 }, +{ 0.809017, -0.309017, 0.500000 }, +{ 0.681718, -0.147621, 0.716567 }, +{ 0.850651, 0.000000, 0.525731 }, +{ 0.864188, 0.442863, -0.238856 }, +{ 0.809017, 0.309017, -0.500000 }, +{ 0.951056, 0.162460, -0.262866 }, +{ 0.525731, 0.000000, -0.850651 }, +{ 0.681718, 0.147621, -0.716567 }, +{ 0.681718, -0.147621, -0.716567 }, +{ 0.850651, 0.000000, -0.525731 }, +{ 0.809017, -0.309017, -0.500000 }, +{ 0.864188, -0.442863, -0.238856 }, +{ 0.951056, -0.162460, -0.262866 }, +{ 0.147621, 0.716567, -0.681718 }, +{ 0.309017, 0.500000, -0.809017 }, +{ 0.425325, 0.688191, -0.587785 }, +{ 0.442863, 0.238856, -0.864188 }, +{ 0.587785, 0.425325, -0.688191 }, +{ 0.688191, 0.587785, -0.425325 }, +{ -0.147621, 0.716567, -0.681718 }, +{ -0.309017, 0.500000, -0.809017 }, +{ 0.000000, 0.525731, -0.850651 }, +{ -0.525731, 0.000000, -0.850651 }, +{ -0.442863, 0.238856, -0.864188 }, +{ -0.295242, 0.000000, -0.955423 }, +{ -0.162460, 0.262866, -0.951056 }, +{ 0.000000, 0.000000, -1.000000 }, +{ 0.295242, 0.000000, -0.955423 }, +{ 0.162460, 0.262866, -0.951056 }, +{ -0.442863, -0.238856, -0.864188 }, +{ -0.309017, -0.500000, -0.809017 }, +{ -0.162460, -0.262866, -0.951056 }, +{ 0.000000, -0.850651, -0.525731 }, +{ -0.147621, -0.716567, -0.681718 }, +{ 0.147621, -0.716567, -0.681718 }, +{ 0.000000, -0.525731, -0.850651 }, +{ 0.309017, -0.500000, -0.809017 }, +{ 0.442863, -0.238856, -0.864188 }, +{ 0.162460, -0.262866, -0.951056 }, +{ 0.238856, -0.864188, -0.442863 }, +{ 0.500000, -0.809017, -0.309017 }, +{ 0.425325, -0.688191, -0.587785 }, +{ 0.716567, -0.681718, -0.147621 }, +{ 0.688191, -0.587785, -0.425325 }, +{ 0.587785, -0.425325, -0.688191 }, +{ 0.000000, -0.955423, -0.295242 }, +{ 0.000000, -1.000000, 0.000000 }, +{ 0.262866, -0.951056, -0.162460 }, +{ 0.000000, -0.850651, 0.525731 }, +{ 0.000000, -0.955423, 0.295242 }, +{ 0.238856, -0.864188, 0.442863 }, +{ 0.262866, -0.951056, 0.162460 }, +{ 0.500000, -0.809017, 0.309017 }, +{ 0.716567, -0.681718, 0.147621 }, +{ 0.525731, -0.850651, 0.000000 }, +{ -0.238856, -0.864188, -0.442863 }, +{ -0.500000, -0.809017, -0.309017 }, +{ -0.262866, -0.951056, -0.162460 }, +{ -0.850651, -0.525731, 0.000000 }, +{ -0.716567, -0.681718, -0.147621 }, +{ -0.716567, -0.681718, 0.147621 }, +{ -0.525731, -0.850651, 0.000000 }, +{ -0.500000, -0.809017, 0.309017 }, +{ -0.238856, -0.864188, 0.442863 }, +{ -0.262866, -0.951056, 0.162460 }, +{ -0.864188, -0.442863, 0.238856 }, +{ -0.809017, -0.309017, 0.500000 }, +{ -0.688191, -0.587785, 0.425325 }, +{ -0.681718, -0.147621, 0.716567 }, +{ -0.442863, -0.238856, 0.864188 }, +{ -0.587785, -0.425325, 0.688191 }, +{ -0.309017, -0.500000, 0.809017 }, +{ -0.147621, -0.716567, 0.681718 }, +{ -0.425325, -0.688191, 0.587785 }, +{ -0.162460, -0.262866, 0.951056 }, +{ 0.442863, -0.238856, 0.864188 }, +{ 0.162460, -0.262866, 0.951056 }, +{ 0.309017, -0.500000, 0.809017 }, +{ 0.147621, -0.716567, 0.681718 }, +{ 0.000000, -0.525731, 0.850651 }, +{ 0.425325, -0.688191, 0.587785 }, +{ 0.587785, -0.425325, 0.688191 }, +{ 0.688191, -0.587785, 0.425325 }, +{ -0.955423, 0.295242, 0.000000 }, +{ -0.951056, 0.162460, 0.262866 }, +{ -1.000000, 0.000000, 0.000000 }, +{ -0.850651, 0.000000, 0.525731 }, +{ -0.955423, -0.295242, 0.000000 }, +{ -0.951056, -0.162460, 0.262866 }, +{ -0.864188, 0.442863, -0.238856 }, +{ -0.951056, 0.162460, -0.262866 }, +{ -0.809017, 0.309017, -0.500000 }, +{ -0.864188, -0.442863, -0.238856 }, +{ -0.951056, -0.162460, -0.262866 }, +{ -0.809017, -0.309017, -0.500000 }, +{ -0.681718, 0.147621, -0.716567 }, +{ -0.681718, -0.147621, -0.716567 }, +{ -0.850651, 0.000000, -0.525731 }, +{ -0.688191, 0.587785, -0.425325 }, +{ -0.587785, 0.425325, -0.688191 }, +{ -0.425325, 0.688191, -0.587785 }, +{ -0.425325, -0.688191, -0.587785 }, +{ -0.587785, -0.425325, -0.688191 }, +{ -0.688191, -0.587785, -0.425325 }, diff --git a/source/arch_def.h b/source/arch_def.h index 4a27d9a..087c55b 100644 --- a/source/arch_def.h +++ b/source/arch_def.h @@ -31,140 +31,140 @@ #if defined(__DJGPP__) || defined(__MSDOS__) || defined(__DOS__) || defined(_MSDOS) # if !defined(PLATFORM_DOS) -# define PLATFORM_DOS 1 +# define PLATFORM_DOS 1 # endif #elif defined(__OS2__) || defined(__EMX__) # if !defined(PLATFORM_OS2) -# define PLATFORM_OS2 1 +# define PLATFORM_OS2 1 # endif #elif defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(__NT__) || defined(_Windows) # if !defined(PLATFORM_WINDOWS) -# define PLATFORM_WINDOWS 1 +# define PLATFORM_WINDOWS 1 # endif -#elif defined(__APPLE__) && defined(__MACH__) /* Mac OS X */ +#elif defined(__APPLE__) && defined(__MACH__) /* Mac OS X */ # if !defined(PLATFORM_OSX) -# define PLATFORM_OSX 1 +# define PLATFORM_OSX 1 # endif -#elif defined(macintosh) /* Mac OS classic */ +#elif defined(macintosh) /* Mac OS classic */ # if !defined(PLATFORM_MAC) -# define PLATFORM_MAC 1 +# define PLATFORM_MAC 1 # endif -#elif defined(__MORPHOS__) || defined(__AROS__) || defined(AMIGAOS) || \ +#elif defined(__MORPHOS__) || defined(__AROS__) || defined(AMIGAOS) || \ defined(__amigaos__) || defined(__amigaos4__) ||defined(__amigados__) || \ defined(AMIGA) || defined(_AMIGA) || defined(__AMIGA__) # if !defined(PLATFORM_AMIGA) -# define PLATFORM_AMIGA 1 +# define PLATFORM_AMIGA 1 # endif #elif defined(__riscos__) # if !defined(PLATFORM_RISCOS) -# define PLATFORM_RISCOS 1 +# define PLATFORM_RISCOS 1 # endif -#else /* here goes the unix platforms */ +#else /* here goes the unix platforms */ -#if defined(__unix) || defined(__unix__) || defined(unix) || \ - defined(__linux__) || defined(__linux) || \ - defined(__FreeBSD__) || defined(__DragonFly__) || \ - defined(__FreeBSD_kernel__) /* Debian GNU/kFreeBSD */ || \ - defined(__OpenBSD__) || defined(__NetBSD__) || \ - defined(__hpux) || defined(__hpux__) || defined(_hpux) || \ - defined(__sun) || defined(sun) || \ - defined(__sgi) || defined(sgi) || defined(__sgi__) || \ - defined(__GNU__) /* GNU/Hurd */ || \ +#if defined(__unix) || defined(__unix__) || defined(unix) || \ + defined(__linux__) || defined(__linux) || \ + defined(__FreeBSD__) || defined(__DragonFly__) || \ + defined(__FreeBSD_kernel__) /* Debian GNU/kFreeBSD */ || \ + defined(__OpenBSD__) || defined(__NetBSD__) || \ + defined(__hpux) || defined(__hpux__) || defined(_hpux) || \ + defined(__sun) || defined(sun) || \ + defined(__sgi) || defined(sgi) || defined(__sgi__) || \ + defined(__GNU__) /* GNU/Hurd */ || \ defined(__QNX__) || defined(__QNXNTO__) # if !defined(PLATFORM_UNIX) -# define PLATFORM_UNIX 1 +# define PLATFORM_UNIX 1 # endif #endif -#endif /* PLATFORM_xxx */ +#endif /* PLATFORM_xxx */ -#if defined (PLATFORM_OSX) /* OS X is unix-based */ +#if defined (PLATFORM_OSX) /* OS X is unix-based */ # if !defined(PLATFORM_UNIX) -# define PLATFORM_UNIX 2 +# define PLATFORM_UNIX 2 # endif -#endif /* OS X -> PLATFORM_UNIX */ +#endif /* OS X -> PLATFORM_UNIX */ -#if defined(__FreeBSD__) || defined(__DragonFly__) || \ - defined(__FreeBSD_kernel__) /* Debian GNU/kFreeBSD */ || \ +#if defined(__FreeBSD__) || defined(__DragonFly__) || \ + defined(__FreeBSD_kernel__) /* Debian GNU/kFreeBSD */ || \ defined(__OpenBSD__) || defined(__NetBSD__) # if !defined(PLATFORM_BSD) -# define PLATFORM_BSD 1 +# define PLATFORM_BSD 1 # endif -#endif /* PLATFORM_BSD (for convenience) */ +#endif /* PLATFORM_BSD (for convenience) */ #if defined(PLATFORM_AMIGA) && !defined(PLATFORM_AMIGAOS3) # if !defined(__MORPHOS__) && !defined(__AROS__) && !defined(__amigaos4__) -# define PLATFORM_AMIGAOS3 1 +# define PLATFORM_AMIGAOS3 1 # endif -#endif /* PLATFORM_AMIGAOS3 (for convenience) */ +#endif /* PLATFORM_AMIGAOS3 (for convenience) */ #if defined(_WIN64) -# define PLATFORM_STRING "Win64" +# define PLATFORM_STRING "Win64" #elif defined(PLATFORM_WINDOWS) -# define PLATFORM_STRING "Windows" +# define PLATFORM_STRING "Windows" #elif defined(PLATFORM_DOS) -# define PLATFORM_STRING "DOS" +# define PLATFORM_STRING "DOS" #elif defined(PLATFORM_OS2) -# define PLATFORM_STRING "OS/2" +# define PLATFORM_STRING "OS/2" #elif defined(__linux__) || defined(__linux) -# define PLATFORM_STRING "Linux" +# define PLATFORM_STRING "Linux" #elif defined(__DragonFly__) -# define PLATFORM_STRING "DragonFly" +# define PLATFORM_STRING "DragonFly" #elif defined(__FreeBSD__) -# define PLATFORM_STRING "FreeBSD" +# define PLATFORM_STRING "FreeBSD" #elif defined(__NetBSD__) -# define PLATFORM_STRING "NetBSD" +# define PLATFORM_STRING "NetBSD" #elif defined(__OpenBSD__) -# define PLATFORM_STRING "OpenBSD" +# define PLATFORM_STRING "OpenBSD" #elif defined(__MORPHOS__) -# define PLATFORM_STRING "MorphOS" +# define PLATFORM_STRING "MorphOS" #elif defined(__AROS__) -# define PLATFORM_STRING "AROS" +# define PLATFORM_STRING "AROS" #elif defined(__amigaos4__) -# define PLATFORM_STRING "AmigaOS4" +# define PLATFORM_STRING "AmigaOS4" #elif defined(PLATFORM_AMIGA) -# define PLATFORM_STRING "AmigaOS" +# define PLATFORM_STRING "AmigaOS" #elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_STRING "QNX" +# define PLATFORM_STRING "QNX" #elif defined(PLATFORM_OSX) -# define PLATFORM_STRING "MacOSX" +# define PLATFORM_STRING "MacOSX" #elif defined(PLATFORM_MAC) -# define PLATFORM_STRING "MacOS" +# define PLATFORM_STRING "MacOS" #elif defined(__hpux) || defined(__hpux__) || defined(_hpux) -# define PLATFORM_STRING "HP-UX" +# define PLATFORM_STRING "HP-UX" #elif (defined(__sun) || defined(sun)) && (defined(__svr4__) || defined(__SVR4)) -# define PLATFORM_STRING "Solaris" +# define PLATFORM_STRING "Solaris" #elif defined(__sun) || defined(sun) -# define PLATFORM_STRING "SunOS" +# define PLATFORM_STRING "SunOS" #elif defined(__sgi) || defined(sgi) || defined(__sgi__) -# define PLATFORM_STRING "Irix" +# define PLATFORM_STRING "Irix" #elif defined(PLATFORM_RISCOS) -# define PLATFORM_STRING "RiscOS" +# define PLATFORM_STRING "RiscOS" #elif defined(__GNU__) -# define PLATFORM_STRING "GNU/Hurd" +# define PLATFORM_STRING "GNU/Hurd" #elif defined(PLATFORM_UNIX) -# define PLATFORM_STRING "Unix" +# define PLATFORM_STRING "Unix" #else -# define PLATFORM_STRING "Unknown" -# warning "Platform is UNKNOWN." -#endif /* PLATFORM_STRING */ +# define PLATFORM_STRING "Unknown" +# warning "Platform is UNKNOWN." +#endif /* PLATFORM_STRING */ #endif /* ARCHDEFS_H */ diff --git a/source/bgmusic.c b/source/bgmusic.c index dec305c..b39f682 100644 --- a/source/bgmusic.c +++ b/source/bgmusic.c @@ -27,13 +27,13 @@ #include "bgmusic.h" #include "cdaudio.h" -#define MUSIC_DIRNAME "music" +#define MUSIC_DIRNAME "music" -bool bgmloop; -cvar_t bgm_extmusic = {"bgm_extmusic", "1", CVAR_ARCHIVE}; +bool bgmloop; +cvar_t bgm_extmusic = {"bgm_extmusic", "1", CVAR_ARCHIVE}; -static bool no_extmusic= false; -static float old_volume = -1.0f; +static bool no_extmusic = false; +static float old_volume = -1.0f; typedef enum _bgm_player { @@ -44,17 +44,17 @@ typedef enum _bgm_player typedef struct music_handler_s { - uint32_t type; /* 1U << n (see snd_codec.h) */ - bgm_player_t player; /* Enumerated bgm player type */ - int32_t is_available; /* -1 means not present */ - const char *ext; /* Expected file extension */ - const char *dir; /* Where to look for music file */ - struct music_handler_s *next; + uint32_t type; /* 1U << n (see snd_codec.h) */ + bgm_player_t player; /* Enumerated bgm player type */ + int32_t is_available; /* -1 means not present */ + const char *ext; /* Expected file extension */ + const char *dir; /* Where to look for music file */ + struct music_handler_s *next; } music_handler_t; static music_handler_t wanted_handlers[] = { - { CODECTYPE_VORBIS,BGM_STREAMER,-1, "ogg", MUSIC_DIRNAME, NULL }, + { CODECTYPE_VORBIS, BGM_STREAMER, -1, "ogg", MUSIC_DIRNAME, NULL }, { CODECTYPE_OPUS, BGM_STREAMER, -1, "opus", MUSIC_DIRNAME, NULL }, { CODECTYPE_MP3, BGM_STREAMER, -1, "mp3", MUSIC_DIRNAME, NULL }, { CODECTYPE_FLAC, BGM_STREAMER, -1, "flac", MUSIC_DIRNAME, NULL }, @@ -69,61 +69,61 @@ static music_handler_t wanted_handlers[] = static music_handler_t *music_handlers = NULL; -#define ANY_CODECTYPE 0xFFFFFFFF -#define CDRIP_TYPES (CODECTYPE_VORBIS | CODECTYPE_MP3 | CODECTYPE_FLAC | CODECTYPE_WAV | CODECTYPE_OPUS) -#define CDRIPTYPE(x) (((x) & CDRIP_TYPES) != 0) +#define ANY_CODECTYPE 0xFFFFFFFF +#define CDRIP_TYPES (CODECTYPE_VORBIS | CODECTYPE_MP3 | CODECTYPE_FLAC | CODECTYPE_WAV | CODECTYPE_OPUS) +#define CDRIPTYPE(x) (((x) & CDRIP_TYPES) != 0) static snd_stream_t *bgmstream = NULL; -static void BGM_Play_f (void) +static void BGM_Play_f(void) { - if (Cmd_Argc() == 2) + if(Cmd_Argc() == 2) { - BGM_Play (Cmd_Argv(1)); + BGM_Play(Cmd_Argv(1)); } else { - Con_Printf ("music \n"); + Con_Printf("music \n"); return; } } -static void BGM_Pause_f (void) +static void BGM_Pause_f(void) { - BGM_Pause (); + BGM_Pause(); } -static void BGM_Resume_f (void) +static void BGM_Resume_f(void) { - BGM_Resume (); + BGM_Resume(); } -static void BGM_Loop_f (void) +static void BGM_Loop_f(void) { - if (Cmd_Argc() == 2) + if(Cmd_Argc() == 2) { - if (q_strcasecmp(Cmd_Argv(1), "0") == 0 || - q_strcasecmp(Cmd_Argv(1),"off") == 0) + if(q_strcasecmp(Cmd_Argv(1), "0") == 0 || + q_strcasecmp(Cmd_Argv(1), "off") == 0) bgmloop = false; - else if (q_strcasecmp(Cmd_Argv(1), "1") == 0 || - q_strcasecmp(Cmd_Argv(1),"on") == 0) + else if(q_strcasecmp(Cmd_Argv(1), "1") == 0 || + q_strcasecmp(Cmd_Argv(1), "on") == 0) bgmloop = true; - else if (q_strcasecmp(Cmd_Argv(1),"toggle") == 0) + else if(q_strcasecmp(Cmd_Argv(1), "toggle") == 0) bgmloop = !bgmloop; } - if (bgmloop) + if(bgmloop) Con_Printf("Music will be looped\n"); else Con_Printf("Music will not be looped\n"); } -static void BGM_Stop_f (void) +static void BGM_Stop_f(void) { BGM_Stop(); } -bool BGM_Init (void) +bool BGM_Init(void) { music_handler_t *handlers = NULL; int32_t i; @@ -135,29 +135,29 @@ bool BGM_Init (void) Cmd_AddCommand("music_loop", BGM_Loop_f); Cmd_AddCommand("music_stop", BGM_Stop_f); - if (COM_CheckParm("-noextmusic") != 0) + if(COM_CheckParm("-noextmusic") != 0) no_extmusic = true; bgmloop = true; - for (i = 0; wanted_handlers[i].type != CODECTYPE_NONE; i++) + for(i = 0; wanted_handlers[i].type != CODECTYPE_NONE; i++) { - switch (wanted_handlers[i].player) + switch(wanted_handlers[i].player) { case BGM_MIDIDRV: - /* not supported in quake */ + /* not supported in quake */ break; case BGM_STREAMER: wanted_handlers[i].is_available = - S_CodecIsAvailable(wanted_handlers[i].type); + S_CodecIsAvailable(wanted_handlers[i].type); break; case BGM_NONE: default: break; } - if (wanted_handlers[i].is_available != -1) + if(wanted_handlers[i].is_available != -1) { - if (handlers) + if(handlers) { handlers->next = &wanted_handlers[i]; handlers = handlers->next; @@ -170,47 +170,47 @@ bool BGM_Init (void) } } - return CDAudio_Init (); + return CDAudio_Init(); } -void BGM_Shutdown (void) +void BGM_Shutdown(void) { BGM_Stop(); -/* sever our connections to - * midi_drv and snd_codec */ + /* sever our connections to + * midi_drv and snd_codec */ music_handlers = NULL; - CDAudio_Shutdown (); + CDAudio_Shutdown(); } -static void BGM_Play_noext (const char *filename, uint32_t allowed_types) +static void BGM_Play_noext(const char *filename, uint32_t allowed_types) { char tmp[MAX_QPATH]; music_handler_t *handler; handler = music_handlers; - while (handler) + while(handler) { - if (! (handler->type & allowed_types)) + if(!(handler->type & allowed_types)) { handler = handler->next; continue; } - if (!handler->is_available) + if(!handler->is_available) { handler = handler->next; continue; } q_snprintf(tmp, sizeof(tmp), "%s/%s.%s", - handler->dir, filename, handler->ext); - switch (handler->player) + handler->dir, filename, handler->ext); + switch(handler->player) { case BGM_MIDIDRV: - /* not supported in quake */ + /* not supported in quake */ break; case BGM_STREAMER: bgmstream = S_CodecOpenStreamType(tmp, handler->type); - if (bgmstream) - return; /* success */ + if(bgmstream) + return; /* success */ break; case BGM_NONE: default: @@ -222,7 +222,7 @@ static void BGM_Play_noext (const char *filename, uint32_t allowed_types) Con_Printf("Couldn't handle music file %s\n", filename); } -void BGM_Play (const char *filename) +void BGM_Play(const char *filename) { char tmp[MAX_QPATH]; const char *ext; @@ -230,45 +230,45 @@ void BGM_Play (const char *filename) BGM_Stop(); - if (music_handlers == NULL) + if(music_handlers == NULL) return; - if (!filename || !*filename) + if(!filename || !*filename) { Con_DPrintf("null music file name\n"); return; } ext = COM_FileGetExtension(filename); - if (! *ext) /* try all things */ + if(! *ext) /* try all things */ { BGM_Play_noext(filename, ANY_CODECTYPE); return; } handler = music_handlers; - while (handler) + while(handler) { - if (handler->is_available && - !q_strcasecmp(ext, handler->ext)) + if(handler->is_available && + !q_strcasecmp(ext, handler->ext)) break; handler = handler->next; } - if (!handler) + if(!handler) { Con_Printf("Unhandled extension for %s\n", filename); return; } q_snprintf(tmp, sizeof(tmp), "%s/%s", handler->dir, filename); - switch (handler->player) + switch(handler->player) { case BGM_MIDIDRV: - /* not supported in quake */ + /* not supported in quake */ break; case BGM_STREAMER: bgmstream = S_CodecOpenStreamType(tmp, handler->type); - if (bgmstream) - return; /* success */ + if(bgmstream) + return; /* success */ break; case BGM_NONE: default: @@ -278,68 +278,68 @@ void BGM_Play (const char *filename) Con_Printf("Couldn't handle music file %s\n", filename); } -void BGM_PlayCDtrack (byte track, bool looping) +void BGM_PlayCDtrack(byte track, bool looping) { -/* instead of searching by the order of music_handlers, do so by - * the order of searchpath priority: the file from the searchpath - * with the highest path_id is most likely from our own gamedir - * itself. This way, if a mod has track02 as a *.mp3 file, which - * is below *.ogg in the music_handler order, the mp3 will still - * have priority over track02.ogg from, say, id1. - */ + /* instead of searching by the order of music_handlers, do so by + * the order of searchpath priority: the file from the searchpath + * with the highest path_id is most likely from our own gamedir + * itself. This way, if a mod has track02 as a *.mp3 file, which + * is below *.ogg in the music_handler order, the mp3 will still + * have priority over track02.ogg from, say, id1. + */ char tmp[MAX_QPATH]; const char *ext; uint32_t path_id, prev_id, type; music_handler_t *handler; BGM_Stop(); - if (CDAudio_Play(track, looping) == 0) + if(CDAudio_Play(track, looping) == 0) return; /* success */ - if (music_handlers == NULL) + if(music_handlers == NULL) return; - if (no_extmusic || !bgm_extmusic.value) + if(no_extmusic || !bgm_extmusic.value) return; prev_id = 0; type = 0; ext = NULL; handler = music_handlers; - while (handler) + while(handler) { - if (! handler->is_available) + if(! handler->is_available) goto _next; - if (! CDRIPTYPE(handler->type)) + if(! CDRIPTYPE(handler->type)) goto _next; q_snprintf(tmp, sizeof(tmp), "%s/track%02" PRIi32 ".%s", - MUSIC_DIRNAME, (int32_t)track, handler->ext); - if (! COM_FileExists(tmp, &path_id)) + MUSIC_DIRNAME, (int32_t)track, handler->ext); + if(! COM_FileExists(tmp, &path_id)) goto _next; - if (path_id > prev_id) + if(path_id > prev_id) { prev_id = path_id; type = handler->type; ext = handler->ext; } - _next: +_next: handler = handler->next; } - if (ext == NULL) + if(ext == NULL) Con_Printf("Couldn't find a cdrip for track %" PRIi32 "\n", (int32_t)track); else { q_snprintf(tmp, sizeof(tmp), "%s/track%02" PRIi32 ".%s", - MUSIC_DIRNAME, (int32_t)track, ext); + MUSIC_DIRNAME, (int32_t)track, ext); bgmstream = S_CodecOpenStreamType(tmp, type); - if (! bgmstream) + if(! bgmstream) Con_Printf("Couldn't handle music file %s\n", tmp); } } -void BGM_Stop (void) +void BGM_Stop(void) { - if (bgmstream) + if(bgmstream) { bgmstream->status = STREAM_NONE; S_CodecCloseStream(bgmstream); @@ -349,85 +349,85 @@ void BGM_Stop (void) CDAudio_Stop(); } -void BGM_Pause (void) +void BGM_Pause(void) { - if (bgmstream) + if(bgmstream) { - if (bgmstream->status == STREAM_PLAY) + if(bgmstream->status == STREAM_PLAY) bgmstream->status = STREAM_PAUSE; } - CDAudio_Pause (); + CDAudio_Pause(); } -void BGM_Resume (void) +void BGM_Resume(void) { - if (bgmstream) + if(bgmstream) { - if (bgmstream->status == STREAM_PAUSE) + if(bgmstream->status == STREAM_PAUSE) bgmstream->status = STREAM_PLAY; } - CDAudio_Resume (); + CDAudio_Resume(); } -static void BGM_UpdateStream (void) +static void BGM_UpdateStream(void) { bool did_rewind = false; - int32_t res; /* Number of bytes read. */ - int32_t bufferSamples; - int32_t fileSamples; - int32_t fileBytes; - byte raw[16384]; + int32_t res; /* Number of bytes read. */ + int32_t bufferSamples; + int32_t fileSamples; + int32_t fileBytes; + byte raw[16384]; - if (bgmstream->status != STREAM_PLAY) + if(bgmstream->status != STREAM_PLAY) return; /* don't bother playing anything if musicvolume is 0 */ - if (bgmvolume.value <= 0) + if(bgmvolume.value <= 0) return; /* see how many samples should be copied into the raw buffer */ - if (s_rawend < paintedtime) + if(s_rawend < paintedtime) s_rawend = paintedtime; - while (s_rawend < paintedtime + MAX_RAW_SAMPLES) + while(s_rawend < paintedtime + MAX_RAW_SAMPLES) { bufferSamples = MAX_RAW_SAMPLES - (s_rawend - paintedtime); /* decide how much data needs to be read from the file */ fileSamples = bufferSamples * bgmstream->info.rate / shm->speed; - if (!fileSamples) + if(!fileSamples) return; /* our max buffer size */ fileBytes = fileSamples * (bgmstream->info.width * bgmstream->info.channels); - if (fileBytes > (int32_t) sizeof(raw)) + if(fileBytes > (int32_t) sizeof(raw)) { fileBytes = (int32_t) sizeof(raw); fileSamples = fileBytes / - (bgmstream->info.width * bgmstream->info.channels); + (bgmstream->info.width * bgmstream->info.channels); } /* Read */ res = S_CodecReadStream(bgmstream, fileBytes, raw); - if (res < fileBytes) + if(res < fileBytes) { fileBytes = res; fileSamples = res / (bgmstream->info.width * bgmstream->info.channels); } - if (res > 0) /* data: add to raw buffer */ + if(res > 0) /* data: add to raw buffer */ { S_RawSamples(fileSamples, bgmstream->info.rate, - bgmstream->info.width, - bgmstream->info.channels, - raw, bgmvolume.value); + bgmstream->info.width, + bgmstream->info.channels, + raw, bgmvolume.value); did_rewind = false; } - else if (res == 0) /* EOF */ + else if(res == 0) /* EOF */ { - if (bgmloop) + if(bgmloop) { - if (did_rewind) + if(did_rewind) { Con_Printf("Stream keeps returning EOF.\n"); BGM_Stop(); @@ -435,7 +435,7 @@ static void BGM_UpdateStream (void) } res = S_CodecRewindStream(bgmstream); - if (res != 0) + if(res != 0) { Con_Printf("Stream seek error (%" PRIi32 "), stopping.\n", res); BGM_Stop(); @@ -449,7 +449,7 @@ static void BGM_UpdateStream (void) return; } } - else /* res < 0: some read error */ + else /* res < 0: some read error */ { Con_Printf("Stream read error (%" PRIi32 "), stopping.\n", res); BGM_Stop(); @@ -458,18 +458,18 @@ static void BGM_UpdateStream (void) } } -void BGM_Update (void) +void BGM_Update(void) { - if (old_volume != bgmvolume.value) + if(old_volume != bgmvolume.value) { - if (bgmvolume.value < 0) - Cvar_SetQuick (&bgmvolume, "0"); - else if (bgmvolume.value > 1) - Cvar_SetQuick (&bgmvolume, "1"); + if(bgmvolume.value < 0) + Cvar_SetQuick(&bgmvolume, "0"); + else if(bgmvolume.value > 1) + Cvar_SetQuick(&bgmvolume, "1"); old_volume = bgmvolume.value; } - if (bgmstream) - BGM_UpdateStream (); + if(bgmstream) + BGM_UpdateStream(); CDAudio_Update(); } diff --git a/source/bgmusic.h b/source/bgmusic.h index ece7c8b..8912190 100644 --- a/source/bgmusic.h +++ b/source/bgmusic.h @@ -25,19 +25,19 @@ #ifndef _BGMUSIC_H_ #define _BGMUSIC_H_ -extern bool bgmloop; -extern cvar_t bgm_extmusic; +extern bool bgmloop; +extern cvar_t bgm_extmusic; -bool BGM_Init (void); -void BGM_Shutdown (void); +bool BGM_Init(void); +void BGM_Shutdown(void); -void BGM_Play (const char *filename); -void BGM_Stop (void); -void BGM_Update (void); -void BGM_Pause (void); -void BGM_Resume (void); +void BGM_Play(const char *filename); +void BGM_Stop(void); +void BGM_Update(void); +void BGM_Pause(void); +void BGM_Resume(void); -void BGM_PlayCDtrack (byte track, bool looping); +void BGM_PlayCDtrack(byte track, bool looping); -#endif /* _BGMUSIC_H_ */ +#endif /* _BGMUSIC_H_ */ diff --git a/source/bspfile.h b/source/bspfile.h index c0249d9..cbfbcf1 100644 --- a/source/bspfile.h +++ b/source/bspfile.h @@ -25,39 +25,39 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // upper design bounds -#define MAX_MAP_HULLS 4 +#define MAX_MAP_HULLS 4 -#define MAX_MAP_MODELS 256 -#define MAX_MAP_BRUSHES 4096 -#define MAX_MAP_ENTITIES 1024 -#define MAX_MAP_ENTSTRING 65536 +#define MAX_MAP_MODELS 256 +#define MAX_MAP_BRUSHES 4096 +#define MAX_MAP_ENTITIES 1024 +#define MAX_MAP_ENTSTRING 65536 -#define MAX_MAP_PLANES 32767 -#define MAX_MAP_NODES 32767 // because negative shorts are contents -#define MAX_MAP_CLIPNODES 32767 -//#define MAX_MAP_LEAFS 80000 //johnfitz -- was 8192 -#define MAX_MAP_VERTS 65535 -#define MAX_MAP_FACES 65535 -#define MAX_MAP_MARKSURFACES 65535 -#define MAX_MAP_TEXINFO 4096 -#define MAX_MAP_EDGES 256000 -#define MAX_MAP_SURFEDGES 512000 -#define MAX_MAP_TEXTURES 512 -#define MAX_MAP_MIPTEX 0x200000 -#define MAX_MAP_LIGHTING 0x100000 -#define MAX_MAP_VISIBILITY 0x100000 +#define MAX_MAP_PLANES 32767 +#define MAX_MAP_NODES 32767 // because negative shorts are contents +#define MAX_MAP_CLIPNODES 32767 +//#define MAX_MAP_LEAFS 80000 //johnfitz -- was 8192 +#define MAX_MAP_VERTS 65535 +#define MAX_MAP_FACES 65535 +#define MAX_MAP_MARKSURFACES 65535 +#define MAX_MAP_TEXINFO 4096 +#define MAX_MAP_EDGES 256000 +#define MAX_MAP_SURFEDGES 512000 +#define MAX_MAP_TEXTURES 512 +#define MAX_MAP_MIPTEX 0x200000 +#define MAX_MAP_LIGHTING 0x100000 +#define MAX_MAP_VISIBILITY 0x100000 -#define MAX_MAP_PORTALS 65536 +#define MAX_MAP_PORTALS 65536 // key / value pair sizes -#define MAX_KEY 32 -#define MAX_VALUE 1024 +#define MAX_KEY 32 +#define MAX_VALUE 1024 //============================================================================= -#define BSPVERSION 29 +#define BSPVERSION 29 /* RMQ support (2PSB). 32bits instead of shorts for all but bbox sizes (which * still use shorts) */ @@ -66,249 +66,249 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /* BSP2 support. 32bits instead of shorts for everything (bboxes use floats) */ #define BSP2VERSION_BSP2 (('B' << 0) | ('S' << 8) | ('P' << 16) | ('2'<<24)) -#define TOOLVERSION 2 +#define TOOLVERSION 2 typedef struct { - int32_t fileofs, filelen; + int32_t fileofs, filelen; } lump_t; -#define LUMP_ENTITIES 0 -#define LUMP_PLANES 1 -#define LUMP_TEXTURES 2 -#define LUMP_VERTEXES 3 -#define LUMP_VISIBILITY 4 -#define LUMP_NODES 5 -#define LUMP_TEXINFO 6 -#define LUMP_FACES 7 -#define LUMP_LIGHTING 8 -#define LUMP_CLIPNODES 9 -#define LUMP_LEAFS 10 -#define LUMP_MARKSURFACES 11 -#define LUMP_EDGES 12 -#define LUMP_SURFEDGES 13 -#define LUMP_MODELS 14 +#define LUMP_ENTITIES 0 +#define LUMP_PLANES 1 +#define LUMP_TEXTURES 2 +#define LUMP_VERTEXES 3 +#define LUMP_VISIBILITY 4 +#define LUMP_NODES 5 +#define LUMP_TEXINFO 6 +#define LUMP_FACES 7 +#define LUMP_LIGHTING 8 +#define LUMP_CLIPNODES 9 +#define LUMP_LEAFS 10 +#define LUMP_MARKSURFACES 11 +#define LUMP_EDGES 12 +#define LUMP_SURFEDGES 13 +#define LUMP_MODELS 14 -#define HEADER_LUMPS 15 +#define HEADER_LUMPS 15 typedef struct { - float mins[3], maxs[3]; - float origin[3]; - int32_t headnode[MAX_MAP_HULLS]; - int32_t visleafs; // not including the solid leaf 0 - int32_t firstface, numfaces; + float mins[3], maxs[3]; + float origin[3]; + int32_t headnode[MAX_MAP_HULLS]; + int32_t visleafs; // not including the solid leaf 0 + int32_t firstface, numfaces; } dmodel_t; typedef struct { - int32_t version; - lump_t lumps[HEADER_LUMPS]; + int32_t version; + lump_t lumps[HEADER_LUMPS]; } dheader_t; typedef struct { - int32_t nummiptex; - int32_t dataofs[4]; // [nummiptex] + int32_t nummiptex; + int32_t dataofs[4]; // [nummiptex] } dmiptexlump_t; -#define MIPLEVELS 4 +#define MIPLEVELS 4 typedef struct miptex_s { - char name[16]; - unsigned width, height; - unsigned offsets[MIPLEVELS]; // four mip maps stored + char name[16]; + unsigned width, height; + unsigned offsets[MIPLEVELS]; // four mip maps stored } miptex_t; typedef struct { - float point[3]; + float point[3]; } dvertex_t; // 0-2 are axial planes -#define PLANE_X 0 -#define PLANE_Y 1 -#define PLANE_Z 2 +#define PLANE_X 0 +#define PLANE_Y 1 +#define PLANE_Z 2 // 3-5 are non-axial planes snapped to the nearest -#define PLANE_ANYX 3 -#define PLANE_ANYY 4 -#define PLANE_ANYZ 5 +#define PLANE_ANYX 3 +#define PLANE_ANYY 4 +#define PLANE_ANYZ 5 typedef struct { - float normal[3]; - float dist; - int32_t type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate + float normal[3]; + float dist; + int32_t type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate } dplane_t; -#define CONTENTS_EMPTY -1 -#define CONTENTS_SOLID -2 -#define CONTENTS_WATER -3 -#define CONTENTS_SLIME -4 -#define CONTENTS_LAVA -5 -#define CONTENTS_SKY -6 -#define CONTENTS_ORIGIN -7 // removed at csg time -#define CONTENTS_CLIP -8 // changed to contents_solid +#define CONTENTS_EMPTY -1 +#define CONTENTS_SOLID -2 +#define CONTENTS_WATER -3 +#define CONTENTS_SLIME -4 +#define CONTENTS_LAVA -5 +#define CONTENTS_SKY -6 +#define CONTENTS_ORIGIN -7 // removed at csg time +#define CONTENTS_CLIP -8 // changed to contents_solid -#define CONTENTS_CURRENT_0 -9 -#define CONTENTS_CURRENT_90 -10 -#define CONTENTS_CURRENT_180 -11 -#define CONTENTS_CURRENT_270 -12 -#define CONTENTS_CURRENT_UP -13 -#define CONTENTS_CURRENT_DOWN -14 +#define CONTENTS_CURRENT_0 -9 +#define CONTENTS_CURRENT_90 -10 +#define CONTENTS_CURRENT_180 -11 +#define CONTENTS_CURRENT_270 -12 +#define CONTENTS_CURRENT_UP -13 +#define CONTENTS_CURRENT_DOWN -14 // !!! if this is changed, it must be changed in asm_i386.h too !!! typedef struct { - int32_t planenum; - int16_t children[2]; // negative numbers are -(leafs+1), not nodes - int16_t mins[3]; // for sphere culling - int16_t maxs[3]; - uint16_t firstface; - uint16_t numfaces; // counting both sides + int32_t planenum; + int16_t children[2]; // negative numbers are -(leafs+1), not nodes + int16_t mins[3]; // for sphere culling + int16_t maxs[3]; + uint16_t firstface; + uint16_t numfaces; // counting both sides } dsnode_t; typedef struct { - int32_t planenum; - int32_t children[2]; // negative numbers are -(leafs+1), not nodes - int16_t mins[3]; // for sphere culling - int16_t maxs[3]; - uint32_t firstface; - uint32_t numfaces; // counting both sides + int32_t planenum; + int32_t children[2]; // negative numbers are -(leafs+1), not nodes + int16_t mins[3]; // for sphere culling + int16_t maxs[3]; + uint32_t firstface; + uint32_t numfaces; // counting both sides } dl1node_t; typedef struct { - int32_t planenum; - int32_t children[2]; // negative numbers are -(leafs+1), not nodes - float mins[3]; // for sphere culling - float maxs[3]; - uint32_t firstface; - uint32_t numfaces; // counting both sides + int32_t planenum; + int32_t children[2]; // negative numbers are -(leafs+1), not nodes + float mins[3]; // for sphere culling + float maxs[3]; + uint32_t firstface; + uint32_t numfaces; // counting both sides } dl2node_t; typedef struct { - int32_t planenum; - int16_t children[2]; // negative numbers are contents + int32_t planenum; + int16_t children[2]; // negative numbers are contents } dsclipnode_t; typedef struct { - int32_t planenum; - int32_t children[2]; // negative numbers are contents + int32_t planenum; + int32_t children[2]; // negative numbers are contents } dlclipnode_t; typedef struct texinfo_s { - float vecs[2][4]; // [s/t][xyz offset] - int32_t miptex; - int32_t flags; + float vecs[2][4]; // [s/t][xyz offset] + int32_t miptex; + int32_t flags; } texinfo_t; -#define TEX_SPECIAL 1 // sky or slime, no lightmap or 256 subdivision -#define TEX_MISSING 2 // johnfitz -- this texinfo does not have a texture +#define TEX_SPECIAL 1 // sky or slime, no lightmap or 256 subdivision +#define TEX_MISSING 2 // johnfitz -- this texinfo does not have a texture // note that edge 0 is never used, because negative edge nums are used for // counterclockwise use of the edge in a face typedef struct { - uint16_t v[2]; // vertex numbers + uint16_t v[2]; // vertex numbers } dsedge_t; typedef struct { - uint32_t v[2]; // vertex numbers + uint32_t v[2]; // vertex numbers } dledge_t; -#define MAXLIGHTMAPS 4 +#define MAXLIGHTMAPS 4 typedef struct { - int16_t planenum; - int16_t side; + int16_t planenum; + int16_t side; - int32_t firstedge; // we must support > 64k edges - int16_t numedges; - int16_t texinfo; + int32_t firstedge; // we must support > 64k edges + int16_t numedges; + int16_t texinfo; // lighting info - byte styles[MAXLIGHTMAPS]; - int32_t lightofs; // start of [numstyles*surfsize] samples + byte styles[MAXLIGHTMAPS]; + int32_t lightofs; // start of [numstyles*surfsize] samples } dsface_t; typedef struct { - int32_t planenum; - int32_t side; + int32_t planenum; + int32_t side; - int32_t firstedge; // we must support > 64k edges - int32_t numedges; - int32_t texinfo; + int32_t firstedge; // we must support > 64k edges + int32_t numedges; + int32_t texinfo; // lighting info - byte styles[MAXLIGHTMAPS]; - int32_t lightofs; // start of [numstyles*surfsize] samples + byte styles[MAXLIGHTMAPS]; + int32_t lightofs; // start of [numstyles*surfsize] samples } dlface_t; -#define AMBIENT_WATER 0 -#define AMBIENT_SKY 1 -#define AMBIENT_SLIME 2 -#define AMBIENT_LAVA 3 +#define AMBIENT_WATER 0 +#define AMBIENT_SKY 1 +#define AMBIENT_SLIME 2 +#define AMBIENT_LAVA 3 -#define NUM_AMBIENTS 4 // automatic ambient sounds +#define NUM_AMBIENTS 4 // automatic ambient sounds // leaf 0 is the generic CONTENTS_SOLID leaf, used for all solid areas // all other leafs need visibility info typedef struct { - int32_t contents; - int32_t visofs; // -1 = no visibility info + int32_t contents; + int32_t visofs; // -1 = no visibility info - int16_t mins[3]; // for frustum culling - int16_t maxs[3]; + int16_t mins[3]; // for frustum culling + int16_t maxs[3]; - uint16_t firstmarksurface; - uint16_t nummarksurfaces; + uint16_t firstmarksurface; + uint16_t nummarksurfaces; - byte ambient_level[NUM_AMBIENTS]; + byte ambient_level[NUM_AMBIENTS]; } dsleaf_t; typedef struct { - int32_t contents; - int32_t visofs; // -1 = no visibility info + int32_t contents; + int32_t visofs; // -1 = no visibility info - int16_t mins[3]; // for frustum culling - int16_t maxs[3]; + int16_t mins[3]; // for frustum culling + int16_t maxs[3]; - uint32_t firstmarksurface; - uint32_t nummarksurfaces; + uint32_t firstmarksurface; + uint32_t nummarksurfaces; - byte ambient_level[NUM_AMBIENTS]; + byte ambient_level[NUM_AMBIENTS]; } dl1leaf_t; typedef struct { - int32_t contents; - int32_t visofs; // -1 = no visibility info + int32_t contents; + int32_t visofs; // -1 = no visibility info - float mins[3]; // for frustum culling - float maxs[3]; + float mins[3]; // for frustum culling + float maxs[3]; - uint32_t firstmarksurface; - uint32_t nummarksurfaces; + uint32_t firstmarksurface; + uint32_t nummarksurfaces; - byte ambient_level[NUM_AMBIENTS]; + byte ambient_level[NUM_AMBIENTS]; } dl2leaf_t; //============================================================================ -#endif /* __BSPFILE_H */ +#endif /* __BSPFILE_H */ diff --git a/source/cd_sdl.c b/source/cd_sdl.c index 5ae33c4..bbf6fce 100644 --- a/source/cd_sdl.c +++ b/source/cd_sdl.c @@ -35,39 +35,39 @@ #include "cdaudio.h" static bool cdValid = false; -static bool playing = false; -static bool wasPlaying = false; -static bool enabled = true; +static bool playing = false; +static bool wasPlaying = false; +static bool enabled = true; static bool playLooping = false; -static byte remap[100]; -static byte playTrack; -static double endOfTrack = -1.0, pausetime = -1.0; -static SDL_CD *cd_handle; -static int32_t cd_dev = -1; -static float old_cdvolume; -static bool hw_vol_works = true; +static byte remap[100]; +static byte playTrack; +static double endOfTrack = -1.0, pausetime = -1.0; +static SDL_CD *cd_handle; +static int32_t cd_dev = -1; +static float old_cdvolume; +static bool hw_vol_works = true; static void CDAudio_Eject(void) { - if (!cd_handle || !enabled) + if(!cd_handle || !enabled) return; #ifdef __linux__ - SDL_CDStop(cd_handle); /* see CDAudio_Stop() */ + SDL_CDStop(cd_handle); /* see CDAudio_Stop() */ #endif - if (SDL_CDEject(cd_handle) < 0) - Con_Printf ("Unable to eject CD-ROM: %s\n", SDL_GetError ()); + if(SDL_CDEject(cd_handle) < 0) + Con_Printf("Unable to eject CD-ROM: %s\n", SDL_GetError()); } static int32_t CDAudio_GetAudioDiskInfo(void) { cdValid = false; - if (!cd_handle) + if(!cd_handle) return -1; - if ( ! CD_INDRIVE(SDL_CDStatus(cd_handle)) ) + if(! CD_INDRIVE(SDL_CDStatus(cd_handle))) return -1; cdValid = true; @@ -77,42 +77,42 @@ static int32_t CDAudio_GetAudioDiskInfo(void) int32_t CDAudio_Play(byte track, bool looping) { - int32_t len_m, len_s, len_f; + int32_t len_m, len_s, len_f; - if (!cd_handle || !enabled) + if(!cd_handle || !enabled) return -1; - if (!cdValid) + if(!cdValid) { CDAudio_GetAudioDiskInfo(); - if (!cdValid) + if(!cdValid) return -1; } track = remap[track]; - if (track < 1 || track > cd_handle->numtracks) + if(track < 1 || track > cd_handle->numtracks) { - Con_Printf ("CDAudio_Play: Bad track number %" PRIi32 ".\n", track); + Con_Printf("CDAudio_Play: Bad track number %" PRIi32 ".\n", track); return -1; } - if (cd_handle->track[track-1].type == SDL_DATA_TRACK) + if(cd_handle->track[track - 1].type == SDL_DATA_TRACK) { - Con_Printf ("CDAudio_Play: track %" PRIi32 " is not audio\n", track); + Con_Printf("CDAudio_Play: track %" PRIi32 " is not audio\n", track); return -1; } - if (playing) + if(playing) { - if (playTrack == track) + if(playTrack == track) return 0; CDAudio_Stop(); } - if (SDL_CDPlay(cd_handle, cd_handle->track[track-1].offset, cd_handle->track[track-1].length) < 0) + if(SDL_CDPlay(cd_handle, cd_handle->track[track - 1].offset, cd_handle->track[track - 1].length) < 0) { - Con_Printf ("CDAudio_Play: Unable to play track %" PRIi32 ": %s\n", track, SDL_GetError ()); + Con_Printf("CDAudio_Play: Unable to play track %" PRIi32 ": %s\n", track, SDL_GetError()); return -1; } @@ -120,7 +120,7 @@ int32_t CDAudio_Play(byte track, bool looping) playTrack = track; playing = true; - FRAMES_TO_MSF(cd_handle->track[track-1].length, &len_m, &len_s, &len_f); + FRAMES_TO_MSF(cd_handle->track[track - 1].length, &len_m, &len_s, &len_f); endOfTrack = realtime + ((double)len_m * 60.0) + (double)len_s + (double)len_f / (double)CD_FPS; /* Add the pregap for the next track. This means that disc-at-once CDs @@ -130,18 +130,18 @@ int32_t CDAudio_Play(byte track, bool looping) endOfTrack += 2.0; pausetime = -1.0; - if (bgmvolume.value == 0) /* don't bother advancing */ - CDAudio_Pause (); + if(bgmvolume.value == 0) /* don't bother advancing */ + CDAudio_Pause(); return 0; } void CDAudio_Stop(void) { - if (!cd_handle || !enabled) + if(!cd_handle || !enabled) return; - if (!playing) + if(!playing) return; #ifdef __linux__ @@ -151,11 +151,11 @@ void CDAudio_Stop(void) * firmware versions running under a 2.6.27.25 kernel, and with a * Samsung DVD r/w drive running under 2.6.35.6 kernel. * Therefore, avoid dead stops if playback may be resumed shortly. */ - if (SDL_CDPause(cd_handle) < 0) - Con_Printf ("CDAudio_Stop: Unable to stop CD-ROM (%s)\n", SDL_GetError()); + if(SDL_CDPause(cd_handle) < 0) + Con_Printf("CDAudio_Stop: Unable to stop CD-ROM (%s)\n", SDL_GetError()); #else - if (SDL_CDStop(cd_handle) < 0) - Con_Printf ("CDAudio_Stop: Unable to stop CD-ROM (%s)\n", SDL_GetError()); + if(SDL_CDStop(cd_handle) < 0) + Con_Printf("CDAudio_Stop: Unable to stop CD-ROM (%s)\n", SDL_GetError()); #endif wasPlaying = false; @@ -166,14 +166,14 @@ void CDAudio_Stop(void) void CDAudio_Pause(void) { - if (!cd_handle || !enabled) + if(!cd_handle || !enabled) return; - if (!playing) + if(!playing) return; - if (SDL_CDPause(cd_handle) < 0) - Con_Printf ("Unable to pause CD-ROM: %s\n", SDL_GetError()); + if(SDL_CDPause(cd_handle) < 0) + Con_Printf("Unable to pause CD-ROM: %s\n", SDL_GetError()); wasPlaying = playing; playing = false; @@ -182,37 +182,37 @@ void CDAudio_Pause(void) void CDAudio_Resume(void) { - if (!cd_handle || !enabled) + if(!cd_handle || !enabled) return; - if (!cdValid) + if(!cdValid) return; - if (!wasPlaying) + if(!wasPlaying) return; - if (SDL_CDResume(cd_handle) < 0) - Con_Printf ("Unable to resume CD-ROM: %s\n", SDL_GetError()); + if(SDL_CDResume(cd_handle) < 0) + Con_Printf("Unable to resume CD-ROM: %s\n", SDL_GetError()); playing = true; endOfTrack += realtime - pausetime; pausetime = -1.0; } -static int32_t get_first_audiotrk (void) +static int32_t get_first_audiotrk(void) { int32_t i; - for (i = 0; i < cd_handle->numtracks; ++i) - if (cd_handle->track[i].type != SDL_DATA_TRACK) + for(i = 0; i < cd_handle->numtracks; ++i) + if(cd_handle->track[i].type != SDL_DATA_TRACK) return ++i; return 1; } -static void CD_f (void) +static void CD_f(void) { - const char *command; - int32_t ret, n; + const char *command; + int32_t ret, n; - if (Cmd_Argc() < 2) + if(Cmd_Argc() < 2) { Con_Printf("commands:"); Con_Printf("on, off, reset, remap, \n"); @@ -221,232 +221,232 @@ static void CD_f (void) return; } - command = Cmd_Argv (1); + command = Cmd_Argv(1); - if (q_strcasecmp(command, "on") == 0) + if(q_strcasecmp(command, "on") == 0) { enabled = true; return; } - if (q_strcasecmp(command, "off") == 0) + if(q_strcasecmp(command, "off") == 0) { - if (playing) + if(playing) CDAudio_Stop(); enabled = false; return; } - if (q_strcasecmp(command, "reset") == 0) + if(q_strcasecmp(command, "reset") == 0) { enabled = true; - if (playing) + if(playing) CDAudio_Stop(); - for (n = 0; n < 100; n++) + for(n = 0; n < 100; n++) remap[n] = n; CDAudio_GetAudioDiskInfo(); return; } - if (q_strcasecmp(command, "remap") == 0) + if(q_strcasecmp(command, "remap") == 0) { ret = Cmd_Argc() - 2; - if (ret <= 0) + if(ret <= 0) { - for (n = 1; n < 100; n++) - if (remap[n] != n) + for(n = 1; n < 100; n++) + if(remap[n] != n) Con_Printf(" %" PRIu32 " -> %" PRIu32 "\n", n, remap[n]); return; } - for (n = 1; n <= ret; n++) - remap[n] = atoi(Cmd_Argv (n + 1)); + for(n = 1; n <= ret; n++) + remap[n] = atoi(Cmd_Argv(n + 1)); return; } - if (!cdValid) + if(!cdValid) { CDAudio_GetAudioDiskInfo(); - if (!cdValid) + if(!cdValid) { Con_Printf("No CD in player.\n"); return; } } - if (q_strcasecmp(command, "play") == 0) + if(q_strcasecmp(command, "play") == 0) { - n = atoi(Cmd_Argv (2)); - if (n == 0) + n = atoi(Cmd_Argv(2)); + if(n == 0) n = 1; CDAudio_Play((byte)n, false); return; } - if (q_strcasecmp(command, "loop") == 0) + if(q_strcasecmp(command, "loop") == 0) { - CDAudio_Play((byte)atoi(Cmd_Argv (2)), true); + CDAudio_Play((byte)atoi(Cmd_Argv(2)), true); return; } - if (q_strcasecmp(command, "stop") == 0) + if(q_strcasecmp(command, "stop") == 0) { CDAudio_Stop(); return; } - if (q_strcasecmp(command, "pause") == 0) + if(q_strcasecmp(command, "pause") == 0) { CDAudio_Pause(); return; } - if (q_strcasecmp(command, "resume") == 0) + if(q_strcasecmp(command, "resume") == 0) { CDAudio_Resume(); return; } - if (q_strcasecmp(command, "eject") == 0) + if(q_strcasecmp(command, "eject") == 0) { - if (playing) + if(playing) CDAudio_Stop(); CDAudio_Eject(); cdValid = false; return; } - if (q_strcasecmp(command, "info") == 0) + if(q_strcasecmp(command, "info") == 0) { - int32_t current_min, current_sec, current_frame; - int32_t length_min, length_sec, length_frame; + int32_t current_min, current_sec, current_frame; + int32_t length_min, length_sec, length_frame; - Con_Printf ("%" PRIu32 " tracks\n", cd_handle->numtracks); + Con_Printf("%" PRIu32 " tracks\n", cd_handle->numtracks); - if (playing) + if(playing) Con_Printf("Currently %s track %" PRIu32 "\n", playLooping ? "looping" : "playing", playTrack); - else if (wasPlaying) + else if(wasPlaying) Con_Printf("Paused %s track %" PRIu32 "\n", playLooping ? "looping" : "playing", playTrack); - if (playing || wasPlaying) + if(playing || wasPlaying) { SDL_CDStatus(cd_handle); FRAMES_TO_MSF(cd_handle->cur_frame, ¤t_min, ¤t_sec, ¤t_frame); - FRAMES_TO_MSF(cd_handle->track[playTrack-1].length, &length_min, &length_sec, &length_frame); + FRAMES_TO_MSF(cd_handle->track[playTrack - 1].length, &length_min, &length_sec, &length_frame); - Con_Printf ("Current position: %" PRIi32 ":%02" PRIi32 ".%02" PRIi32 " (of %" PRIi32 ":%02" PRIi32 ".%02" PRIi32 ")\n", - current_min, current_sec, current_frame * 60 / CD_FPS, - length_min, length_sec, length_frame * 60 / CD_FPS); + Con_Printf("Current position: %" PRIi32 ":%02" PRIi32 ".%02" PRIi32 " (of %" PRIi32 ":%02" PRIi32 ".%02" PRIi32 ")\n", + current_min, current_sec, current_frame * 60 / CD_FPS, + length_min, length_sec, length_frame * 60 / CD_FPS); } Con_Printf("Volume is %f\n", bgmvolume.value); return; } - if (q_strcasecmp(command, "next") == 0) + if(q_strcasecmp(command, "next") == 0) { - if (playTrack == cd_handle->numtracks) + if(playTrack == cd_handle->numtracks) playTrack = get_first_audiotrk() - 1; CDAudio_Play(playTrack + 1, playLooping); return; } - if (q_strcasecmp(command, "prev") == 0) + if(q_strcasecmp(command, "prev") == 0) { - if (playTrack == get_first_audiotrk()) + if(playTrack == get_first_audiotrk()) playTrack = cd_handle->numtracks + 1; CDAudio_Play(playTrack - 1, playLooping); return; } - Con_Printf ("cd: unknown command \"%s\"\n", command); + Con_Printf("cd: unknown command \"%s\"\n", command); } -static bool CD_GetVolume (void *unused) +static bool CD_GetVolume(void *unused) { -/* FIXME: write proper code in here when SDL - supports cdrom volume control some day. */ + /* FIXME: write proper code in here when SDL + supports cdrom volume control some day. */ return false; } -static bool CD_SetVolume (void *unused) +static bool CD_SetVolume(void *unused) { -/* FIXME: write proper code in here when SDL - supports cdrom volume control some day. */ + /* FIXME: write proper code in here when SDL + supports cdrom volume control some day. */ return false; } -static bool CDAudio_SetVolume (float value) +static bool CDAudio_SetVolume(float value) { - if (!cd_handle || !enabled) + if(!cd_handle || !enabled) return false; old_cdvolume = value; - if (value == 0.0f) - CDAudio_Pause (); + if(value == 0.0f) + CDAudio_Pause(); else CDAudio_Resume(); - if (!hw_vol_works) + if(!hw_vol_works) { return false; } else { -/* FIXME: write proper code in here when SDL - supports cdrom volume control some day. */ - return CD_SetVolume (NULL); + /* FIXME: write proper code in here when SDL + supports cdrom volume control some day. */ + return CD_SetVolume(NULL); } } void CDAudio_Update(void) { - CDstatus curstat; -/* static double lastchk;*/ + CDstatus curstat; + /* static double lastchk;*/ - if (!cd_handle || !enabled) + if(!cd_handle || !enabled) return; - if (old_cdvolume != bgmvolume.value) - CDAudio_SetVolume (bgmvolume.value); + if(old_cdvolume != bgmvolume.value) + CDAudio_SetVolume(bgmvolume.value); -/* if (playing && realtime > lastchk)*/ - if (playing && realtime > endOfTrack) + /* if (playing && realtime > lastchk)*/ + if(playing && realtime > endOfTrack) { - /* lastchk = realtime + 2;*/ /* two seconds between chks */ + /* lastchk = realtime + 2;*/ /* two seconds between chks */ curstat = SDL_CDStatus(cd_handle); - if (curstat != CD_PLAYING && curstat != CD_PAUSED) + if(curstat != CD_PLAYING && curstat != CD_PAUSED) { playing = false; endOfTrack = -1.0; - if (playLooping) + if(playLooping) CDAudio_Play(playTrack, true); } } } -static const char *get_cddev_arg (const char *arg) +static const char *get_cddev_arg(const char *arg) { #if defined(_WIN32) -/* arg should be like "D:\", make sure it is so, - * but tolerate args like "D" or "D:", as well. */ + /* arg should be like "D:\", make sure it is so, + * but tolerate args like "D" or "D:", as well. */ static char drive[4]; - if (!arg || ! *arg) + if(!arg || ! *arg) return NULL; - if (arg[1] != '\0') + if(arg[1] != '\0') { - if (arg[1] != ':') + if(arg[1] != ':') return NULL; - if (arg[2] != '\0') + if(arg[2] != '\0') { - if (arg[2] != '\\' && - arg[2] != '/') + if(arg[2] != '\\' && + arg[2] != '/') return NULL; - if (arg[3] != '\0') + if(arg[3] != '\0') return NULL; } } - if (*arg >= 'A' && *arg <= 'Z') + if(*arg >= 'A' && *arg <= 'Z') { drive[0] = *arg; drive[1] = ':'; @@ -454,9 +454,9 @@ static const char *get_cddev_arg (const char *arg) drive[3] = '\0'; return drive; } - else if (*arg >= 'a' && *arg <= 'z') + else if(*arg >= 'a' && *arg <= 'z') { - /* make it uppercase for SDL */ + /* make it uppercase for SDL */ drive[0] = *arg - ('a' - 'A'); drive[1] = ':'; drive[2] = '\\'; @@ -465,22 +465,22 @@ static const char *get_cddev_arg (const char *arg) } return NULL; #else - if (!arg || ! *arg) + if(!arg || ! *arg) return NULL; return arg; #endif } -static void export_cddev_arg (void) +static void export_cddev_arg(void) { -/* Bad ugly hack to workaround SDL's cdrom device detection. - * not needed for windows due to the way SDL_cdrom works. */ + /* Bad ugly hack to workaround SDL's cdrom device detection. + * not needed for windows due to the way SDL_cdrom works. */ #if !defined(_WIN32) int32_t i = COM_CheckParm("-cddev"); - if (i != 0 && i < com_argc - 1 && com_argv[i+1][0] != '\0') + if(i != 0 && i < com_argc - 1 && com_argv[i + 1][0] != '\0') { static char arg[64]; - q_snprintf(arg, sizeof(arg), "SDL_CDROM=%s", com_argv[i+1]); + q_snprintf(arg, sizeof(arg), "SDL_CDROM=%s", com_argv[i + 1]); putenv(arg); } #endif @@ -488,91 +488,91 @@ static void export_cddev_arg (void) int32_t CDAudio_Init(void) { - int32_t i, sdl_num_drives; + int32_t i, sdl_num_drives; - if (safemode || COM_CheckParm("-nocdaudio")) + if(safemode || COM_CheckParm("-nocdaudio")) return -1; export_cddev_arg(); - if (SDL_InitSubSystem(SDL_INIT_CDROM) < 0) + if(SDL_InitSubSystem(SDL_INIT_CDROM) < 0) { Con_Printf("Couldn't init SDL cdrom: %s\n", SDL_GetError()); return -1; } - sdl_num_drives = SDL_CDNumDrives (); - Con_Printf ("SDL detected %" PRIi32 " CD-ROM drive%c\n", sdl_num_drives, - sdl_num_drives == 1 ? ' ' : 's'); + sdl_num_drives = SDL_CDNumDrives(); + Con_Printf("SDL detected %" PRIi32 " CD-ROM drive%c\n", sdl_num_drives, + sdl_num_drives == 1 ? ' ' : 's'); - if (sdl_num_drives < 1) + if(sdl_num_drives < 1) return -1; - if ((i = COM_CheckParm("-cddev")) != 0 && i < com_argc - 1) + if((i = COM_CheckParm("-cddev")) != 0 && i < com_argc - 1) { - const char *userdev = get_cddev_arg(com_argv[i+1]); - if (!userdev) + const char *userdev = get_cddev_arg(com_argv[i + 1]); + if(!userdev) { Con_Printf("Invalid argument to -cddev\n"); return -1; } - for (i = 0; i < sdl_num_drives; i++) + for(i = 0; i < sdl_num_drives; i++) { - if (!q_strcasecmp(SDL_CDName(i), userdev)) + if(!q_strcasecmp(SDL_CDName(i), userdev)) { cd_dev = i; break; } } - if (cd_dev == -1) + if(cd_dev == -1) { Con_Printf("SDL couldn't find cdrom device %s\n", userdev); return -1; } } - if (cd_dev == -1) - cd_dev = 0; /* default drive */ + if(cd_dev == -1) + cd_dev = 0; /* default drive */ cd_handle = SDL_CDOpen(cd_dev); - if (!cd_handle) + if(!cd_handle) { - Con_Printf ("CDAudio_Init: Unable to open CD-ROM drive %s (%s)\n", - SDL_CDName(cd_dev), SDL_GetError()); + Con_Printf("CDAudio_Init: Unable to open CD-ROM drive %s (%s)\n", + SDL_CDName(cd_dev), SDL_GetError()); return -1; } - for (i = 0; i < 100; i++) + for(i = 0; i < 100; i++) remap[i] = i; enabled = true; old_cdvolume = bgmvolume.value; Con_Printf("CDAudio initialized (SDL, using %s)\n", SDL_CDName(cd_dev)); - if (CDAudio_GetAudioDiskInfo()) + if(CDAudio_GetAudioDiskInfo()) { Con_Printf("CDAudio_Init: No CD in drive\n"); cdValid = false; } - Cmd_AddCommand ("cd", CD_f); + Cmd_AddCommand("cd", CD_f); - hw_vol_works = CD_GetVolume (NULL); /* no SDL support at present. */ - if (hw_vol_works) - hw_vol_works = CDAudio_SetVolume (bgmvolume.value); + hw_vol_works = CD_GetVolume(NULL); /* no SDL support at present. */ + if(hw_vol_works) + hw_vol_works = CDAudio_SetVolume(bgmvolume.value); return 0; } void CDAudio_Shutdown(void) { - if (!cd_handle) + if(!cd_handle) return; CDAudio_Stop(); - if (hw_vol_works) - CD_SetVolume (NULL); /* no SDL support at present. */ + if(hw_vol_works) + CD_SetVolume(NULL); /* no SDL support at present. */ #ifdef __linux__ - SDL_CDStop(cd_handle); /* see CDAudio_Stop() */ + SDL_CDStop(cd_handle); /* see CDAudio_Stop() */ #endif SDL_CDClose(cd_handle); cd_handle = NULL; diff --git a/source/cdaudio.h b/source/cdaudio.h index 6f90978..e2f716d 100644 --- a/source/cdaudio.h +++ b/source/cdaudio.h @@ -22,14 +22,14 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef __CDAUDIO_H #define __CDAUDIO_H -int32_t CDAudio_Init (void); -int32_t CDAudio_Play (byte track, bool looping); - /* returns 0 for success, -1 for failure. */ -void CDAudio_Stop (void); -void CDAudio_Pause (void); -void CDAudio_Resume (void); -void CDAudio_Shutdown (void); -void CDAudio_Update (void); +int32_t CDAudio_Init(void); +int32_t CDAudio_Play(byte track, bool looping); +/* returns 0 for success, -1 for failure. */ +void CDAudio_Stop(void); +void CDAudio_Pause(void); +void CDAudio_Resume(void); +void CDAudio_Shutdown(void); +void CDAudio_Update(void); -#endif /* __CDAUDIO_H */ +#endif /* __CDAUDIO_H */ diff --git a/source/cfgfile.c b/source/cfgfile.c index 016514c..1d6a189 100644 --- a/source/cfgfile.c +++ b/source/cfgfile.c @@ -22,7 +22,7 @@ #include "quakedef.h" -static fshandle_t *cfg_file; +static fshandle_t *cfg_file; /* =================== @@ -35,42 +35,43 @@ the num_vars argument must be the exact number of strings in the array, otherwise I have nothing against going out of bounds. =================== */ -void CFG_ReadCvars (const char **vars, int32_t num_vars) +void CFG_ReadCvars(const char **vars, int32_t num_vars) { - char buff[1024], *tmp; - int32_t i, j; + char buff[1024], *tmp; + int32_t i, j; - if (!cfg_file || num_vars < 1) + if(!cfg_file || num_vars < 1) return; j = 0; - do { + do + { i = 0; - memset (buff, 0, sizeof(buff)); + memset(buff, 0, sizeof(buff)); // we expect a line in the format that Cvar_WriteVariables // writes to the config file. although I'm trying to be as // much cautious as possible, if the user screws it up by // editing it, it's his fault. - if (FS_fgets(buff, sizeof(buff), cfg_file)) + if(FS_fgets(buff, sizeof(buff), cfg_file)) { // remove end-of-line characters - while (buff[i]) + while(buff[i]) { - if (buff[i] == '\r' || buff[i] == '\n') + if(buff[i] == '\r' || buff[i] == '\n') buff[i] = '\0'; // while we're here, replace tabs with spaces - if (buff[i] == '\t') + if(buff[i] == '\t') buff[i] = ' '; i++; } // go to the last character - while (buff[i] == 0 && i > 0) + while(buff[i] == 0 && i > 0) i--; // remove trailing spaces - while (i > 0) + while(i > 0) { - if (buff[i] == ' ') + if(buff[i] == ' ') { buff[i] = '\0'; i--; @@ -80,33 +81,34 @@ void CFG_ReadCvars (const char **vars, int32_t num_vars) } // the line must end with a quotation mark - if (buff[i] != '\"') + if(buff[i] != '\"') continue; buff[i] = '\0'; - for (i = 0; i < num_vars && vars[i]; i++) + for(i = 0; i < num_vars && vars[i]; i++) { // look for the cvar name + one space - tmp = strstr(buff, va("%s ",vars[i])); - if (tmp != buff) + tmp = strstr(buff, va("%s ", vars[i])); + if(tmp != buff) continue; // locate the first quotation mark tmp = strchr(buff, '\"'); - if (tmp) + if(tmp) { - Cvar_Set (vars[i], tmp + 1); + Cvar_Set(vars[i], tmp + 1); j++; break; } } } - if (j == num_vars) + if(j == num_vars) break; - } while (!FS_feof(cfg_file) && !FS_ferror(cfg_file)); + } + while(!FS_feof(cfg_file) && !FS_ferror(cfg_file)); - FS_rewind (cfg_file); + FS_rewind(cfg_file); } /* @@ -118,31 +120,31 @@ values of cvars in the given list. doesn't do anything with the config file. =================== */ -void CFG_ReadCvarOverrides (const char **vars, int32_t num_vars) +void CFG_ReadCvarOverrides(const char **vars, int32_t num_vars) { - char buff[64]; - int32_t i, j; + char buff[64]; + int32_t i, j; - if (num_vars < 1) + if(num_vars < 1) return; buff[0] = '+'; - for (i = 0; i < num_vars; i++) + for(i = 0; i < num_vars; i++) { - q_strlcpy (&buff[1], vars[i], sizeof(buff) - 1); + q_strlcpy(&buff[1], vars[i], sizeof(buff) - 1); j = COM_CheckParm(buff); - if (j != 0 && j < com_argc - 1) + if(j != 0 && j < com_argc - 1) { - if (com_argv[j + 1][0] != '-' && com_argv[j + 1][0] != '+') + if(com_argv[j + 1][0] != '-' && com_argv[j + 1][0] != '+') Cvar_Set(vars[i], com_argv[j + 1]); } } } -void CFG_CloseConfig (void) +void CFG_CloseConfig(void) { - if (cfg_file) + if(cfg_file) { FS_fclose(cfg_file); Z_Free(cfg_file); @@ -150,17 +152,17 @@ void CFG_CloseConfig (void) } } -int32_t CFG_OpenConfig (const char *cfg_name) +int32_t CFG_OpenConfig(const char *cfg_name) { - FILE *f; - long length; - bool pak; + FILE *f; + long length; + bool pak; - CFG_CloseConfig (); + CFG_CloseConfig(); - length = (long) COM_FOpenFile (cfg_name, &f, NULL); + length = (long) COM_FOpenFile(cfg_name, &f, NULL); pak = file_from_pak; - if (length == -1) + if(length == -1) return -1; cfg_file = (fshandle_t *) Z_Malloc(sizeof(fshandle_t)); diff --git a/source/cfgfile.h b/source/cfgfile.h index 869b17b..97af3da 100644 --- a/source/cfgfile.h +++ b/source/cfgfile.h @@ -22,21 +22,21 @@ #ifndef __CFGFILE_H #define __CFGFILE_H -int32_t CFG_OpenConfig (const char *cfg_name); +int32_t CFG_OpenConfig(const char *cfg_name); // opens the given config file. only one open config file is // kept: previosly opened one, if any, will be closed. -void CFG_CloseConfig (void); +void CFG_CloseConfig(void); // closes the currently open config file. -void CFG_ReadCvars (const char **vars, int32_t num_vars); +void CFG_ReadCvars(const char **vars, int32_t num_vars); // reads the values of cvars in the given list from the opened // config file. -void CFG_ReadCvarOverrides (const char **vars, int32_t num_vars); +void CFG_ReadCvarOverrides(const char **vars, int32_t num_vars); // convenience function, reading the "+" command line override // values of cvars in the given list. doesn't do anything with // the config file. call this after CFG_ReadCvars() and before // locking your cvars. -#endif /* __CFGFILE_H */ +#endif /* __CFGFILE_H */ diff --git a/source/chase.c b/source/chase.c index 3b987e8..bbec0b8 100644 --- a/source/chase.c +++ b/source/chase.c @@ -23,22 +23,22 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -cvar_t chase_back = {"chase_back", "100", CVAR_NONE}; -cvar_t chase_up = {"chase_up", "16", CVAR_NONE}; -cvar_t chase_right = {"chase_right", "0", CVAR_NONE}; -cvar_t chase_active = {"chase_active", "0", CVAR_NONE}; +cvar_t chase_back = {"chase_back", "100", CVAR_NONE}; +cvar_t chase_up = {"chase_up", "16", CVAR_NONE}; +cvar_t chase_right = {"chase_right", "0", CVAR_NONE}; +cvar_t chase_active = {"chase_active", "0", CVAR_NONE}; /* ============== Chase_Init ============== */ -void Chase_Init (void) +void Chase_Init(void) { - Cvar_RegisterVariable (&chase_back); - Cvar_RegisterVariable (&chase_up); - Cvar_RegisterVariable (&chase_right); - Cvar_RegisterVariable (&chase_active); + Cvar_RegisterVariable(&chase_back); + Cvar_RegisterVariable(&chase_up); + Cvar_RegisterVariable(&chase_right); + Cvar_RegisterVariable(&chase_active); } /* @@ -48,14 +48,14 @@ TraceLine TODO: impact on bmodels, monsters ============== */ -void TraceLine (vec3_t start, vec3_t end, vec3_t impact) +void TraceLine(vec3_t start, vec3_t end, vec3_t impact) { - trace_t trace; + trace_t trace; - memset (&trace, 0, sizeof(trace)); - SV_RecursiveHullCheck (cl.worldmodel->hulls, 0, 0, 1, start, end, &trace); + memset(&trace, 0, sizeof(trace)); + SV_RecursiveHullCheck(cl.worldmodel->hulls, 0, 0, 1, start, end, &trace); - VectorCopy (trace.endpos, impact); + VectorCopy(trace.endpos, impact); } /* @@ -63,7 +63,7 @@ void TraceLine (vec3_t start, vec3_t end, vec3_t impact) Chase_UpdateForClient -- johnfitz -- orient client based on camera. called after input ============== */ -void Chase_UpdateForClient (void) +void Chase_UpdateForClient(void) { //place camera @@ -81,38 +81,38 @@ Chase_UpdateForDrawing -- johnfitz -- orient camera based on client. called befo TODO: stay at least 8 units away from all walls in this leaf ============== */ -void Chase_UpdateForDrawing (void) +void Chase_UpdateForDrawing(void) { - int32_t i; - vec3_t forward, up, right; - vec3_t ideal, crosshair, temp; + int32_t i; + vec3_t forward, up, right; + vec3_t ideal, crosshair, temp; - AngleVectors (cl.viewangles, forward, right, up); + AngleVectors(cl.viewangles, forward, right, up); // calc ideal camera location before checking for walls - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) ideal[i] = cl.viewent.origin[i] - - forward[i]*chase_back.value - + right[i]*chase_right.value; - //+ up[i]*chase_up.value; + - forward[i] * chase_back.value + + right[i] * chase_right.value; + //+ up[i]*chase_up.value; ideal[2] = cl.viewent.origin[2] + chase_up.value; // make sure camera is not in or behind a wall TraceLine(r_refdef.vieworg, ideal, temp); - if (VectorLength(temp) != 0) + if(VectorLength(temp) != 0) VectorCopy(temp, ideal); // place camera - VectorCopy (ideal, r_refdef.vieworg); + VectorCopy(ideal, r_refdef.vieworg); // find the spot the player is looking at - VectorMA (cl.viewent.origin, 4096, forward, temp); - TraceLine (cl.viewent.origin, temp, crosshair); + VectorMA(cl.viewent.origin, 4096, forward, temp); + TraceLine(cl.viewent.origin, temp, crosshair); // calculate camera angles to look at the same spot - VectorSubtract (crosshair, r_refdef.vieworg, temp); - VectorAngles (temp, r_refdef.viewangles); - if (r_refdef.viewangles[PITCH] == 90 || r_refdef.viewangles[PITCH] == -90) + VectorSubtract(crosshair, r_refdef.vieworg, temp); + VectorAngles(temp, r_refdef.viewangles); + if(r_refdef.viewangles[PITCH] == 90 || r_refdef.viewangles[PITCH] == -90) r_refdef.viewangles[YAW] = cl.viewangles[YAW]; } diff --git a/source/cl_demo.c b/source/cl_demo.c index 55800d1..fca410c 100644 --- a/source/cl_demo.c +++ b/source/cl_demo.c @@ -21,7 +21,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -static void CL_FinishTimeDemo (void); +static void CL_FinishTimeDemo(void); /* ============================================================================== @@ -37,8 +37,8 @@ read from the demo file. */ // from ProQuake: space to fill out the demo header for record at any time -static byte demo_head[3][MAX_MSGLEN]; -static int32_t demo_head_size[2]; +static byte demo_head[3][MAX_MSGLEN]; +static int32_t demo_head_size[2]; /* ============== @@ -47,19 +47,19 @@ CL_StopPlayback Called when a demo file runs out, or the user starts a game ============== */ -void CL_StopPlayback (void) +void CL_StopPlayback(void) { - if (!cls.demoplayback) + if(!cls.demoplayback) return; - fclose (cls.demofile); + fclose(cls.demofile); cls.demoplayback = false; cls.demopaused = false; cls.demofile = NULL; cls.state = ca_disconnected; - if (cls.timedemo) - CL_FinishTimeDemo (); + if(cls.timedemo) + CL_FinishTimeDemo(); } /* @@ -69,66 +69,66 @@ CL_WriteDemoMessage Dumps the current net message, prefixed by the length and view angles ==================== */ -static void CL_WriteDemoMessage (void) +static void CL_WriteDemoMessage(void) { - int32_t len; - int32_t i; - float f; + int32_t len; + int32_t i; + float f; - len = LittleLong (net_message.cursize); - fwrite (&len, 4, 1, cls.demofile); - for (i = 0; i < 3; i++) + len = LittleLong(net_message.cursize); + fwrite(&len, 4, 1, cls.demofile); + for(i = 0; i < 3; i++) { - f = LittleFloat (cl.viewangles[i]); - fwrite (&f, 4, 1, cls.demofile); + f = LittleFloat(cl.viewangles[i]); + fwrite(&f, 4, 1, cls.demofile); } - fwrite (net_message.data, net_message.cursize, 1, cls.demofile); - fflush (cls.demofile); + fwrite(net_message.data, net_message.cursize, 1, cls.demofile); + fflush(cls.demofile); } -static int32_t CL_GetDemoMessage (void) +static int32_t CL_GetDemoMessage(void) { - int32_t r, i; - float f; + int32_t r, i; + float f; - if (cls.demopaused) + if(cls.demopaused) return 0; // decide if it is time to grab the next message - if (cls.signon == SIGNONS) // always grab until fully connected + if(cls.signon == SIGNONS) // always grab until fully connected { - if (cls.timedemo) + if(cls.timedemo) { - if (host_framecount == cls.td_lastframe) - return 0; // already read this frame's message + if(host_framecount == cls.td_lastframe) + return 0; // already read this frame's message cls.td_lastframe = host_framecount; - // if this is the second frame, grab the real td_starttime - // so the bogus time on the first frame doesn't count - if (host_framecount == cls.td_startframe + 1) + // if this is the second frame, grab the real td_starttime + // so the bogus time on the first frame doesn't count + if(host_framecount == cls.td_startframe + 1) cls.td_starttime = realtime; } - else if (/* cl.time > 0 && */ cl.time <= cl.mtime[0]) + else if(/* cl.time > 0 && */ cl.time <= cl.mtime[0]) { - return 0; // don't need another message yet + return 0; // don't need another message yet } } // get the next message - fread (&net_message.cursize, 4, 1, cls.demofile); - VectorCopy (cl.mviewangles[0], cl.mviewangles[1]); - for (i = 0 ; i < 3 ; i++) + fread(&net_message.cursize, 4, 1, cls.demofile); + VectorCopy(cl.mviewangles[0], cl.mviewangles[1]); + for(i = 0 ; i < 3 ; i++) { - r = fread (&f, 4, 1, cls.demofile); - cl.mviewangles[0][i] = LittleFloat (f); + r = fread(&f, 4, 1, cls.demofile); + cl.mviewangles[0][i] = LittleFloat(f); } - net_message.cursize = LittleLong (net_message.cursize); - if (net_message.cursize > MAX_MSGLEN) - Sys_Error ("Demo message > MAX_MSGLEN"); - r = fread (net_message.data, net_message.cursize, 1, cls.demofile); - if (r != 1) + net_message.cursize = LittleLong(net_message.cursize); + if(net_message.cursize > MAX_MSGLEN) + Sys_Error("Demo message > MAX_MSGLEN"); + r = fread(net_message.data, net_message.cursize, 1, cls.demofile); + if(r != 1) { - CL_StopPlayback (); + CL_StopPlayback(); return 0; } @@ -142,34 +142,34 @@ CL_GetMessage Handles recording and playback of demos, on top of NET_ code ==================== */ -int32_t CL_GetMessage (void) +int32_t CL_GetMessage(void) { - int32_t r; + int32_t r; - if (cls.demoplayback) - return CL_GetDemoMessage (); + if(cls.demoplayback) + return CL_GetDemoMessage(); - while (1) + while(1) { - r = NET_GetMessage (cls.netcon); + r = NET_GetMessage(cls.netcon); - if (r != 1 && r != 2) + if(r != 1 && r != 2) return r; - // discard nop keepalive message - if (net_message.cursize == 1 && net_message.data[0] == svc_nop) - Con_Printf ("<-- server to client keepalive\n"); + // discard nop keepalive message + if(net_message.cursize == 1 && net_message.data[0] == svc_nop) + Con_Printf("<-- server to client keepalive\n"); else break; } - if (cls.demorecording) - CL_WriteDemoMessage (); + if(cls.demorecording) + CL_WriteDemoMessage(); - if (cls.signon < 2) + if(cls.signon < 2) { - // record messages before full connection, so that a - // demo record can happen after connection is done + // record messages before full connection, so that a + // demo record can happen after connection is done memcpy(demo_head[cls.signon], net_message.data, net_message.cursize); demo_head_size[cls.signon] = net_message.cursize; } @@ -185,30 +185,30 @@ CL_Stop_f stop recording a demo ==================== */ -void CL_Stop_f (void) +void CL_Stop_f(void) { - if (cmd_source != src_command) + if(cmd_source != src_command) return; - if (!cls.demorecording) + if(!cls.demorecording) { - Con_Printf ("Not recording a demo.\n"); + Con_Printf("Not recording a demo.\n"); return; } // write a disconnect message to the demo file - SZ_Clear (&net_message); - MSG_WriteByte (&net_message, svc_disconnect); - CL_WriteDemoMessage (); + SZ_Clear(&net_message); + MSG_WriteByte(&net_message, svc_disconnect); + CL_WriteDemoMessage(); // finish up - fclose (cls.demofile); + fclose(cls.demofile); cls.demofile = NULL; cls.demorecording = false; - Con_Printf ("Completed demo\n"); - + Con_Printf("Completed demo\n"); + // ericw -- update demo tab-completion list - DemoList_Rebuild (); + DemoList_Rebuild(); } /* @@ -218,44 +218,44 @@ CL_Record_f record [cd track] ==================== */ -void CL_Record_f (void) +void CL_Record_f(void) { - int32_t c; - char name[MAX_OSPATH]; - int32_t track; + int32_t c; + char name[MAX_OSPATH]; + int32_t track; - if (cmd_source != src_command) + if(cmd_source != src_command) return; - if (cls.demoplayback) + if(cls.demoplayback) { - Con_Printf ("Can't record during demo playback\n"); + Con_Printf("Can't record during demo playback\n"); return; } - if (cls.demorecording) + if(cls.demorecording) CL_Stop_f(); c = Cmd_Argc(); - if (c != 2 && c != 3 && c != 4) + if(c != 2 && c != 3 && c != 4) { - Con_Printf ("record [ [cd track]]\n"); + Con_Printf("record [ [cd track]]\n"); return; } - if (strstr(Cmd_Argv(1), "..")) + if(strstr(Cmd_Argv(1), "..")) { - Con_Printf ("Relative pathnames are not allowed.\n"); + Con_Printf("Relative pathnames are not allowed.\n"); return; } - if (c == 2 && cls.state == ca_connected) + if(c == 2 && cls.state == ca_connected) { #if 0 Con_Printf("Can not record - already connected to server\nClient demo recording must be started before connecting\n"); return; #endif - if (cls.signon < 2) + if(cls.signon < 2) { Con_Printf("Can't record - try again when connected\n"); return; @@ -263,50 +263,50 @@ void CL_Record_f (void) } // write the forced cd track number, or -1 - if (c == 4) + if(c == 4) { track = atoi(Cmd_Argv(3)); - Con_Printf ("Forcing CD track to %" PRIi32 "\n", cls.forcetrack); + Con_Printf("Forcing CD track to %" PRIi32 "\n", cls.forcetrack); } else { track = -1; } - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); + q_snprintf(name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); // start the map up - if (c > 2) + if(c > 2) { - Cmd_ExecuteString ( va("map %s", Cmd_Argv(2)), src_command); - if (cls.state != ca_connected) + Cmd_ExecuteString(va("map %s", Cmd_Argv(2)), src_command); + if(cls.state != ca_connected) return; } // open the demo file - COM_AddExtension (name, ".dem", sizeof(name)); + COM_AddExtension(name, ".dem", sizeof(name)); - Con_Printf ("recording to %s.\n", name); - cls.demofile = fopen (name, "wb"); - if (!cls.demofile) + Con_Printf("recording to %s.\n", name); + cls.demofile = fopen(name, "wb"); + if(!cls.demofile) { - Con_Printf ("ERROR: couldn't create %s\n", name); + Con_Printf("ERROR: couldn't create %s\n", name); return; } cls.forcetrack = track; - fprintf (cls.demofile, "%" PRIi32 "\n", cls.forcetrack); + fprintf(cls.demofile, "%" PRIi32 "\n", cls.forcetrack); cls.demorecording = true; // from ProQuake: initialize the demo file if we're already connected - if (c == 2 && cls.state == ca_connected) + if(c == 2 && cls.state == ca_connected) { byte *data = net_message.data; int32_t cursize = net_message.cursize; int32_t i; - for (i = 0; i < 2; i++) + for(i = 0; i < 2; i++) { net_message.data = demo_head[i]; net_message.cursize = demo_head_size[i]; @@ -314,54 +314,54 @@ void CL_Record_f (void) } net_message.data = demo_head[2]; - SZ_Clear (&net_message); + SZ_Clear(&net_message); // current names, colors, and frag counts - for (i = 0; i < cl.maxclients; i++) + for(i = 0; i < cl.maxclients; i++) { - MSG_WriteByte (&net_message, svc_updatename); - MSG_WriteByte (&net_message, i); - MSG_WriteString (&net_message, cl.scores[i].name); - MSG_WriteByte (&net_message, svc_updatefrags); - MSG_WriteByte (&net_message, i); - MSG_WriteShort (&net_message, cl.scores[i].frags); - MSG_WriteByte (&net_message, svc_updatecolors); - MSG_WriteByte (&net_message, i); - MSG_WriteByte (&net_message, cl.scores[i].colors); + MSG_WriteByte(&net_message, svc_updatename); + MSG_WriteByte(&net_message, i); + MSG_WriteString(&net_message, cl.scores[i].name); + MSG_WriteByte(&net_message, svc_updatefrags); + MSG_WriteByte(&net_message, i); + MSG_WriteShort(&net_message, cl.scores[i].frags); + MSG_WriteByte(&net_message, svc_updatecolors); + MSG_WriteByte(&net_message, i); + MSG_WriteByte(&net_message, cl.scores[i].colors); } // send all current light styles - for (i = 0; i < MAX_LIGHTSTYLES; i++) + for(i = 0; i < MAX_LIGHTSTYLES; i++) { - MSG_WriteByte (&net_message, svc_lightstyle); - MSG_WriteByte (&net_message, i); - MSG_WriteString (&net_message, cl_lightstyle[i].map); + MSG_WriteByte(&net_message, svc_lightstyle); + MSG_WriteByte(&net_message, i); + MSG_WriteString(&net_message, cl_lightstyle[i].map); } // what about the CD track or SVC fog... future consideration. - MSG_WriteByte (&net_message, svc_updatestat); - MSG_WriteByte (&net_message, STAT_TOTALSECRETS); - MSG_WriteLong (&net_message, cl.stats[STAT_TOTALSECRETS]); + MSG_WriteByte(&net_message, svc_updatestat); + MSG_WriteByte(&net_message, STAT_TOTALSECRETS); + MSG_WriteLong(&net_message, cl.stats[STAT_TOTALSECRETS]); - MSG_WriteByte (&net_message, svc_updatestat); - MSG_WriteByte (&net_message, STAT_TOTALMONSTERS); - MSG_WriteLong (&net_message, cl.stats[STAT_TOTALMONSTERS]); + MSG_WriteByte(&net_message, svc_updatestat); + MSG_WriteByte(&net_message, STAT_TOTALMONSTERS); + MSG_WriteLong(&net_message, cl.stats[STAT_TOTALMONSTERS]); - MSG_WriteByte (&net_message, svc_updatestat); - MSG_WriteByte (&net_message, STAT_SECRETS); - MSG_WriteLong (&net_message, cl.stats[STAT_SECRETS]); + MSG_WriteByte(&net_message, svc_updatestat); + MSG_WriteByte(&net_message, STAT_SECRETS); + MSG_WriteLong(&net_message, cl.stats[STAT_SECRETS]); - MSG_WriteByte (&net_message, svc_updatestat); - MSG_WriteByte (&net_message, STAT_MONSTERS); - MSG_WriteLong (&net_message, cl.stats[STAT_MONSTERS]); + MSG_WriteByte(&net_message, svc_updatestat); + MSG_WriteByte(&net_message, STAT_MONSTERS); + MSG_WriteLong(&net_message, cl.stats[STAT_MONSTERS]); // view entity - MSG_WriteByte (&net_message, svc_setview); - MSG_WriteShort (&net_message, cl.viewentity); + MSG_WriteByte(&net_message, svc_setview); + MSG_WriteShort(&net_message, cl.viewentity); // signon - MSG_WriteByte (&net_message, svc_signonnum); - MSG_WriteByte (&net_message, 3); + MSG_WriteByte(&net_message, svc_signonnum); + MSG_WriteByte(&net_message, 3); CL_WriteDemoMessage(); @@ -379,35 +379,35 @@ CL_PlayDemo_f play [demoname] ==================== */ -void CL_PlayDemo_f (void) +void CL_PlayDemo_f(void) { - char name[MAX_OSPATH]; - int32_t i, c; + char name[MAX_OSPATH]; + int32_t i, c; bool neg; - if (cmd_source != src_command) + if(cmd_source != src_command) return; - if (Cmd_Argc() != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("playdemo : plays a demo\n"); + Con_Printf("playdemo : plays a demo\n"); return; } // disconnect from server - CL_Disconnect (); + CL_Disconnect(); // open the demo file - q_strlcpy (name, Cmd_Argv(1), sizeof(name)); - COM_AddExtension (name, ".dem", sizeof(name)); + q_strlcpy(name, Cmd_Argv(1), sizeof(name)); + COM_AddExtension(name, ".dem", sizeof(name)); - Con_Printf ("Playing demo from %s.\n", name); + Con_Printf("Playing demo from %s.\n", name); - COM_FOpenFile (name, &cls.demofile, NULL); - if (!cls.demofile) + COM_FOpenFile(name, &cls.demofile, NULL); + if(!cls.demofile) { - Con_Printf ("ERROR: couldn't open %s\n", name); - cls.demonum = -1; // stop demo loop + Con_Printf("ERROR: couldn't open %s\n", name); + cls.demonum = -1; // stop demo loop return; } @@ -420,27 +420,28 @@ void CL_PlayDemo_f (void) neg = false; // read a decimal integer possibly with a leading '-', // followed by a '\n': - for (i = 0; i < 13; i++) + for(i = 0; i < 13; i++) { c = getc(cls.demofile); - if (c == '\n') + if(c == '\n') break; - if (c == '-') { + if(c == '-') + { neg = true; continue; } // check for multiple '-' or legal digits? meh... cls.forcetrack = cls.forcetrack * 10 + (c - '0'); } - if (c != '\n') + if(c != '\n') { - fclose (cls.demofile); + fclose(cls.demofile); cls.demofile = NULL; - cls.demonum = -1; // stop demo loop - Con_Printf ("ERROR: demo \"%s\" is invalid\n", name); + cls.demonum = -1; // stop demo loop + Con_Printf("ERROR: demo \"%s\" is invalid\n", name); return; } - if (neg) + if(neg) cls.forcetrack = -cls.forcetrack; cls.demoplayback = true; @@ -457,19 +458,19 @@ CL_FinishTimeDemo ==================== */ -static void CL_FinishTimeDemo (void) +static void CL_FinishTimeDemo(void) { - int32_t frames; - float time; + int32_t frames; + float time; cls.timedemo = false; // the first frame didn't count frames = (host_framecount - cls.td_startframe) - 1; time = realtime - cls.td_starttime; - if (!time) + if(!time) time = 1; - Con_Printf ("%" PRIi32 " frames %5.1f seconds %5.1f fps\n", frames, time, frames/time); + Con_Printf("%" PRIi32 " frames %5.1f seconds %5.1f fps\n", frames, time, frames / time); } /* @@ -479,19 +480,19 @@ CL_TimeDemo_f timedemo [demoname] ==================== */ -void CL_TimeDemo_f (void) +void CL_TimeDemo_f(void) { - if (cmd_source != src_command) + if(cmd_source != src_command) return; - if (Cmd_Argc() != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("timedemo : gets demo speeds\n"); + Con_Printf("timedemo : gets demo speeds\n"); return; } - CL_PlayDemo_f (); - if (!cls.demofile) + CL_PlayDemo_f(); + if(!cls.demofile) return; // cls.td_starttime will be grabbed at the second frame of the demo, so @@ -499,6 +500,6 @@ void CL_TimeDemo_f (void) cls.timedemo = true; cls.td_startframe = host_framecount; - cls.td_lastframe = -1; // get a new message this frame + cls.td_lastframe = -1; // get a new message this frame } diff --git a/source/cl_input.c b/source/cl_input.c index 6844fe3..0301af0 100644 --- a/source/cl_input.c +++ b/source/cl_input.c @@ -51,117 +51,221 @@ state bit 2 is edge triggered on the down to up transition */ -kbutton_t in_mlook, in_klook; -kbutton_t in_left, in_right, in_forward, in_back; -kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; -kbutton_t in_strafe, in_speed, in_use, in_jump, in_attack; -kbutton_t in_up, in_down; +kbutton_t in_mlook, in_klook; +kbutton_t in_left, in_right, in_forward, in_back; +kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; +kbutton_t in_strafe, in_speed, in_use, in_jump, in_attack; +kbutton_t in_up, in_down; -int32_t in_impulse; +int32_t in_impulse; -void KeyDown (kbutton_t *b) +void KeyDown(kbutton_t *b) { - int32_t k; - const char *c; + int32_t k; + const char *c; c = Cmd_Argv(1); - if (c[0]) + if(c[0]) k = atoi(c); else - k = -1; // typed manually at the console for continuous down + k = -1; // typed manually at the console for continuous down - if (k == b->down[0] || k == b->down[1]) - return; // repeating key + if(k == b->down[0] || k == b->down[1]) + return; // repeating key - if (!b->down[0]) + if(!b->down[0]) b->down[0] = k; - else if (!b->down[1]) + else if(!b->down[1]) b->down[1] = k; else { - Con_Printf ("Three keys down for a button!\n"); + Con_Printf("Three keys down for a button!\n"); return; } - if (b->state & 1) - return; // still down - b->state |= 1 + 2; // down + impulse down + if(b->state & 1) + return; // still down + b->state |= 1 + 2; // down + impulse down } -void KeyUp (kbutton_t *b) +void KeyUp(kbutton_t *b) { - int32_t k; - const char *c; + int32_t k; + const char *c; c = Cmd_Argv(1); - if (c[0]) + if(c[0]) k = atoi(c); else - { // typed manually at the console, assume for unsticking, so clear all + { + // typed manually at the console, assume for unsticking, so clear all b->down[0] = b->down[1] = 0; - b->state = 4; // impulse up + b->state = 4; // impulse up return; } - if (b->down[0] == k) + if(b->down[0] == k) b->down[0] = 0; - else if (b->down[1] == k) + else if(b->down[1] == k) b->down[1] = 0; else - return; // key up without coresponding down (menu pass through) - if (b->down[0] || b->down[1]) - return; // some other key is still holding it down + return; // key up without coresponding down (menu pass through) + if(b->down[0] || b->down[1]) + return; // some other key is still holding it down - if (!(b->state & 1)) - return; // still up (this should not happen) - b->state &= ~1; // now up - b->state |= 4; // impulse up + if(!(b->state & 1)) + return; // still up (this should not happen) + b->state &= ~1; // now up + b->state |= 4; // impulse up } -void IN_KLookDown (void) {KeyDown(&in_klook);} -void IN_KLookUp (void) {KeyUp(&in_klook);} -void IN_MLookDown (void) {KeyDown(&in_mlook);} -void IN_MLookUp (void) { +void IN_KLookDown(void) +{ + KeyDown(&in_klook); +} +void IN_KLookUp(void) +{ + KeyUp(&in_klook); +} +void IN_MLookDown(void) +{ + KeyDown(&in_mlook); +} +void IN_MLookUp(void) +{ KeyUp(&in_mlook); - if ( !(in_mlook.state&1) && lookspring.value) + if(!(in_mlook.state & 1) && lookspring.value) V_StartPitchDrift(); } -void IN_UpDown(void) {KeyDown(&in_up);} -void IN_UpUp(void) {KeyUp(&in_up);} -void IN_DownDown(void) {KeyDown(&in_down);} -void IN_DownUp(void) {KeyUp(&in_down);} -void IN_LeftDown(void) {KeyDown(&in_left);} -void IN_LeftUp(void) {KeyUp(&in_left);} -void IN_RightDown(void) {KeyDown(&in_right);} -void IN_RightUp(void) {KeyUp(&in_right);} -void IN_ForwardDown(void) {KeyDown(&in_forward);} -void IN_ForwardUp(void) {KeyUp(&in_forward);} -void IN_BackDown(void) {KeyDown(&in_back);} -void IN_BackUp(void) {KeyUp(&in_back);} -void IN_LookupDown(void) {KeyDown(&in_lookup);} -void IN_LookupUp(void) {KeyUp(&in_lookup);} -void IN_LookdownDown(void) {KeyDown(&in_lookdown);} -void IN_LookdownUp(void) {KeyUp(&in_lookdown);} -void IN_MoveleftDown(void) {KeyDown(&in_moveleft);} -void IN_MoveleftUp(void) {KeyUp(&in_moveleft);} -void IN_MoverightDown(void) {KeyDown(&in_moveright);} -void IN_MoverightUp(void) {KeyUp(&in_moveright);} +void IN_UpDown(void) +{ + KeyDown(&in_up); +} +void IN_UpUp(void) +{ + KeyUp(&in_up); +} +void IN_DownDown(void) +{ + KeyDown(&in_down); +} +void IN_DownUp(void) +{ + KeyUp(&in_down); +} +void IN_LeftDown(void) +{ + KeyDown(&in_left); +} +void IN_LeftUp(void) +{ + KeyUp(&in_left); +} +void IN_RightDown(void) +{ + KeyDown(&in_right); +} +void IN_RightUp(void) +{ + KeyUp(&in_right); +} +void IN_ForwardDown(void) +{ + KeyDown(&in_forward); +} +void IN_ForwardUp(void) +{ + KeyUp(&in_forward); +} +void IN_BackDown(void) +{ + KeyDown(&in_back); +} +void IN_BackUp(void) +{ + KeyUp(&in_back); +} +void IN_LookupDown(void) +{ + KeyDown(&in_lookup); +} +void IN_LookupUp(void) +{ + KeyUp(&in_lookup); +} +void IN_LookdownDown(void) +{ + KeyDown(&in_lookdown); +} +void IN_LookdownUp(void) +{ + KeyUp(&in_lookdown); +} +void IN_MoveleftDown(void) +{ + KeyDown(&in_moveleft); +} +void IN_MoveleftUp(void) +{ + KeyUp(&in_moveleft); +} +void IN_MoverightDown(void) +{ + KeyDown(&in_moveright); +} +void IN_MoverightUp(void) +{ + KeyUp(&in_moveright); +} -void IN_SpeedDown(void) {KeyDown(&in_speed);} -void IN_SpeedUp(void) {KeyUp(&in_speed);} -void IN_StrafeDown(void) {KeyDown(&in_strafe);} -void IN_StrafeUp(void) {KeyUp(&in_strafe);} +void IN_SpeedDown(void) +{ + KeyDown(&in_speed); +} +void IN_SpeedUp(void) +{ + KeyUp(&in_speed); +} +void IN_StrafeDown(void) +{ + KeyDown(&in_strafe); +} +void IN_StrafeUp(void) +{ + KeyUp(&in_strafe); +} -void IN_AttackDown(void) {KeyDown(&in_attack);} -void IN_AttackUp(void) {KeyUp(&in_attack);} +void IN_AttackDown(void) +{ + KeyDown(&in_attack); +} +void IN_AttackUp(void) +{ + KeyUp(&in_attack); +} -void IN_UseDown (void) {KeyDown(&in_use);} -void IN_UseUp (void) {KeyUp(&in_use);} -void IN_JumpDown (void) {KeyDown(&in_jump);} -void IN_JumpUp (void) {KeyUp(&in_jump);} +void IN_UseDown(void) +{ + KeyDown(&in_use); +} +void IN_UseUp(void) +{ + KeyUp(&in_use); +} +void IN_JumpDown(void) +{ + KeyDown(&in_jump); +} +void IN_JumpUp(void) +{ + KeyUp(&in_jump); +} -void IN_Impulse (void) {in_impulse=Q_atoi(Cmd_Argv(1));} +void IN_Impulse(void) +{ + in_impulse = Q_atoi(Cmd_Argv(1)); +} /* =============== @@ -173,46 +277,46 @@ Returns 0.25 if a key was pressed and released during the frame, 1.0 if held for the entire time =============== */ -float CL_KeyState (kbutton_t *key) +float CL_KeyState(kbutton_t *key) { - float val; - bool impulsedown, impulseup, down; + float val; + bool impulsedown, impulseup, down; impulsedown = key->state & 2; impulseup = key->state & 4; down = key->state & 1; val = 0; - if (impulsedown && !impulseup) + if(impulsedown && !impulseup) { - if (down) - val = 0.5; // pressed and held this frame + if(down) + val = 0.5; // pressed and held this frame else - val = 0; // I_Error (); + val = 0; // I_Error (); } - if (impulseup && !impulsedown) + if(impulseup && !impulsedown) { - if (down) - val = 0; // I_Error (); + if(down) + val = 0; // I_Error (); else - val = 0; // released this frame + val = 0; // released this frame } - if (!impulsedown && !impulseup) + if(!impulsedown && !impulseup) { - if (down) - val = 1.0; // held the entire frame + if(down) + val = 1.0; // held the entire frame else - val = 0; // up the entire frame + val = 0; // up the entire frame } - if (impulsedown && impulseup) + if(impulsedown && impulseup) { - if (down) - val = 0.75; // released and re-pressed this frame + if(down) + val = 0.75; // released and re-pressed this frame else - val = 0.25; // pressed and released this frame + val = 0.25; // pressed and released this frame } - key->state &= 1; // clear impulses + key->state &= 1; // clear impulses return val; } @@ -220,19 +324,19 @@ float CL_KeyState (kbutton_t *key) //========================================================================== -cvar_t cl_upspeed = {"cl_upspeed","200",CVAR_NONE}; -cvar_t cl_forwardspeed = {"cl_forwardspeed","200", CVAR_ARCHIVE}; -cvar_t cl_backspeed = {"cl_backspeed","200", CVAR_ARCHIVE}; -cvar_t cl_sidespeed = {"cl_sidespeed","350",CVAR_NONE}; +cvar_t cl_upspeed = {"cl_upspeed", "200", CVAR_NONE}; +cvar_t cl_forwardspeed = {"cl_forwardspeed", "200", CVAR_ARCHIVE}; +cvar_t cl_backspeed = {"cl_backspeed", "200", CVAR_ARCHIVE}; +cvar_t cl_sidespeed = {"cl_sidespeed", "350", CVAR_NONE}; -cvar_t cl_movespeedkey = {"cl_movespeedkey","2.0",CVAR_NONE}; +cvar_t cl_movespeedkey = {"cl_movespeedkey", "2.0", CVAR_NONE}; -cvar_t cl_yawspeed = {"cl_yawspeed","140",CVAR_NONE}; -cvar_t cl_pitchspeed = {"cl_pitchspeed","150",CVAR_NONE}; +cvar_t cl_yawspeed = {"cl_yawspeed", "140", CVAR_NONE}; +cvar_t cl_pitchspeed = {"cl_pitchspeed", "150", CVAR_NONE}; -cvar_t cl_anglespeedkey = {"cl_anglespeedkey","1.5",CVAR_NONE}; +cvar_t cl_anglespeedkey = {"cl_anglespeedkey", "1.5", CVAR_NONE}; -cvar_t cl_alwaysrun = {"cl_alwaysrun","0",CVAR_ARCHIVE}; // QuakeSpasm -- new always run +cvar_t cl_alwaysrun = {"cl_alwaysrun", "0", CVAR_ARCHIVE}; // QuakeSpasm -- new always run /* ================ @@ -241,48 +345,48 @@ CL_AdjustAngles Moves the local angle positions ================ */ -void CL_AdjustAngles (void) +void CL_AdjustAngles(void) { - float speed; - float up, down; + float speed; + float up, down; - if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) + if((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) speed = host_frametime * cl_anglespeedkey.value; else speed = host_frametime; - if (!(in_strafe.state & 1)) + if(!(in_strafe.state & 1)) { - cl.viewangles[YAW] -= speed*cl_yawspeed.value*CL_KeyState (&in_right); - cl.viewangles[YAW] += speed*cl_yawspeed.value*CL_KeyState (&in_left); + cl.viewangles[YAW] -= speed * cl_yawspeed.value * CL_KeyState(&in_right); + cl.viewangles[YAW] += speed * cl_yawspeed.value * CL_KeyState(&in_left); cl.viewangles[YAW] = anglemod(cl.viewangles[YAW]); } - if (in_klook.state & 1) + if(in_klook.state & 1) { - V_StopPitchDrift (); - cl.viewangles[PITCH] -= speed*cl_pitchspeed.value * CL_KeyState (&in_forward); - cl.viewangles[PITCH] += speed*cl_pitchspeed.value * CL_KeyState (&in_back); + V_StopPitchDrift(); + cl.viewangles[PITCH] -= speed * cl_pitchspeed.value * CL_KeyState(&in_forward); + cl.viewangles[PITCH] += speed * cl_pitchspeed.value * CL_KeyState(&in_back); } - up = CL_KeyState (&in_lookup); + up = CL_KeyState(&in_lookup); down = CL_KeyState(&in_lookdown); - cl.viewangles[PITCH] -= speed*cl_pitchspeed.value * up; - cl.viewangles[PITCH] += speed*cl_pitchspeed.value * down; + cl.viewangles[PITCH] -= speed * cl_pitchspeed.value * up; + cl.viewangles[PITCH] += speed * cl_pitchspeed.value * down; - if (up || down) - V_StopPitchDrift (); + if(up || down) + V_StopPitchDrift(); //johnfitz -- variable pitch clamping - if (cl.viewangles[PITCH] > cl_maxpitch.value) + if(cl.viewangles[PITCH] > cl_maxpitch.value) cl.viewangles[PITCH] = cl_maxpitch.value; - if (cl.viewangles[PITCH] < cl_minpitch.value) + if(cl.viewangles[PITCH] < cl_minpitch.value) cl.viewangles[PITCH] = cl_minpitch.value; //johnfitz - if (cl.viewangles[ROLL] > 50) + if(cl.viewangles[ROLL] > 50) cl.viewangles[ROLL] = 50; - if (cl.viewangles[ROLL] < -50) + if(cl.viewangles[ROLL] < -50) cl.viewangles[ROLL] = -50; } @@ -293,37 +397,37 @@ CL_BaseMove Send the intended movement message to the server ================ */ -void CL_BaseMove (usercmd_t *cmd) +void CL_BaseMove(usercmd_t *cmd) { - if (cls.signon != SIGNONS) + if(cls.signon != SIGNONS) return; - CL_AdjustAngles (); + CL_AdjustAngles(); - Q_memset (cmd, 0, sizeof(*cmd)); + Q_memset(cmd, 0, sizeof(*cmd)); - if (in_strafe.state & 1) + if(in_strafe.state & 1) { - cmd->sidemove += cl_sidespeed.value * CL_KeyState (&in_right); - cmd->sidemove -= cl_sidespeed.value * CL_KeyState (&in_left); + cmd->sidemove += cl_sidespeed.value * CL_KeyState(&in_right); + cmd->sidemove -= cl_sidespeed.value * CL_KeyState(&in_left); } - cmd->sidemove += cl_sidespeed.value * CL_KeyState (&in_moveright); - cmd->sidemove -= cl_sidespeed.value * CL_KeyState (&in_moveleft); + cmd->sidemove += cl_sidespeed.value * CL_KeyState(&in_moveright); + cmd->sidemove -= cl_sidespeed.value * CL_KeyState(&in_moveleft); - cmd->upmove += cl_upspeed.value * CL_KeyState (&in_up); - cmd->upmove -= cl_upspeed.value * CL_KeyState (&in_down); + cmd->upmove += cl_upspeed.value * CL_KeyState(&in_up); + cmd->upmove -= cl_upspeed.value * CL_KeyState(&in_down); - if (! (in_klook.state & 1) ) + if(!(in_klook.state & 1)) { - cmd->forwardmove += cl_forwardspeed.value * CL_KeyState (&in_forward); - cmd->forwardmove -= cl_backspeed.value * CL_KeyState (&in_back); + cmd->forwardmove += cl_forwardspeed.value * CL_KeyState(&in_forward); + cmd->forwardmove -= cl_backspeed.value * CL_KeyState(&in_back); } // // adjust for speed key // - if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) + if((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) { cmd->forwardmove *= cl_movespeedkey.value; cmd->sidemove *= cl_movespeedkey.value; @@ -337,12 +441,12 @@ void CL_BaseMove (usercmd_t *cmd) CL_SendMove ============== */ -void CL_SendMove (const usercmd_t *cmd) +void CL_SendMove(const usercmd_t *cmd) { - int32_t i; - int32_t bits; - sizebuf_t buf; - byte data[128]; + int32_t i; + int32_t bits; + sizebuf_t buf; + byte data[128]; buf.maxsize = 128; buf.cursize = 0; @@ -353,57 +457,57 @@ void CL_SendMove (const usercmd_t *cmd) // // send the movement message // - MSG_WriteByte (&buf, clc_move); + MSG_WriteByte(&buf, clc_move); - MSG_WriteFloat (&buf, cl.mtime[0]); // so server can get ping times + MSG_WriteFloat(&buf, cl.mtime[0]); // so server can get ping times - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) //johnfitz -- 16-bit angles for PROTOCOL_FITZQUAKE - if (cl.protocol == PROTOCOL_NETQUAKE) - MSG_WriteAngle (&buf, cl.viewangles[i], cl.protocolflags); + if(cl.protocol == PROTOCOL_NETQUAKE) + MSG_WriteAngle(&buf, cl.viewangles[i], cl.protocolflags); else - MSG_WriteAngle16 (&buf, cl.viewangles[i], cl.protocolflags); - //johnfitz + MSG_WriteAngle16(&buf, cl.viewangles[i], cl.protocolflags); + //johnfitz - MSG_WriteShort (&buf, cmd->forwardmove); - MSG_WriteShort (&buf, cmd->sidemove); - MSG_WriteShort (&buf, cmd->upmove); + MSG_WriteShort(&buf, cmd->forwardmove); + MSG_WriteShort(&buf, cmd->sidemove); + MSG_WriteShort(&buf, cmd->upmove); // // send button bits // bits = 0; - if ( in_attack.state & 3 ) + if(in_attack.state & 3) bits |= 1; in_attack.state &= ~2; - if (in_jump.state & 3) + if(in_jump.state & 3) bits |= 2; in_jump.state &= ~2; - MSG_WriteByte (&buf, bits); + MSG_WriteByte(&buf, bits); - MSG_WriteByte (&buf, in_impulse); + MSG_WriteByte(&buf, in_impulse); in_impulse = 0; // // deliver the message // - if (cls.demoplayback) + if(cls.demoplayback) return; // // allways dump the first two message, because it may contain leftover inputs // from the last level // - if (++cl.movemessages <= 2) + if(++cl.movemessages <= 2) return; - if (NET_SendUnreliableMessage (cls.netcon, &buf) == -1) + if(NET_SendUnreliableMessage(cls.netcon, &buf) == -1) { - Con_Printf ("CL_SendMove: lost server connection\n"); - CL_Disconnect (); + Con_Printf("CL_SendMove: lost server connection\n"); + CL_Disconnect(); } } @@ -412,43 +516,43 @@ void CL_SendMove (const usercmd_t *cmd) CL_InitInput ============ */ -void CL_InitInput (void) +void CL_InitInput(void) { - Cmd_AddCommand ("+moveup",IN_UpDown); - Cmd_AddCommand ("-moveup",IN_UpUp); - Cmd_AddCommand ("+movedown",IN_DownDown); - Cmd_AddCommand ("-movedown",IN_DownUp); - Cmd_AddCommand ("+left",IN_LeftDown); - Cmd_AddCommand ("-left",IN_LeftUp); - Cmd_AddCommand ("+right",IN_RightDown); - Cmd_AddCommand ("-right",IN_RightUp); - Cmd_AddCommand ("+forward",IN_ForwardDown); - Cmd_AddCommand ("-forward",IN_ForwardUp); - Cmd_AddCommand ("+back",IN_BackDown); - Cmd_AddCommand ("-back",IN_BackUp); - Cmd_AddCommand ("+lookup", IN_LookupDown); - Cmd_AddCommand ("-lookup", IN_LookupUp); - Cmd_AddCommand ("+lookdown", IN_LookdownDown); - Cmd_AddCommand ("-lookdown", IN_LookdownUp); - Cmd_AddCommand ("+strafe", IN_StrafeDown); - Cmd_AddCommand ("-strafe", IN_StrafeUp); - Cmd_AddCommand ("+moveleft", IN_MoveleftDown); - Cmd_AddCommand ("-moveleft", IN_MoveleftUp); - Cmd_AddCommand ("+moveright", IN_MoverightDown); - Cmd_AddCommand ("-moveright", IN_MoverightUp); - Cmd_AddCommand ("+speed", IN_SpeedDown); - Cmd_AddCommand ("-speed", IN_SpeedUp); - Cmd_AddCommand ("+attack", IN_AttackDown); - Cmd_AddCommand ("-attack", IN_AttackUp); - Cmd_AddCommand ("+use", IN_UseDown); - Cmd_AddCommand ("-use", IN_UseUp); - Cmd_AddCommand ("+jump", IN_JumpDown); - Cmd_AddCommand ("-jump", IN_JumpUp); - Cmd_AddCommand ("impulse", IN_Impulse); - Cmd_AddCommand ("+klook", IN_KLookDown); - Cmd_AddCommand ("-klook", IN_KLookUp); - Cmd_AddCommand ("+mlook", IN_MLookDown); - Cmd_AddCommand ("-mlook", IN_MLookUp); + Cmd_AddCommand("+moveup", IN_UpDown); + Cmd_AddCommand("-moveup", IN_UpUp); + Cmd_AddCommand("+movedown", IN_DownDown); + Cmd_AddCommand("-movedown", IN_DownUp); + Cmd_AddCommand("+left", IN_LeftDown); + Cmd_AddCommand("-left", IN_LeftUp); + Cmd_AddCommand("+right", IN_RightDown); + Cmd_AddCommand("-right", IN_RightUp); + Cmd_AddCommand("+forward", IN_ForwardDown); + Cmd_AddCommand("-forward", IN_ForwardUp); + Cmd_AddCommand("+back", IN_BackDown); + Cmd_AddCommand("-back", IN_BackUp); + Cmd_AddCommand("+lookup", IN_LookupDown); + Cmd_AddCommand("-lookup", IN_LookupUp); + Cmd_AddCommand("+lookdown", IN_LookdownDown); + Cmd_AddCommand("-lookdown", IN_LookdownUp); + Cmd_AddCommand("+strafe", IN_StrafeDown); + Cmd_AddCommand("-strafe", IN_StrafeUp); + Cmd_AddCommand("+moveleft", IN_MoveleftDown); + Cmd_AddCommand("-moveleft", IN_MoveleftUp); + Cmd_AddCommand("+moveright", IN_MoverightDown); + Cmd_AddCommand("-moveright", IN_MoverightUp); + Cmd_AddCommand("+speed", IN_SpeedDown); + Cmd_AddCommand("-speed", IN_SpeedUp); + Cmd_AddCommand("+attack", IN_AttackDown); + Cmd_AddCommand("-attack", IN_AttackUp); + Cmd_AddCommand("+use", IN_UseDown); + Cmd_AddCommand("-use", IN_UseUp); + Cmd_AddCommand("+jump", IN_JumpDown); + Cmd_AddCommand("-jump", IN_JumpUp); + Cmd_AddCommand("impulse", IN_Impulse); + Cmd_AddCommand("+klook", IN_KLookDown); + Cmd_AddCommand("-klook", IN_KLookUp); + Cmd_AddCommand("+mlook", IN_MLookDown); + Cmd_AddCommand("-mlook", IN_MLookUp); } diff --git a/source/cl_main.c b/source/cl_main.c index ac3f8ec..ec2de00 100644 --- a/source/cl_main.c +++ b/source/cl_main.c @@ -28,40 +28,40 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // references them even when on a unix system. // these two are not intended to be set directly -cvar_t cl_name = {"_cl_name", "player", CVAR_ARCHIVE}; -cvar_t cl_color = {"_cl_color", "0", CVAR_ARCHIVE}; +cvar_t cl_name = {"_cl_name", "player", CVAR_ARCHIVE}; +cvar_t cl_color = {"_cl_color", "0", CVAR_ARCHIVE}; -cvar_t cl_shownet = {"cl_shownet","0",CVAR_NONE}; // can be 0, 1, or 2 -cvar_t cl_nolerp = {"cl_nolerp","0",CVAR_NONE}; +cvar_t cl_shownet = {"cl_shownet", "0", CVAR_NONE}; // can be 0, 1, or 2 +cvar_t cl_nolerp = {"cl_nolerp", "0", CVAR_NONE}; -cvar_t cfg_unbindall = {"cfg_unbindall", "1", CVAR_ARCHIVE}; +cvar_t cfg_unbindall = {"cfg_unbindall", "1", CVAR_ARCHIVE}; -cvar_t lookspring = {"lookspring","0", CVAR_ARCHIVE}; -cvar_t lookstrafe = {"lookstrafe","0", CVAR_ARCHIVE}; -cvar_t sensitivity = {"sensitivity","3", CVAR_ARCHIVE}; +cvar_t lookspring = {"lookspring", "0", CVAR_ARCHIVE}; +cvar_t lookstrafe = {"lookstrafe", "0", CVAR_ARCHIVE}; +cvar_t sensitivity = {"sensitivity", "3", CVAR_ARCHIVE}; -cvar_t m_pitch = {"m_pitch","0.022", CVAR_ARCHIVE}; -cvar_t m_yaw = {"m_yaw","0.022", CVAR_ARCHIVE}; -cvar_t m_forward = {"m_forward","1", CVAR_ARCHIVE}; -cvar_t m_side = {"m_side","0.8", CVAR_ARCHIVE}; +cvar_t m_pitch = {"m_pitch", "0.022", CVAR_ARCHIVE}; +cvar_t m_yaw = {"m_yaw", "0.022", CVAR_ARCHIVE}; +cvar_t m_forward = {"m_forward", "1", CVAR_ARCHIVE}; +cvar_t m_side = {"m_side", "0.8", CVAR_ARCHIVE}; -cvar_t cl_maxpitch = {"cl_maxpitch", "90", CVAR_ARCHIVE}; //johnfitz -- variable pitch clamping -cvar_t cl_minpitch = {"cl_minpitch", "-90", CVAR_ARCHIVE}; //johnfitz -- variable pitch clamping +cvar_t cl_maxpitch = {"cl_maxpitch", "90", CVAR_ARCHIVE}; //johnfitz -- variable pitch clamping +cvar_t cl_minpitch = {"cl_minpitch", "-90", CVAR_ARCHIVE}; //johnfitz -- variable pitch clamping -client_static_t cls; -client_state_t cl; +client_static_t cls; +client_state_t cl; // FIXME: put these on hunk? -entity_t cl_static_entities[MAX_STATIC_ENTITIES]; -lightstyle_t cl_lightstyle[MAX_LIGHTSTYLES]; -dlight_t cl_dlights[MAX_DLIGHTS]; +entity_t cl_static_entities[MAX_STATIC_ENTITIES]; +lightstyle_t cl_lightstyle[MAX_LIGHTSTYLES]; +dlight_t cl_dlights[MAX_DLIGHTS]; -entity_t *cl_entities; //johnfitz -- was a static array, now on hunk -int32_t cl_max_edicts; //johnfitz -- only changes when new map loads +entity_t *cl_entities; //johnfitz -- was a static array, now on hunk +int32_t cl_max_edicts; //johnfitz -- only changes when new map loads -int32_t cl_numvisedicts; -entity_t *cl_visedicts[MAX_VISEDICTS]; +int32_t cl_numvisedicts; +entity_t *cl_visedicts[MAX_VISEDICTS]; -extern cvar_t r_lerpmodels, r_lerpmove; //johnfitz +extern cvar_t r_lerpmodels, r_lerpmove; //johnfitz /* ===================== @@ -69,25 +69,25 @@ CL_ClearState ===================== */ -void CL_ClearState (void) +void CL_ClearState(void) { - if (!sv.active) - Host_ClearMemory (); + if(!sv.active) + Host_ClearMemory(); // wipe the entire cl structure - memset (&cl, 0, sizeof(cl)); + memset(&cl, 0, sizeof(cl)); - SZ_Clear (&cls.message); + SZ_Clear(&cls.message); // clear other arrays - memset (cl_dlights, 0, sizeof(cl_dlights)); - memset (cl_lightstyle, 0, sizeof(cl_lightstyle)); - memset (cl_temp_entities, 0, sizeof(cl_temp_entities)); - memset (cl_beams, 0, sizeof(cl_beams)); + memset(cl_dlights, 0, sizeof(cl_dlights)); + memset(cl_lightstyle, 0, sizeof(cl_lightstyle)); + memset(cl_temp_entities, 0, sizeof(cl_temp_entities)); + memset(cl_beams, 0, sizeof(cl_beams)); //johnfitz -- cl_entities is now dynamically allocated - cl_max_edicts = CLAMP (MIN_EDICTS,(int32_t)max_edicts.value,MAX_EDICTS); - cl_entities = (entity_t *) Hunk_AllocName (cl_max_edicts*sizeof(entity_t), "cl_entities"); + cl_max_edicts = CLAMP(MIN_EDICTS, (int32_t)max_edicts.value, MAX_EDICTS); + cl_entities = (entity_t *) Hunk_AllocName(cl_max_edicts * sizeof(entity_t), "cl_entities"); //johnfitz } @@ -99,32 +99,32 @@ Sends a disconnect message to the server This is also called on Host_Error, so it shouldn't cause any errors ===================== */ -void CL_Disconnect (void) +void CL_Disconnect(void) { - if (key_dest == key_message) - Key_EndChat (); // don't get stuck in chat mode + if(key_dest == key_message) + Key_EndChat(); // don't get stuck in chat mode // stop sounds (especially looping!) - S_StopAllSounds (true); + S_StopAllSounds(true); BGM_Stop(); // if running a local server, shut it down - if (cls.demoplayback) - CL_StopPlayback (); - else if (cls.state == ca_connected) + if(cls.demoplayback) + CL_StopPlayback(); + else if(cls.state == ca_connected) { - if (cls.demorecording) - CL_Stop_f (); + if(cls.demorecording) + CL_Stop_f(); - Con_DPrintf ("Sending clc_disconnect\n"); - SZ_Clear (&cls.message); - MSG_WriteByte (&cls.message, clc_disconnect); - NET_SendUnreliableMessage (cls.netcon, &cls.message); - SZ_Clear (&cls.message); - NET_Close (cls.netcon); + Con_DPrintf("Sending clc_disconnect\n"); + SZ_Clear(&cls.message); + MSG_WriteByte(&cls.message, clc_disconnect); + NET_SendUnreliableMessage(cls.netcon, &cls.message); + SZ_Clear(&cls.message); + NET_Close(cls.netcon); cls.state = ca_disconnected; - if (sv.active) + if(sv.active) Host_ShutdownServer(false); } @@ -134,11 +134,11 @@ void CL_Disconnect (void) cl.intermission = 0; } -void CL_Disconnect_f (void) +void CL_Disconnect_f(void) { - CL_Disconnect (); - if (sv.active) - Host_ShutdownServer (false); + CL_Disconnect(); + if(sv.active) + Host_ShutdownServer(false); } @@ -149,25 +149,25 @@ CL_EstablishConnection Host should be either "local" or a net address to be passed on ===================== */ -void CL_EstablishConnection (const char *host) +void CL_EstablishConnection(const char *host) { - if (cls.state == ca_dedicated) + if(cls.state == ca_dedicated) return; - if (cls.demoplayback) + if(cls.demoplayback) return; - CL_Disconnect (); + CL_Disconnect(); - cls.netcon = NET_Connect (host); - if (!cls.netcon) - Host_Error ("CL_Connect: connect failed\n"); - Con_DPrintf ("CL_EstablishConnection: connected to %s\n", host); + cls.netcon = NET_Connect(host); + if(!cls.netcon) + Host_Error("CL_Connect: connect failed\n"); + Con_DPrintf("CL_EstablishConnection: connected to %s\n", host); - cls.demonum = -1; // not in the demo loop now + cls.demonum = -1; // not in the demo loop now cls.state = ca_connected; - cls.signon = 0; // need all the signon messages before playing - MSG_WriteByte (&cls.message, clc_nop); // NAT Fix from ProQuake + cls.signon = 0; // need all the signon messages before playing + MSG_WriteByte(&cls.message, clc_nop); // NAT Fix from ProQuake } /* @@ -177,39 +177,39 @@ CL_SignonReply An svc_signonnum has been received, perform a client side setup ===================== */ -void CL_SignonReply (void) +void CL_SignonReply(void) { - char str[8192]; + char str[8192]; - Con_DPrintf ("CL_SignonReply: %" PRIi32 "\n", cls.signon); + Con_DPrintf("CL_SignonReply: %" PRIi32 "\n", cls.signon); - switch (cls.signon) + switch(cls.signon) { case 1: - MSG_WriteByte (&cls.message, clc_stringcmd); - MSG_WriteString (&cls.message, "prespawn"); + MSG_WriteByte(&cls.message, clc_stringcmd); + MSG_WriteString(&cls.message, "prespawn"); break; case 2: - MSG_WriteByte (&cls.message, clc_stringcmd); - MSG_WriteString (&cls.message, va("name \"%s\"\n", cl_name.string)); + MSG_WriteByte(&cls.message, clc_stringcmd); + MSG_WriteString(&cls.message, va("name \"%s\"\n", cl_name.string)); - MSG_WriteByte (&cls.message, clc_stringcmd); - MSG_WriteString (&cls.message, va("color %" PRIi32 " %" PRIi32 "\n", ((int32_t)cl_color.value)>>4, ((int32_t)cl_color.value)&15)); + MSG_WriteByte(&cls.message, clc_stringcmd); + MSG_WriteString(&cls.message, va("color %" PRIi32 " %" PRIi32 "\n", ((int32_t)cl_color.value) >> 4, ((int32_t)cl_color.value) & 15)); - MSG_WriteByte (&cls.message, clc_stringcmd); - sprintf (str, "spawn %s", cls.spawnparms); - MSG_WriteString (&cls.message, str); + MSG_WriteByte(&cls.message, clc_stringcmd); + sprintf(str, "spawn %s", cls.spawnparms); + MSG_WriteString(&cls.message, str); break; case 3: - MSG_WriteByte (&cls.message, clc_stringcmd); - MSG_WriteString (&cls.message, "begin"); - Cache_Report (); // print remaining memory + MSG_WriteByte(&cls.message, clc_stringcmd); + MSG_WriteString(&cls.message, "begin"); + Cache_Report(); // print remaining memory break; case 4: - SCR_EndLoadingPlaque (); // allow normal screen updates + SCR_EndLoadingPlaque(); // allow normal screen updates break; } } @@ -221,29 +221,29 @@ CL_NextDemo Called to play the next demo in the demo loop ===================== */ -void CL_NextDemo (void) +void CL_NextDemo(void) { - char str[1024]; + char str[1024]; - if (cls.demonum == -1) - return; // don't play demos + if(cls.demonum == -1) + return; // don't play demos - if (!cls.demos[cls.demonum][0] || cls.demonum == MAX_DEMOS) + if(!cls.demos[cls.demonum][0] || cls.demonum == MAX_DEMOS) { cls.demonum = 0; - if (!cls.demos[cls.demonum][0]) + if(!cls.demos[cls.demonum][0]) { - Con_Printf ("No demos listed with startdemos\n"); + Con_Printf("No demos listed with startdemos\n"); cls.demonum = -1; CL_Disconnect(); return; } } - SCR_BeginLoadingPlaque (); + SCR_BeginLoadingPlaque(); - sprintf (str,"playdemo %s\n", cls.demos[cls.demonum]); - Cbuf_InsertText (str); + sprintf(str, "playdemo %s\n", cls.demos[cls.demonum]); + Cbuf_InsertText(str); cls.demonum++; } @@ -252,24 +252,24 @@ void CL_NextDemo (void) CL_PrintEntities_f ============== */ -void CL_PrintEntities_f (void) +void CL_PrintEntities_f(void) { - entity_t *ent; - int32_t i; + entity_t *ent; + int32_t i; - if (cls.state != ca_connected) + if(cls.state != ca_connected) return; - for (i=0,ent=cl_entities ; imodel) + Con_Printf("%3" PRIi32 ":", i); + if(!ent->model) { - Con_Printf ("EMPTY\n"); + Con_Printf("EMPTY\n"); continue; } - Con_Printf ("%s:%2" PRIi32 " (%5.1f,%5.1f,%5.1f) [%5.1f %5.1f %5.1f]\n" - ,ent->model->name,ent->frame, ent->origin[0], ent->origin[1], ent->origin[2], ent->angles[0], ent->angles[1], ent->angles[2]); + Con_Printf("%s:%2" PRIi32 " (%5.1f,%5.1f,%5.1f) [%5.1f %5.1f %5.1f]\n" + , ent->model->name, ent->frame, ent->origin[0], ent->origin[1], ent->origin[2], ent->angles[0], ent->angles[1], ent->angles[2]); } } @@ -279,20 +279,20 @@ CL_AllocDlight =============== */ -dlight_t *CL_AllocDlight (int32_t key) +dlight_t *CL_AllocDlight(int32_t key) { - int32_t i; - dlight_t *dl; + int32_t i; + dlight_t *dl; // first look for an exact key match - if (key) + if(key) { dl = cl_dlights; - for (i=0 ; ikey == key) + if(dl->key == key) { - memset (dl, 0, sizeof(*dl)); + memset(dl, 0, sizeof(*dl)); dl->key = key; dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc return dl; @@ -302,11 +302,11 @@ dlight_t *CL_AllocDlight (int32_t key) // then look for anything else dl = cl_dlights; - for (i=0 ; idie < cl.time) + if(dl->die < cl.time) { - memset (dl, 0, sizeof(*dl)); + memset(dl, 0, sizeof(*dl)); dl->key = key; dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc return dl; @@ -314,7 +314,7 @@ dlight_t *CL_AllocDlight (int32_t key) } dl = &cl_dlights[0]; - memset (dl, 0, sizeof(*dl)); + memset(dl, 0, sizeof(*dl)); dl->key = key; dl->color[0] = dl->color[1] = dl->color[2] = 1; //johnfitz -- lit support via lordhavoc return dl; @@ -327,22 +327,22 @@ CL_DecayLights =============== */ -void CL_DecayLights (void) +void CL_DecayLights(void) { - int32_t i; - dlight_t *dl; - float time; + int32_t i; + dlight_t *dl; + float time; time = cl.time - cl.oldtime; dl = cl_dlights; - for (i=0 ; idie < cl.time || !dl->radius) + if(dl->die < cl.time || !dl->radius) continue; - dl->radius -= time*dl->decay; - if (dl->radius < 0) + dl->radius -= time * dl->decay; + if(dl->radius < 0) dl->radius = 0; } } @@ -356,19 +356,19 @@ Determines the fraction between the last two messages that the objects should be put at. =============== */ -float CL_LerpPoint (void) +float CL_LerpPoint(void) { - float f, frac; + float f, frac; f = cl.mtime[0] - cl.mtime[1]; - if (!f || cls.timedemo || sv.active) + if(!f || cls.timedemo || sv.active) { cl.time = cl.mtime[0]; return 1; } - if (f > 0.1) // dropped packet, or start of demo + if(f > 0.1) // dropped packet, or start of demo { cl.mtime[1] = cl.mtime[0] - 0.1; f = 0.1; @@ -376,21 +376,21 @@ float CL_LerpPoint (void) frac = (cl.time - cl.mtime[1]) / f; - if (frac < 0) + if(frac < 0) { - if (frac < -0.01) + if(frac < -0.01) cl.time = cl.mtime[1]; frac = 0; } - else if (frac > 1) + else if(frac > 1) { - if (frac > 1.01) + if(frac > 1.01) cl.time = cl.mtime[0]; frac = 1; } //johnfitz -- better nolerp behavior - if (cl_nolerp.value) + if(cl_nolerp.value) return 1; //johnfitz @@ -402,179 +402,182 @@ float CL_LerpPoint (void) CL_RelinkEntities =============== */ -void CL_RelinkEntities (void) +void CL_RelinkEntities(void) { - entity_t *ent; - int32_t i, j; - float frac, f, d; - vec3_t delta; - float bobjrotate; - vec3_t oldorg; - dlight_t *dl; + entity_t *ent; + int32_t i, j; + float frac, f, d; + vec3_t delta; + float bobjrotate; + vec3_t oldorg; + dlight_t *dl; // determine partial update time - frac = CL_LerpPoint (); + frac = CL_LerpPoint(); cl_numvisedicts = 0; // // interpolate player info // - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) cl.velocity[i] = cl.mvelocity[1][i] + - frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]); + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]); - if (cls.demoplayback) + if(cls.demoplayback) { - // interpolate the angles - for (j=0 ; j<3 ; j++) + // interpolate the angles + for(j = 0 ; j < 3 ; j++) { d = cl.mviewangles[0][j] - cl.mviewangles[1][j]; - if (d > 180) + if(d > 180) d -= 360; - else if (d < -180) + else if(d < -180) d += 360; - cl.viewangles[j] = cl.mviewangles[1][j] + frac*d; + cl.viewangles[j] = cl.mviewangles[1][j] + frac * d; } } - bobjrotate = anglemod(100*cl.time); + bobjrotate = anglemod(100 * cl.time); // start on the entity after the world - for (i=1,ent=cl_entities+1 ; imodel) - { // empty slot + if(!ent->model) + { + // empty slot // ericw -- efrags are only used for static entities in GLQuake // ent can't be static, so this is a no-op. //if (ent->forcelink) - // R_RemoveEfrags (ent); // just became empty + // R_RemoveEfrags (ent); // just became empty continue; } // if the object wasn't included in the last packet, remove it - if (ent->msgtime != cl.mtime[0]) + if(ent->msgtime != cl.mtime[0]) { ent->model = NULL; - ent->lerpflags |= LERP_RESETMOVE|LERP_RESETANIM; //johnfitz -- next time this entity slot is reused, the lerp will need to be reset + ent->lerpflags |= LERP_RESETMOVE | LERP_RESETANIM; //johnfitz -- next time this entity slot is reused, the lerp will need to be reset continue; } - VectorCopy (ent->origin, oldorg); + VectorCopy(ent->origin, oldorg); - if (ent->forcelink) - { // the entity was not updated in the last message + if(ent->forcelink) + { + // the entity was not updated in the last message // so move to the final spot - VectorCopy (ent->msg_origins[0], ent->origin); - VectorCopy (ent->msg_angles[0], ent->angles); + VectorCopy(ent->msg_origins[0], ent->origin); + VectorCopy(ent->msg_angles[0], ent->angles); } else - { // if the delta is large, assume a teleport and don't lerp + { + // if the delta is large, assume a teleport and don't lerp f = frac; - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { delta[j] = ent->msg_origins[0][j] - ent->msg_origins[1][j]; - if (delta[j] > 100 || delta[j] < -100) + if(delta[j] > 100 || delta[j] < -100) { - f = 1; // assume a teleportation, not a motion + f = 1; // assume a teleportation, not a motion ent->lerpflags |= LERP_RESETMOVE; //johnfitz -- don't lerp teleports } } //johnfitz -- don't cl_lerp entities that will be r_lerped - if (r_lerpmove.value && (ent->lerpflags & LERP_MOVESTEP)) + if(r_lerpmove.value && (ent->lerpflags & LERP_MOVESTEP)) f = 1; //johnfitz - // interpolate the origin and angles - for (j=0 ; j<3 ; j++) + // interpolate the origin and angles + for(j = 0 ; j < 3 ; j++) { - ent->origin[j] = ent->msg_origins[1][j] + f*delta[j]; + ent->origin[j] = ent->msg_origins[1][j] + f * delta[j]; d = ent->msg_angles[0][j] - ent->msg_angles[1][j]; - if (d > 180) + if(d > 180) d -= 360; - else if (d < -180) + else if(d < -180) d += 360; - ent->angles[j] = ent->msg_angles[1][j] + f*d; + ent->angles[j] = ent->msg_angles[1][j] + f * d; } } // rotate binary objects locally - if (ent->model->flags & EF_ROTATE) + if(ent->model->flags & EF_ROTATE) ent->angles[1] = bobjrotate; - if (ent->effects & EF_BRIGHTFIELD) - R_EntityParticles (ent); + if(ent->effects & EF_BRIGHTFIELD) + R_EntityParticles(ent); - if (ent->effects & EF_MUZZLEFLASH) + if(ent->effects & EF_MUZZLEFLASH) { - vec3_t fv, rv, uv; + vec3_t fv, rv, uv; - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); dl->origin[2] += 16; - AngleVectors (ent->angles, fv, rv, uv); + AngleVectors(ent->angles, fv, rv, uv); - VectorMA (dl->origin, 18, fv, dl->origin); - dl->radius = 200 + (rand()&31); + VectorMA(dl->origin, 18, fv, dl->origin); + dl->radius = 200 + (rand() & 31); dl->minlight = 32; dl->die = cl.time + 0.1; //johnfitz -- assume muzzle flash accompanied by muzzle flare, which looks bad when lerped - if (r_lerpmodels.value != 2) + if(r_lerpmodels.value != 2) { - if (ent == &cl_entities[cl.viewentity]) - cl.viewent.lerpflags |= LERP_RESETANIM|LERP_RESETANIM2; //no lerping for two frames - else - ent->lerpflags |= LERP_RESETANIM|LERP_RESETANIM2; //no lerping for two frames + if(ent == &cl_entities[cl.viewentity]) + cl.viewent.lerpflags |= LERP_RESETANIM | LERP_RESETANIM2; //no lerping for two frames + else + ent->lerpflags |= LERP_RESETANIM | LERP_RESETANIM2; //no lerping for two frames } //johnfitz } - if (ent->effects & EF_BRIGHTLIGHT) + if(ent->effects & EF_BRIGHTLIGHT) { - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); dl->origin[2] += 16; - dl->radius = 400 + (rand()&31); + dl->radius = 400 + (rand() & 31); dl->die = cl.time + 0.001; } - if (ent->effects & EF_DIMLIGHT) + if(ent->effects & EF_DIMLIGHT) { - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); - dl->radius = 200 + (rand()&31); + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); + dl->radius = 200 + (rand() & 31); dl->die = cl.time + 0.001; } - if (ent->model->flags & EF_GIB) - R_RocketTrail (oldorg, ent->origin, 2); - else if (ent->model->flags & EF_ZOMGIB) - R_RocketTrail (oldorg, ent->origin, 4); - else if (ent->model->flags & EF_TRACER) - R_RocketTrail (oldorg, ent->origin, 3); - else if (ent->model->flags & EF_TRACER2) - R_RocketTrail (oldorg, ent->origin, 5); - else if (ent->model->flags & EF_ROCKET) + if(ent->model->flags & EF_GIB) + R_RocketTrail(oldorg, ent->origin, 2); + else if(ent->model->flags & EF_ZOMGIB) + R_RocketTrail(oldorg, ent->origin, 4); + else if(ent->model->flags & EF_TRACER) + R_RocketTrail(oldorg, ent->origin, 3); + else if(ent->model->flags & EF_TRACER2) + R_RocketTrail(oldorg, ent->origin, 5); + else if(ent->model->flags & EF_ROCKET) { - R_RocketTrail (oldorg, ent->origin, 0); - dl = CL_AllocDlight (i); - VectorCopy (ent->origin, dl->origin); + R_RocketTrail(oldorg, ent->origin, 0); + dl = CL_AllocDlight(i); + VectorCopy(ent->origin, dl->origin); dl->radius = 200; dl->die = cl.time + 0.01; } - else if (ent->model->flags & EF_GRENADE) - R_RocketTrail (oldorg, ent->origin, 1); - else if (ent->model->flags & EF_TRACER3) - R_RocketTrail (oldorg, ent->origin, 6); + else if(ent->model->flags & EF_GRENADE) + R_RocketTrail(oldorg, ent->origin, 1); + else if(ent->model->flags & EF_TRACER3) + R_RocketTrail(oldorg, ent->origin, 6); ent->forcelink = false; - if (i == cl.viewentity && !chase_active.value) + if(i == cl.viewentity && !chase_active.value) continue; - if (cl_numvisedicts < MAX_VISEDICTS) + if(cl_numvisedicts < MAX_VISEDICTS) { cl_visedicts[cl_numvisedicts] = ent; cl_numvisedicts++; @@ -590,15 +593,15 @@ CL_ReadFromServer Read all incoming data from the server =============== */ -int32_t CL_ReadFromServer (void) +int32_t CL_ReadFromServer(void) { - int32_t ret; - extern int32_t num_temp_entities; //johnfitz - int32_t num_beams = 0; //johnfitz - int32_t num_dlights = 0; //johnfitz - beam_t *b; //johnfitz - dlight_t *l; //johnfitz - int32_t i; //johnfitz + int32_t ret; + extern int32_t num_temp_entities; //johnfitz + int32_t num_beams = 0; //johnfitz + int32_t num_dlights = 0; //johnfitz + beam_t *b; //johnfitz + dlight_t *l; //johnfitz + int32_t i; //johnfitz cl.oldtime = cl.time; @@ -606,51 +609,52 @@ int32_t CL_ReadFromServer (void) do { - ret = CL_GetMessage (); - if (ret == -1) - Host_Error ("CL_ReadFromServer: lost server connection"); - if (!ret) + ret = CL_GetMessage(); + if(ret == -1) + Host_Error("CL_ReadFromServer: lost server connection"); + if(!ret) break; cl.last_received_message = realtime; - CL_ParseServerMessage (); - } while (ret && cls.state == ca_connected); + CL_ParseServerMessage(); + } + while(ret && cls.state == ca_connected); - if (cl_shownet.value) - Con_Printf ("\n"); + if(cl_shownet.value) + Con_Printf("\n"); - CL_RelinkEntities (); - CL_UpdateTEnts (); + CL_RelinkEntities(); + CL_UpdateTEnts(); //johnfitz -- devstats //visedicts - if (cl_numvisedicts > 256 && dev_peakstats.visedicts <= 256) - Con_DWarning ("%" PRIi32 " visedicts exceeds standard limit of 256 (max = %" PRIi32 ").\n", cl_numvisedicts, MAX_VISEDICTS); + if(cl_numvisedicts > 256 && dev_peakstats.visedicts <= 256) + Con_DWarning("%" PRIi32 " visedicts exceeds standard limit of 256 (max = %" PRIi32 ").\n", cl_numvisedicts, MAX_VISEDICTS); dev_stats.visedicts = cl_numvisedicts; dev_peakstats.visedicts = q_max(cl_numvisedicts, dev_peakstats.visedicts); //temp entities - if (num_temp_entities > 64 && dev_peakstats.tempents <= 64) - Con_DWarning ("%" PRIi32 " tempentities exceeds standard limit of 64 (max = %" PRIi32 ").\n", num_temp_entities, MAX_TEMP_ENTITIES); + if(num_temp_entities > 64 && dev_peakstats.tempents <= 64) + Con_DWarning("%" PRIi32 " tempentities exceeds standard limit of 64 (max = %" PRIi32 ").\n", num_temp_entities, MAX_TEMP_ENTITIES); dev_stats.tempents = num_temp_entities; dev_peakstats.tempents = q_max(num_temp_entities, dev_peakstats.tempents); //beams - for (i=0, b=cl_beams ; i< MAX_BEAMS ; i++, b++) - if (b->model && b->endtime >= cl.time) + for(i = 0, b = cl_beams ; i < MAX_BEAMS ; i++, b++) + if(b->model && b->endtime >= cl.time) num_beams++; - if (num_beams > 24 && dev_peakstats.beams <= 24) - Con_DWarning ("%" PRIi32 " beams exceeded standard limit of 24 (max = %" PRIi32 ").\n", num_beams, MAX_BEAMS); + if(num_beams > 24 && dev_peakstats.beams <= 24) + Con_DWarning("%" PRIi32 " beams exceeded standard limit of 24 (max = %" PRIi32 ").\n", num_beams, MAX_BEAMS); dev_stats.beams = num_beams; dev_peakstats.beams = q_max(num_beams, dev_peakstats.beams); //dlights - for (i=0, l=cl_dlights ; idie >= cl.time && l->radius) + for(i = 0, l = cl_dlights ; i < MAX_DLIGHTS ; i++, l++) + if(l->die >= cl.time && l->radius) num_dlights++; - if (num_dlights > 32 && dev_peakstats.dlights <= 32) - Con_DWarning ("%" PRIi32 " dlights exceeded standard limit of 32 (max = %" PRIi32 ").\n", num_dlights, MAX_DLIGHTS); + if(num_dlights > 32 && dev_peakstats.dlights <= 32) + Con_DWarning("%" PRIi32 " dlights exceeded standard limit of 32 (max = %" PRIi32 ").\n", num_dlights, MAX_DLIGHTS); dev_stats.dlights = num_dlights; dev_peakstats.dlights = q_max(num_dlights, dev_peakstats.dlights); @@ -667,45 +671,45 @@ int32_t CL_ReadFromServer (void) CL_SendCmd ================= */ -void CL_SendCmd (void) +void CL_SendCmd(void) { - usercmd_t cmd; + usercmd_t cmd; - if (cls.state != ca_connected) + if(cls.state != ca_connected) return; - if (cls.signon == SIGNONS) + if(cls.signon == SIGNONS) { - // get basic movement from keyboard - CL_BaseMove (&cmd); + // get basic movement from keyboard + CL_BaseMove(&cmd); - // allow mice or other external controllers to add to the move - IN_Move (&cmd); + // allow mice or other external controllers to add to the move + IN_Move(&cmd); - // send the unreliable message - CL_SendMove (&cmd); + // send the unreliable message + CL_SendMove(&cmd); } - if (cls.demoplayback) + if(cls.demoplayback) { - SZ_Clear (&cls.message); + SZ_Clear(&cls.message); return; } // send the reliable message - if (!cls.message.cursize) - return; // no message at all + if(!cls.message.cursize) + return; // no message at all - if (!NET_CanSendMessage (cls.netcon)) + if(!NET_CanSendMessage(cls.netcon)) { - Con_DPrintf ("CL_SendCmd: can't send\n"); + Con_DPrintf("CL_SendCmd: can't send\n"); return; } - if (NET_SendMessage (cls.netcon, &cls.message) == -1) - Host_Error ("CL_SendCmd: lost server connection"); + if(NET_SendMessage(cls.netcon, &cls.message) == -1) + Host_Error("CL_SendCmd: lost server connection"); - SZ_Clear (&cls.message); + SZ_Clear(&cls.message); } /* @@ -715,20 +719,20 @@ CL_Tracepos_f -- johnfitz display impact point of trace along VPN ============= */ -void CL_Tracepos_f (void) +void CL_Tracepos_f(void) { - vec3_t v, w; + vec3_t v, w; - if (cls.state != ca_connected) + if(cls.state != ca_connected) return; VectorMA(r_refdef.vieworg, 8192.0, vpn, v); TraceLine(r_refdef.vieworg, v, w); - if (VectorLength(w) == 0) - Con_Printf ("Tracepos: trace didn't hit anything\n"); + if(VectorLength(w) == 0) + Con_Printf("Tracepos: trace didn't hit anything\n"); else - Con_Printf ("Tracepos: (%" PRIi32 " %" PRIi32 " %" PRIi32 ")\n", (int32_t)w[0], (int32_t)w[1], (int32_t)w[2]); + Con_Printf("Tracepos: (%" PRIi32 " %" PRIi32 " %" PRIi32 ")\n", (int32_t)w[0], (int32_t)w[1], (int32_t)w[2]); } /* @@ -738,28 +742,28 @@ CL_Viewpos_f -- johnfitz display client's position and angles ============= */ -void CL_Viewpos_f (void) +void CL_Viewpos_f(void) { - if (cls.state != ca_connected) + if(cls.state != ca_connected) return; #if 0 //camera position - Con_Printf ("Viewpos: (%" PRIi32 " %" PRIi32 " %" PRIi32 ") %" PRIi32 " %" PRIi32 " %" PRIi32 "\n", - (int32_t)r_refdef.vieworg[0], - (int32_t)r_refdef.vieworg[1], - (int32_t)r_refdef.vieworg[2], - (int32_t)r_refdef.viewangles[PITCH], - (int32_t)r_refdef.viewangles[YAW], - (int32_t)r_refdef.viewangles[ROLL]); + Con_Printf("Viewpos: (%" PRIi32 " %" PRIi32 " %" PRIi32 ") %" PRIi32 " %" PRIi32 " %" PRIi32 "\n", + (int32_t)r_refdef.vieworg[0], + (int32_t)r_refdef.vieworg[1], + (int32_t)r_refdef.vieworg[2], + (int32_t)r_refdef.viewangles[PITCH], + (int32_t)r_refdef.viewangles[YAW], + (int32_t)r_refdef.viewangles[ROLL]); #else //player position - Con_Printf ("Viewpos: (%" PRIi32 " %" PRIi32 " %" PRIi32 ") %" PRIi32 " %" PRIi32 " %" PRIi32 "\n", - (int32_t)cl_entities[cl.viewentity].origin[0], - (int32_t)cl_entities[cl.viewentity].origin[1], - (int32_t)cl_entities[cl.viewentity].origin[2], - (int32_t)cl.viewangles[PITCH], - (int32_t)cl.viewangles[YAW], - (int32_t)cl.viewangles[ROLL]); + Con_Printf("Viewpos: (%" PRIi32 " %" PRIi32 " %" PRIi32 ") %" PRIi32 " %" PRIi32 " %" PRIi32 "\n", + (int32_t)cl_entities[cl.viewentity].origin[0], + (int32_t)cl_entities[cl.viewentity].origin[1], + (int32_t)cl_entities[cl.viewentity].origin[2], + (int32_t)cl.viewangles[PITCH], + (int32_t)cl.viewangles[YAW], + (int32_t)cl.viewangles[ROLL]); #endif } @@ -768,49 +772,49 @@ void CL_Viewpos_f (void) CL_Init ================= */ -void CL_Init (void) +void CL_Init(void) { - SZ_Alloc (&cls.message, 1024); + SZ_Alloc(&cls.message, 1024); - CL_InitInput (); - CL_InitTEnts (); + CL_InitInput(); + CL_InitTEnts(); - Cvar_RegisterVariable (&cl_name); - Cvar_RegisterVariable (&cl_color); - Cvar_RegisterVariable (&cl_upspeed); - Cvar_RegisterVariable (&cl_forwardspeed); - Cvar_RegisterVariable (&cl_backspeed); - Cvar_RegisterVariable (&cl_sidespeed); - Cvar_RegisterVariable (&cl_movespeedkey); - Cvar_RegisterVariable (&cl_yawspeed); - Cvar_RegisterVariable (&cl_pitchspeed); - Cvar_RegisterVariable (&cl_anglespeedkey); - Cvar_RegisterVariable (&cl_shownet); - Cvar_RegisterVariable (&cl_nolerp); - Cvar_RegisterVariable (&lookspring); - Cvar_RegisterVariable (&lookstrafe); - Cvar_RegisterVariable (&sensitivity); + Cvar_RegisterVariable(&cl_name); + Cvar_RegisterVariable(&cl_color); + Cvar_RegisterVariable(&cl_upspeed); + Cvar_RegisterVariable(&cl_forwardspeed); + Cvar_RegisterVariable(&cl_backspeed); + Cvar_RegisterVariable(&cl_sidespeed); + Cvar_RegisterVariable(&cl_movespeedkey); + Cvar_RegisterVariable(&cl_yawspeed); + Cvar_RegisterVariable(&cl_pitchspeed); + Cvar_RegisterVariable(&cl_anglespeedkey); + Cvar_RegisterVariable(&cl_shownet); + Cvar_RegisterVariable(&cl_nolerp); + Cvar_RegisterVariable(&lookspring); + Cvar_RegisterVariable(&lookstrafe); + Cvar_RegisterVariable(&sensitivity); - Cvar_RegisterVariable (&cl_alwaysrun); + Cvar_RegisterVariable(&cl_alwaysrun); - Cvar_RegisterVariable (&m_pitch); - Cvar_RegisterVariable (&m_yaw); - Cvar_RegisterVariable (&m_forward); - Cvar_RegisterVariable (&m_side); + Cvar_RegisterVariable(&m_pitch); + Cvar_RegisterVariable(&m_yaw); + Cvar_RegisterVariable(&m_forward); + Cvar_RegisterVariable(&m_side); - Cvar_RegisterVariable (&cfg_unbindall); + Cvar_RegisterVariable(&cfg_unbindall); - Cvar_RegisterVariable (&cl_maxpitch); //johnfitz -- variable pitch clamping - Cvar_RegisterVariable (&cl_minpitch); //johnfitz -- variable pitch clamping + Cvar_RegisterVariable(&cl_maxpitch); //johnfitz -- variable pitch clamping + Cvar_RegisterVariable(&cl_minpitch); //johnfitz -- variable pitch clamping - Cmd_AddCommand ("entities", CL_PrintEntities_f); - Cmd_AddCommand ("disconnect", CL_Disconnect_f); - Cmd_AddCommand ("record", CL_Record_f); - Cmd_AddCommand ("stop", CL_Stop_f); - Cmd_AddCommand ("playdemo", CL_PlayDemo_f); - Cmd_AddCommand ("timedemo", CL_TimeDemo_f); + Cmd_AddCommand("entities", CL_PrintEntities_f); + Cmd_AddCommand("disconnect", CL_Disconnect_f); + Cmd_AddCommand("record", CL_Record_f); + Cmd_AddCommand("stop", CL_Stop_f); + Cmd_AddCommand("playdemo", CL_PlayDemo_f); + Cmd_AddCommand("timedemo", CL_TimeDemo_f); - Cmd_AddCommand ("tracepos", CL_Tracepos_f); //johnfitz - Cmd_AddCommand ("viewpos", CL_Viewpos_f); //johnfitz + Cmd_AddCommand("tracepos", CL_Tracepos_f); //johnfitz + Cmd_AddCommand("viewpos", CL_Viewpos_f); //johnfitz } diff --git a/source/cl_parse.c b/source/cl_parse.c index 0dc26f1..e333e9f 100644 --- a/source/cl_parse.c +++ b/source/cl_parse.c @@ -31,33 +31,33 @@ const char *svc_strings[] = "svc_nop", "svc_disconnect", "svc_updatestat", - "svc_version", // [long] server version - "svc_setview", // [int16_t] entity number - "svc_sound", // - "svc_time", // [float] server time - "svc_print", // [string] null terminated string - "svc_stufftext", // [string] stuffed into client's console buffer - // the string should be \n terminated - "svc_setangle", // [vec3] set the view angle to this absolute value + "svc_version", // [long] server version + "svc_setview", // [int16_t] entity number + "svc_sound", // + "svc_time", // [float] server time + "svc_print", // [string] null terminated string + "svc_stufftext", // [string] stuffed into client's console buffer + // the string should be \n terminated + "svc_setangle", // [vec3] set the view angle to this absolute value - "svc_serverinfo", // [long] version - // [string] signon string - // [string]..[0]model cache [string]...[0]sounds cache - // [string]..[0]item cache - "svc_lightstyle", // [byte] [string] - "svc_updatename", // [byte] [string] - "svc_updatefrags", // [byte] [int16_t] - "svc_clientdata", // - "svc_stopsound", // - "svc_updatecolors", // [byte] [byte] - "svc_particle", // [vec3] - "svc_damage", // [byte] impact [byte] blood [vec3] from + "svc_serverinfo", // [long] version + // [string] signon string + // [string]..[0]model cache [string]...[0]sounds cache + // [string]..[0]item cache + "svc_lightstyle", // [byte] [string] + "svc_updatename", // [byte] [string] + "svc_updatefrags", // [byte] [int16_t] + "svc_clientdata", // + "svc_stopsound", // + "svc_updatecolors", // [byte] [byte] + "svc_particle", // [vec3] + "svc_damage", // [byte] impact [byte] blood [vec3] from "svc_spawnstatic", "OBSOLETE svc_spawnbinary", "svc_spawnbaseline", - "svc_temp_entity", // + "svc_temp_entity", // "svc_setpause", "svc_signonnum", "svc_centerprint", @@ -65,21 +65,21 @@ const char *svc_strings[] = "svc_foundsecret", "svc_spawnstaticsound", "svc_intermission", - "svc_finale", // [string] music [string] text - "svc_cdtrack", // [byte] track [byte] looptrack + "svc_finale", // [string] music [string] text + "svc_cdtrack", // [byte] track [byte] looptrack "svc_sellscreen", "svc_cutscene", //johnfitz -- new server messages - "", // 35 - "", // 36 - "svc_skybox", // 37 // [string] skyname + "", // 35 + "", // 36 + "svc_skybox", // 37 // [string] skyname "", // 38 "", // 39 - "svc_bf", // 40 // no data - "svc_fog", // 41 // [byte] density [byte] red [byte] green [byte] blue [float] time - "svc_spawnbaseline2", //42 // support for large modelindex, large framenum, alpha, using flags - "svc_spawnstatic2", // 43 // support for large modelindex, large framenum, alpha, using flags - "svc_spawnstaticsound2", // 44 // [coord3] [int16_t] samp [byte] vol [byte] aten + "svc_bf", // 40 // no data + "svc_fog", // 41 // [byte] density [byte] red [byte] green [byte] blue [float] time + "svc_spawnbaseline2", //42 // support for large modelindex, large framenum, alpha, using flags + "svc_spawnstatic2", // 43 // support for large modelindex, large framenum, alpha, using flags + "svc_spawnstaticsound2", // 44 // [coord3] [int16_t] samp [byte] vol [byte] aten "", // 44 "", // 45 "", // 46 @@ -91,7 +91,7 @@ const char *svc_strings[] = bool warn_about_nehahra_protocol; //johnfitz -extern vec3_t v_punchangles[2]; //johnfitz +extern vec3_t v_punchangles[2]; //johnfitz //============================================================================= @@ -102,21 +102,21 @@ CL_EntityNum This error checks and tracks the total number of entities =============== */ -entity_t *CL_EntityNum (int32_t num) +entity_t *CL_EntityNum(int32_t num) { //johnfitz -- check minimum number too - if (num < 0) - Host_Error ("CL_EntityNum: %" PRIi32 " is an invalid number",num); + if(num < 0) + Host_Error("CL_EntityNum: %" PRIi32 " is an invalid number", num); //john - if (num >= cl.num_entities) + if(num >= cl.num_entities) { - if (num >= cl_max_edicts) //johnfitz -- no more MAX_EDICTS - Host_Error ("CL_EntityNum: %" PRIi32 " is an invalid number",num); - while (cl.num_entities<=num) + if(num >= cl_max_edicts) //johnfitz -- no more MAX_EDICTS + Host_Error("CL_EntityNum: %" PRIi32 " is an invalid number", num); + while(cl.num_entities <= num) { cl_entities[cl.num_entities].colormap = vid.colormap; - cl_entities[cl.num_entities].lerpflags |= LERP_RESETMOVE|LERP_RESETANIM; //johnfitz + cl_entities[cl.num_entities].lerpflags |= LERP_RESETMOVE | LERP_RESETANIM; //johnfitz cl.num_entities++; } } @@ -132,57 +132,57 @@ CL_ParseStartSoundPacket */ void CL_ParseStartSoundPacket(void) { - vec3_t pos; - int32_t channel, ent; - int32_t sound_num; - int32_t volume; - int32_t field_mask; - float attenuation; - int32_t i; + vec3_t pos; + int32_t channel, ent; + int32_t sound_num; + int32_t volume; + int32_t field_mask; + float attenuation; + int32_t i; field_mask = MSG_ReadByte(); - if (field_mask & SND_VOLUME) - volume = MSG_ReadByte (); + if(field_mask & SND_VOLUME) + volume = MSG_ReadByte(); else volume = DEFAULT_SOUND_PACKET_VOLUME; - if (field_mask & SND_ATTENUATION) - attenuation = MSG_ReadByte () / 64.0; + if(field_mask & SND_ATTENUATION) + attenuation = MSG_ReadByte() / 64.0; else attenuation = DEFAULT_SOUND_PACKET_ATTENUATION; //johnfitz -- PROTOCOL_FITZQUAKE - if (field_mask & SND_LARGEENTITY) + if(field_mask & SND_LARGEENTITY) { - ent = (uint16_t) MSG_ReadShort (); - channel = MSG_ReadByte (); + ent = (uint16_t) MSG_ReadShort(); + channel = MSG_ReadByte(); } else { - channel = (uint16_t) MSG_ReadShort (); + channel = (uint16_t) MSG_ReadShort(); ent = channel >> 3; channel &= 7; } - if (field_mask & SND_LARGESOUND) - sound_num = (uint16_t) MSG_ReadShort (); + if(field_mask & SND_LARGESOUND) + sound_num = (uint16_t) MSG_ReadShort(); else - sound_num = MSG_ReadByte (); + sound_num = MSG_ReadByte(); //johnfitz //johnfitz -- check soundnum - if (sound_num >= MAX_SOUNDS) - Host_Error ("CL_ParseStartSoundPacket: %" PRIi32 " > MAX_SOUNDS", sound_num); + if(sound_num >= MAX_SOUNDS) + Host_Error("CL_ParseStartSoundPacket: %" PRIi32 " > MAX_SOUNDS", sound_num); //johnfitz - if (ent > cl_max_edicts) //johnfitz -- no more MAX_EDICTS - Host_Error ("CL_ParseStartSoundPacket: ent = %" PRIi32 "", ent); + if(ent > cl_max_edicts) //johnfitz -- no more MAX_EDICTS + Host_Error("CL_ParseStartSoundPacket: ent = %" PRIi32 "", ent); - for (i = 0; i < 3; i++) - pos[i] = MSG_ReadCoord (cl.protocolflags); + for(i = 0; i < 3; i++) + pos[i] = MSG_ReadCoord(cl.protocolflags); - S_StartSound (ent, channel, cl.sound_precache[sound_num], pos, volume/255.0, attenuation); + S_StartSound(ent, channel, cl.sound_precache[sound_num], pos, volume / 255.0, attenuation); } /* @@ -193,59 +193,60 @@ When the client is taking a long time to load stuff, send keepalive messages so the server doesn't disconnect. ================== */ -static byte net_olddata[NET_MAXMESSAGE]; -void CL_KeepaliveMessage (void) +static byte net_olddata[NET_MAXMESSAGE]; +void CL_KeepaliveMessage(void) { - float time; + float time; static float lastmsg; - int32_t ret; - sizebuf_t old; - byte *olddata; + int32_t ret; + sizebuf_t old; + byte *olddata; - if (sv.active) - return; // no need if server is local - if (cls.demoplayback) + if(sv.active) + return; // no need if server is local + if(cls.demoplayback) return; // read messages from server, should just be nops olddata = net_olddata; old = net_message; - memcpy (olddata, net_message.data, net_message.cursize); + memcpy(olddata, net_message.data, net_message.cursize); do { - ret = CL_GetMessage (); - switch (ret) + ret = CL_GetMessage(); + switch(ret) { default: - Host_Error ("CL_KeepaliveMessage: CL_GetMessage failed"); + Host_Error("CL_KeepaliveMessage: CL_GetMessage failed"); case 0: - break; // nothing waiting + break; // nothing waiting case 1: - Host_Error ("CL_KeepaliveMessage: received a message"); + Host_Error("CL_KeepaliveMessage: received a message"); break; case 2: - if (MSG_ReadByte() != svc_nop) - Host_Error ("CL_KeepaliveMessage: datagram wasn't a nop"); + if(MSG_ReadByte() != svc_nop) + Host_Error("CL_KeepaliveMessage: datagram wasn't a nop"); break; } - } while (ret); + } + while(ret); net_message = old; - memcpy (net_message.data, olddata, net_message.cursize); + memcpy(net_message.data, olddata, net_message.cursize); // check time - time = Sys_DoubleTime (); - if (time - lastmsg < 5) + time = Sys_DoubleTime(); + if(time - lastmsg < 5) return; lastmsg = time; // write out a nop - Con_Printf ("--> client to server keepalive\n"); + Con_Printf("--> client to server keepalive\n"); - MSG_WriteByte (&cls.message, clc_nop); - NET_SendMessage (cls.netcon, &cls.message); - SZ_Clear (&cls.message); + MSG_WriteByte(&cls.message, clc_nop); + NET_SendMessage(cls.netcon, &cls.message); + SZ_Clear(&cls.message); } /* @@ -253,44 +254,45 @@ void CL_KeepaliveMessage (void) CL_ParseServerInfo ================== */ -void CL_ParseServerInfo (void) +void CL_ParseServerInfo(void) { - const char *str; - int32_t i; - int32_t nummodels, numsounds; - char model_precache[MAX_MODELS][MAX_QPATH]; - char sound_precache[MAX_SOUNDS][MAX_QPATH]; + const char *str; + int32_t i; + int32_t nummodels, numsounds; + char model_precache[MAX_MODELS][MAX_QPATH]; + char sound_precache[MAX_SOUNDS][MAX_QPATH]; - Con_DPrintf ("Serverinfo packet received.\n"); + Con_DPrintf("Serverinfo packet received.\n"); // ericw -- bring up loading plaque for map changes within a demo. // it will be hidden in CL_SignonReply. - if (cls.demoplayback) + if(cls.demoplayback) SCR_BeginLoadingPlaque(); // // wipe the client_state_t struct // - CL_ClearState (); + CL_ClearState(); // parse protocol version number - i = MSG_ReadLong (); + i = MSG_ReadLong(); //johnfitz -- support multiple protocols - if (i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) { - Con_Printf ("\n"); //because there's no newline after serverinfo print - Host_Error ("Server returned version %" PRIi32 ", not %" PRIi32 " or %" PRIi32 " or %" PRIi32 "", i, PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ); + if(i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) + { + Con_Printf("\n"); //because there's no newline after serverinfo print + Host_Error("Server returned version %" PRIi32 ", not %" PRIi32 " or %" PRIi32 " or %" PRIi32 "", i, PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ); } cl.protocol = i; //johnfitz - if (cl.protocol == PROTOCOL_RMQ) + if(cl.protocol == PROTOCOL_RMQ) { const uint32_t supportedflags = (PRFL_SHORTANGLE | PRFL_FLOATANGLE | PRFL_24BITCOORD | PRFL_FLOATCOORD | PRFL_EDICTSCALE | PRFL_INT32COORD); // mh - read protocol flags from server so that we know what protocol features to expect - cl.protocolflags = (uint32_t) MSG_ReadLong (); + cl.protocolflags = (uint32_t) MSG_ReadLong(); - if (0 != (cl.protocolflags & (~supportedflags))) + if(0 != (cl.protocolflags & (~supportedflags))) { Con_Warning("PROTOCOL_RMQ protocolflags %" PRIi32 " contains unsupported flags\n", cl.protocolflags); } @@ -298,69 +300,69 @@ void CL_ParseServerInfo (void) else cl.protocolflags = 0; // parse maxclients - cl.maxclients = MSG_ReadByte (); - if (cl.maxclients < 1 || cl.maxclients > MAX_SCOREBOARD) + cl.maxclients = MSG_ReadByte(); + if(cl.maxclients < 1 || cl.maxclients > MAX_SCOREBOARD) { - Host_Error ("Bad maxclients (%" PRIu32 ") from server", cl.maxclients); + Host_Error("Bad maxclients (%" PRIu32 ") from server", cl.maxclients); } - cl.scores = (scoreboard_t *) Hunk_AllocName (cl.maxclients*sizeof(*cl.scores), "scores"); + cl.scores = (scoreboard_t *) Hunk_AllocName(cl.maxclients * sizeof(*cl.scores), "scores"); // parse gametype - cl.gametype = MSG_ReadByte (); + cl.gametype = MSG_ReadByte(); // parse signon message - str = MSG_ReadString (); - q_strlcpy (cl.levelname, str, sizeof(cl.levelname)); + str = MSG_ReadString(); + q_strlcpy(cl.levelname, str, sizeof(cl.levelname)); // seperate the printfs so the server message can have a color - Con_Printf ("\n%s\n", Con_Quakebar(40)); //johnfitz - Con_Printf ("%c%s\n", 2, str); + Con_Printf("\n%s\n", Con_Quakebar(40)); //johnfitz + Con_Printf("%c%s\n", 2, str); //johnfitz -- tell user which protocol this is - Con_Printf ("Using protocol %" PRIi32 "\n", i); + Con_Printf("Using protocol %" PRIi32 "\n", i); // first we go through and touch all of the precache data that still // happens to be in the cache, so precaching something else doesn't // needlessly purge it // precache models - memset (cl.model_precache, 0, sizeof(cl.model_precache)); - for (nummodels = 1 ; ; nummodels++) + memset(cl.model_precache, 0, sizeof(cl.model_precache)); + for(nummodels = 1 ; ; nummodels++) { - str = MSG_ReadString (); - if (!str[0]) + str = MSG_ReadString(); + if(!str[0]) break; - if (nummodels==MAX_MODELS) + if(nummodels == MAX_MODELS) { - Host_Error ("Server sent too many model precaches"); + Host_Error("Server sent too many model precaches"); } - q_strlcpy (model_precache[nummodels], str, MAX_QPATH); - Mod_TouchModel (str); + q_strlcpy(model_precache[nummodels], str, MAX_QPATH); + Mod_TouchModel(str); } //johnfitz -- check for excessive models - if (nummodels >= 256) - Con_DWarning ("%" PRIi32 " models exceeds standard limit of 256 (max = %" PRIi32 ").\n", nummodels, MAX_MODELS); + if(nummodels >= 256) + Con_DWarning("%" PRIi32 " models exceeds standard limit of 256 (max = %" PRIi32 ").\n", nummodels, MAX_MODELS); //johnfitz // precache sounds - memset (cl.sound_precache, 0, sizeof(cl.sound_precache)); - for (numsounds = 1 ; ; numsounds++) + memset(cl.sound_precache, 0, sizeof(cl.sound_precache)); + for(numsounds = 1 ; ; numsounds++) { - str = MSG_ReadString (); - if (!str[0]) + str = MSG_ReadString(); + if(!str[0]) break; - if (numsounds==MAX_SOUNDS) + if(numsounds == MAX_SOUNDS) { - Host_Error ("Server sent too many sound precaches"); + Host_Error("Server sent too many sound precaches"); } - q_strlcpy (sound_precache[numsounds], str, MAX_QPATH); - S_TouchSound (str); + q_strlcpy(sound_precache[numsounds], str, MAX_QPATH); + S_TouchSound(str); } //johnfitz -- check for excessive sounds - if (numsounds >= 256) - Con_DWarning ("%" PRIi32 " sounds exceeds standard limit of 256 (max = %" PRIi32 ").\n", numsounds, MAX_SOUNDS); + if(numsounds >= 256) + Con_DWarning("%" PRIi32 " sounds exceeds standard limit of 256 (max = %" PRIi32 ").\n", numsounds, MAX_SOUNDS); //johnfitz // @@ -368,39 +370,39 @@ void CL_ParseServerInfo (void) // // copy the naked name of the map file to the cl structure -- O.S - COM_StripExtension (COM_SkipPath(model_precache[1]), cl.mapname, sizeof(cl.mapname)); + COM_StripExtension(COM_SkipPath(model_precache[1]), cl.mapname, sizeof(cl.mapname)); - for (i = 1; i < nummodels; i++) + for(i = 1; i < nummodels; i++) { - cl.model_precache[i] = Mod_ForName (model_precache[i], false); - if (cl.model_precache[i] == NULL) + cl.model_precache[i] = Mod_ForName(model_precache[i], false); + if(cl.model_precache[i] == NULL) { - Host_Error ("Model %s not found", model_precache[i]); + Host_Error("Model %s not found", model_precache[i]); } - CL_KeepaliveMessage (); + CL_KeepaliveMessage(); } - S_BeginPrecaching (); - for (i = 1; i < numsounds; i++) + S_BeginPrecaching(); + for(i = 1; i < numsounds; i++) { - cl.sound_precache[i] = S_PrecacheSound (sound_precache[i]); - CL_KeepaliveMessage (); + cl.sound_precache[i] = S_PrecacheSound(sound_precache[i]); + CL_KeepaliveMessage(); } - S_EndPrecaching (); + S_EndPrecaching(); // local state cl_entities[0].model = cl.worldmodel = cl.model_precache[1]; - R_NewMap (); + R_NewMap(); //johnfitz -- clear out string; we don't consider identical //messages to be duplicates if the map has changed in between con_lastcenterstring[0] = 0; //johnfitz - Hunk_Check (); // make sure nothing is hurt + Hunk_Check(); // make sure nothing is hurt - noclip_anglehack = false; // noclip is turned off at start + noclip_anglehack = false; // noclip is turned off at start warn_about_nehahra_protocol = true; //johnfitz -- warn about nehahra protocol hack once per server connection @@ -419,131 +421,132 @@ If an entities model or origin changes from frame to frame, it must be relinked. Other attributes can change without relinking. ================== */ -void CL_ParseUpdate (int32_t bits) +void CL_ParseUpdate(int32_t bits) { - int32_t i; - qmodel_t *model; - int32_t modnum; - bool forcelink; - entity_t *ent; - int32_t num; - int32_t skin; + int32_t i; + qmodel_t *model; + int32_t modnum; + bool forcelink; + entity_t *ent; + int32_t num; + int32_t skin; - if (cls.signon == SIGNONS - 1) - { // first update is the final signon stage + if(cls.signon == SIGNONS - 1) + { + // first update is the final signon stage cls.signon = SIGNONS; - CL_SignonReply (); + CL_SignonReply(); } - if (bits & U_MOREBITS) + if(bits & U_MOREBITS) { - i = MSG_ReadByte (); - bits |= (i<<8); + i = MSG_ReadByte(); + bits |= (i << 8); } //johnfitz -- PROTOCOL_FITZQUAKE - if (cl.protocol == PROTOCOL_FITZQUAKE || cl.protocol == PROTOCOL_RMQ) + if(cl.protocol == PROTOCOL_FITZQUAKE || cl.protocol == PROTOCOL_RMQ) { - if (bits & U_EXTEND1) + if(bits & U_EXTEND1) bits |= MSG_ReadByte() << 16; - if (bits & U_EXTEND2) + if(bits & U_EXTEND2) bits |= MSG_ReadByte() << 24; } //johnfitz - if (bits & U_LONGENTITY) - num = MSG_ReadShort (); + if(bits & U_LONGENTITY) + num = MSG_ReadShort(); else - num = MSG_ReadByte (); + num = MSG_ReadByte(); - ent = CL_EntityNum (num); + ent = CL_EntityNum(num); - if (ent->msgtime != cl.mtime[1]) - forcelink = true; // no previous frame to lerp from + if(ent->msgtime != cl.mtime[1]) + forcelink = true; // no previous frame to lerp from else forcelink = false; //johnfitz -- lerping - if (ent->msgtime + 0.2 < cl.mtime[0]) //more than 0.2 seconds since the last message (most entities think every 0.1 sec) + if(ent->msgtime + 0.2 < cl.mtime[0]) //more than 0.2 seconds since the last message (most entities think every 0.1 sec) ent->lerpflags |= LERP_RESETANIM; //if we missed a think, we'd be lerping from the wrong frame //johnfitz ent->msgtime = cl.mtime[0]; - if (bits & U_MODEL) + if(bits & U_MODEL) { - modnum = MSG_ReadByte (); - if (modnum >= MAX_MODELS) - Host_Error ("CL_ParseModel: bad modnum"); + modnum = MSG_ReadByte(); + if(modnum >= MAX_MODELS) + Host_Error("CL_ParseModel: bad modnum"); } else modnum = ent->baseline.modelindex; - if (bits & U_FRAME) - ent->frame = MSG_ReadByte (); + if(bits & U_FRAME) + ent->frame = MSG_ReadByte(); else ent->frame = ent->baseline.frame; - if (bits & U_COLORMAP) + if(bits & U_COLORMAP) i = MSG_ReadByte(); else i = ent->baseline.colormap; - if (!i) + if(!i) ent->colormap = vid.colormap; else { - if (i > cl.maxclients) - Sys_Error ("i >= cl.maxclients"); - ent->colormap = cl.scores[i-1].translations; + if(i > cl.maxclients) + Sys_Error("i >= cl.maxclients"); + ent->colormap = cl.scores[i - 1].translations; } - if (bits & U_SKIN) + if(bits & U_SKIN) skin = MSG_ReadByte(); else skin = ent->baseline.skin; - if (skin != ent->skinnum) + if(skin != ent->skinnum) { ent->skinnum = skin; - if (num > 0 && num <= cl.maxclients) - R_TranslateNewPlayerSkin (num - 1); //johnfitz -- was R_TranslatePlayerSkin + if(num > 0 && num <= cl.maxclients) + R_TranslateNewPlayerSkin(num - 1); //johnfitz -- was R_TranslatePlayerSkin } - if (bits & U_EFFECTS) + if(bits & U_EFFECTS) ent->effects = MSG_ReadByte(); else ent->effects = ent->baseline.effects; // shift the known values for interpolation - VectorCopy (ent->msg_origins[0], ent->msg_origins[1]); - VectorCopy (ent->msg_angles[0], ent->msg_angles[1]); + VectorCopy(ent->msg_origins[0], ent->msg_origins[1]); + VectorCopy(ent->msg_angles[0], ent->msg_angles[1]); - if (bits & U_ORIGIN1) - ent->msg_origins[0][0] = MSG_ReadCoord (cl.protocolflags); + if(bits & U_ORIGIN1) + ent->msg_origins[0][0] = MSG_ReadCoord(cl.protocolflags); else ent->msg_origins[0][0] = ent->baseline.origin[0]; - if (bits & U_ANGLE1) + if(bits & U_ANGLE1) ent->msg_angles[0][0] = MSG_ReadAngle(cl.protocolflags); else ent->msg_angles[0][0] = ent->baseline.angles[0]; - if (bits & U_ORIGIN2) - ent->msg_origins[0][1] = MSG_ReadCoord (cl.protocolflags); + if(bits & U_ORIGIN2) + ent->msg_origins[0][1] = MSG_ReadCoord(cl.protocolflags); else ent->msg_origins[0][1] = ent->baseline.origin[1]; - if (bits & U_ANGLE2) + if(bits & U_ANGLE2) ent->msg_angles[0][1] = MSG_ReadAngle(cl.protocolflags); else ent->msg_angles[0][1] = ent->baseline.angles[1]; - if (bits & U_ORIGIN3) - ent->msg_origins[0][2] = MSG_ReadCoord (cl.protocolflags); + if(bits & U_ORIGIN3) + ent->msg_origins[0][2] = MSG_ReadCoord(cl.protocolflags); else ent->msg_origins[0][2] = ent->baseline.origin[2]; - if (bits & U_ANGLE3) + if(bits & U_ANGLE3) ent->msg_angles[0][2] = MSG_ReadAngle(cl.protocolflags); else ent->msg_angles[0][2] = ent->baseline.angles[2]; //johnfitz -- lerping for movetype_step entities - if (bits & U_STEP) + if(bits & U_STEP) { ent->lerpflags |= LERP_MOVESTEP; ent->forcelink = true; @@ -553,19 +556,19 @@ void CL_ParseUpdate (int32_t bits) //johnfitz //johnfitz -- PROTOCOL_FITZQUAKE and PROTOCOL_NEHAHRA - if (cl.protocol == PROTOCOL_FITZQUAKE || cl.protocol == PROTOCOL_RMQ) + if(cl.protocol == PROTOCOL_FITZQUAKE || cl.protocol == PROTOCOL_RMQ) { - if (bits & U_ALPHA) + if(bits & U_ALPHA) ent->alpha = MSG_ReadByte(); else ent->alpha = ent->baseline.alpha; - if (bits & U_SCALE) + if(bits & U_SCALE) MSG_ReadByte(); // PROTOCOL_RMQ: currently ignored - if (bits & U_FRAME2) + if(bits & U_FRAME2) ent->frame = (ent->frame & 0x00FF) | (MSG_ReadByte() << 8); - if (bits & U_MODEL2) + if(bits & U_MODEL2) modnum = (modnum & 0x00FF) | (MSG_ReadByte() << 8); - if (bits & U_LERPFINISH) + if(bits & U_LERPFINISH) { ent->lerpfinish = ent->msgtime + ((float)(MSG_ReadByte()) / 255); ent->lerpflags |= LERP_FINISH; @@ -573,22 +576,22 @@ void CL_ParseUpdate (int32_t bits) else ent->lerpflags &= ~LERP_FINISH; } - else if (cl.protocol == PROTOCOL_NETQUAKE) + else if(cl.protocol == PROTOCOL_NETQUAKE) { //HACK: if this bit is set, assume this is PROTOCOL_NEHAHRA - if (bits & U_TRANS) + if(bits & U_TRANS) { float a, b; - if (warn_about_nehahra_protocol) + if(warn_about_nehahra_protocol) { - Con_Warning ("nonstandard update bit, assuming Nehahra protocol\n"); + Con_Warning("nonstandard update bit, assuming Nehahra protocol\n"); warn_about_nehahra_protocol = false; } a = MSG_ReadFloat(); b = MSG_ReadFloat(); //alpha - if (a == 2) + if(a == 2) MSG_ReadFloat(); //fullbright (not using this yet) ent->alpha = ENTALPHA_ENCODE(b); } @@ -599,33 +602,34 @@ void CL_ParseUpdate (int32_t bits) //johnfitz -- moved here from above model = cl.model_precache[modnum]; - if (model != ent->model) + if(model != ent->model) { ent->model = model; - // automatic animation (torches, etc) can be either all together - // or randomized - if (model) + // automatic animation (torches, etc) can be either all together + // or randomized + if(model) { - if (model->synctype == ST_RAND) - ent->syncbase = (float)(rand()&0x7fff) / 0x7fff; + if(model->synctype == ST_RAND) + ent->syncbase = (float)(rand() & 0x7fff) / 0x7fff; else ent->syncbase = 0.0; } else - forcelink = true; // hack to make null model players work - if (num > 0 && num <= cl.maxclients) - R_TranslateNewPlayerSkin (num - 1); //johnfitz -- was R_TranslatePlayerSkin + forcelink = true; // hack to make null model players work + if(num > 0 && num <= cl.maxclients) + R_TranslateNewPlayerSkin(num - 1); //johnfitz -- was R_TranslatePlayerSkin ent->lerpflags |= LERP_RESETANIM; //johnfitz -- don't lerp animation across model changes } //johnfitz - if ( forcelink ) - { // didn't have an update last message - VectorCopy (ent->msg_origins[0], ent->msg_origins[1]); - VectorCopy (ent->msg_origins[0], ent->origin); - VectorCopy (ent->msg_angles[0], ent->msg_angles[1]); - VectorCopy (ent->msg_angles[0], ent->angles); + if(forcelink) + { + // didn't have an update last message + VectorCopy(ent->msg_origins[0], ent->msg_origins[1]); + VectorCopy(ent->msg_origins[0], ent->origin); + VectorCopy(ent->msg_angles[0], ent->msg_angles[1]); + VectorCopy(ent->msg_angles[0], ent->angles); ent->forcelink = true; } } @@ -635,9 +639,9 @@ void CL_ParseUpdate (int32_t bits) CL_ParseBaseline ================== */ -void CL_ParseBaseline (entity_t *ent, int32_t version) //johnfitz -- added argument +void CL_ParseBaseline(entity_t *ent, int32_t version) //johnfitz -- added argument { - int32_t i; + int32_t i; int32_t bits; //johnfitz //johnfitz -- PROTOCOL_FITZQUAKE @@ -648,10 +652,10 @@ void CL_ParseBaseline (entity_t *ent, int32_t version) //johnfitz -- added argum ent->baseline.colormap = MSG_ReadByte(); ent->baseline.skin = MSG_ReadByte(); - for (i = 0; i < 3; i++) + for(i = 0; i < 3; i++) { - ent->baseline.origin[i] = MSG_ReadCoord (cl.protocolflags); - ent->baseline.angles[i] = MSG_ReadAngle (cl.protocolflags); + ent->baseline.origin[i] = MSG_ReadCoord(cl.protocolflags); + ent->baseline.angles[i] = MSG_ReadAngle(cl.protocolflags); } ent->baseline.alpha = (bits & B_ALPHA) ? MSG_ReadByte() : ENTALPHA_DEFAULT; //johnfitz -- PROTOCOL_FITZQUAKE @@ -665,60 +669,61 @@ CL_ParseClientdata Server information pertaining to this client only ================== */ -void CL_ParseClientdata (void) +void CL_ParseClientdata(void) { - int32_t i, j; - int32_t bits; //johnfitz + int32_t i, j; + int32_t bits; //johnfitz - bits = (uint16_t)MSG_ReadShort (); //johnfitz -- read bits here isntead of in CL_ParseServerMessage() + bits = (uint16_t)MSG_ReadShort(); //johnfitz -- read bits here isntead of in CL_ParseServerMessage() //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & SU_EXTEND1) + if(bits & SU_EXTEND1) bits |= (MSG_ReadByte() << 16); - if (bits & SU_EXTEND2) + if(bits & SU_EXTEND2) bits |= (MSG_ReadByte() << 24); //johnfitz - if (bits & SU_VIEWHEIGHT) - cl.viewheight = MSG_ReadChar (); + if(bits & SU_VIEWHEIGHT) + cl.viewheight = MSG_ReadChar(); else cl.viewheight = DEFAULT_VIEWHEIGHT; - if (bits & SU_IDEALPITCH) - cl.idealpitch = MSG_ReadChar (); + if(bits & SU_IDEALPITCH) + cl.idealpitch = MSG_ReadChar(); else cl.idealpitch = 0; - VectorCopy (cl.mvelocity[0], cl.mvelocity[1]); - for (i = 0; i < 3; i++) + VectorCopy(cl.mvelocity[0], cl.mvelocity[1]); + for(i = 0; i < 3; i++) { - if (bits & (SU_PUNCH1< cl.maxclients) - Sys_Error ("CL_NewTranslation: slot > cl.maxclients"); + if(slot > cl.maxclients) + Sys_Error("CL_NewTranslation: slot > cl.maxclients"); dest = cl.scores[slot].translations; source = vid.colormap; - memcpy (dest, vid.colormap, sizeof(cl.scores[slot].translations)); + memcpy(dest, vid.colormap, sizeof(cl.scores[slot].translations)); top = cl.scores[slot].colors & 0xf0; - bottom = (cl.scores[slot].colors &15)<<4; - R_TranslatePlayerSkin (slot); + bottom = (cl.scores[slot].colors & 15) << 4; + R_TranslatePlayerSkin(slot); - for (i = 0; i < VID_GRADES; i++, dest += 256, source+=256) + for(i = 0; i < VID_GRADES; i++, dest += 256, source += 256) { - if (top < 128) // the artists made some backwards ranges. sigh. - memcpy (dest + TOP_RANGE, source + top, 16); + if(top < 128) // the artists made some backwards ranges. sigh. + memcpy(dest + TOP_RANGE, source + top, 16); else { - for (j = 0; j < 16; j++) - dest[TOP_RANGE+j] = source[top+15-j]; + for(j = 0; j < 16; j++) + dest[TOP_RANGE + j] = source[top + 15 - j]; } - if (bottom < 128) - memcpy (dest + BOTTOM_RANGE, source + bottom, 16); + if(bottom < 128) + memcpy(dest + BOTTOM_RANGE, source + bottom, 16); else { - for (j = 0; j < 16; j++) - dest[BOTTOM_RANGE+j] = source[bottom+15-j]; + for(j = 0; j < 16; j++) + dest[BOTTOM_RANGE + j] = source[bottom + 15 - j]; } } } @@ -871,18 +876,18 @@ void CL_NewTranslation (int32_t slot) CL_ParseStatic ===================== */ -void CL_ParseStatic (int32_t version) //johnfitz -- added a parameter +void CL_ParseStatic(int32_t version) //johnfitz -- added a parameter { entity_t *ent; - int32_t i; + int32_t i; i = cl.num_statics; - if (i >= MAX_STATIC_ENTITIES) - Host_Error ("Too many static entities"); + if(i >= MAX_STATIC_ENTITIES) + Host_Error("Too many static entities"); ent = &cl_static_entities[i]; cl.num_statics++; - CL_ParseBaseline (ent, version); //johnfitz -- added second parameter + CL_ParseBaseline(ent, version); //johnfitz -- added second parameter // copy it to the current state @@ -895,9 +900,9 @@ void CL_ParseStatic (int32_t version) //johnfitz -- added a parameter ent->effects = ent->baseline.effects; ent->alpha = ent->baseline.alpha; //johnfitz -- alpha - VectorCopy (ent->baseline.origin, ent->origin); - VectorCopy (ent->baseline.angles, ent->angles); - R_AddEfrags (ent); + VectorCopy(ent->baseline.origin, ent->origin); + VectorCopy(ent->baseline.angles, ent->angles); + R_AddEfrags(ent); } /* @@ -905,26 +910,26 @@ void CL_ParseStatic (int32_t version) //johnfitz -- added a parameter CL_ParseStaticSound =================== */ -void CL_ParseStaticSound (int32_t version) //johnfitz -- added argument +void CL_ParseStaticSound(int32_t version) //johnfitz -- added argument { - vec3_t org; - int32_t sound_num, vol, atten; - int32_t i; + vec3_t org; + int32_t sound_num, vol, atten; + int32_t i; - for (i = 0; i < 3; i++) - org[i] = MSG_ReadCoord (cl.protocolflags); + for(i = 0; i < 3; i++) + org[i] = MSG_ReadCoord(cl.protocolflags); //johnfitz -- PROTOCOL_FITZQUAKE - if (version == 2) - sound_num = MSG_ReadShort (); + if(version == 2) + sound_num = MSG_ReadShort(); else - sound_num = MSG_ReadByte (); + sound_num = MSG_ReadByte(); //johnfitz - vol = MSG_ReadByte (); - atten = MSG_ReadByte (); + vol = MSG_ReadByte(); + atten = MSG_ReadByte(); - S_StaticSound (cl.sound_precache[sound_num], org, vol, atten); + S_StaticSound(cl.sound_precache[sound_num], org, vol, atten); } @@ -935,129 +940,129 @@ void CL_ParseStaticSound (int32_t version) //johnfitz -- added argument CL_ParseServerMessage ===================== */ -void CL_ParseServerMessage (void) +void CL_ParseServerMessage(void) { - int32_t cmd; - int32_t i; - const char *str; //johnfitz - int32_t total, j, lastcmd; //johnfitz + int32_t cmd; + int32_t i; + const char *str; //johnfitz + int32_t total, j, lastcmd; //johnfitz // // if recording demos, copy the message out // - if (cl_shownet.value == 1) - Con_Printf ("%" PRIi32 " ",net_message.cursize); - else if (cl_shownet.value == 2) - Con_Printf ("------------------\n"); + if(cl_shownet.value == 1) + Con_Printf("%" PRIi32 " ", net_message.cursize); + else if(cl_shownet.value == 2) + Con_Printf("------------------\n"); - cl.onground = false; // unless the server says otherwise + cl.onground = false; // unless the server says otherwise // // parse the message // - MSG_BeginReading (); + MSG_BeginReading(); lastcmd = 0; - while (1) + while(1) { - if (msg_badread) - Host_Error ("CL_ParseServerMessage: Bad server message"); + if(msg_badread) + Host_Error("CL_ParseServerMessage: Bad server message"); - cmd = MSG_ReadByte (); + cmd = MSG_ReadByte(); - if (cmd == -1) + if(cmd == -1) { SHOWNET("END OF MESSAGE"); - return; // end of message + return; // end of message } - // if the high bit of the command byte is set, it is a fast update - if (cmd & U_SIGNAL) //johnfitz -- was 128, changed for clarity + // if the high bit of the command byte is set, it is a fast update + if(cmd & U_SIGNAL) //johnfitz -- was 128, changed for clarity { SHOWNET("fast update"); - CL_ParseUpdate (cmd&127); + CL_ParseUpdate(cmd & 127); continue; } SHOWNET(svc_strings[cmd]); - // other commands - switch (cmd) + // other commands + switch(cmd) { default: - Host_Error ("Illegible server message, previous was %s", svc_strings[lastcmd]); //johnfitz -- added svc_strings[lastcmd] + Host_Error("Illegible server message, previous was %s", svc_strings[lastcmd]); //johnfitz -- added svc_strings[lastcmd] break; case svc_nop: - // Con_Printf ("svc_nop\n"); + // Con_Printf ("svc_nop\n"); break; case svc_time: cl.mtime[1] = cl.mtime[0]; - cl.mtime[0] = MSG_ReadFloat (); + cl.mtime[0] = MSG_ReadFloat(); break; case svc_clientdata: - CL_ParseClientdata (); //johnfitz -- removed bits parameter, we will read this inside CL_ParseClientdata() + CL_ParseClientdata(); //johnfitz -- removed bits parameter, we will read this inside CL_ParseClientdata() break; case svc_version: - i = MSG_ReadLong (); + i = MSG_ReadLong(); //johnfitz -- support multiple protocols - if (i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) - Host_Error ("Server returned version %" PRIi32 ", not %" PRIi32 " or %" PRIi32 " or %" PRIi32 "", i, PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ); + if(i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) + Host_Error("Server returned version %" PRIi32 ", not %" PRIi32 " or %" PRIi32 " or %" PRIi32 "", i, PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ); cl.protocol = i; //johnfitz break; case svc_disconnect: - Host_EndGame ("Server disconnected\n"); + Host_EndGame("Server disconnected\n"); case svc_print: - Con_Printf ("%s", MSG_ReadString ()); + Con_Printf("%s", MSG_ReadString()); break; case svc_centerprint: //johnfitz -- log centerprints to console - str = MSG_ReadString (); - SCR_CenterPrint (str); - Con_LogCenterPrint (str); + str = MSG_ReadString(); + SCR_CenterPrint(str); + Con_LogCenterPrint(str); //johnfitz break; case svc_stufftext: - Cbuf_AddText (MSG_ReadString ()); + Cbuf_AddText(MSG_ReadString()); break; case svc_damage: - V_ParseDamage (); + V_ParseDamage(); break; case svc_serverinfo: - CL_ParseServerInfo (); - vid.recalc_refdef = true; // leave intermission full screen + CL_ParseServerInfo(); + vid.recalc_refdef = true; // leave intermission full screen break; case svc_setangle: - for (i=0 ; i<3 ; i++) - cl.viewangles[i] = MSG_ReadAngle (cl.protocolflags); + for(i = 0 ; i < 3 ; i++) + cl.viewangles[i] = MSG_ReadAngle(cl.protocolflags); break; case svc_setview: - cl.viewentity = MSG_ReadShort (); + cl.viewentity = MSG_ReadShort(); break; case svc_lightstyle: - i = MSG_ReadByte (); - if (i >= MAX_LIGHTSTYLES) - Sys_Error ("svc_lightstyle > MAX_LIGHTSTYLES"); - q_strlcpy (cl_lightstyle[i].map, MSG_ReadString(), MAX_STYLESTRING); + i = MSG_ReadByte(); + if(i >= MAX_LIGHTSTYLES) + Sys_Error("svc_lightstyle > MAX_LIGHTSTYLES"); + q_strlcpy(cl_lightstyle[i].map, MSG_ReadString(), MAX_STYLESTRING); cl_lightstyle[i].length = Q_strlen(cl_lightstyle[i].map); //johnfitz -- save extra info - if (cl_lightstyle[i].length) + if(cl_lightstyle[i].length) { total = 0; cl_lightstyle[i].peak = 'a'; - for (j=0; j>3, i&7); + S_StopSound(i >> 3, i & 7); break; case svc_updatename: - Sbar_Changed (); - i = MSG_ReadByte (); - if (i >= cl.maxclients) - Host_Error ("CL_ParseServerMessage: svc_updatename > MAX_SCOREBOARD"); - q_strlcpy (cl.scores[i].name, MSG_ReadString(), MAX_SCOREBOARDNAME); + Sbar_Changed(); + i = MSG_ReadByte(); + if(i >= cl.maxclients) + Host_Error("CL_ParseServerMessage: svc_updatename > MAX_SCOREBOARD"); + q_strlcpy(cl.scores[i].name, MSG_ReadString(), MAX_SCOREBOARDNAME); break; case svc_updatefrags: - Sbar_Changed (); - i = MSG_ReadByte (); - if (i >= cl.maxclients) - Host_Error ("CL_ParseServerMessage: svc_updatefrags > MAX_SCOREBOARD"); - cl.scores[i].frags = MSG_ReadShort (); + Sbar_Changed(); + i = MSG_ReadByte(); + if(i >= cl.maxclients) + Host_Error("CL_ParseServerMessage: svc_updatefrags > MAX_SCOREBOARD"); + cl.scores[i].frags = MSG_ReadShort(); break; case svc_updatecolors: - Sbar_Changed (); - i = MSG_ReadByte (); - if (i >= cl.maxclients) - Host_Error ("CL_ParseServerMessage: svc_updatecolors > MAX_SCOREBOARD"); - cl.scores[i].colors = MSG_ReadByte (); - CL_NewTranslation (i); + Sbar_Changed(); + i = MSG_ReadByte(); + if(i >= cl.maxclients) + Host_Error("CL_ParseServerMessage: svc_updatecolors > MAX_SCOREBOARD"); + cl.scores[i].colors = MSG_ReadByte(); + CL_NewTranslation(i); break; case svc_particle: - R_ParseParticleEffect (); + R_ParseParticleEffect(); break; case svc_spawnbaseline: - i = MSG_ReadShort (); + i = MSG_ReadShort(); // must use CL_EntityNum() to force cl.num_entities up - CL_ParseBaseline (CL_EntityNum(i), 1); // johnfitz -- added second parameter + CL_ParseBaseline(CL_EntityNum(i), 1); // johnfitz -- added second parameter break; case svc_spawnstatic: - CL_ParseStatic (1); //johnfitz -- added parameter + CL_ParseStatic(1); //johnfitz -- added parameter break; case svc_temp_entity: - CL_ParseTEnt (); + CL_ParseTEnt(); break; case svc_setpause: - cl.paused = MSG_ReadByte (); - if (cl.paused) - BGM_Pause (); + cl.paused = MSG_ReadByte(); + if(cl.paused) + BGM_Pause(); else - BGM_Resume (); + BGM_Resume(); break; case svc_signonnum: - i = MSG_ReadByte (); - if (i <= cls.signon) - Host_Error ("Received signon %" PRIi32 " when at %" PRIi32 "", i, cls.signon); + i = MSG_ReadByte(); + if(i <= cls.signon) + Host_Error("Received signon %" PRIi32 " when at %" PRIi32 "", i, cls.signon); cls.signon = i; //johnfitz -- if signonnum==2, signon packet has been fully parsed, so check for excessive static ents and efrags - if (i == 2) + if(i == 2) { - if (cl.num_statics > 128) - Con_DWarning ("%" PRIi32 " static entities exceeds standard limit of 128 (max = %" PRIi32 ").\n", cl.num_statics, MAX_STATIC_ENTITIES); - R_CheckEfrags (); + if(cl.num_statics > 128) + Con_DWarning("%" PRIi32 " static entities exceeds standard limit of 128 (max = %" PRIi32 ").\n", cl.num_statics, MAX_STATIC_ENTITIES); + R_CheckEfrags(); } //johnfitz - CL_SignonReply (); + CL_SignonReply(); break; case svc_killedmonster: @@ -1154,84 +1159,84 @@ void CL_ParseServerMessage (void) break; case svc_updatestat: - i = MSG_ReadByte (); - if (i < 0 || i >= MAX_CL_STATS) - Sys_Error ("svc_updatestat: %" PRIi32 " is invalid", i); - cl.stats[i] = MSG_ReadLong ();; + i = MSG_ReadByte(); + if(i < 0 || i >= MAX_CL_STATS) + Sys_Error("svc_updatestat: %" PRIi32 " is invalid", i); + cl.stats[i] = MSG_ReadLong();; break; case svc_spawnstaticsound: - CL_ParseStaticSound (1); //johnfitz -- added parameter + CL_ParseStaticSound(1); //johnfitz -- added parameter break; case svc_cdtrack: - cl.cdtrack = MSG_ReadByte (); - cl.looptrack = MSG_ReadByte (); - if ( (cls.demoplayback || cls.demorecording) && (cls.forcetrack != -1) ) - BGM_PlayCDtrack ((byte)cls.forcetrack, true); + cl.cdtrack = MSG_ReadByte(); + cl.looptrack = MSG_ReadByte(); + if((cls.demoplayback || cls.demorecording) && (cls.forcetrack != -1)) + BGM_PlayCDtrack((byte)cls.forcetrack, true); else - BGM_PlayCDtrack ((byte)cl.cdtrack, true); + BGM_PlayCDtrack((byte)cl.cdtrack, true); break; case svc_intermission: cl.intermission = 1; cl.completed_time = cl.time; - vid.recalc_refdef = true; // go to full screen + vid.recalc_refdef = true; // go to full screen break; case svc_finale: cl.intermission = 2; cl.completed_time = cl.time; - vid.recalc_refdef = true; // go to full screen + vid.recalc_refdef = true; // go to full screen //johnfitz -- log centerprints to console - str = MSG_ReadString (); - SCR_CenterPrint (str); - Con_LogCenterPrint (str); + str = MSG_ReadString(); + SCR_CenterPrint(str); + Con_LogCenterPrint(str); //johnfitz break; case svc_cutscene: cl.intermission = 3; cl.completed_time = cl.time; - vid.recalc_refdef = true; // go to full screen + vid.recalc_refdef = true; // go to full screen //johnfitz -- log centerprints to console - str = MSG_ReadString (); - SCR_CenterPrint (str); - Con_LogCenterPrint (str); + str = MSG_ReadString(); + SCR_CenterPrint(str); + Con_LogCenterPrint(str); //johnfitz break; case svc_sellscreen: - Cmd_ExecuteString ("help", src_command); + Cmd_ExecuteString("help", src_command); break; //johnfitz -- new svc types case svc_skybox: - Sky_LoadSkyBox (MSG_ReadString()); + Sky_LoadSkyBox(MSG_ReadString()); break; case svc_bf: - Cmd_ExecuteString ("bf", src_command); + Cmd_ExecuteString("bf", src_command); break; case svc_fog: - Fog_ParseServerMessage (); + Fog_ParseServerMessage(); break; case svc_spawnbaseline2: //PROTOCOL_FITZQUAKE - i = MSG_ReadShort (); + i = MSG_ReadShort(); // must use CL_EntityNum() to force cl.num_entities up - CL_ParseBaseline (CL_EntityNum(i), 2); + CL_ParseBaseline(CL_EntityNum(i), 2); break; case svc_spawnstatic2: //PROTOCOL_FITZQUAKE - CL_ParseStatic (2); + CL_ParseStatic(2); break; case svc_spawnstaticsound2: //PROTOCOL_FITZQUAKE - CL_ParseStaticSound (2); + CL_ParseStaticSound(2); break; - //johnfitz + //johnfitz } lastcmd = cmd; //johnfitz diff --git a/source/cl_tent.c b/source/cl_tent.c index 6333063..a818278 100644 --- a/source/cl_tent.c +++ b/source/cl_tent.c @@ -23,32 +23,32 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -int32_t num_temp_entities; -entity_t cl_temp_entities[MAX_TEMP_ENTITIES]; -beam_t cl_beams[MAX_BEAMS]; +int32_t num_temp_entities; +entity_t cl_temp_entities[MAX_TEMP_ENTITIES]; +beam_t cl_beams[MAX_BEAMS]; -sfx_t *cl_sfx_wizhit; -sfx_t *cl_sfx_knighthit; -sfx_t *cl_sfx_tink1; -sfx_t *cl_sfx_ric1; -sfx_t *cl_sfx_ric2; -sfx_t *cl_sfx_ric3; -sfx_t *cl_sfx_r_exp3; +sfx_t *cl_sfx_wizhit; +sfx_t *cl_sfx_knighthit; +sfx_t *cl_sfx_tink1; +sfx_t *cl_sfx_ric1; +sfx_t *cl_sfx_ric2; +sfx_t *cl_sfx_ric3; +sfx_t *cl_sfx_r_exp3; /* ================= CL_ParseTEnt ================= */ -void CL_InitTEnts (void) +void CL_InitTEnts(void) { - cl_sfx_wizhit = S_PrecacheSound ("wizard/hit.wav"); - cl_sfx_knighthit = S_PrecacheSound ("hknight/hit.wav"); - cl_sfx_tink1 = S_PrecacheSound ("weapons/tink1.wav"); - cl_sfx_ric1 = S_PrecacheSound ("weapons/ric1.wav"); - cl_sfx_ric2 = S_PrecacheSound ("weapons/ric2.wav"); - cl_sfx_ric3 = S_PrecacheSound ("weapons/ric3.wav"); - cl_sfx_r_exp3 = S_PrecacheSound ("weapons/r_exp3.wav"); + cl_sfx_wizhit = S_PrecacheSound("wizard/hit.wav"); + cl_sfx_knighthit = S_PrecacheSound("hknight/hit.wav"); + cl_sfx_tink1 = S_PrecacheSound("weapons/tink1.wav"); + cl_sfx_ric1 = S_PrecacheSound("weapons/ric1.wav"); + cl_sfx_ric2 = S_PrecacheSound("weapons/ric2.wav"); + cl_sfx_ric3 = S_PrecacheSound("weapons/ric3.wav"); + cl_sfx_r_exp3 = S_PrecacheSound("weapons/r_exp3.wav"); } /* @@ -56,53 +56,53 @@ void CL_InitTEnts (void) CL_ParseBeam ================= */ -void CL_ParseBeam (qmodel_t *m) +void CL_ParseBeam(qmodel_t *m) { - int32_t ent; - vec3_t start, end; - beam_t *b; - int32_t i; + int32_t ent; + vec3_t start, end; + beam_t *b; + int32_t i; - ent = MSG_ReadShort (); + ent = MSG_ReadShort(); - start[0] = MSG_ReadCoord (cl.protocolflags); - start[1] = MSG_ReadCoord (cl.protocolflags); - start[2] = MSG_ReadCoord (cl.protocolflags); + start[0] = MSG_ReadCoord(cl.protocolflags); + start[1] = MSG_ReadCoord(cl.protocolflags); + start[2] = MSG_ReadCoord(cl.protocolflags); - end[0] = MSG_ReadCoord (cl.protocolflags); - end[1] = MSG_ReadCoord (cl.protocolflags); - end[2] = MSG_ReadCoord (cl.protocolflags); + end[0] = MSG_ReadCoord(cl.protocolflags); + end[1] = MSG_ReadCoord(cl.protocolflags); + end[2] = MSG_ReadCoord(cl.protocolflags); // override any beam with the same entity - for (i=0, b=cl_beams ; i< MAX_BEAMS ; i++, b++) - if (b->entity == ent) + for(i = 0, b = cl_beams ; i < MAX_BEAMS ; i++, b++) + if(b->entity == ent) { b->entity = ent; b->model = m; b->endtime = cl.time + 0.2; - VectorCopy (start, b->start); - VectorCopy (end, b->end); + VectorCopy(start, b->start); + VectorCopy(end, b->end); return; } // find a free beam - for (i=0, b=cl_beams ; i< MAX_BEAMS ; i++, b++) + for(i = 0, b = cl_beams ; i < MAX_BEAMS ; i++, b++) { - if (!b->model || b->endtime < cl.time) + if(!b->model || b->endtime < cl.time) { b->entity = ent; b->model = m; b->endtime = cl.time + 0.2; - VectorCopy (start, b->start); - VectorCopy (end, b->end); + VectorCopy(start, b->start); + VectorCopy(end, b->end); return; } } //johnfitz -- less spammy overflow message - if (!dev_overflows.beams || dev_overflows.beams + CONSOLE_RESPAM_TIME < realtime ) + if(!dev_overflows.beams || dev_overflows.beams + CONSOLE_RESPAM_TIME < realtime) { - Con_Printf ("Beam list overflow!\n"); + Con_Printf("Beam list overflow!\n"); dev_overflows.beams = realtime; } //johnfitz @@ -113,149 +113,149 @@ void CL_ParseBeam (qmodel_t *m) CL_ParseTEnt ================= */ -void CL_ParseTEnt (void) +void CL_ParseTEnt(void) { - int32_t type; - vec3_t pos; - dlight_t *dl; - int32_t rnd; - int32_t colorStart, colorLength; + int32_t type; + vec3_t pos; + dlight_t *dl; + int32_t rnd; + int32_t colorStart, colorLength; - type = MSG_ReadByte (); - switch (type) + type = MSG_ReadByte(); + switch(type) { - case TE_WIZSPIKE: // spike hitting wall - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - R_RunParticleEffect (pos, vec3_origin, 20, 30); - S_StartSound (-1, 0, cl_sfx_wizhit, pos, 1, 1); + case TE_WIZSPIKE: // spike hitting wall + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + R_RunParticleEffect(pos, vec3_origin, 20, 30); + S_StartSound(-1, 0, cl_sfx_wizhit, pos, 1, 1); break; - case TE_KNIGHTSPIKE: // spike hitting wall - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - R_RunParticleEffect (pos, vec3_origin, 226, 20); - S_StartSound (-1, 0, cl_sfx_knighthit, pos, 1, 1); + case TE_KNIGHTSPIKE: // spike hitting wall + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + R_RunParticleEffect(pos, vec3_origin, 226, 20); + S_StartSound(-1, 0, cl_sfx_knighthit, pos, 1, 1); break; - case TE_SPIKE: // spike hitting wall - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - R_RunParticleEffect (pos, vec3_origin, 0, 10); - if ( rand() % 5 ) - S_StartSound (-1, 0, cl_sfx_tink1, pos, 1, 1); + case TE_SPIKE: // spike hitting wall + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + R_RunParticleEffect(pos, vec3_origin, 0, 10); + if(rand() % 5) + S_StartSound(-1, 0, cl_sfx_tink1, pos, 1, 1); else { rnd = rand() & 3; - if (rnd == 1) - S_StartSound (-1, 0, cl_sfx_ric1, pos, 1, 1); - else if (rnd == 2) - S_StartSound (-1, 0, cl_sfx_ric2, pos, 1, 1); + if(rnd == 1) + S_StartSound(-1, 0, cl_sfx_ric1, pos, 1, 1); + else if(rnd == 2) + S_StartSound(-1, 0, cl_sfx_ric2, pos, 1, 1); else - S_StartSound (-1, 0, cl_sfx_ric3, pos, 1, 1); + S_StartSound(-1, 0, cl_sfx_ric3, pos, 1, 1); } break; - case TE_SUPERSPIKE: // super spike hitting wall - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - R_RunParticleEffect (pos, vec3_origin, 0, 20); + case TE_SUPERSPIKE: // super spike hitting wall + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + R_RunParticleEffect(pos, vec3_origin, 0, 20); - if ( rand() % 5 ) - S_StartSound (-1, 0, cl_sfx_tink1, pos, 1, 1); + if(rand() % 5) + S_StartSound(-1, 0, cl_sfx_tink1, pos, 1, 1); else { rnd = rand() & 3; - if (rnd == 1) - S_StartSound (-1, 0, cl_sfx_ric1, pos, 1, 1); - else if (rnd == 2) - S_StartSound (-1, 0, cl_sfx_ric2, pos, 1, 1); + if(rnd == 1) + S_StartSound(-1, 0, cl_sfx_ric1, pos, 1, 1); + else if(rnd == 2) + S_StartSound(-1, 0, cl_sfx_ric2, pos, 1, 1); else - S_StartSound (-1, 0, cl_sfx_ric3, pos, 1, 1); + S_StartSound(-1, 0, cl_sfx_ric3, pos, 1, 1); } break; - case TE_GUNSHOT: // bullet hitting wall - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - R_RunParticleEffect (pos, vec3_origin, 0, 20); + case TE_GUNSHOT: // bullet hitting wall + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + R_RunParticleEffect(pos, vec3_origin, 0, 20); break; - case TE_EXPLOSION: // rocket explosion - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - R_ParticleExplosion (pos); - dl = CL_AllocDlight (0); - VectorCopy (pos, dl->origin); + case TE_EXPLOSION: // rocket explosion + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + R_ParticleExplosion(pos); + dl = CL_AllocDlight(0); + VectorCopy(pos, dl->origin); dl->radius = 350; dl->die = cl.time + 0.5; dl->decay = 300; - S_StartSound (-1, 0, cl_sfx_r_exp3, pos, 1, 1); + S_StartSound(-1, 0, cl_sfx_r_exp3, pos, 1, 1); break; - case TE_TAREXPLOSION: // tarbaby explosion - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - R_BlobExplosion (pos); + case TE_TAREXPLOSION: // tarbaby explosion + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + R_BlobExplosion(pos); - S_StartSound (-1, 0, cl_sfx_r_exp3, pos, 1, 1); + S_StartSound(-1, 0, cl_sfx_r_exp3, pos, 1, 1); break; - case TE_LIGHTNING1: // lightning bolts - CL_ParseBeam (Mod_ForName("progs/bolt.mdl", true)); + case TE_LIGHTNING1: // lightning bolts + CL_ParseBeam(Mod_ForName("progs/bolt.mdl", true)); break; - case TE_LIGHTNING2: // lightning bolts - CL_ParseBeam (Mod_ForName("progs/bolt2.mdl", true)); + case TE_LIGHTNING2: // lightning bolts + CL_ParseBeam(Mod_ForName("progs/bolt2.mdl", true)); break; - case TE_LIGHTNING3: // lightning bolts - CL_ParseBeam (Mod_ForName("progs/bolt3.mdl", true)); + case TE_LIGHTNING3: // lightning bolts + CL_ParseBeam(Mod_ForName("progs/bolt3.mdl", true)); break; // PGM 01/21/97 - case TE_BEAM: // grappling hook beam - CL_ParseBeam (Mod_ForName("progs/beam.mdl", true)); + case TE_BEAM: // grappling hook beam + CL_ParseBeam(Mod_ForName("progs/beam.mdl", true)); break; // PGM 01/21/97 case TE_LAVASPLASH: - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - R_LavaSplash (pos); + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + R_LavaSplash(pos); break; case TE_TELEPORT: - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - R_TeleportSplash (pos); + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + R_TeleportSplash(pos); break; - case TE_EXPLOSION2: // color mapped explosion - pos[0] = MSG_ReadCoord (cl.protocolflags); - pos[1] = MSG_ReadCoord (cl.protocolflags); - pos[2] = MSG_ReadCoord (cl.protocolflags); - colorStart = MSG_ReadByte (); - colorLength = MSG_ReadByte (); - R_ParticleExplosion2 (pos, colorStart, colorLength); - dl = CL_AllocDlight (0); - VectorCopy (pos, dl->origin); + case TE_EXPLOSION2: // color mapped explosion + pos[0] = MSG_ReadCoord(cl.protocolflags); + pos[1] = MSG_ReadCoord(cl.protocolflags); + pos[2] = MSG_ReadCoord(cl.protocolflags); + colorStart = MSG_ReadByte(); + colorLength = MSG_ReadByte(); + R_ParticleExplosion2(pos, colorStart, colorLength); + dl = CL_AllocDlight(0); + VectorCopy(pos, dl->origin); dl->radius = 350; dl->die = cl.time + 0.5; dl->decay = 300; - S_StartSound (-1, 0, cl_sfx_r_exp3, pos, 1, 1); + S_StartSound(-1, 0, cl_sfx_r_exp3, pos, 1, 1); break; default: - Sys_Error ("CL_ParseTEnt: bad type"); + Sys_Error("CL_ParseTEnt: bad type"); } } @@ -265,16 +265,16 @@ void CL_ParseTEnt (void) CL_NewTempEntity ================= */ -entity_t *CL_NewTempEntity (void) +entity_t *CL_NewTempEntity(void) { - entity_t *ent; + entity_t *ent; - if (cl_numvisedicts == MAX_VISEDICTS) + if(cl_numvisedicts == MAX_VISEDICTS) return NULL; - if (num_temp_entities == MAX_TEMP_ENTITIES) + if(num_temp_entities == MAX_TEMP_ENTITIES) return NULL; ent = &cl_temp_entities[num_temp_entities]; - memset (ent, 0, sizeof(*ent)); + memset(ent, 0, sizeof(*ent)); num_temp_entities++; cl_visedicts[cl_numvisedicts] = ent; cl_numvisedicts++; @@ -289,72 +289,72 @@ entity_t *CL_NewTempEntity (void) CL_UpdateTEnts ================= */ -void CL_UpdateTEnts (void) +void CL_UpdateTEnts(void) { - int32_t i, j; //johnfitz -- use j instead of using i twice, so we don't corrupt memory - beam_t *b; - vec3_t dist, org; - float d; - entity_t *ent; - float yaw, pitch; - float forward; + int32_t i, j; //johnfitz -- use j instead of using i twice, so we don't corrupt memory + beam_t *b; + vec3_t dist, org; + float d; + entity_t *ent; + float yaw, pitch; + float forward; num_temp_entities = 0; - srand ((int32_t) (cl.time * 1000)); //johnfitz -- freeze beams when paused + srand((int32_t)(cl.time * 1000)); //johnfitz -- freeze beams when paused // update lightning - for (i=0, b=cl_beams ; i< MAX_BEAMS ; i++, b++) + for(i = 0, b = cl_beams ; i < MAX_BEAMS ; i++, b++) { - if (!b->model || b->endtime < cl.time) + if(!b->model || b->endtime < cl.time) continue; - // if coming from the player, update the start position - if (b->entity == cl.viewentity) + // if coming from the player, update the start position + if(b->entity == cl.viewentity) { - VectorCopy (cl_entities[cl.viewentity].origin, b->start); + VectorCopy(cl_entities[cl.viewentity].origin, b->start); } - // calculate pitch and yaw - VectorSubtract (b->end, b->start, dist); + // calculate pitch and yaw + VectorSubtract(b->end, b->start, dist); - if (dist[1] == 0 && dist[0] == 0) + if(dist[1] == 0 && dist[0] == 0) { yaw = 0; - if (dist[2] > 0) + if(dist[2] > 0) pitch = 90; else pitch = 270; } else { - yaw = (int32_t) (atan2(dist[1], dist[0]) * 180 / M_PI); - if (yaw < 0) + yaw = (int32_t)(atan2(dist[1], dist[0]) * 180 / M_PI); + if(yaw < 0) yaw += 360; - forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]); - pitch = (int32_t) (atan2(dist[2], forward) * 180 / M_PI); - if (pitch < 0) + forward = sqrt(dist[0] * dist[0] + dist[1] * dist[1]); + pitch = (int32_t)(atan2(dist[2], forward) * 180 / M_PI); + if(pitch < 0) pitch += 360; } - // add new entities for the lightning - VectorCopy (b->start, org); + // add new entities for the lightning + VectorCopy(b->start, org); d = VectorNormalize(dist); - while (d > 0) + while(d > 0) { - ent = CL_NewTempEntity (); - if (!ent) + ent = CL_NewTempEntity(); + if(!ent) return; - VectorCopy (org, ent->origin); + VectorCopy(org, ent->origin); ent->model = b->model; ent->angles[0] = pitch; ent->angles[1] = yaw; - ent->angles[2] = rand()%360; + ent->angles[2] = rand() % 360; //johnfitz -- use j instead of using i twice, so we don't corrupt memory - for (j=0 ; j<3 ; j++) - org[j] += dist[j]*30; + for(j = 0 ; j < 3 ; j++) + org[j] += dist[j] * 30; d -= 30; } } diff --git a/source/client.h b/source/client.h index dd24429..d5b597f 100644 --- a/source/client.h +++ b/source/client.h @@ -27,72 +27,73 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. typedef struct { - int32_t length; - char map[MAX_STYLESTRING]; - char average; //johnfitz - char peak; //johnfitz + int32_t length; + char map[MAX_STYLESTRING]; + char average; //johnfitz + char peak; //johnfitz } lightstyle_t; typedef struct { - char name[MAX_SCOREBOARDNAME]; - float entertime; - int32_t frags; - int32_t colors; // two 4 bit fields - byte translations[VID_GRADES*256]; + char name[MAX_SCOREBOARDNAME]; + float entertime; + int32_t frags; + int32_t colors; // two 4 bit fields + byte translations[VID_GRADES * 256]; } scoreboard_t; typedef struct { - int32_t destcolor[3]; - int32_t percent; // 0-256 + int32_t destcolor[3]; + int32_t percent; // 0-256 } cshift_t; -#define CSHIFT_CONTENTS 0 -#define CSHIFT_DAMAGE 1 -#define CSHIFT_BONUS 2 -#define CSHIFT_POWERUP 3 -#define NUM_CSHIFTS 4 +#define CSHIFT_CONTENTS 0 +#define CSHIFT_DAMAGE 1 +#define CSHIFT_BONUS 2 +#define CSHIFT_POWERUP 3 +#define NUM_CSHIFTS 4 -#define NAME_LENGTH 64 +#define NAME_LENGTH 64 // // client_state_t should hold all pieces of the client state // -#define SIGNONS 4 // signon messages to receive before connected +#define SIGNONS 4 // signon messages to receive before connected -#define MAX_DLIGHTS 64 //johnfitz -- was 32 +#define MAX_DLIGHTS 64 //johnfitz -- was 32 typedef struct { - vec3_t origin; - float radius; - float die; // stop lighting after this time - float decay; // drop this each second - float minlight; // don't add when contributing less - int32_t key; - vec3_t color; //johnfitz -- lit support via lordhavoc + vec3_t origin; + float radius; + float die; // stop lighting after this time + float decay; // drop this each second + float minlight; // don't add when contributing less + int32_t key; + vec3_t color; //johnfitz -- lit support via lordhavoc } dlight_t; -#define MAX_BEAMS 32 //johnfitz -- was 24 +#define MAX_BEAMS 32 //johnfitz -- was 24 typedef struct { - int32_t entity; - struct qmodel_s *model; - float endtime; - vec3_t start, end; + int32_t entity; + struct qmodel_s *model; + float endtime; + vec3_t start, end; } beam_t; -#define MAX_MAPSTRING 2048 -#define MAX_DEMOS 8 -#define MAX_DEMONAME 16 +#define MAX_MAPSTRING 2048 +#define MAX_DEMOS 8 +#define MAX_DEMONAME 16 -typedef enum { -ca_dedicated, // a dedicated server with no ability to start a client -ca_disconnected, // full screen console with no connection -ca_connected // valid netcon, talking to a server +typedef enum +{ + ca_dedicated, // a dedicated server with no ability to start a client + ca_disconnected, // full screen console with no connection + ca_connected // valid netcon, talking to a server } cactive_t; // @@ -101,39 +102,39 @@ ca_connected // valid netcon, talking to a server // typedef struct { - cactive_t state; + cactive_t state; // personalization data sent to server - char spawnparms[MAX_MAPSTRING]; // to restart a level + char spawnparms[MAX_MAPSTRING]; // to restart a level // demo loop control - int32_t demonum; // -1 = don't play demos - char demos[MAX_DEMOS][MAX_DEMONAME]; // when not playing + int32_t demonum; // -1 = don't play demos + char demos[MAX_DEMOS][MAX_DEMONAME]; // when not playing // demo recording info must be here, because record is started before // entering a map (and clearing client_state_t) - bool demorecording; - bool demoplayback; + bool demorecording; + bool demoplayback; // did the user pause demo playback? (separate from cl.paused because we don't // want a svc_setpause inside the demo to actually pause demo playback). - bool demopaused; + bool demopaused; - bool timedemo; - int32_t forcetrack; // -1 = use normal cd track - FILE *demofile; - int32_t td_lastframe; // to meter out one message a frame - int32_t td_startframe; // host_framecount at start - float td_starttime; // realtime at second frame of timedemo + bool timedemo; + int32_t forcetrack; // -1 = use normal cd track + FILE *demofile; + int32_t td_lastframe; // to meter out one message a frame + int32_t td_startframe; // host_framecount at start + float td_starttime; // realtime at second frame of timedemo // connection information - int32_t signon; // 0 to SIGNONS - struct qsocket_s *netcon; - sizebuf_t message; // writing buffer to send to server + int32_t signon; // 0 to SIGNONS + struct qsocket_s *netcon; + sizebuf_t message; // writing buffer to send to server } client_static_t; -extern client_static_t cls; +extern client_static_t cls; // // the client_state_t structure is wiped completely at every @@ -141,236 +142,236 @@ extern client_static_t cls; // typedef struct { - int32_t movemessages; // since connecting to this server - // throw out the first couple, so the player - // doesn't accidentally do something the - // first frame - usercmd_t cmd; // last command sent to the server + int32_t movemessages; // since connecting to this server + // throw out the first couple, so the player + // doesn't accidentally do something the + // first frame + usercmd_t cmd; // last command sent to the server // information for local display - int32_t stats[MAX_CL_STATS]; // health, etc - int32_t items; // inventory bit flags - float item_gettime[32]; // cl.time of aquiring item, for blinking - float faceanimtime; // use anim frame if cl.time < this + int32_t stats[MAX_CL_STATS]; // health, etc + int32_t items; // inventory bit flags + float item_gettime[32]; // cl.time of aquiring item, for blinking + float faceanimtime; // use anim frame if cl.time < this - cshift_t cshifts[NUM_CSHIFTS]; // color shifts for damage, powerups - cshift_t prev_cshifts[NUM_CSHIFTS]; // and content types + cshift_t cshifts[NUM_CSHIFTS]; // color shifts for damage, powerups + cshift_t prev_cshifts[NUM_CSHIFTS]; // and content types // the client maintains its own idea of view angles, which are // sent to the server each frame. The server sets punchangle when // the view is temporarliy offset, and an angle reset commands at the start // of each level and after teleporting. - vec3_t mviewangles[2]; // during demo playback viewangles is lerped - // between these - vec3_t viewangles; + vec3_t mviewangles[2]; // during demo playback viewangles is lerped + // between these + vec3_t viewangles; - vec3_t mvelocity[2]; // update by server, used for lean+bob - // (0 is newest) - vec3_t velocity; // lerped between mvelocity[0] and [1] + vec3_t mvelocity[2]; // update by server, used for lean+bob + // (0 is newest) + vec3_t velocity; // lerped between mvelocity[0] and [1] - vec3_t punchangle; // temporary offset + vec3_t punchangle; // temporary offset // pitch drifting vars - float idealpitch; - float pitchvel; - bool nodrift; - float driftmove; - double laststop; + float idealpitch; + float pitchvel; + bool nodrift; + float driftmove; + double laststop; - float viewheight; - float crouch; // local amount for smoothing stepups + float viewheight; + float crouch; // local amount for smoothing stepups - bool paused; // send over by server - bool onground; - bool inwater; + bool paused; // send over by server + bool onground; + bool inwater; - int32_t intermission; // don't change view angle, full screen, etc - int32_t completed_time; // latched at intermission start + int32_t intermission; // don't change view angle, full screen, etc + int32_t completed_time; // latched at intermission start - double mtime[2]; // the timestamp of last two messages - double time; // clients view of time, should be between - // servertime and oldservertime to generate - // a lerp point for other data - double oldtime; // previous cl.time, time-oldtime is used - // to decay light values and smooth step ups + double mtime[2]; // the timestamp of last two messages + double time; // clients view of time, should be between + // servertime and oldservertime to generate + // a lerp point for other data + double oldtime; // previous cl.time, time-oldtime is used + // to decay light values and smooth step ups - float last_received_message; // (realtime) for net trouble icon + float last_received_message; // (realtime) for net trouble icon // // information that is static for the entire time connected to a server // - struct qmodel_s *model_precache[MAX_MODELS]; - struct sfx_s *sound_precache[MAX_SOUNDS]; + struct qmodel_s *model_precache[MAX_MODELS]; + struct sfx_s *sound_precache[MAX_SOUNDS]; - char mapname[128]; - char levelname[128]; // for display on solo scoreboard //johnfitz -- was 40. - int32_t viewentity; // cl_entitites[cl.viewentity] = player - int32_t maxclients; - int32_t gametype; + char mapname[128]; + char levelname[128]; // for display on solo scoreboard //johnfitz -- was 40. + int32_t viewentity; // cl_entitites[cl.viewentity] = player + int32_t maxclients; + int32_t gametype; // refresh related state - struct qmodel_s *worldmodel; // cl_entitites[0].model - struct efrag_s *free_efrags; - int32_t num_efrags; - int32_t num_entities; // held in cl_entities array - int32_t num_statics; // held in cl_staticentities array - entity_t viewent; // the gun model + struct qmodel_s *worldmodel; // cl_entitites[0].model + struct efrag_s *free_efrags; + int32_t num_efrags; + int32_t num_entities; // held in cl_entities array + int32_t num_statics; // held in cl_staticentities array + entity_t viewent; // the gun model - int32_t cdtrack, looptrack; // cd audio + int32_t cdtrack, looptrack; // cd audio // frag scoreboard - scoreboard_t *scores; // [cl.maxclients] + scoreboard_t *scores; // [cl.maxclients] - unsigned protocol; //johnfitz - unsigned protocolflags; + unsigned protocol; //johnfitz + unsigned protocolflags; } client_state_t; // // cvars // -extern cvar_t cl_name; -extern cvar_t cl_color; +extern cvar_t cl_name; +extern cvar_t cl_color; -extern cvar_t cl_upspeed; -extern cvar_t cl_forwardspeed; -extern cvar_t cl_backspeed; -extern cvar_t cl_sidespeed; +extern cvar_t cl_upspeed; +extern cvar_t cl_forwardspeed; +extern cvar_t cl_backspeed; +extern cvar_t cl_sidespeed; -extern cvar_t cl_movespeedkey; +extern cvar_t cl_movespeedkey; -extern cvar_t cl_yawspeed; -extern cvar_t cl_pitchspeed; +extern cvar_t cl_yawspeed; +extern cvar_t cl_pitchspeed; -extern cvar_t cl_anglespeedkey; +extern cvar_t cl_anglespeedkey; -extern cvar_t cl_alwaysrun; // QuakeSpasm +extern cvar_t cl_alwaysrun; // QuakeSpasm -extern cvar_t cl_autofire; +extern cvar_t cl_autofire; -extern cvar_t cl_shownet; -extern cvar_t cl_nolerp; +extern cvar_t cl_shownet; +extern cvar_t cl_nolerp; -extern cvar_t cfg_unbindall; +extern cvar_t cfg_unbindall; -extern cvar_t cl_pitchdriftspeed; -extern cvar_t lookspring; -extern cvar_t lookstrafe; -extern cvar_t sensitivity; +extern cvar_t cl_pitchdriftspeed; +extern cvar_t lookspring; +extern cvar_t lookstrafe; +extern cvar_t sensitivity; -extern cvar_t m_pitch; -extern cvar_t m_yaw; -extern cvar_t m_forward; -extern cvar_t m_side; +extern cvar_t m_pitch; +extern cvar_t m_yaw; +extern cvar_t m_forward; +extern cvar_t m_side; -#define MAX_TEMP_ENTITIES 256 //johnfitz -- was 64 -#define MAX_STATIC_ENTITIES 4096 //ericw -- was 512 //johnfitz -- was 128 -#define MAX_VISEDICTS 4096 // larger, now we support BSP2 +#define MAX_TEMP_ENTITIES 256 //johnfitz -- was 64 +#define MAX_STATIC_ENTITIES 4096 //ericw -- was 512 //johnfitz -- was 128 +#define MAX_VISEDICTS 4096 // larger, now we support BSP2 -extern client_state_t cl; +extern client_state_t cl; // FIXME, allocate dynamically -extern entity_t cl_static_entities[MAX_STATIC_ENTITIES]; -extern lightstyle_t cl_lightstyle[MAX_LIGHTSTYLES]; -extern dlight_t cl_dlights[MAX_DLIGHTS]; -extern entity_t cl_temp_entities[MAX_TEMP_ENTITIES]; -extern beam_t cl_beams[MAX_BEAMS]; -extern entity_t *cl_visedicts[MAX_VISEDICTS]; -extern int32_t cl_numvisedicts; +extern entity_t cl_static_entities[MAX_STATIC_ENTITIES]; +extern lightstyle_t cl_lightstyle[MAX_LIGHTSTYLES]; +extern dlight_t cl_dlights[MAX_DLIGHTS]; +extern entity_t cl_temp_entities[MAX_TEMP_ENTITIES]; +extern beam_t cl_beams[MAX_BEAMS]; +extern entity_t *cl_visedicts[MAX_VISEDICTS]; +extern int32_t cl_numvisedicts; -extern entity_t *cl_entities; //johnfitz -- was a static array, now on hunk -extern int32_t cl_max_edicts; //johnfitz -- only changes when new map loads +extern entity_t *cl_entities; //johnfitz -- was a static array, now on hunk +extern int32_t cl_max_edicts; //johnfitz -- only changes when new map loads //============================================================================= // // cl_main // -dlight_t *CL_AllocDlight (int32_t key); -void CL_DecayLights (void); +dlight_t *CL_AllocDlight(int32_t key); +void CL_DecayLights(void); -void CL_Init (void); +void CL_Init(void); -void CL_EstablishConnection (const char *host); -void CL_Signon1 (void); -void CL_Signon2 (void); -void CL_Signon3 (void); -void CL_Signon4 (void); +void CL_EstablishConnection(const char *host); +void CL_Signon1(void); +void CL_Signon2(void); +void CL_Signon3(void); +void CL_Signon4(void); -void CL_Disconnect (void); -void CL_Disconnect_f (void); -void CL_NextDemo (void); +void CL_Disconnect(void); +void CL_Disconnect_f(void); +void CL_NextDemo(void); // // cl_input // typedef struct { - int32_t down[2]; // key nums holding it down - int32_t state; // low bit is down state + int32_t down[2]; // key nums holding it down + int32_t state; // low bit is down state } kbutton_t; -extern kbutton_t in_mlook, in_klook; -extern kbutton_t in_strafe; -extern kbutton_t in_speed; +extern kbutton_t in_mlook, in_klook; +extern kbutton_t in_strafe; +extern kbutton_t in_speed; -void CL_InitInput (void); -void CL_SendCmd (void); -void CL_SendMove (const usercmd_t *cmd); -int32_t CL_ReadFromServer (void); -void CL_BaseMove (usercmd_t *cmd); +void CL_InitInput(void); +void CL_SendCmd(void); +void CL_SendMove(const usercmd_t *cmd); +int32_t CL_ReadFromServer(void); +void CL_BaseMove(usercmd_t *cmd); -void CL_ParseTEnt (void); -void CL_UpdateTEnts (void); +void CL_ParseTEnt(void); +void CL_UpdateTEnts(void); -void CL_ClearState (void); +void CL_ClearState(void); // // cl_demo.c // -void CL_StopPlayback (void); -int32_t CL_GetMessage (void); +void CL_StopPlayback(void); +int32_t CL_GetMessage(void); -void CL_Stop_f (void); -void CL_Record_f (void); -void CL_PlayDemo_f (void); -void CL_TimeDemo_f (void); +void CL_Stop_f(void); +void CL_Record_f(void); +void CL_PlayDemo_f(void); +void CL_TimeDemo_f(void); // // cl_parse.c // -void CL_ParseServerMessage (void); -void CL_NewTranslation (int32_t slot); +void CL_ParseServerMessage(void); +void CL_NewTranslation(int32_t slot); // // view // -void V_StartPitchDrift (void); -void V_StopPitchDrift (void); +void V_StartPitchDrift(void); +void V_StopPitchDrift(void); -void V_RenderView (void); +void V_RenderView(void); //void V_UpdatePalette (void); //johnfitz -void V_Register (void); -void V_ParseDamage (void); -void V_SetContentsColor (int32_t contents); +void V_Register(void); +void V_ParseDamage(void); +void V_SetContentsColor(int32_t contents); // // cl_tent // -void CL_InitTEnts (void); -void CL_SignonReply (void); +void CL_InitTEnts(void); +void CL_SignonReply(void); // // chase // -extern cvar_t chase_active; +extern cvar_t chase_active; -void Chase_Init (void); -void TraceLine (vec3_t start, vec3_t end, vec3_t impact); -void Chase_UpdateForClient (void); //johnfitz -void Chase_UpdateForDrawing (void); //johnfitz +void Chase_Init(void); +void TraceLine(vec3_t start, vec3_t end, vec3_t impact); +void Chase_UpdateForClient(void); //johnfitz +void Chase_UpdateForDrawing(void); //johnfitz -#endif /* _CLIENT_H_ */ +#endif /* _CLIENT_H_ */ diff --git a/source/cmd.c b/source/cmd.c index 744880b..7b393b3 100644 --- a/source/cmd.c +++ b/source/cmd.c @@ -24,22 +24,22 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -void Cmd_ForwardToServer (void); +void Cmd_ForwardToServer(void); -#define MAX_ALIAS_NAME 32 +#define MAX_ALIAS_NAME 32 #define CMDLINE_LENGTH 256 //johnfitz -- mirrored in common.c typedef struct cmdalias_s { - struct cmdalias_s *next; - char name[MAX_ALIAS_NAME]; - char *value; + struct cmdalias_s *next; + char name[MAX_ALIAS_NAME]; + char *value; } cmdalias_t; -cmdalias_t *cmd_alias; +cmdalias_t *cmd_alias; -bool cmd_wait; +bool cmd_wait; //============================================================================= @@ -52,7 +52,7 @@ next frame. This allows commands like: bind g "impulse 5 ; +attack ; wait ; -attack ; impulse 2" ============ */ -void Cmd_Wait_f (void) +void Cmd_Wait_f(void) { cmd_wait = true; } @@ -60,21 +60,21 @@ void Cmd_Wait_f (void) /* ============================================================================= - COMMAND BUFFER + COMMAND BUFFER ============================================================================= */ -sizebuf_t cmd_text; +sizebuf_t cmd_text; /* ============ Cbuf_Init ============ */ -void Cbuf_Init (void) +void Cbuf_Init(void) { - SZ_Alloc (&cmd_text, 1<<18); // space for commands and script files. spike -- was 8192, but modern configs can be _HUGE_, at least if they contain lots of comments/docs for things. + SZ_Alloc(&cmd_text, 1 << 18); // space for commands and script files. spike -- was 8192, but modern configs can be _HUGE_, at least if they contain lots of comments/docs for things. } @@ -85,19 +85,19 @@ Cbuf_AddText Adds command text at the end of the buffer ============ */ -void Cbuf_AddText (const char *text) +void Cbuf_AddText(const char *text) { - int32_t l; + int32_t l; - l = Q_strlen (text); + l = Q_strlen(text); - if (cmd_text.cursize + l >= cmd_text.maxsize) + if(cmd_text.cursize + l >= cmd_text.maxsize) { - Con_Printf ("Cbuf_AddText: overflow\n"); + Con_Printf("Cbuf_AddText: overflow\n"); return; } - SZ_Write (&cmd_text, text, Q_strlen (text)); + SZ_Write(&cmd_text, text, Q_strlen(text)); } @@ -110,30 +110,30 @@ Adds a \n to the text FIXME: actually change the command buffer to do less copying ============ */ -void Cbuf_InsertText (const char *text) +void Cbuf_InsertText(const char *text) { - char *temp; - int32_t templen; + char *temp; + int32_t templen; // copy off any commands still remaining in the exec buffer templen = cmd_text.cursize; - if (templen) + if(templen) { - temp = (char *) Z_Malloc (templen); - Q_memcpy (temp, cmd_text.data, templen); - SZ_Clear (&cmd_text); + temp = (char *) Z_Malloc(templen); + Q_memcpy(temp, cmd_text.data, templen); + SZ_Clear(&cmd_text); } else - temp = NULL; // shut up compiler + temp = NULL; // shut up compiler // add the entire text of the file - Cbuf_AddText (text); - SZ_Write (&cmd_text, "\n", 1); + Cbuf_AddText(text); + SZ_Write(&cmd_text, "\n", 1); // add the copied off data - if (templen) + if(templen) { - SZ_Write (&cmd_text, temp, templen); - Z_Free (temp); + SZ_Write(&cmd_text, temp, templen); + Z_Free(temp); } } @@ -142,37 +142,37 @@ void Cbuf_InsertText (const char *text) Cbuf_Execute ============ */ -void Cbuf_Execute (void) +void Cbuf_Execute(void) { - int32_t i; - char *text; - char line[1024]; - int32_t quotes; + int32_t i; + char *text; + char line[1024]; + int32_t quotes; - while (cmd_text.cursize) + while(cmd_text.cursize) { // find a \n or ; line break text = (char *)cmd_text.data; quotes = 0; - for (i=0 ; i< cmd_text.cursize ; i++) + for(i = 0 ; i < cmd_text.cursize ; i++) { - if (text[i] == '"') + if(text[i] == '"') quotes++; - if ( !(quotes&1) && text[i] == ';') - break; // don't break if inside a quoted string - if (text[i] == '\n') + if(!(quotes & 1) && text[i] == ';') + break; // don't break if inside a quoted string + if(text[i] == '\n') break; } - if (i > (int32_t)sizeof(line) - 1) + if(i > (int32_t)sizeof(line) - 1) { - memcpy (line, text, sizeof(line) - 1); + memcpy(line, text, sizeof(line) - 1); line[sizeof(line) - 1] = 0; } else { - memcpy (line, text, i); + memcpy(line, text, i); line[i] = 0; } @@ -180,20 +180,21 @@ void Cbuf_Execute (void) // this is necessary because commands (exec, alias) can insert data at the // beginning of the text buffer - if (i == cmd_text.cursize) + if(i == cmd_text.cursize) cmd_text.cursize = 0; else { i++; cmd_text.cursize -= i; - memmove (text, text + i, cmd_text.cursize); + memmove(text, text + i, cmd_text.cursize); } // execute the command line - Cmd_ExecuteString (line, src_command); + Cmd_ExecuteString(line, src_command); - if (cmd_wait) - { // skip out while text still remains in buffer, leaving it + if(cmd_wait) + { + // skip out while text still remains in buffer, leaving it // for next frame cmd_wait = false; break; @@ -204,7 +205,7 @@ void Cbuf_Execute (void) /* ============================================================================== - SCRIPT COMMANDS + SCRIPT COMMANDS ============================================================================== */ @@ -219,34 +220,34 @@ quake +prog jctest.qp +cmd amlev1 quake -nosound +cmd amlev1 =============== */ -void Cmd_StuffCmds_f (void) +void Cmd_StuffCmds_f(void) { extern cvar_t cmdline; - char cmds[CMDLINE_LENGTH]; - int32_t i, j, plus; + char cmds[CMDLINE_LENGTH]; + int32_t i, j, plus; - plus = false; // On Unix, argv[0] is command name + plus = false; // On Unix, argv[0] is command name - for (i = 0, j = 0; cmdline.string[i]; i++) + for(i = 0, j = 0; cmdline.string[i]; i++) { - if (cmdline.string[i] == '+') + if(cmdline.string[i] == '+') { plus = true; - if (j > 0) + if(j > 0) { - cmds[j-1] = ';'; + cmds[j - 1] = ';'; cmds[j++] = ' '; } } - else if (cmdline.string[i] == '-' && - (i==0 || cmdline.string[i-1] == ' ')) //johnfitz -- allow hypenated map names with +map - plus = false; - else if (plus) + else if(cmdline.string[i] == '-' && + (i == 0 || cmdline.string[i - 1] == ' ')) //johnfitz -- allow hypenated map names with +map + plus = false; + else if(plus) cmds[j++] = cmdline.string[i]; } cmds[j] = 0; - Cbuf_InsertText (cmds); + Cbuf_InsertText(cmds); } @@ -255,28 +256,28 @@ void Cmd_StuffCmds_f (void) Cmd_Exec_f =============== */ -void Cmd_Exec_f (void) +void Cmd_Exec_f(void) { - char *f; - int32_t mark; + char *f; + int32_t mark; - if (Cmd_Argc () != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("exec : execute a script file\n"); + Con_Printf("exec : execute a script file\n"); return; } - mark = Hunk_LowMark (); - f = (char *)COM_LoadHunkFile (Cmd_Argv(1), NULL); - if (!f) + mark = Hunk_LowMark(); + f = (char *)COM_LoadHunkFile(Cmd_Argv(1), NULL); + if(!f) { - Con_Printf ("couldn't exec %s\n",Cmd_Argv(1)); + Con_Printf("couldn't exec %s\n", Cmd_Argv(1)); return; } - Con_Printf ("execing %s\n",Cmd_Argv(1)); + Con_Printf("execing %s\n", Cmd_Argv(1)); - Cbuf_InsertText (f); - Hunk_FreeToLowMark (mark); + Cbuf_InsertText(f); + Hunk_FreeToLowMark(mark); } @@ -287,13 +288,13 @@ Cmd_Echo_f Just prints the rest of the line to the console =============== */ -void Cmd_Echo_f (void) +void Cmd_Echo_f(void) { - int32_t i; + int32_t i; - for (i=1 ; inext, i++) - Con_SafePrintf (" %s: %s", a->name, a->value); - if (i) - Con_SafePrintf ("%" PRIi32 " alias command(s)\n", i); + for(a = cmd_alias, i = 0; a; a = a->next, i++) + Con_SafePrintf(" %s: %s", a->name, a->value); + if(i) + Con_SafePrintf("%" PRIi32 " alias command(s)\n", i); else - Con_SafePrintf ("no alias commands found\n"); + Con_SafePrintf("no alias commands found\n"); break; case 2: //output current alias string - for (a = cmd_alias ; a ; a=a->next) - if (!strcmp(Cmd_Argv(1), a->name)) - Con_Printf (" %s: %s", a->name, a->value); + for(a = cmd_alias ; a ; a = a->next) + if(!strcmp(Cmd_Argv(1), a->name)) + Con_Printf(" %s: %s", a->name, a->value); break; default: //set alias string s = Cmd_Argv(1); - if (strlen(s) >= MAX_ALIAS_NAME) + if(strlen(s) >= MAX_ALIAS_NAME) { - Con_Printf ("Alias name is too long\n"); + Con_Printf("Alias name is too long\n"); return; } // if the alias allready exists, reuse it - for (a = cmd_alias ; a ; a=a->next) + for(a = cmd_alias ; a ; a = a->next) { - if (!strcmp(s, a->name)) + if(!strcmp(s, a->name)) { - Z_Free (a->value); + Z_Free(a->value); break; } } - if (!a) + if(!a) { - a = (cmdalias_t *) Z_Malloc (sizeof(cmdalias_t)); + a = (cmdalias_t *) Z_Malloc(sizeof(cmdalias_t)); a->next = cmd_alias; cmd_alias = a; } - strcpy (a->name, s); + strcpy(a->name, s); // copy the rest of the command line - cmd[0] = 0; // start out with a null string + cmd[0] = 0; // start out with a null string c = Cmd_Argc(); - for (i = 2; i < c; i++) + for(i = 2; i < c; i++) { - q_strlcat (cmd, Cmd_Argv(i), sizeof(cmd)); - if (i != c - 1) - q_strlcat (cmd, " ", sizeof(cmd)); + q_strlcat(cmd, Cmd_Argv(i), sizeof(cmd)); + if(i != c - 1) + q_strlcat(cmd, " ", sizeof(cmd)); } - if (q_strlcat(cmd, "\n", sizeof(cmd)) >= sizeof(cmd)) + if(q_strlcat(cmd, "\n", sizeof(cmd)) >= sizeof(cmd)) { Con_Printf("alias value too long!\n"); - cmd[0] = '\n'; // nullify the string + cmd[0] = '\n'; // nullify the string cmd[1] = 0; } - a->value = Z_Strdup (cmd); + a->value = Z_Strdup(cmd); break; } } @@ -378,11 +379,11 @@ void Cmd_Alias_f (void) Cmd_Unalias_f -- johnfitz =============== */ -void Cmd_Unalias_f (void) +void Cmd_Unalias_f(void) { - cmdalias_t *a, *prev; + cmdalias_t *a, *prev; - switch (Cmd_Argc()) + switch(Cmd_Argc()) { default: case 1: @@ -390,22 +391,22 @@ void Cmd_Unalias_f (void) break; case 2: prev = NULL; - for (a = cmd_alias; a; a = a->next) + for(a = cmd_alias; a; a = a->next) { - if (!strcmp(Cmd_Argv(1), a->name)) + if(!strcmp(Cmd_Argv(1), a->name)) { - if (prev) + if(prev) prev->next = a->next; else cmd_alias = a->next; - Z_Free (a->value); - Z_Free (a); + Z_Free(a->value); + Z_Free(a); return; } prev = a; } - Con_Printf ("No alias named %s\n", Cmd_Argv(1)); + Con_Printf("No alias named %s\n", Cmd_Argv(1)); break; } } @@ -415,11 +416,11 @@ void Cmd_Unalias_f (void) Cmd_Unaliasall_f -- johnfitz =============== */ -void Cmd_Unaliasall_f (void) +void Cmd_Unaliasall_f(void) { - cmdalias_t *blah; + cmdalias_t *blah; - while (cmd_alias) + while(cmd_alias) { blah = cmd_alias->next; Z_Free(cmd_alias->value); @@ -431,31 +432,31 @@ void Cmd_Unaliasall_f (void) /* ============================================================================= - COMMAND EXECUTION + COMMAND EXECUTION ============================================================================= */ typedef struct cmd_function_s { - struct cmd_function_s *next; - const char *name; - xcommand_t function; + struct cmd_function_s *next; + const char *name; + xcommand_t function; } cmd_function_t; -#define MAX_ARGS 80 +#define MAX_ARGS 80 -static int32_t cmd_argc; -static char *cmd_argv[MAX_ARGS]; -static char cmd_null_string[] = ""; -static const char *cmd_args = NULL; +static int32_t cmd_argc; +static char *cmd_argv[MAX_ARGS]; +static char cmd_null_string[] = ""; +static const char *cmd_args = NULL; -cmd_source_t cmd_source; +cmd_source_t cmd_source; //johnfitz -- better tab completion -//static cmd_function_t *cmd_functions; // possible commands to execute -cmd_function_t *cmd_functions; // possible commands to execute +//static cmd_function_t *cmd_functions; // possible commands to execute +cmd_function_t *cmd_functions; // possible commands to execute //johnfitz /* @@ -463,15 +464,15 @@ cmd_function_t *cmd_functions; // possible commands to execute Cmd_List_f -- johnfitz ============ */ -void Cmd_List_f (void) +void Cmd_List_f(void) { - cmd_function_t *cmd; - const char *partial; - int32_t len, count; + cmd_function_t *cmd; + const char *partial; + int32_t len, count; - if (Cmd_Argc() > 1) + if(Cmd_Argc() > 1) { - partial = Cmd_Argv (1); + partial = Cmd_Argv(1); len = Q_strlen(partial); } else @@ -480,23 +481,23 @@ void Cmd_List_f (void) len = 0; } - count=0; - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) + count = 0; + for(cmd = cmd_functions ; cmd ; cmd = cmd->next) { - if (partial && Q_strncmp (partial,cmd->name, len)) + if(partial && Q_strncmp(partial, cmd->name, len)) { continue; } - Con_SafePrintf (" %s\n", cmd->name); + Con_SafePrintf(" %s\n", cmd->name); count++; } - Con_SafePrintf ("%" PRIi32 " commands", count); - if (partial) + Con_SafePrintf("%" PRIi32 " commands", count); + if(partial) { - Con_SafePrintf (" beginning with \"%s\"", partial); + Con_SafePrintf(" beginning with \"%s\"", partial); } - Con_SafePrintf ("\n"); + Con_SafePrintf("\n"); } static char *Cmd_TintSubstring(const char *in, const char *substr, char *out, size_t outsize) @@ -504,11 +505,11 @@ static char *Cmd_TintSubstring(const char *in, const char *substr, char *out, si int32_t l; char *m; q_strlcpy(out, in, outsize); - while ((m = q_strcasestr(out, substr))) + while((m = q_strcasestr(out, substr))) { l = strlen(substr); - while (l-->0) - if (*m >= ' ' && *m < 127) + while(l-- > 0) + if(*m >= ' ' && *m < 127) *m++ |= 0x80; } return out; @@ -526,33 +527,33 @@ void Cmd_Apropos_f(void) { char tmpbuf[256]; int32_t hits = 0; - cmd_function_t *cmd; + cmd_function_t *cmd; cvar_t *var; - const char *substr = Cmd_Argv (1); - if (!*substr) + const char *substr = Cmd_Argv(1); + if(!*substr) { - Con_SafePrintf ("%s : search through commands and cvars for the given substring\n", Cmd_Argv(0)); + Con_SafePrintf("%s : search through commands and cvars for the given substring\n", Cmd_Argv(0)); return; } - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) + for(cmd = cmd_functions ; cmd ; cmd = cmd->next) { - if (q_strcasestr(cmd->name, substr)) + if(q_strcasestr(cmd->name, substr)) { hits++; - Con_SafePrintf ("%s\n", Cmd_TintSubstring(cmd->name, substr, tmpbuf, sizeof(tmpbuf))); + Con_SafePrintf("%s\n", Cmd_TintSubstring(cmd->name, substr, tmpbuf, sizeof(tmpbuf))); } } - - for (var=Cvar_FindVarAfter("", 0) ; var ; var=var->next) + + for(var = Cvar_FindVarAfter("", 0) ; var ; var = var->next) { - if (q_strcasestr(var->name, substr)) + if(q_strcasestr(var->name, substr)) { hits++; - Con_SafePrintf ("%s (current value: \"%s\")\n", Cmd_TintSubstring(var->name, substr, tmpbuf, sizeof(tmpbuf)), var->string); + Con_SafePrintf("%s (current value: \"%s\")\n", Cmd_TintSubstring(var->name, substr, tmpbuf, sizeof(tmpbuf)), var->string); } } - if (!hits) - Con_SafePrintf ("no cvars nor commands contain that substring\n"); + if(!hits) + Con_SafePrintf("no cvars nor commands contain that substring\n"); } /* @@ -560,21 +561,21 @@ void Cmd_Apropos_f(void) Cmd_Init ============ */ -void Cmd_Init (void) +void Cmd_Init(void) { - Cmd_AddCommand ("cmdlist", Cmd_List_f); //johnfitz - Cmd_AddCommand ("unalias", Cmd_Unalias_f); //johnfitz - Cmd_AddCommand ("unaliasall", Cmd_Unaliasall_f); //johnfitz + Cmd_AddCommand("cmdlist", Cmd_List_f); //johnfitz + Cmd_AddCommand("unalias", Cmd_Unalias_f); //johnfitz + Cmd_AddCommand("unaliasall", Cmd_Unaliasall_f); //johnfitz - Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f); - Cmd_AddCommand ("exec",Cmd_Exec_f); - Cmd_AddCommand ("echo",Cmd_Echo_f); - Cmd_AddCommand ("alias",Cmd_Alias_f); - Cmd_AddCommand ("cmd", Cmd_ForwardToServer); - Cmd_AddCommand ("wait", Cmd_Wait_f); + Cmd_AddCommand("stuffcmds", Cmd_StuffCmds_f); + Cmd_AddCommand("exec", Cmd_Exec_f); + Cmd_AddCommand("echo", Cmd_Echo_f); + Cmd_AddCommand("alias", Cmd_Alias_f); + Cmd_AddCommand("cmd", Cmd_ForwardToServer); + Cmd_AddCommand("wait", Cmd_Wait_f); - Cmd_AddCommand ("apropos", Cmd_Apropos_f); - Cmd_AddCommand ("find", Cmd_Apropos_f); + Cmd_AddCommand("apropos", Cmd_Apropos_f); + Cmd_AddCommand("find", Cmd_Apropos_f); } /* @@ -582,7 +583,7 @@ void Cmd_Init (void) Cmd_Argc ============ */ -int32_t Cmd_Argc (void) +int32_t Cmd_Argc(void) { return cmd_argc; } @@ -592,9 +593,9 @@ int32_t Cmd_Argc (void) Cmd_Argv ============ */ -const char *Cmd_Argv (int32_t arg) +const char *Cmd_Argv(int32_t arg) { - if (arg < 0 || arg >= cmd_argc) + if(arg < 0 || arg >= cmd_argc) return cmd_null_string; return cmd_argv[arg]; } @@ -604,7 +605,7 @@ const char *Cmd_Argv (int32_t arg) Cmd_Args ============ */ -const char *Cmd_Args (void) +const char *Cmd_Args(void) { return cmd_args; } @@ -617,44 +618,45 @@ Cmd_TokenizeString Parses the given string into command line tokens. ============ */ -void Cmd_TokenizeString (const char *text) +void Cmd_TokenizeString(const char *text) { - int32_t i; + int32_t i; // clear the args from the last string - for (i=0 ; inext) + for(cmd = cmd_functions ; cmd ; cmd = cmd->next) { - if (!Q_strcmp (cmd_name, cmd->name)) + if(!Q_strcmp(cmd_name, cmd->name)) { - Con_Printf ("Cmd_AddCommand: %s already defined\n", cmd_name); + Con_Printf("Cmd_AddCommand: %s already defined\n", cmd_name); return; } } - cmd = (cmd_function_t *) Hunk_Alloc (sizeof(cmd_function_t)); + cmd = (cmd_function_t *) Hunk_Alloc(sizeof(cmd_function_t)); cmd->name = cmd_name; cmd->function = function; //johnfitz -- insert each entry in alphabetical order - if (cmd_functions == NULL || strcmp(cmd->name, cmd_functions->name) < 0) //insert at front + if(cmd_functions == NULL || strcmp(cmd->name, cmd_functions->name) < 0) //insert at front { cmd->next = cmd_functions; cmd_functions = cmd; @@ -705,7 +707,7 @@ void Cmd_AddCommand (const char *cmd_name, xcommand_t function) { prev = cmd_functions; cursor = cmd_functions->next; - while ((cursor != NULL) && (strcmp(cmd->name, cursor->name) > 0)) + while((cursor != NULL) && (strcmp(cmd->name, cursor->name) > 0)) { prev = cursor; cursor = cursor->next; @@ -721,13 +723,13 @@ void Cmd_AddCommand (const char *cmd_name, xcommand_t function) Cmd_Exists ============ */ -bool Cmd_Exists (const char *cmd_name) +bool Cmd_Exists(const char *cmd_name) { - cmd_function_t *cmd; + cmd_function_t *cmd; - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) + for(cmd = cmd_functions ; cmd ; cmd = cmd->next) { - if (!Q_strcmp (cmd_name,cmd->name)) + if(!Q_strcmp(cmd_name, cmd->name)) return true; } @@ -741,19 +743,19 @@ bool Cmd_Exists (const char *cmd_name) Cmd_CompleteCommand ============ */ -const char *Cmd_CompleteCommand (const char *partial) +const char *Cmd_CompleteCommand(const char *partial) { - cmd_function_t *cmd; - int32_t len; + cmd_function_t *cmd; + int32_t len; len = Q_strlen(partial); - if (!len) + if(!len) return NULL; // check functions - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - if (!Q_strncmp (partial,cmd->name, len)) + for(cmd = cmd_functions ; cmd ; cmd = cmd->next) + if(!Q_strncmp(partial, cmd->name, len)) return cmd->name; return NULL; @@ -767,41 +769,41 @@ A complete command line has been parsed, so try to execute it FIXME: lookupnoadd the token to speed search? ============ */ -void Cmd_ExecuteString (const char *text, cmd_source_t src) +void Cmd_ExecuteString(const char *text, cmd_source_t src) { - cmd_function_t *cmd; - cmdalias_t *a; + cmd_function_t *cmd; + cmdalias_t *a; cmd_source = src; - Cmd_TokenizeString (text); + Cmd_TokenizeString(text); // execute the command line - if (!Cmd_Argc()) - return; // no tokens + if(!Cmd_Argc()) + return; // no tokens // check functions - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) + for(cmd = cmd_functions ; cmd ; cmd = cmd->next) { - if (!q_strcasecmp (cmd_argv[0],cmd->name)) + if(!q_strcasecmp(cmd_argv[0], cmd->name)) { - cmd->function (); + cmd->function(); return; } } // check alias - for (a=cmd_alias ; a ; a=a->next) + for(a = cmd_alias ; a ; a = a->next) { - if (!q_strcasecmp (cmd_argv[0], a->name)) + if(!q_strcasecmp(cmd_argv[0], a->name)) { - Cbuf_InsertText (a->value); + Cbuf_InsertText(a->value); return; } } // check cvars - if (!Cvar_Command ()) - Con_Printf ("Unknown command \"%s\"\n", Cmd_Argv(0)); + if(!Cvar_Command()) + Con_Printf("Unknown command \"%s\"\n", Cmd_Argv(0)); } @@ -813,27 +815,27 @@ Cmd_ForwardToServer Sends the entire command line over to the server =================== */ -void Cmd_ForwardToServer (void) +void Cmd_ForwardToServer(void) { - if (cls.state != ca_connected) + if(cls.state != ca_connected) { - Con_Printf ("Can't \"%s\", not connected\n", Cmd_Argv(0)); + Con_Printf("Can't \"%s\", not connected\n", Cmd_Argv(0)); return; } - if (cls.demoplayback) - return; // not really connected + if(cls.demoplayback) + return; // not really connected - MSG_WriteByte (&cls.message, clc_stringcmd); - if (q_strcasecmp(Cmd_Argv(0), "cmd") != 0) + MSG_WriteByte(&cls.message, clc_stringcmd); + if(q_strcasecmp(Cmd_Argv(0), "cmd") != 0) { - SZ_Print (&cls.message, Cmd_Argv(0)); - SZ_Print (&cls.message, " "); + SZ_Print(&cls.message, Cmd_Argv(0)); + SZ_Print(&cls.message, " "); } - if (Cmd_Argc() > 1) - SZ_Print (&cls.message, Cmd_Args()); + if(Cmd_Argc() > 1) + SZ_Print(&cls.message, Cmd_Args()); else - SZ_Print (&cls.message, "\n"); + SZ_Print(&cls.message, "\n"); } @@ -846,15 +848,15 @@ where the given parameter apears, or 0 if not present ================ */ -int32_t Cmd_CheckParm (const char *parm) +int32_t Cmd_CheckParm(const char *parm) { int32_t i; - if (!parm) - Sys_Error ("Cmd_CheckParm: NULL"); + if(!parm) + Sys_Error("Cmd_CheckParm: NULL"); - for (i = 1; i < Cmd_Argc (); i++) - if (! q_strcasecmp (parm, Cmd_Argv (i))) + for(i = 1; i < Cmd_Argc(); i++) + if(! q_strcasecmp(parm, Cmd_Argv(i))) return i; return 0; diff --git a/source/cmd.h b/source/cmd.h index 32cd3bd..4724d81 100644 --- a/source/cmd.h +++ b/source/cmd.h @@ -39,19 +39,19 @@ The game starts with a Cbuf_AddText ("exec quake.rc\n"); Cbuf_Execute (); */ -void Cbuf_Init (void); +void Cbuf_Init(void); // allocates an initial text buffer that will grow as needed -void Cbuf_AddText (const char *text); +void Cbuf_AddText(const char *text); // as new commands are generated from the console or keybindings, // the text is added to the end of the command buffer. -void Cbuf_InsertText (const char *text); +void Cbuf_InsertText(const char *text); // when a command wants to issue other commands immediately, the text is // inserted at the beginning of the buffer, before any remaining unexecuted // commands. -void Cbuf_Execute (void); +void Cbuf_Execute(void); // Pulls off \n terminated lines of text from the command buffer and sends // them through Cmd_ExecuteString. Stops when the buffer is empty. // Normally called once per frame, but may be explicitly invoked. @@ -70,58 +70,58 @@ not apropriate. */ -typedef void (*xcommand_t) (void); +typedef void (*xcommand_t)(void); typedef enum { - src_client, // came in over a net connection as a clc_stringcmd - // host_client will be valid during this state. - src_command // from the command buffer + src_client, // came in over a net connection as a clc_stringcmd + // host_client will be valid during this state. + src_command // from the command buffer } cmd_source_t; -extern cmd_source_t cmd_source; +extern cmd_source_t cmd_source; -void Cmd_Init (void); +void Cmd_Init(void); -void Cmd_AddCommand (const char *cmd_name, xcommand_t function); +void Cmd_AddCommand(const char *cmd_name, xcommand_t function); // called by the init functions of other parts of the program to // register commands and functions to call for them. // The cmd_name is referenced later, so it should not be in temp memory -bool Cmd_Exists (const char *cmd_name); +bool Cmd_Exists(const char *cmd_name); // used by the cvar code to check for cvar / command name overlap -const char *Cmd_CompleteCommand (const char *partial); +const char *Cmd_CompleteCommand(const char *partial); // attempts to match a partial command for automatic command line completion // returns NULL if nothing fits -int32_t Cmd_Argc (void); -const char *Cmd_Argv (int32_t arg); -const char *Cmd_Args (void); +int32_t Cmd_Argc(void); +const char *Cmd_Argv(int32_t arg); +const char *Cmd_Args(void); // The functions that execute commands get their parameters with these // functions. Cmd_Argv () will return an empty string, not a NULL // if arg > argc, so string operations are allways safe. -int32_t Cmd_CheckParm (const char *parm); +int32_t Cmd_CheckParm(const char *parm); // Returns the position (1 to argc-1) in the command's argument list // where the given parameter apears, or 0 if not present -void Cmd_TokenizeString (const char *text); +void Cmd_TokenizeString(const char *text); // Takes a null terminated string. Does not need to be /n terminated. // breaks the string up into arg tokens. -void Cmd_ExecuteString (const char *text, cmd_source_t src); +void Cmd_ExecuteString(const char *text, cmd_source_t src); // Parses a single line of text into arguments and tries to execute it. // The text can come from the command buffer, a remote client, or stdin. -void Cmd_ForwardToServer (void); +void Cmd_ForwardToServer(void); // adds the current command line as a clc_stringcmd to the client message. // things like godmode, noclip, etc, are commands directed to the server, // so when they are typed in at the console, they will need to be forwarded. -void Cmd_Print (const char *text); +void Cmd_Print(const char *text); // used by command functions to send output to either the graphics console or // passed as a print message to the client -#endif /* _QUAKE_CMD_H */ +#endif /* _QUAKE_CMD_H */ diff --git a/source/common.c b/source/common.c index 4c6591d..b613a94 100644 --- a/source/common.c +++ b/source/common.c @@ -26,57 +26,57 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "q_ctype.h" #include -static char *largv[MAX_NUM_ARGVS + 1]; -static char argvdummy[] = " "; +static char *largv[MAX_NUM_ARGVS + 1]; +static char argvdummy[] = " "; -int32_t safemode; +int32_t safemode; -cvar_t registered = {"registered","1",CVAR_ROM}; /* set to correct value in COM_CheckRegistered() */ -cvar_t cmdline = {"cmdline","",CVAR_ROM/*|CVAR_SERVERINFO*/}; /* sending cmdline upon CCREQ_RULE_INFO is evil */ +cvar_t registered = {"registered", "1", CVAR_ROM}; /* set to correct value in COM_CheckRegistered() */ +cvar_t cmdline = {"cmdline", "", CVAR_ROM/*|CVAR_SERVERINFO*/}; /* sending cmdline upon CCREQ_RULE_INFO is evil */ -static bool com_modified; // set true if using non-id files +static bool com_modified; // set true if using non-id files -bool fitzmode; +bool fitzmode; -static void COM_Path_f (void); +static void COM_Path_f(void); // if a packfile directory differs from this, it is assumed to be hacked -#define PAK0_COUNT 339 /* id1/pak0.pak - v1.0x */ -#define PAK0_CRC_V100 13900 /* id1/pak0.pak - v1.00 */ -#define PAK0_CRC_V101 62751 /* id1/pak0.pak - v1.01 */ -#define PAK0_CRC_V106 32981 /* id1/pak0.pak - v1.06 */ -#define PAK0_CRC (PAK0_CRC_V106) -#define PAK0_COUNT_V091 308 /* id1/pak0.pak - v0.91/0.92, not supported */ -#define PAK0_CRC_V091 28804 /* id1/pak0.pak - v0.91/0.92, not supported */ +#define PAK0_COUNT 339 /* id1/pak0.pak - v1.0x */ +#define PAK0_CRC_V100 13900 /* id1/pak0.pak - v1.00 */ +#define PAK0_CRC_V101 62751 /* id1/pak0.pak - v1.01 */ +#define PAK0_CRC_V106 32981 /* id1/pak0.pak - v1.06 */ +#define PAK0_CRC (PAK0_CRC_V106) +#define PAK0_COUNT_V091 308 /* id1/pak0.pak - v0.91/0.92, not supported */ +#define PAK0_CRC_V091 28804 /* id1/pak0.pak - v0.91/0.92, not supported */ -char com_token[1024]; -int32_t com_argc; -char **com_argv; +char com_token[1024]; +int32_t com_argc; +char **com_argv; -#define CMDLINE_LENGTH 256 /* johnfitz -- mirrored in cmd.c */ -char com_cmdline[CMDLINE_LENGTH]; +#define CMDLINE_LENGTH 256 /* johnfitz -- mirrored in cmd.c */ +char com_cmdline[CMDLINE_LENGTH]; bool standard_quake = true, rogue, hipnotic; // this graphic needs to be in the pak file to use registered features static uint16_t pop[] = { - 0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000, - 0x0000,0x0000,0x6600,0x0000,0x0000,0x0000,0x6600,0x0000, - 0x0000,0x0066,0x0000,0x0000,0x0000,0x0000,0x0067,0x0000, - 0x0000,0x6665,0x0000,0x0000,0x0000,0x0000,0x0065,0x6600, - 0x0063,0x6561,0x0000,0x0000,0x0000,0x0000,0x0061,0x6563, - 0x0064,0x6561,0x0000,0x0000,0x0000,0x0000,0x0061,0x6564, - 0x0064,0x6564,0x0000,0x6469,0x6969,0x6400,0x0064,0x6564, - 0x0063,0x6568,0x6200,0x0064,0x6864,0x0000,0x6268,0x6563, - 0x0000,0x6567,0x6963,0x0064,0x6764,0x0063,0x6967,0x6500, - 0x0000,0x6266,0x6769,0x6a68,0x6768,0x6a69,0x6766,0x6200, - 0x0000,0x0062,0x6566,0x6666,0x6666,0x6666,0x6562,0x0000, - 0x0000,0x0000,0x0062,0x6364,0x6664,0x6362,0x0000,0x0000, - 0x0000,0x0000,0x0000,0x0062,0x6662,0x0000,0x0000,0x0000, - 0x0000,0x0000,0x0000,0x0061,0x6661,0x0000,0x0000,0x0000, - 0x0000,0x0000,0x0000,0x0000,0x6500,0x0000,0x0000,0x0000, - 0x0000,0x0000,0x0000,0x0000,0x6400,0x0000,0x0000,0x0000 + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x6600, 0x0000, 0x0000, 0x0000, 0x6600, 0x0000, + 0x0000, 0x0066, 0x0000, 0x0000, 0x0000, 0x0000, 0x0067, 0x0000, + 0x0000, 0x6665, 0x0000, 0x0000, 0x0000, 0x0000, 0x0065, 0x6600, + 0x0063, 0x6561, 0x0000, 0x0000, 0x0000, 0x0000, 0x0061, 0x6563, + 0x0064, 0x6561, 0x0000, 0x0000, 0x0000, 0x0000, 0x0061, 0x6564, + 0x0064, 0x6564, 0x0000, 0x6469, 0x6969, 0x6400, 0x0064, 0x6564, + 0x0063, 0x6568, 0x6200, 0x0064, 0x6864, 0x0000, 0x6268, 0x6563, + 0x0000, 0x6567, 0x6963, 0x0064, 0x6764, 0x0063, 0x6967, 0x6500, + 0x0000, 0x6266, 0x6769, 0x6a68, 0x6768, 0x6a69, 0x6766, 0x6200, + 0x0000, 0x0062, 0x6566, 0x6666, 0x6666, 0x6666, 0x6562, 0x0000, + 0x0000, 0x0000, 0x0062, 0x6364, 0x6664, 0x6362, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0062, 0x6662, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0061, 0x6661, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x6500, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x6400, 0x0000, 0x0000, 0x0000 }; /* @@ -115,18 +115,18 @@ override an explicit setting on the original command line. // ClearLink is used for new headnodes -void ClearLink (link_t *l) +void ClearLink(link_t *l) { l->prev = l->next = l; } -void RemoveLink (link_t *l) +void RemoveLink(link_t *l) { l->next->prev = l->prev; l->prev->next = l->next; } -void InsertLinkBefore (link_t *l, link_t *before) +void InsertLinkBefore(link_t *l, link_t *before) { l->next = before; l->prev = before->prev; @@ -134,7 +134,7 @@ void InsertLinkBefore (link_t *l, link_t *before) l->next->prev = l; } -void InsertLinkAfter (link_t *l, link_t *after) +void InsertLinkAfter(link_t *l, link_t *after) { l->next = after->next; l->prev = after; @@ -145,7 +145,7 @@ void InsertLinkAfter (link_t *l, link_t *after) /* ============================================================================ - LIBRARY REPLACEMENT FUNCTIONS + LIBRARY REPLACEMENT FUNCTIONS ============================================================================ */ @@ -156,16 +156,17 @@ int32_t q_strcasecmp(const char * s1, const char * s2) const char * p2 = s2; char c1, c2; - if (p1 == p2) + if(p1 == p2) return 0; do { - c1 = q_tolower (*p1++); - c2 = q_tolower (*p2++); - if (c1 == '\0') + c1 = q_tolower(*p1++); + c2 = q_tolower(*p2++); + if(c1 == '\0') break; - } while (c1 == c2); + } + while(c1 == c2); return (int32_t)(c1 - c2); } @@ -176,16 +177,17 @@ int32_t q_strncasecmp(const char *s1, const char *s2, size_t n) const char * p2 = s2; char c1, c2; - if (p1 == p2 || n == 0) + if(p1 == p2 || n == 0) return 0; do { - c1 = q_tolower (*p1++); - c2 = q_tolower (*p2++); - if (c1 == '\0' || c1 != c2) + c1 = q_tolower(*p1++); + c2 = q_tolower(*p2++); + if(c1 == '\0' || c1 != c2) break; - } while (--n > 0); + } + while(--n > 0); return (int32_t)(c1 - c2); } @@ -196,45 +198,45 @@ char *q_strcasestr(const char *haystack, const char *needle) int32_t c1, c2, c2f; int32_t i; c2f = *needle; - if (c2f >= 'a' && c2f <= 'z') + if(c2f >= 'a' && c2f <= 'z') c2f -= ('a' - 'A'); - if (!c2f) + if(!c2f) return (char*)haystack; - while (1) + while(1) { c1 = *haystack; - if (!c1) + if(!c1) return NULL; - if (c1 >= 'a' && c1 <= 'z') + if(c1 >= 'a' && c1 <= 'z') c1 -= ('a' - 'A'); - if (c1 == c2f) + if(c1 == c2f) { - for (i = 1; ; i++) + for(i = 1; ; i++) { c1 = haystack[i]; c2 = needle[i]; - if (c1 >= 'a' && c1 <= 'z') + if(c1 >= 'a' && c1 <= 'z') c1 -= ('a' - 'A'); - if (c2 >= 'a' && c2 <= 'z') + if(c2 >= 'a' && c2 <= 'z') c2 -= ('a' - 'A'); - if (!c2) - return (char*)haystack; //end of needle means we found a complete match - if (!c1) //end of haystack means we can't possibly find needle in it any more + if(!c2) + return (char*)haystack; //end of needle means we found a complete match + if(!c1) //end of haystack means we can't possibly find needle in it any more return NULL; - if (c1 != c2) //mismatch means no match starting at haystack[0] + if(c1 != c2) //mismatch means no match starting at haystack[0] break; } } haystack++; } - return NULL; //didn't find it + return NULL; //didn't find it } -char *q_strlwr (char *str) +char *q_strlwr(char *str) { - char *c; + char *c; c = str; - while (*c) + while(*c) { *c = q_tolower(*c); c++; @@ -242,11 +244,11 @@ char *q_strlwr (char *str) return str; } -char *q_strupr (char *str) +char *q_strupr(char *str) { - char *c; + char *c; c = str; - while (*c) + while(*c) { *c = q_toupper(*c); c++; @@ -256,108 +258,108 @@ char *q_strupr (char *str) /* platform dependant (v)snprintf function names: */ #if defined(_WIN32) -#define snprintf_func _snprintf -#define vsnprintf_func _vsnprintf +#define snprintf_func _snprintf +#define vsnprintf_func _vsnprintf #else -#define snprintf_func snprintf -#define vsnprintf_func vsnprintf +#define snprintf_func snprintf +#define vsnprintf_func vsnprintf #endif int32_t q_vsnprintf(char *str, size_t size, const char *format, va_list args) { - int32_t ret; + int32_t ret; - ret = vsnprintf_func (str, size, format, args); + ret = vsnprintf_func(str, size, format, args); - if (ret < 0) + if(ret < 0) ret = (int32_t)size; - if (size == 0) /* no buffer */ + if(size == 0) /* no buffer */ return ret; - if ((size_t)ret >= size) + if((size_t)ret >= size) str[size - 1] = '\0'; return ret; } -int32_t q_snprintf (char *str, size_t size, const char *format, ...) +int32_t q_snprintf(char *str, size_t size, const char *format, ...) { - int32_t ret; - va_list argptr; + int32_t ret; + va_list argptr; - va_start (argptr, format); - ret = q_vsnprintf (str, size, format, argptr); - va_end (argptr); + va_start(argptr, format); + ret = q_vsnprintf(str, size, format, argptr); + va_end(argptr); return ret; } -void Q_memset (void *dest, int32_t fill, size_t count) +void Q_memset(void *dest, int32_t fill, size_t count) { - size_t i; + size_t i; - if ( (((size_t)dest | count) & 3) == 0) + if((((size_t)dest | count) & 3) == 0) { count >>= 2; - fill = fill | (fill<<8) | (fill<<16) | (fill<<24); - for (i = 0; i < count; i++) + fill = fill | (fill << 8) | (fill << 16) | (fill << 24); + for(i = 0; i < count; i++) ((int32_t *)dest)[i] = fill; } else - for (i = 0; i < count; i++) + for(i = 0; i < count; i++) ((byte *)dest)[i] = fill; } -void Q_memcpy (void *dest, const void *src, size_t count) +void Q_memcpy(void *dest, const void *src, size_t count) { - size_t i; + size_t i; - if (( ( (size_t)dest | (size_t)src | count) & 3) == 0 ) + if((((size_t)dest | (size_t)src | count) & 3) == 0) { count >>= 2; - for (i = 0; i < count; i++) + for(i = 0; i < count; i++) ((int32_t *)dest)[i] = ((int32_t *)src)[i]; } else - for (i = 0; i < count; i++) + for(i = 0; i < count; i++) ((byte *)dest)[i] = ((byte *)src)[i]; } -int32_t Q_memcmp (const void *m1, const void *m2, size_t count) +int32_t Q_memcmp(const void *m1, const void *m2, size_t count) { while(count) { count--; - if (((byte *)m1)[count] != ((byte *)m2)[count]) + if(((byte *)m1)[count] != ((byte *)m2)[count]) return -1; } return 0; } -void Q_strcpy (char *dest, const char *src) +void Q_strcpy(char *dest, const char *src) { - while (*src) + while(*src) { *dest++ = *src++; } *dest++ = 0; } -void Q_strncpy (char *dest, const char *src, int32_t count) +void Q_strncpy(char *dest, const char *src, int32_t count) { - while (*src && count--) + while(*src && count--) { *dest++ = *src++; } - if (count) + if(count) *dest++ = 0; } -int32_t Q_strlen (const char *str) +int32_t Q_strlen(const char *str) { - int32_t count; + int32_t count; count = 0; - while (str[count]) + while(str[count]) count++; return count; @@ -367,28 +369,28 @@ char *Q_strrchr(const char *s, char c) { int32_t len = Q_strlen(s); s += len; - while (len--) + while(len--) { - if (*--s == c) + if(*--s == c) return (char *)s; } return NULL; } -void Q_strcat (char *dest, const char *src) +void Q_strcat(char *dest, const char *src) { dest += Q_strlen(dest); - Q_strcpy (dest, src); + Q_strcpy(dest, src); } -int32_t Q_strcmp (const char *s1, const char *s2) +int32_t Q_strcmp(const char *s1, const char *s2) { - while (1) + while(1) { - if (*s1 != *s2) - return -1; // strings not equal - if (!*s1) - return 0; // strings are equal + if(*s1 != *s2) + return -1; // strings not equal + if(!*s1) + return 0; // strings are equal s1++; s2++; } @@ -396,16 +398,16 @@ int32_t Q_strcmp (const char *s1, const char *s2) return -1; } -int32_t Q_strncmp (const char *s1, const char *s2, int32_t count) +int32_t Q_strncmp(const char *s1, const char *s2, int32_t count) { - while (1) + while(1) { - if (!count--) + if(!count--) return 0; - if (*s1 != *s2) - return -1; // strings not equal - if (!*s1) - return 0; // strings are equal + if(*s1 != *s2) + return -1; // strings not equal + if(!*s1) + return 0; // strings are equal s1++; s2++; } @@ -413,13 +415,13 @@ int32_t Q_strncmp (const char *s1, const char *s2, int32_t count) return -1; } -int32_t Q_atoi (const char *str) +int32_t Q_atoi(const char *str) { - int32_t val; - int32_t sign; - int32_t c; + int32_t val; + int32_t sign; + int32_t c; - if (*str == '-') + if(*str == '-') { sign = -1; str++; @@ -432,27 +434,27 @@ int32_t Q_atoi (const char *str) // // check for hex // - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') ) + if(str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { str += 2; - while (1) + while(1) { c = *str++; - if (c >= '0' && c <= '9') - val = (val<<4) + c - '0'; - else if (c >= 'a' && c <= 'f') - val = (val<<4) + c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - val = (val<<4) + c - 'A' + 10; + if(c >= '0' && c <= '9') + val = (val << 4) + c - '0'; + else if(c >= 'a' && c <= 'f') + val = (val << 4) + c - 'a' + 10; + else if(c >= 'A' && c <= 'F') + val = (val << 4) + c - 'A' + 10; else - return val*sign; + return val * sign; } } // // check for character // - if (str[0] == '\'') + if(str[0] == '\'') { return sign * str[1]; } @@ -460,26 +462,26 @@ int32_t Q_atoi (const char *str) // // assume decimal // - while (1) + while(1) { c = *str++; - if (c <'0' || c > '9') - return val*sign; - val = val*10 + c - '0'; + if(c < '0' || c > '9') + return val * sign; + val = val * 10 + c - '0'; } return 0; } -float Q_atof (const char *str) +float Q_atof(const char *str) { - double val; - int32_t sign; - int32_t c; - int32_t decimal, total; + double val; + int32_t sign; + int32_t c; + int32_t decimal, total; - if (*str == '-') + if(*str == '-') { sign = -1; str++; @@ -492,27 +494,27 @@ float Q_atof (const char *str) // // check for hex // - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') ) + if(str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { str += 2; - while (1) + while(1) { c = *str++; - if (c >= '0' && c <= '9') - val = (val*16) + c - '0'; - else if (c >= 'a' && c <= 'f') - val = (val*16) + c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - val = (val*16) + c - 'A' + 10; + if(c >= '0' && c <= '9') + val = (val * 16) + c - '0'; + else if(c >= 'a' && c <= 'f') + val = (val * 16) + c - 'a' + 10; + else if(c >= 'A' && c <= 'F') + val = (val * 16) + c - 'A' + 10; else - return val*sign; + return val * sign; } } // // check for character // - if (str[0] == '\'') + if(str[0] == '\'') { return sign * str[1]; } @@ -522,86 +524,86 @@ float Q_atof (const char *str) // decimal = -1; total = 0; - while (1) + while(1) { c = *str++; - if (c == '.') + if(c == '.') { decimal = total; continue; } - if (c <'0' || c > '9') + if(c < '0' || c > '9') break; - val = val*10 + c - '0'; + val = val * 10 + c - '0'; total++; } - if (decimal == -1) - return val*sign; - while (total > decimal) + if(decimal == -1) + return val * sign; + while(total > decimal) { val /= 10; total--; } - return val*sign; + return val * sign; } /* ============================================================================ - BYTE ORDER FUNCTIONS + BYTE ORDER FUNCTIONS ============================================================================ */ -bool host_bigendian; +bool host_bigendian; -int16_t (*BigShort) (int16_t l); -int16_t (*LittleShort) (int16_t l); -int32_t (*BigLong) (int32_t l); -int32_t (*LittleLong) (int32_t l); -float (*BigFloat) (float l); -float (*LittleFloat) (float l); +int16_t (*BigShort)(int16_t l); +int16_t (*LittleShort)(int16_t l); +int32_t (*BigLong)(int32_t l); +int32_t (*LittleLong)(int32_t l); +float (*BigFloat)(float l); +float (*LittleFloat)(float l); -int16_t ShortSwap (int16_t l) +int16_t ShortSwap(int16_t l) { - byte b1, b2; + byte b1, b2; - b1 = l&255; - b2 = (l>>8)&255; + b1 = l & 255; + b2 = (l >> 8) & 255; - return (b1<<8) + b2; + return (b1 << 8) + b2; } -int16_t ShortNoSwap (int16_t l) +int16_t ShortNoSwap(int16_t l) { return l; } -int32_t LongSwap (int32_t l) +int32_t LongSwap(int32_t l) { - byte b1, b2, b3, b4; + byte b1, b2, b3, b4; - b1 = l&255; - b2 = (l>>8)&255; - b3 = (l>>16)&255; - b4 = (l>>24)&255; + b1 = l & 255; + b2 = (l >> 8) & 255; + b3 = (l >> 16) & 255; + b4 = (l >> 24) & 255; - return ((int32_t)b1<<24) + ((int32_t)b2<<16) + ((int32_t)b3<<8) + b4; + return ((int32_t)b1 << 24) + ((int32_t)b2 << 16) + ((int32_t)b3 << 8) + b4; } -int32_t LongNoSwap (int32_t l) +int32_t LongNoSwap(int32_t l) { return l; } -float FloatSwap (float f) +float FloatSwap(float f) { union { - float f; - byte b[4]; + float f; + byte b[4]; } dat1, dat2; @@ -613,7 +615,7 @@ float FloatSwap (float f) return dat2.f; } -float FloatNoSwap (float f) +float FloatNoSwap(float f) { return f; } @@ -621,7 +623,7 @@ float FloatNoSwap (float f) /* ============================================================================== - MESSAGE IO FUNCTIONS + MESSAGE IO FUNCTIONS Handles byte ordering and avoids alignment errors ============================================================================== @@ -631,145 +633,145 @@ Handles byte ordering and avoids alignment errors // writing functions // -void MSG_WriteChar (sizebuf_t *sb, int32_t c) +void MSG_WriteChar(sizebuf_t *sb, int32_t c) { - byte *buf; + byte *buf; #ifdef PARANOID - if (c < -128 || c > 127) - Sys_Error ("MSG_WriteChar: range error"); + if(c < -128 || c > 127) + Sys_Error("MSG_WriteChar: range error"); #endif - buf = (byte *) SZ_GetSpace (sb, 1); + buf = (byte *) SZ_GetSpace(sb, 1); buf[0] = c; } -void MSG_WriteByte (sizebuf_t *sb, int32_t c) +void MSG_WriteByte(sizebuf_t *sb, int32_t c) { - byte *buf; + byte *buf; #ifdef PARANOID - if (c < 0 || c > 255) - Sys_Error ("MSG_WriteByte: range error"); + if(c < 0 || c > 255) + Sys_Error("MSG_WriteByte: range error"); #endif - buf = (byte *) SZ_GetSpace (sb, 1); + buf = (byte *) SZ_GetSpace(sb, 1); buf[0] = c; } -void MSG_WriteShort (sizebuf_t *sb, int32_t c) +void MSG_WriteShort(sizebuf_t *sb, int32_t c) { - byte *buf; + byte *buf; #ifdef PARANOID - if (c < ((int16_t)0x8000) || c > (int16_t)0x7fff) - Sys_Error ("MSG_WriteShort: range error"); + if(c < ((int16_t)0x8000) || c > (int16_t)0x7fff) + Sys_Error("MSG_WriteShort: range error"); #endif - buf = (byte *) SZ_GetSpace (sb, 2); - buf[0] = c&0xff; - buf[1] = c>>8; + buf = (byte *) SZ_GetSpace(sb, 2); + buf[0] = c & 0xff; + buf[1] = c >> 8; } -void MSG_WriteLong (sizebuf_t *sb, int32_t c) +void MSG_WriteLong(sizebuf_t *sb, int32_t c) { - byte *buf; + byte *buf; - buf = (byte *) SZ_GetSpace (sb, 4); - buf[0] = c&0xff; - buf[1] = (c>>8)&0xff; - buf[2] = (c>>16)&0xff; - buf[3] = c>>24; + buf = (byte *) SZ_GetSpace(sb, 4); + buf[0] = c & 0xff; + buf[1] = (c >> 8) & 0xff; + buf[2] = (c >> 16) & 0xff; + buf[3] = c >> 24; } -void MSG_WriteFloat (sizebuf_t *sb, float f) +void MSG_WriteFloat(sizebuf_t *sb, float f) { union { - float f; - int32_t l; + float f; + int32_t l; } dat; dat.f = f; - dat.l = LittleLong (dat.l); + dat.l = LittleLong(dat.l); - SZ_Write (sb, &dat.l, 4); + SZ_Write(sb, &dat.l, 4); } -void MSG_WriteString (sizebuf_t *sb, const char *s) +void MSG_WriteString(sizebuf_t *sb, const char *s) { - if (!s) - SZ_Write (sb, "", 1); + if(!s) + SZ_Write(sb, "", 1); else - SZ_Write (sb, s, Q_strlen(s)+1); + SZ_Write(sb, s, Q_strlen(s) + 1); } //johnfitz -- original behavior, 13.3 fixed point coords, max range +-4096 -void MSG_WriteCoord16 (sizebuf_t *sb, float f) +void MSG_WriteCoord16(sizebuf_t *sb, float f) { - MSG_WriteShort (sb, Q_rint(f*8)); + MSG_WriteShort(sb, Q_rint(f * 8)); } //johnfitz -- 16.8 fixed point coords, max range +-32768 -void MSG_WriteCoord24 (sizebuf_t *sb, float f) +void MSG_WriteCoord24(sizebuf_t *sb, float f) { - MSG_WriteShort (sb, f); - MSG_WriteByte (sb, (int32_t)(f*255)%255); + MSG_WriteShort(sb, f); + MSG_WriteByte(sb, (int32_t)(f * 255) % 255); } //johnfitz -- 32-bit float coords -void MSG_WriteCoord32f (sizebuf_t *sb, float f) +void MSG_WriteCoord32f(sizebuf_t *sb, float f) { - MSG_WriteFloat (sb, f); + MSG_WriteFloat(sb, f); } -void MSG_WriteCoord (sizebuf_t *sb, float f, uint32_t flags) +void MSG_WriteCoord(sizebuf_t *sb, float f, uint32_t flags) { - if (flags & PRFL_FLOATCOORD) - MSG_WriteFloat (sb, f); - else if (flags & PRFL_INT32COORD) - MSG_WriteLong (sb, Q_rint (f * 16)); - else if (flags & PRFL_24BITCOORD) - MSG_WriteCoord24 (sb, f); - else MSG_WriteCoord16 (sb, f); + if(flags & PRFL_FLOATCOORD) + MSG_WriteFloat(sb, f); + else if(flags & PRFL_INT32COORD) + MSG_WriteLong(sb, Q_rint(f * 16)); + else if(flags & PRFL_24BITCOORD) + MSG_WriteCoord24(sb, f); + else MSG_WriteCoord16(sb, f); } -void MSG_WriteAngle (sizebuf_t *sb, float f, uint32_t flags) +void MSG_WriteAngle(sizebuf_t *sb, float f, uint32_t flags) { - if (flags & PRFL_FLOATANGLE) - MSG_WriteFloat (sb, f); - else if (flags & PRFL_SHORTANGLE) - MSG_WriteShort (sb, Q_rint(f * 65536.0 / 360.0) & 65535); - else MSG_WriteByte (sb, Q_rint(f * 256.0 / 360.0) & 255); //johnfitz -- use Q_rint instead of (int32_t) } + if(flags & PRFL_FLOATANGLE) + MSG_WriteFloat(sb, f); + else if(flags & PRFL_SHORTANGLE) + MSG_WriteShort(sb, Q_rint(f * 65536.0 / 360.0) & 65535); + else MSG_WriteByte(sb, Q_rint(f * 256.0 / 360.0) & 255); //johnfitz -- use Q_rint instead of (int32_t) } } //johnfitz -- for PROTOCOL_FITZQUAKE -void MSG_WriteAngle16 (sizebuf_t *sb, float f, uint32_t flags) +void MSG_WriteAngle16(sizebuf_t *sb, float f, uint32_t flags) { - if (flags & PRFL_FLOATANGLE) - MSG_WriteFloat (sb, f); - else MSG_WriteShort (sb, Q_rint(f * 65536.0 / 360.0) & 65535); + if(flags & PRFL_FLOATANGLE) + MSG_WriteFloat(sb, f); + else MSG_WriteShort(sb, Q_rint(f * 65536.0 / 360.0) & 65535); } //johnfitz // // reading functions // -int32_t msg_readcount; -bool msg_badread; +int32_t msg_readcount; +bool msg_badread; -void MSG_BeginReading (void) +void MSG_BeginReading(void) { msg_readcount = 0; msg_badread = false; } // returns -1 and sets msg_badread if no more characters are available -int32_t MSG_ReadChar (void) +int32_t MSG_ReadChar(void) { - int32_t c; + int32_t c; - if (msg_readcount+1 > net_message.cursize) + if(msg_readcount + 1 > net_message.cursize) { msg_badread = true; return -1; @@ -781,11 +783,11 @@ int32_t MSG_ReadChar (void) return c; } -int32_t MSG_ReadByte (void) +int32_t MSG_ReadByte(void) { - int32_t c; + int32_t c; - if (msg_readcount+1 > net_message.cursize) + if(msg_readcount + 1 > net_message.cursize) { msg_badread = true; return -1; @@ -797,79 +799,80 @@ int32_t MSG_ReadByte (void) return c; } -int32_t MSG_ReadShort (void) +int32_t MSG_ReadShort(void) { - int32_t c; + int32_t c; - if (msg_readcount+2 > net_message.cursize) + if(msg_readcount + 2 > net_message.cursize) { msg_badread = true; return -1; } c = (int16_t)(net_message.data[msg_readcount] - + (net_message.data[msg_readcount+1]<<8)); + + (net_message.data[msg_readcount + 1] << 8)); msg_readcount += 2; return c; } -int32_t MSG_ReadLong (void) +int32_t MSG_ReadLong(void) { - int32_t c; + int32_t c; - if (msg_readcount+4 > net_message.cursize) + if(msg_readcount + 4 > net_message.cursize) { msg_badread = true; return -1; } c = net_message.data[msg_readcount] - + (net_message.data[msg_readcount+1]<<8) - + (net_message.data[msg_readcount+2]<<16) - + (net_message.data[msg_readcount+3]<<24); + + (net_message.data[msg_readcount + 1] << 8) + + (net_message.data[msg_readcount + 2] << 16) + + (net_message.data[msg_readcount + 3] << 24); msg_readcount += 4; return c; } -float MSG_ReadFloat (void) +float MSG_ReadFloat(void) { union { - byte b[4]; - float f; - int32_t l; + byte b[4]; + float f; + int32_t l; } dat; dat.b[0] = net_message.data[msg_readcount]; - dat.b[1] = net_message.data[msg_readcount+1]; - dat.b[2] = net_message.data[msg_readcount+2]; - dat.b[3] = net_message.data[msg_readcount+3]; + dat.b[1] = net_message.data[msg_readcount + 1]; + dat.b[2] = net_message.data[msg_readcount + 2]; + dat.b[3] = net_message.data[msg_readcount + 3]; msg_readcount += 4; - dat.l = LittleLong (dat.l); + dat.l = LittleLong(dat.l); return dat.f; } -const char *MSG_ReadString (void) +const char *MSG_ReadString(void) { - static char string[2048]; - int32_t c; - size_t l; + static char string[2048]; + int32_t c; + size_t l; l = 0; do { - c = MSG_ReadByte (); - if (c == -1 || c == 0) + c = MSG_ReadByte(); + if(c == -1 || c == 0) break; string[l] = c; l++; - } while (l < sizeof(string) - 1); + } + while(l < sizeof(string) - 1); string[l] = 0; @@ -877,65 +880,65 @@ const char *MSG_ReadString (void) } //johnfitz -- original behavior, 13.3 fixed point coords, max range +-4096 -float MSG_ReadCoord16 (void) +float MSG_ReadCoord16(void) { - return MSG_ReadShort() * (1.0/8); + return MSG_ReadShort() * (1.0 / 8); } //johnfitz -- 16.8 fixed point coords, max range +-32768 -float MSG_ReadCoord24 (void) +float MSG_ReadCoord24(void) { - return MSG_ReadShort() + MSG_ReadByte() * (1.0/255); + return MSG_ReadShort() + MSG_ReadByte() * (1.0 / 255); } //johnfitz -- 32-bit float coords -float MSG_ReadCoord32f (void) +float MSG_ReadCoord32f(void) { return MSG_ReadFloat(); } -float MSG_ReadCoord (uint32_t flags) +float MSG_ReadCoord(uint32_t flags) { - if (flags & PRFL_FLOATCOORD) - return MSG_ReadFloat (); - else if (flags & PRFL_INT32COORD) - return MSG_ReadLong () * (1.0 / 16.0); - else if (flags & PRFL_24BITCOORD) - return MSG_ReadCoord24 (); - else return MSG_ReadCoord16 (); + if(flags & PRFL_FLOATCOORD) + return MSG_ReadFloat(); + else if(flags & PRFL_INT32COORD) + return MSG_ReadLong() * (1.0 / 16.0); + else if(flags & PRFL_24BITCOORD) + return MSG_ReadCoord24(); + else return MSG_ReadCoord16(); } -float MSG_ReadAngle (uint32_t flags) +float MSG_ReadAngle(uint32_t flags) { - if (flags & PRFL_FLOATANGLE) - return MSG_ReadFloat (); - else if (flags & PRFL_SHORTANGLE) - return MSG_ReadShort () * (360.0 / 65536); - else return MSG_ReadChar () * (360.0 / 256); + if(flags & PRFL_FLOATANGLE) + return MSG_ReadFloat(); + else if(flags & PRFL_SHORTANGLE) + return MSG_ReadShort() * (360.0 / 65536); + else return MSG_ReadChar() * (360.0 / 256); } //johnfitz -- for PROTOCOL_FITZQUAKE -float MSG_ReadAngle16 (uint32_t flags) +float MSG_ReadAngle16(uint32_t flags) { - if (flags & PRFL_FLOATANGLE) - return MSG_ReadFloat (); // make sure - else return MSG_ReadShort () * (360.0 / 65536); + if(flags & PRFL_FLOATANGLE) + return MSG_ReadFloat(); // make sure + else return MSG_ReadShort() * (360.0 / 65536); } //johnfitz //=========================================================================== -void SZ_Alloc (sizebuf_t *buf, int32_t startsize) +void SZ_Alloc(sizebuf_t *buf, int32_t startsize) { - if (startsize < 256) + if(startsize < 256) startsize = 256; - buf->data = (byte *) Hunk_AllocName (startsize, "sizebuf"); + buf->data = (byte *) Hunk_AllocName(startsize, "sizebuf"); buf->maxsize = startsize; buf->cursize = 0; } -void SZ_Free (sizebuf_t *buf) +void SZ_Free(sizebuf_t *buf) { // Z_Free (buf->data); // buf->data = NULL; @@ -943,26 +946,26 @@ void SZ_Free (sizebuf_t *buf) buf->cursize = 0; } -void SZ_Clear (sizebuf_t *buf) +void SZ_Clear(sizebuf_t *buf) { buf->cursize = 0; } -void *SZ_GetSpace (sizebuf_t *buf, int32_t length) +void *SZ_GetSpace(sizebuf_t *buf, int32_t length) { - void *data; + void *data; - if (buf->cursize + length > buf->maxsize) + if(buf->cursize + length > buf->maxsize) { - if (!buf->allowoverflow) - Host_Error ("SZ_GetSpace: overflow without allowoverflow set"); // ericw -- made Host_Error to be less annoying + if(!buf->allowoverflow) + Host_Error("SZ_GetSpace: overflow without allowoverflow set"); // ericw -- made Host_Error to be less annoying - if (length > buf->maxsize) - Sys_Error ("SZ_GetSpace: %" PRIi32 " is > full buffer size", length); + if(length > buf->maxsize) + Sys_Error("SZ_GetSpace: %" PRIi32 " is > full buffer size", length); buf->overflowed = true; - Con_Printf ("SZ_GetSpace: overflow"); - SZ_Clear (buf); + Con_Printf("SZ_GetSpace: overflow"); + SZ_Clear(buf); } data = buf->data + buf->cursize; @@ -971,22 +974,24 @@ void *SZ_GetSpace (sizebuf_t *buf, int32_t length) return data; } -void SZ_Write (sizebuf_t *buf, const void *data, int32_t length) +void SZ_Write(sizebuf_t *buf, const void *data, int32_t length) { - Q_memcpy (SZ_GetSpace(buf,length),data,length); + Q_memcpy(SZ_GetSpace(buf, length), data, length); } -void SZ_Print (sizebuf_t *buf, const char *data) +void SZ_Print(sizebuf_t *buf, const char *data) { - int32_t len = Q_strlen(data) + 1; + int32_t len = Q_strlen(data) + 1; - if (buf->data[buf->cursize-1]) - { /* no trailing 0 */ - Q_memcpy ((byte *)SZ_GetSpace(buf, len ) , data, len); + if(buf->data[buf->cursize - 1]) + { + /* no trailing 0 */ + Q_memcpy((byte *)SZ_GetSpace(buf, len), data, len); } else - { /* write over trailing 0 */ - Q_memcpy ((byte *)SZ_GetSpace(buf, len-1)-1, data, len); + { + /* write over trailing 0 */ + Q_memcpy((byte *)SZ_GetSpace(buf, len - 1) - 1, data, len); } } @@ -998,14 +1003,14 @@ void SZ_Print (sizebuf_t *buf, const char *data) COM_SkipPath ============ */ -const char *COM_SkipPath (const char *pathname) +const char *COM_SkipPath(const char *pathname) { - const char *last; + const char *last; last = pathname; - while (*pathname) + while(*pathname) { - if (*pathname == '/') + if(*pathname == '/') last = pathname + 1; pathname++; } @@ -1017,25 +1022,25 @@ const char *COM_SkipPath (const char *pathname) COM_StripExtension ============ */ -void COM_StripExtension (const char *in, char *out, size_t outsize) +void COM_StripExtension(const char *in, char *out, size_t outsize) { - int32_t length; + int32_t length; - if (!*in) + if(!*in) { *out = '\0'; return; } - if (in != out) /* copy when not in-place editing */ - q_strlcpy (out, in, outsize); + if(in != out) /* copy when not in-place editing */ + q_strlcpy(out, in, outsize); length = (int32_t)strlen(out) - 1; - while (length > 0 && out[length] != '.') + while(length > 0 && out[length] != '.') { --length; - if (out[length] == '/' || out[length] == '\\') - return; /* no extension */ + if(out[length] == '/' || out[length] == '\\') + return; /* no extension */ } - if (length > 0) + if(length > 0) out[length] = '\0'; } @@ -1044,20 +1049,20 @@ void COM_StripExtension (const char *in, char *out, size_t outsize) COM_FileGetExtension - doesn't return NULL ============ */ -const char *COM_FileGetExtension (const char *in) +const char *COM_FileGetExtension(const char *in) { - const char *src; - size_t len; + const char *src; + size_t len; len = strlen(in); - if (len < 2) /* nothing meaningful */ + if(len < 2) /* nothing meaningful */ return ""; src = in + len - 1; - while (src != in && src[-1] != '.') + while(src != in && src[-1] != '.') src--; - if (src == in || strchr(src, '/') != NULL || strchr(src, '\\') != NULL) - return ""; /* no extension, or parent directory has a dot */ + if(src == in || strchr(src, '/') != NULL || strchr(src, '\\') != NULL) + return ""; /* no extension, or parent directory has a dot */ return src; } @@ -1067,13 +1072,13 @@ const char *COM_FileGetExtension (const char *in) COM_ExtractExtension ============ */ -void COM_ExtractExtension (const char *in, char *out, size_t outsize) +void COM_ExtractExtension(const char *in, char *out, size_t outsize) { - const char *ext = COM_FileGetExtension (in); - if (! *ext) + const char *ext = COM_FileGetExtension(in); + if(! *ext) *out = '\0'; else - q_strlcpy (out, ext, outsize); + q_strlcpy(out, ext, outsize); } /* @@ -1083,32 +1088,32 @@ take 'somedir/otherdir/filename.ext', write only 'filename' to the output ============ */ -void COM_FileBase (const char *in, char *out, size_t outsize) +void COM_FileBase(const char *in, char *out, size_t outsize) { - const char *dot, *slash, *s; + const char *dot, *slash, *s; s = in; slash = in; dot = NULL; - while (*s) + while(*s) { - if (*s == '/') + if(*s == '/') slash = s + 1; - if (*s == '.') + if(*s == '.') dot = s; s++; } - if (dot == NULL) + if(dot == NULL) dot = s; - if (dot - slash < 2) - q_strlcpy (out, "?model?", outsize); + if(dot - slash < 2) + q_strlcpy(out, "?model?", outsize); else { - size_t len = dot - slash; - if (len >= outsize) + size_t len = dot - slash; + if(len >= outsize) len = outsize - 1; - memcpy (out, slash, len); + memcpy(out, slash, len); out[len] = '\0'; } } @@ -1121,16 +1126,16 @@ if path doesn't have a .EXT, append extension ================== */ #if 0 /* can be dangerous */ -void COM_DefaultExtension (char *path, const char *extension, size_t len) +void COM_DefaultExtension(char *path, const char *extension, size_t len) { - char *src; + char *src; - if (!*path) return; + if(!*path) return; src = path + strlen(path) - 1; - while (*src != '/' && *src != '\\' && src != path) + while(*src != '/' && *src != '\\' && src != path) { - if (*src == '.') + if(*src == '.') return; // it has an extension src--; } @@ -1146,9 +1151,9 @@ if path extension doesn't match .EXT, append it (extension should include the leading ".") ================== */ -void COM_AddExtension (char *path, const char *extension, size_t len) +void COM_AddExtension(char *path, const char *extension, size_t len) { - if (strcmp(COM_FileGetExtension(path), extension + 1) != 0) + if(strcmp(COM_FileGetExtension(path), extension + 1) != 0) q_strlcat(path, extension, len); } @@ -1160,54 +1165,54 @@ COM_Parse Parse a token out of a string ============== */ -const char *COM_Parse (const char *data) +const char *COM_Parse(const char *data) { - int32_t c; - int32_t len; + int32_t c; + int32_t len; len = 0; com_token[0] = 0; - if (!data) + if(!data) return NULL; // skip whitespace skipwhite: - while ((c = *data) <= ' ') + while((c = *data) <= ' ') { - if (c == 0) - return NULL; // end of file + if(c == 0) + return NULL; // end of file data++; } // skip // comments - if (c == '/' && data[1] == '/') + if(c == '/' && data[1] == '/') { - while (*data && *data != '\n') + while(*data && *data != '\n') data++; goto skipwhite; } // skip /*..*/ comments - if (c == '/' && data[1] == '*') + if(c == '/' && data[1] == '*') { data += 2; - while (*data && !(*data == '*' && data[1] == '/')) + while(*data && !(*data == '*' && data[1] == '/')) data++; - if (*data) + if(*data) data += 2; goto skipwhite; } // handle quoted strings specially - if (c == '\"') + if(c == '\"') { data++; - while (1) + while(1) { - if ((c = *data) != 0) + if((c = *data) != 0) ++data; - if (c == '\"' || !c) + if(c == '\"' || !c) { com_token[len] = 0; return data; @@ -1218,12 +1223,12 @@ skipwhite: } // parse single characters - if (c == '{' || c == '}'|| c == '('|| c == ')' || c == '\'' || c == ':') + if(c == '{' || c == '}' || c == '(' || c == ')' || c == '\'' || c == ':') { com_token[len] = c; len++; com_token[len] = 0; - return data+1; + return data + 1; } // parse a regular word @@ -1234,9 +1239,10 @@ skipwhite: len++; c = *data; /* commented out the check for ':' so that ip:port works */ - if (c == '{' || c == '}'|| c == '('|| c == ')' || c == '\''/* || c == ':' */) + if(c == '{' || c == '}' || c == '(' || c == ')' || c == '\''/* || c == ':' */) break; - } while (c > 32); + } + while(c > 32); com_token[len] = 0; return data; @@ -1251,15 +1257,15 @@ Returns the position (1 to argc-1) in the program's argument list where the given parameter apears, or 0 if not present ================ */ -int32_t COM_CheckParm (const char *parm) +int32_t COM_CheckParm(const char *parm) { - int32_t i; + int32_t i; - for (i = 1; i < com_argc; i++) + for(i = 1; i < com_argc; i++) { - if (!com_argv[i]) - continue; // NEXTSTEP sometimes clears appkit vars. - if (!Q_strcmp (parm,com_argv[i])) + if(!com_argv[i]) + continue; // NEXTSTEP sometimes clears appkit vars. + if(!Q_strcmp(parm, com_argv[i])) return i; } @@ -1276,45 +1282,45 @@ Immediately exits out if an alternate game was attempted to be started without being registered. ================ */ -static void COM_CheckRegistered (void) +static void COM_CheckRegistered(void) { - int32_t h; - uint16_t check[128]; - int32_t i; + int32_t h; + uint16_t check[128]; + int32_t i; COM_OpenFile("gfx/pop.lmp", &h, NULL); - if (h == -1) + if(h == -1) { - Cvar_SetROM ("registered", "0"); - Con_Printf ("Playing shareware version.\n"); - if (com_modified) - Sys_Error ("You must have the registered version to use modified games.\n\n" - "Basedir is: %s\n\n" - "Check that this has an " GAMENAME " subdirectory containing pak0.pak and pak1.pak, " - "or use the -basedir command-line option to specify another directory.", - com_basedir); + Cvar_SetROM("registered", "0"); + Con_Printf("Playing shareware version.\n"); + if(com_modified) + Sys_Error("You must have the registered version to use modified games.\n\n" + "Basedir is: %s\n\n" + "Check that this has an " GAMENAME " subdirectory containing pak0.pak and pak1.pak, " + "or use the -basedir command-line option to specify another directory.", + com_basedir); return; } - Sys_FileRead (h, check, sizeof(check)); - COM_CloseFile (h); + Sys_FileRead(h, check, sizeof(check)); + COM_CloseFile(h); - for (i = 0; i < 128; i++) + for(i = 0; i < 128; i++) { - if (pop[i] != (uint16_t)BigShort (check[i])) - Sys_Error ("Corrupted data file."); + if(pop[i] != (uint16_t)BigShort(check[i])) + Sys_Error("Corrupted data file."); } - for (i = 0; com_cmdline[i]; i++) + for(i = 0; com_cmdline[i]; i++) { - if (com_cmdline[i]!= ' ') + if(com_cmdline[i] != ' ') break; } - Cvar_SetROM ("cmdline", &com_cmdline[i]); - Cvar_SetROM ("registered", "1"); - Con_Printf ("Playing registered version.\n"); + Cvar_SetROM("cmdline", &com_cmdline[i]); + Cvar_SetROM("registered", "1"); + Con_Printf("Playing registered version.\n"); } @@ -1323,50 +1329,50 @@ static void COM_CheckRegistered (void) COM_InitArgv ================ */ -void COM_InitArgv (int32_t argc, char **argv) +void COM_InitArgv(int32_t argc, char **argv) { - int32_t i, j, n; + int32_t i, j, n; // reconstitute the command line for the cmdline externally visible cvar n = 0; - for (j = 0; (j 0 && com_cmdline[n-1] == ' ') - com_cmdline[n-1] = 0; //johnfitz -- kill the trailing space + if(n > 0 && com_cmdline[n - 1] == ' ') + com_cmdline[n - 1] = 0; //johnfitz -- kill the trailing space Con_Printf("Command line: %s\n", com_cmdline); - for (com_argc = 0; (com_argc < MAX_NUM_ARGVS) && (com_argc < argc); com_argc++) + for(com_argc = 0; (com_argc < MAX_NUM_ARGVS) && (com_argc < argc); com_argc++) { largv[com_argc] = argv[com_argc]; - if (!Q_strcmp ("-safe", argv[com_argc])) + if(!Q_strcmp("-safe", argv[com_argc])) safemode = 1; } largv[com_argc] = argvdummy; com_argv = largv; - if (COM_CheckParm ("-rogue")) + if(COM_CheckParm("-rogue")) { rogue = true; standard_quake = false; } - if (COM_CheckParm ("-hipnotic") || COM_CheckParm ("-quoth")) //johnfitz -- "-quoth" support + if(COM_CheckParm("-hipnotic") || COM_CheckParm("-quoth")) //johnfitz -- "-quoth" support { hipnotic = true; standard_quake = false; @@ -1379,7 +1385,7 @@ Test_f -- johnfitz ================ */ #ifdef _DEBUG -static void FitzTest_f (void) +static void FitzTest_f(void) { } #endif @@ -1389,29 +1395,29 @@ static void FitzTest_f (void) COM_Init ================ */ -void COM_Init (void) +void COM_Init(void) { - int32_t i = 0x12345678; - /* U N I X */ + int32_t i = 0x12345678; + /* U N I X */ /* BE_ORDER: 12 34 56 78 - U N I X + U N I X LE_ORDER: 78 56 34 12 - X I N U + X I N U PDP_ORDER: 34 12 78 56 - N U X I + N U X I */ - if ( *(char *)&i == 0x12 ) + if(*(char *)&i == 0x12) host_bigendian = true; - else if ( *(char *)&i == 0x78 ) + else if(*(char *)&i == 0x78) host_bigendian = false; else /* if ( *(char *)&i == 0x34 ) */ - Sys_Error ("Unsupported endianism."); + Sys_Error("Unsupported endianism."); - if (host_bigendian) + if(host_bigendian) { BigShort = ShortNoSwap; LittleShort = ShortSwap; @@ -1430,10 +1436,10 @@ void COM_Init (void) LittleFloat = FloatNoSwap; } - if (COM_CheckParm("-fitz")) + if(COM_CheckParm("-fitz")) fitzmode = true; #ifdef _DEBUG - Cmd_AddCommand ("fitztest", FitzTest_f); //johnfitz + Cmd_AddCommand("fitztest", FitzTest_f); //johnfitz #endif } @@ -1448,8 +1454,8 @@ is defined in VA_NUM_BUFFS. FIXME: make this buffer size safe someday ============ */ -#define VA_NUM_BUFFS 4 -#define VA_BUFFERLEN 1024 +#define VA_NUM_BUFFS 4 +#define VA_BUFFERLEN 1024 static char *get_va_buffer(void) { @@ -1459,15 +1465,15 @@ static char *get_va_buffer(void) return va_buffers[buffer_idx]; } -char *va (const char *format, ...) +char *va(const char *format, ...) { - va_list argptr; - char *va_buf; + va_list argptr; + char *va_buf; - va_buf = get_va_buffer (); - va_start (argptr, format); - q_vsnprintf (va_buf, VA_BUFFERLEN, format, argptr); - va_end (argptr); + va_buf = get_va_buffer(); + va_start(argptr, format); + q_vsnprintf(va_buf, VA_BUFFERLEN, format, argptr); + va_end(argptr); return va_buf; } @@ -1480,7 +1486,7 @@ QUAKE FILESYSTEM ============================================================================= */ -int32_t com_filesize; +int32_t com_filesize; // @@ -1488,44 +1494,44 @@ int32_t com_filesize; // typedef struct { - char name[56]; - int32_t filepos, filelen; + char name[56]; + int32_t filepos, filelen; } dpackfile_t; typedef struct { - char id[4]; - int32_t dirofs; - int32_t dirlen; + char id[4]; + int32_t dirofs; + int32_t dirlen; } dpackheader_t; -#define MAX_FILES_IN_PACK 2048 +#define MAX_FILES_IN_PACK 2048 -char com_gamedir[MAX_OSPATH]; -char com_basedir[MAX_OSPATH]; -int32_t file_from_pak; // ZOID: global indicating that file came from a pak +char com_gamedir[MAX_OSPATH]; +char com_basedir[MAX_OSPATH]; +int32_t file_from_pak; // ZOID: global indicating that file came from a pak -searchpath_t *com_searchpaths; -searchpath_t *com_base_searchpaths; +searchpath_t *com_searchpaths; +searchpath_t *com_base_searchpaths; /* ============ COM_Path_f ============ */ -static void COM_Path_f (void) +static void COM_Path_f(void) { - searchpath_t *s; + searchpath_t *s; - Con_Printf ("Current search path:\n"); - for (s = com_searchpaths; s; s = s->next) + Con_Printf("Current search path:\n"); + for(s = com_searchpaths; s; s = s->next) { - if (s->pack) + if(s->pack) { - Con_Printf ("%s (%" PRIi32 " files)\n", s->pack->filename, s->pack->numfiles); + Con_Printf("%s (%" PRIi32 " files)\n", s->pack->filename, s->pack->numfiles); } else - Con_Printf ("%s\n", s->filename); + Con_Printf("%s\n", s->filename); } } @@ -1536,25 +1542,25 @@ COM_WriteFile The filename will be prefixed by the current game directory ============ */ -void COM_WriteFile (const char *filename, const void *data, int32_t len) +void COM_WriteFile(const char *filename, const void *data, int32_t len) { - int32_t handle; - char name[MAX_OSPATH]; + int32_t handle; + char name[MAX_OSPATH]; - Sys_mkdir (com_gamedir); //johnfitz -- if we've switched to a nonexistant gamedir, create it now so we don't crash + Sys_mkdir(com_gamedir); //johnfitz -- if we've switched to a nonexistant gamedir, create it now so we don't crash - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, filename); + q_snprintf(name, sizeof(name), "%s/%s", com_gamedir, filename); - handle = Sys_FileOpenWrite (name); - if (handle == -1) + handle = Sys_FileOpenWrite(name); + if(handle == -1) { - Sys_Printf ("COM_WriteFile: failed on %s\n", name); + Sys_Printf("COM_WriteFile: failed on %s\n", name); return; } - Sys_Printf ("COM_WriteFile: %s\n", name); - Sys_FileWrite (handle, data, len); - Sys_FileClose (handle); + Sys_Printf("COM_WriteFile: %s\n", name); + Sys_FileWrite(handle, data, len); + Sys_FileClose(handle); } /* @@ -1562,16 +1568,17 @@ void COM_WriteFile (const char *filename, const void *data, int32_t len) COM_CreatePath ============ */ -void COM_CreatePath (char *path) +void COM_CreatePath(char *path) { - char *ofs; + char *ofs; - for (ofs = path + 1; *ofs; ofs++) + for(ofs = path + 1; *ofs; ofs++) { - if (*ofs == '/') - { // create the directory + if(*ofs == '/') + { + // create the directory *ofs = 0; - Sys_mkdir (path); + Sys_mkdir(path); *ofs = '/'; } } @@ -1582,14 +1589,14 @@ void COM_CreatePath (char *path) COM_filelength ================ */ -long COM_filelength (FILE *f) +long COM_filelength(FILE *f) { - long pos, end; + long pos, end; - pos = ftell (f); - fseek (f, 0, SEEK_END); - end = ftell (f); - fseek (f, pos, SEEK_SET); + pos = ftell(f); + fseek(f, 0, SEEK_END); + end = ftell(f); + fseek(f, pos, SEEK_SET); return end; } @@ -1604,47 +1611,48 @@ If neither of file or handle is set, this can be used for detecting a file's presence. =========== */ -static int32_t COM_FindFile (const char *filename, int32_t *handle, FILE **file, - uint32_t *path_id) +static int32_t COM_FindFile(const char *filename, int32_t *handle, FILE **file, + uint32_t *path_id) { - searchpath_t *search; - char netpath[MAX_OSPATH]; - pack_t *pak; - int32_t i, findtime; + searchpath_t *search; + char netpath[MAX_OSPATH]; + pack_t *pak; + int32_t i, findtime; - if (file && handle) - Sys_Error ("COM_FindFile: both handle and file set"); + if(file && handle) + Sys_Error("COM_FindFile: both handle and file set"); file_from_pak = 0; // // search through the path, one element at a time // - for (search = com_searchpaths; search; search = search->next) + for(search = com_searchpaths; search; search = search->next) { - if (search->pack) /* look through all the pak file elements */ + if(search->pack) /* look through all the pak file elements */ { pak = search->pack; - for (i = 0; i < pak->numfiles; i++) + for(i = 0; i < pak->numfiles; i++) { - if (strcmp(pak->files[i].name, filename) != 0) + if(strcmp(pak->files[i].name, filename) != 0) continue; // found it! com_filesize = pak->files[i].filelen; file_from_pak = 1; - if (path_id) + if(path_id) *path_id = search->path_id; - if (handle) + if(handle) { *handle = pak->handle; - Sys_FileSeek (pak->handle, pak->files[i].filepos); + Sys_FileSeek(pak->handle, pak->files[i].filepos); return com_filesize; } - else if (file) - { /* open a new file on the pakfile */ - *file = fopen (pak->filename, "rb"); - if (*file) - fseek (*file, pak->files[i].filepos, SEEK_SET); + else if(file) + { + /* open a new file on the pakfile */ + *file = fopen(pak->filename, "rb"); + if(*file) + fseek(*file, pak->files[i].filepos, SEEK_SET); return com_filesize; } else /* for COM_FileExists() */ @@ -1653,31 +1661,32 @@ static int32_t COM_FindFile (const char *filename, int32_t *handle, FILE **file, } } } - else /* check a file in the directory tree */ + else /* check a file in the directory tree */ { - if (!registered.value) - { /* if not a registered version, don't ever go beyond base */ - if ( strchr (filename, '/') || strchr (filename,'\\')) + if(!registered.value) + { + /* if not a registered version, don't ever go beyond base */ + if(strchr(filename, '/') || strchr(filename, '\\')) continue; } - q_snprintf (netpath, sizeof(netpath), "%s/%s",search->filename, filename); - findtime = Sys_FileTime (netpath); - if (findtime == -1) + q_snprintf(netpath, sizeof(netpath), "%s/%s", search->filename, filename); + findtime = Sys_FileTime(netpath); + if(findtime == -1) continue; - if (path_id) + if(path_id) *path_id = search->path_id; - if (handle) + if(handle) { - com_filesize = Sys_FileOpenRead (netpath, &i); + com_filesize = Sys_FileOpenRead(netpath, &i); *handle = i; return com_filesize; } - else if (file) + else if(file) { - *file = fopen (netpath, "rb"); - com_filesize = (*file == NULL) ? -1 : COM_filelength (*file); + *file = fopen(netpath, "rb"); + com_filesize = (*file == NULL) ? -1 : COM_filelength(*file); return com_filesize; } else @@ -1687,17 +1696,17 @@ static int32_t COM_FindFile (const char *filename, int32_t *handle, FILE **file, } } - if (strcmp(COM_FileGetExtension(filename), "pcx") != 0 - && strcmp(COM_FileGetExtension(filename), "tga") != 0 - && strcmp(COM_FileGetExtension(filename), "lit") != 0 - && strcmp(COM_FileGetExtension(filename), "ent") != 0) - Con_DPrintf ("FindFile: can't find %s\n", filename); - else Con_DPrintf2("FindFile: can't find %s\n", filename); - // Log pcx, tga, lit, ent misses only if (developer.value >= 2) + if(strcmp(COM_FileGetExtension(filename), "pcx") != 0 + && strcmp(COM_FileGetExtension(filename), "tga") != 0 + && strcmp(COM_FileGetExtension(filename), "lit") != 0 + && strcmp(COM_FileGetExtension(filename), "ent") != 0) + Con_DPrintf("FindFile: can't find %s\n", filename); + else Con_DPrintf2("FindFile: can't find %s\n", filename); + // Log pcx, tga, lit, ent misses only if (developer.value >= 2) - if (handle) + if(handle) *handle = -1; - if (file) + if(file) *file = NULL; com_filesize = -1; return com_filesize; @@ -1711,9 +1720,9 @@ COM_FileExists Returns whether the file is found in the quake filesystem. =========== */ -bool COM_FileExists (const char *filename, uint32_t *path_id) +bool COM_FileExists(const char *filename, uint32_t *path_id) { - int32_t ret = COM_FindFile (filename, NULL, NULL, path_id); + int32_t ret = COM_FindFile(filename, NULL, NULL, path_id); return (ret == -1) ? false : true; } @@ -1726,9 +1735,9 @@ returns a handle and a length it may actually be inside a pak file =========== */ -int32_t COM_OpenFile (const char *filename, int32_t *handle, uint32_t *path_id) +int32_t COM_OpenFile(const char *filename, int32_t *handle, uint32_t *path_id) { - return COM_FindFile (filename, handle, NULL, path_id); + return COM_FindFile(filename, handle, NULL, path_id); } /* @@ -1739,9 +1748,9 @@ If the requested file is inside a packfile, a new FILE * will be opened into the file. =========== */ -int32_t COM_FOpenFile (const char *filename, FILE **file, uint32_t *path_id) +int32_t COM_FOpenFile(const char *filename, FILE **file, uint32_t *path_id) { - return COM_FindFile (filename, NULL, file, path_id); + return COM_FindFile(filename, NULL, file, path_id); } /* @@ -1751,15 +1760,15 @@ COM_CloseFile If it is a pak file handle, don't really close it ============ */ -void COM_CloseFile (int32_t h) +void COM_CloseFile(int32_t h) { - searchpath_t *s; + searchpath_t *s; - for (s = com_searchpaths; s; s = s->next) - if (s->pack && s->pack->handle == h) + for(s = com_searchpaths; s; s = s->next) + if(s->pack && s->pack->handle == h) return; - Sys_FileClose (h); + Sys_FileClose(h); } @@ -1771,143 +1780,143 @@ Filename are reletive to the quake directory. Allways appends a 0 byte. ============ */ -#define LOADFILE_ZONE 0 -#define LOADFILE_HUNK 1 -#define LOADFILE_TEMPHUNK 2 -#define LOADFILE_CACHE 3 -#define LOADFILE_STACK 4 -#define LOADFILE_MALLOC 5 +#define LOADFILE_ZONE 0 +#define LOADFILE_HUNK 1 +#define LOADFILE_TEMPHUNK 2 +#define LOADFILE_CACHE 3 +#define LOADFILE_STACK 4 +#define LOADFILE_MALLOC 5 -static byte *loadbuf; +static byte *loadbuf; static cache_user_t *loadcache; -static int32_t loadsize; +static int32_t loadsize; -byte *COM_LoadFile (const char *path, int32_t usehunk, uint32_t *path_id) +byte *COM_LoadFile(const char *path, int32_t usehunk, uint32_t *path_id) { - int32_t h; - byte *buf; - char base[32]; - int32_t len; + int32_t h; + byte *buf; + char base[32]; + int32_t len; - buf = NULL; // quiet compiler warning + buf = NULL; // quiet compiler warning // look for it in the filesystem or pack files - len = COM_OpenFile (path, &h, path_id); - if (h == -1) + len = COM_OpenFile(path, &h, path_id); + if(h == -1) return NULL; // extract the filename base name for hunk tag - COM_FileBase (path, base, sizeof(base)); + COM_FileBase(path, base, sizeof(base)); - switch (usehunk) + switch(usehunk) { case LOADFILE_HUNK: - buf = (byte *) Hunk_AllocName (len+1, base); + buf = (byte *) Hunk_AllocName(len + 1, base); break; case LOADFILE_TEMPHUNK: - buf = (byte *) Hunk_TempAlloc (len+1); + buf = (byte *) Hunk_TempAlloc(len + 1); break; case LOADFILE_ZONE: - buf = (byte *) Z_Malloc (len+1); + buf = (byte *) Z_Malloc(len + 1); break; case LOADFILE_CACHE: - buf = (byte *) Cache_Alloc (loadcache, len+1, base); + buf = (byte *) Cache_Alloc(loadcache, len + 1, base); break; case LOADFILE_STACK: - if (len < loadsize) + if(len < loadsize) buf = loadbuf; else - buf = (byte *) Hunk_TempAlloc (len+1); + buf = (byte *) Hunk_TempAlloc(len + 1); break; case LOADFILE_MALLOC: - buf = (byte *) malloc (len+1); + buf = (byte *) malloc(len + 1); break; default: - Sys_Error ("COM_LoadFile: bad usehunk"); + Sys_Error("COM_LoadFile: bad usehunk"); } - if (!buf) - Sys_Error ("COM_LoadFile: not enough space for %s", path); + if(!buf) + Sys_Error("COM_LoadFile: not enough space for %s", path); ((byte *)buf)[len] = 0; - Sys_FileRead (h, buf, len); - COM_CloseFile (h); + Sys_FileRead(h, buf, len); + COM_CloseFile(h); return buf; } -byte *COM_LoadHunkFile (const char *path, uint32_t *path_id) +byte *COM_LoadHunkFile(const char *path, uint32_t *path_id) { - return COM_LoadFile (path, LOADFILE_HUNK, path_id); + return COM_LoadFile(path, LOADFILE_HUNK, path_id); } -byte *COM_LoadZoneFile (const char *path, uint32_t *path_id) +byte *COM_LoadZoneFile(const char *path, uint32_t *path_id) { - return COM_LoadFile (path, LOADFILE_ZONE, path_id); + return COM_LoadFile(path, LOADFILE_ZONE, path_id); } -byte *COM_LoadTempFile (const char *path, uint32_t *path_id) +byte *COM_LoadTempFile(const char *path, uint32_t *path_id) { - return COM_LoadFile (path, LOADFILE_TEMPHUNK, path_id); + return COM_LoadFile(path, LOADFILE_TEMPHUNK, path_id); } -void COM_LoadCacheFile (const char *path, struct cache_user_s *cu, uint32_t *path_id) +void COM_LoadCacheFile(const char *path, struct cache_user_s *cu, uint32_t *path_id) { loadcache = cu; - COM_LoadFile (path, LOADFILE_CACHE, path_id); + COM_LoadFile(path, LOADFILE_CACHE, path_id); } // uses temp hunk if larger than bufsize -byte *COM_LoadStackFile (const char *path, void *buffer, int32_t bufsize, uint32_t *path_id) +byte *COM_LoadStackFile(const char *path, void *buffer, int32_t bufsize, uint32_t *path_id) { - byte *buf; + byte *buf; loadbuf = (byte *)buffer; loadsize = bufsize; - buf = COM_LoadFile (path, LOADFILE_STACK, path_id); + buf = COM_LoadFile(path, LOADFILE_STACK, path_id); return buf; } // returns malloc'd memory -byte *COM_LoadMallocFile (const char *path, uint32_t *path_id) +byte *COM_LoadMallocFile(const char *path, uint32_t *path_id) { - return COM_LoadFile (path, LOADFILE_MALLOC, path_id); + return COM_LoadFile(path, LOADFILE_MALLOC, path_id); } -byte *COM_LoadMallocFile_TextMode_OSPath (const char *path, long *len_out) +byte *COM_LoadMallocFile_TextMode_OSPath(const char *path, long *len_out) { - FILE *f; - byte *data; - long len, actuallen; - + FILE *f; + byte *data; + long len, actuallen; + // ericw -- this is used by Host_Loadgame_f. Translate CRLF to LF on load games, // othewise multiline messages have a garbage character at the end of each line. // TODO: could handle in a way that allows loading CRLF savegames on mac/linux // without the junk characters appearing. - f = fopen (path, "rt"); - if (f == NULL) + f = fopen(path, "rt"); + if(f == NULL) return NULL; - - len = COM_filelength (f); - if (len < 0) + + len = COM_filelength(f); + if(len < 0) return NULL; - - data = (byte *) malloc (len + 1); - if (data == NULL) + + data = (byte *) malloc(len + 1); + if(data == NULL) return NULL; // (actuallen < len) if CRLF to LF translation was performed - actuallen = fread (data, 1, len, f); - if (ferror(f)) + actuallen = fread(data, 1, len, f); + if(ferror(f)) { - free (data); + free(data); return NULL; } data[actuallen] = '\0'; - - if (len_out != NULL) + + if(len_out != NULL) *len_out = actuallen; return data; } @@ -1915,14 +1924,14 @@ byte *COM_LoadMallocFile_TextMode_OSPath (const char *path, long *len_out) const char *COM_ParseIntNewline(const char *buffer, int32_t *value) { int32_t consumed = 0; - sscanf (buffer, "%" PRIi32 "\n%n", value, &consumed); + sscanf(buffer, "%" PRIi32 "\n%n", value, &consumed); return buffer + consumed; } const char *COM_ParseFloatNewline(const char *buffer, float *value) { int32_t consumed = 0; - sscanf (buffer, "%f\n%n", value, &consumed); + sscanf(buffer, "%f\n%n", value, &consumed); return buffer + consumed; } @@ -1930,7 +1939,7 @@ const char *COM_ParseStringNewline(const char *buffer) { int32_t consumed = 0; com_token[0] = '\0'; - sscanf (buffer, "%1023s\n%n", com_token, &consumed); + sscanf(buffer, "%1023s\n%n", com_token, &consumed); return buffer + consumed; } @@ -1944,68 +1953,68 @@ Loads the header and directory, adding the files at the beginning of the list so they override previous pack files. ================= */ -static pack_t *COM_LoadPackFile (const char *packfile) +static pack_t *COM_LoadPackFile(const char *packfile) { - dpackheader_t header; - int32_t i; - packfile_t *newfiles; - int32_t numpackfiles; - pack_t *pack; - int32_t packhandle; - dpackfile_t info[MAX_FILES_IN_PACK]; - uint16_t crc; + dpackheader_t header; + int32_t i; + packfile_t *newfiles; + int32_t numpackfiles; + pack_t *pack; + int32_t packhandle; + dpackfile_t info[MAX_FILES_IN_PACK]; + uint16_t crc; - if (Sys_FileOpenRead (packfile, &packhandle) == -1) + if(Sys_FileOpenRead(packfile, &packhandle) == -1) return NULL; - Sys_FileRead (packhandle, (void *)&header, sizeof(header)); - if (header.id[0] != 'P' || header.id[1] != 'A' || header.id[2] != 'C' || header.id[3] != 'K') - Sys_Error ("%s is not a packfile", packfile); + Sys_FileRead(packhandle, (void *)&header, sizeof(header)); + if(header.id[0] != 'P' || header.id[1] != 'A' || header.id[2] != 'C' || header.id[3] != 'K') + Sys_Error("%s is not a packfile", packfile); - header.dirofs = LittleLong (header.dirofs); - header.dirlen = LittleLong (header.dirlen); + header.dirofs = LittleLong(header.dirofs); + header.dirlen = LittleLong(header.dirlen); numpackfiles = header.dirlen / sizeof(dpackfile_t); - if (header.dirlen < 0 || header.dirofs < 0) + if(header.dirlen < 0 || header.dirofs < 0) { - Sys_Error ("Invalid packfile %s (dirlen: %" PRIi32 ", dirofs: %" PRIi32 ")", - packfile, header.dirlen, header.dirofs); + Sys_Error("Invalid packfile %s (dirlen: %" PRIi32 ", dirofs: %" PRIi32 ")", + packfile, header.dirlen, header.dirofs); } - if (!numpackfiles) + if(!numpackfiles) { - Sys_Printf ("WARNING: %s has no files, ignored\n", packfile); - Sys_FileClose (packhandle); + Sys_Printf("WARNING: %s has no files, ignored\n", packfile); + Sys_FileClose(packhandle); return NULL; } - if (numpackfiles > MAX_FILES_IN_PACK) - Sys_Error ("%s has %" PRIi32 " files", packfile, numpackfiles); + if(numpackfiles > MAX_FILES_IN_PACK) + Sys_Error("%s has %" PRIi32 " files", packfile, numpackfiles); - if (numpackfiles != PAK0_COUNT) - com_modified = true; // not the original file + if(numpackfiles != PAK0_COUNT) + com_modified = true; // not the original file newfiles = (packfile_t *) Z_Malloc(numpackfiles * sizeof(packfile_t)); - Sys_FileSeek (packhandle, header.dirofs); - Sys_FileRead (packhandle, (void *)info, header.dirlen); + Sys_FileSeek(packhandle, header.dirofs); + Sys_FileRead(packhandle, (void *)info, header.dirlen); // crc the directory to check for modifications - CRC_Init (&crc); - for (i = 0; i < header.dirlen; i++) - CRC_ProcessByte (&crc, ((byte *)info)[i]); - if (crc != PAK0_CRC_V106 && crc != PAK0_CRC_V101 && crc != PAK0_CRC_V100) + CRC_Init(&crc); + for(i = 0; i < header.dirlen; i++) + CRC_ProcessByte(&crc, ((byte *)info)[i]); + if(crc != PAK0_CRC_V106 && crc != PAK0_CRC_V101 && crc != PAK0_CRC_V100) com_modified = true; // parse the directory - for (i = 0; i < numpackfiles; i++) + for(i = 0; i < numpackfiles; i++) { - q_strlcpy (newfiles[i].name, info[i].name, sizeof(newfiles[i].name)); + q_strlcpy(newfiles[i].name, info[i].name, sizeof(newfiles[i].name)); newfiles[i].filepos = LittleLong(info[i].filepos); newfiles[i].filelen = LittleLong(info[i].filelen); } - pack = (pack_t *) Z_Malloc (sizeof (pack_t)); - q_strlcpy (pack->filename, packfile, sizeof(pack->filename)); + pack = (pack_t *) Z_Malloc(sizeof(pack_t)); + q_strlcpy(pack->filename, packfile, sizeof(pack->filename)); pack->handle = packhandle; pack->numfiles = numpackfiles; pack->files = newfiles; @@ -2019,7 +2028,7 @@ static pack_t *COM_LoadPackFile (const char *packfile) COM_AddGameDirectory -- johnfitz -- modified based on topaz's tutorial ================= */ -static void COM_AddGameDirectory (const char *base, const char *dir) +static void COM_AddGameDirectory(const char *base, const char *dir) { int32_t i; uint32_t path_id; @@ -2028,53 +2037,56 @@ static void COM_AddGameDirectory (const char *base, const char *dir) char pakfile[MAX_OSPATH]; bool been_here = false; - q_strlcpy (com_gamedir, va("%s/%s", base, dir), sizeof(com_gamedir)); + q_strlcpy(com_gamedir, va("%s/%s", base, dir), sizeof(com_gamedir)); // assign a path_id to this game directory - if (com_searchpaths) + if(com_searchpaths) path_id = com_searchpaths->path_id << 1; - else path_id = 1U; + else path_id = 1U; _add_path: // add the directory to the search path search = (searchpath_t *) Z_Malloc(sizeof(searchpath_t)); search->path_id = path_id; - q_strlcpy (search->filename, com_gamedir, sizeof(search->filename)); + q_strlcpy(search->filename, com_gamedir, sizeof(search->filename)); search->next = com_searchpaths; com_searchpaths = search; // add any pak files in the format pak0.pak pak1.pak, ... - for (i = 0; ; i++) + for(i = 0; ; i++) { - q_snprintf (pakfile, sizeof(pakfile), "%s/pak%" PRIi32 ".pak", com_gamedir, i); - pak = COM_LoadPackFile (pakfile); - if (i != 0 || path_id != 1 || fitzmode) + q_snprintf(pakfile, sizeof(pakfile), "%s/pak%" PRIi32 ".pak", com_gamedir, i); + pak = COM_LoadPackFile(pakfile); + if(i != 0 || path_id != 1 || fitzmode) qspak = NULL; - else { + else + { bool old = com_modified; - if (been_here) base = host_parms->userdir; - q_snprintf (pakfile, sizeof(pakfile), "%s/quakespasm.pak", base); - qspak = COM_LoadPackFile (pakfile); + if(been_here) base = host_parms->userdir; + q_snprintf(pakfile, sizeof(pakfile), "%s/quakespasm.pak", base); + qspak = COM_LoadPackFile(pakfile); com_modified = old; } - if (pak) { + if(pak) + { search = (searchpath_t *) Z_Malloc(sizeof(searchpath_t)); search->path_id = path_id; search->pack = pak; search->next = com_searchpaths; com_searchpaths = search; } - if (qspak) { + if(qspak) + { search = (searchpath_t *) Z_Malloc(sizeof(searchpath_t)); search->path_id = path_id; search->pack = qspak; search->next = com_searchpaths; com_searchpaths = search; } - if (!pak) break; + if(!pak) break; } - if (!been_here && host_parms->userdir != host_parms->basedir) + if(!been_here && host_parms->userdir != host_parms->basedir) { been_here = true; q_strlcpy(com_gamedir, va("%s/%s", host_parms->userdir, dir), sizeof(com_gamedir)); @@ -2086,54 +2098,60 @@ _add_path: //============================================================================== //johnfitz -- dynamic gamedir stuff -- modified by QuakeSpasm team. //============================================================================== -void ExtraMaps_NewGame (void); -static void COM_Game_f (void) +void ExtraMaps_NewGame(void); +static void COM_Game_f(void) { - if (Cmd_Argc() > 1) + if(Cmd_Argc() > 1) { const char *p = Cmd_Argv(1); const char *p2 = Cmd_Argv(2); searchpath_t *search; - if (!registered.value) //disable shareware quake + if(!registered.value) //disable shareware quake { Con_Printf("You must have the registered version to use modified games\n"); return; } - if (!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) + if(!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) { - Con_Printf ("gamedir should be a single directory name, not a path\n"); + Con_Printf("gamedir should be a single directory name, not a path\n"); return; } - if (*p2) + if(*p2) { - if (strcmp(p2,"-hipnotic") && strcmp(p2,"-rogue") && strcmp(p2,"-quoth")) { - Con_Printf ("invalid mission pack argument to \"game\"\n"); + if(strcmp(p2, "-hipnotic") && strcmp(p2, "-rogue") && strcmp(p2, "-quoth")) + { + Con_Printf("invalid mission pack argument to \"game\"\n"); return; } - if (!q_strcasecmp(p, GAMENAME)) { - Con_Printf ("no mission pack arguments to %s game\n", GAMENAME); + if(!q_strcasecmp(p, GAMENAME)) + { + Con_Printf("no mission pack arguments to %s game\n", GAMENAME); return; } } - if (!q_strcasecmp(p, COM_SkipPath(com_gamedir))) //no change + if(!q_strcasecmp(p, COM_SkipPath(com_gamedir))) //no change { - if (com_searchpaths->path_id > 1) { //current game not id1 - if (*p2 && com_searchpaths->path_id == 2) { + if(com_searchpaths->path_id > 1) //current game not id1 + { + if(*p2 && com_searchpaths->path_id == 2) + { // rely on QuakeSpasm extension treating '-game missionpack' // as '-missionpack', otherwise would be a mess - if (!q_strcasecmp(p, &p2[1])) + if(!q_strcasecmp(p, &p2[1])) goto _same; Con_Printf("reloading game \"%s\" with \"%s\" support\n", p, &p2[1]); } - else if (!*p2 && com_searchpaths->path_id > 2) + else if(!*p2 && com_searchpaths->path_id > 2) Con_Printf("reloading game \"%s\" without mission pack support\n", p); else goto _same; } - else { _same: + else + { +_same: Con_Printf("\"game\" is already \"%s\"\n", COM_SkipPath(com_gamedir)); return; } @@ -2142,49 +2160,53 @@ static void COM_Game_f (void) com_modified = true; //Kill the server - CL_Disconnect (); + CL_Disconnect(); Host_ShutdownServer(true); //Write config file - Host_WriteConfiguration (); + Host_WriteConfiguration(); //Kill the extra game if it is loaded - while (com_searchpaths != com_base_searchpaths) + while(com_searchpaths != com_base_searchpaths) { - if (com_searchpaths->pack) + if(com_searchpaths->pack) { - Sys_FileClose (com_searchpaths->pack->handle); - Z_Free (com_searchpaths->pack->files); - Z_Free (com_searchpaths->pack); + Sys_FileClose(com_searchpaths->pack->handle); + Z_Free(com_searchpaths->pack->files); + Z_Free(com_searchpaths->pack); } search = com_searchpaths->next; - Z_Free (com_searchpaths); + Z_Free(com_searchpaths); com_searchpaths = search; } hipnotic = false; rogue = false; standard_quake = true; - if (q_strcasecmp(p, GAMENAME)) //game is not id1 + if(q_strcasecmp(p, GAMENAME)) //game is not id1 { - if (*p2) { - COM_AddGameDirectory (com_basedir, &p2[1]); + if(*p2) + { + COM_AddGameDirectory(com_basedir, &p2[1]); standard_quake = false; - if (!strcmp(p2,"-hipnotic") || !strcmp(p2,"-quoth")) + if(!strcmp(p2, "-hipnotic") || !strcmp(p2, "-quoth")) hipnotic = true; - else if (!strcmp(p2,"-rogue")) + else if(!strcmp(p2, "-rogue")) rogue = true; - if (q_strcasecmp(p, &p2[1])) //don't load twice - COM_AddGameDirectory (com_basedir, p); + if(q_strcasecmp(p, &p2[1])) //don't load twice + COM_AddGameDirectory(com_basedir, p); } - else { - COM_AddGameDirectory (com_basedir, p); + else + { + COM_AddGameDirectory(com_basedir, p); // QuakeSpasm extension: treat '-game missionpack' as '-missionpack' - if (!q_strcasecmp(p,"hipnotic") || !q_strcasecmp(p,"quoth")) { + if(!q_strcasecmp(p, "hipnotic") || !q_strcasecmp(p, "quoth")) + { hipnotic = true; standard_quake = false; } - else if (!q_strcasecmp(p,"rogue")) { + else if(!q_strcasecmp(p, "rogue")) + { rogue = true; standard_quake = false; } @@ -2192,29 +2214,29 @@ static void COM_Game_f (void) } else // just update com_gamedir { - q_snprintf (com_gamedir, sizeof(com_gamedir), "%s/%s", - (host_parms->userdir != host_parms->basedir)? - host_parms->userdir : com_basedir, - GAMENAME); + q_snprintf(com_gamedir, sizeof(com_gamedir), "%s/%s", + (host_parms->userdir != host_parms->basedir) ? + host_parms->userdir : com_basedir, + GAMENAME); } //clear out and reload appropriate data - Cache_Flush (); + Cache_Flush(); Mod_ResetAll(); - if (!isDedicated) + if(!isDedicated) { - TexMgr_NewGame (); - Draw_NewGame (); - R_NewGame (); + TexMgr_NewGame(); + Draw_NewGame(); + R_NewGame(); } - ExtraMaps_NewGame (); - DemoList_Rebuild (); + ExtraMaps_NewGame(); + DemoList_Rebuild(); Con_Printf("\"game\" changed to \"%s\"\n", COM_SkipPath(com_gamedir)); - VID_Lock (); - Cbuf_AddText ("exec quake.rc\n"); - Cbuf_AddText ("vid_unlock\n"); + VID_Lock(); + Cbuf_AddText("exec quake.rc\n"); + Cbuf_AddText("vid_unlock\n"); } else //Diplay the current gamedir Con_Printf("\"game\" is \"%s\"\n", COM_SkipPath(com_gamedir)); @@ -2225,28 +2247,28 @@ static void COM_Game_f (void) COM_InitFilesystem ================= */ -void COM_InitFilesystem (void) //johnfitz -- modified based on topaz's tutorial +void COM_InitFilesystem(void) //johnfitz -- modified based on topaz's tutorial { int32_t i, j; - Cvar_RegisterVariable (®istered); - Cvar_RegisterVariable (&cmdline); - Cmd_AddCommand ("path", COM_Path_f); - Cmd_AddCommand ("game", COM_Game_f); //johnfitz + Cvar_RegisterVariable(®istered); + Cvar_RegisterVariable(&cmdline); + Cmd_AddCommand("path", COM_Path_f); + Cmd_AddCommand("game", COM_Game_f); //johnfitz - i = COM_CheckParm ("-basedir"); - if (i && i < com_argc-1) - q_strlcpy (com_basedir, com_argv[i + 1], sizeof(com_basedir)); + i = COM_CheckParm("-basedir"); + if(i && i < com_argc - 1) + q_strlcpy(com_basedir, com_argv[i + 1], sizeof(com_basedir)); else - q_strlcpy (com_basedir, host_parms->basedir, sizeof(com_basedir)); + q_strlcpy(com_basedir, host_parms->basedir, sizeof(com_basedir)); - j = strlen (com_basedir); - if (j < 1) Sys_Error("Bad argument to -basedir"); - if ((com_basedir[j-1] == '\\') || (com_basedir[j-1] == '/')) - com_basedir[j-1] = 0; + j = strlen(com_basedir); + if(j < 1) Sys_Error("Bad argument to -basedir"); + if((com_basedir[j - 1] == '\\') || (com_basedir[j - 1] == '/')) + com_basedir[j - 1] = 0; // start up with GAMENAME by default (id1) - COM_AddGameDirectory (com_basedir, GAMENAME); + COM_AddGameDirectory(com_basedir, GAMENAME); /* this is the end of our base searchpath: * any set gamedirs, such as those from -game command line @@ -2255,40 +2277,43 @@ void COM_InitFilesystem (void) //johnfitz -- modified based on topaz's tutorial com_base_searchpaths = com_searchpaths; // add mission pack requests (only one should be specified) - if (COM_CheckParm ("-rogue")) - COM_AddGameDirectory (com_basedir, "rogue"); - if (COM_CheckParm ("-hipnotic")) - COM_AddGameDirectory (com_basedir, "hipnotic"); - if (COM_CheckParm ("-quoth")) - COM_AddGameDirectory (com_basedir, "quoth"); + if(COM_CheckParm("-rogue")) + COM_AddGameDirectory(com_basedir, "rogue"); + if(COM_CheckParm("-hipnotic")) + COM_AddGameDirectory(com_basedir, "hipnotic"); + if(COM_CheckParm("-quoth")) + COM_AddGameDirectory(com_basedir, "quoth"); - i = COM_CheckParm ("-game"); - if (i && i < com_argc-1) + i = COM_CheckParm("-game"); + if(i && i < com_argc - 1) { const char *p = com_argv[i + 1]; - if (!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) - Sys_Error ("gamedir should be a single directory name, not a path\n"); + if(!*p || !strcmp(p, ".") || strstr(p, "..") || strstr(p, "/") || strstr(p, "\\") || strstr(p, ":")) + Sys_Error("gamedir should be a single directory name, not a path\n"); com_modified = true; // don't load mission packs twice - if (COM_CheckParm ("-rogue") && !q_strcasecmp(p, "rogue")) p = NULL; - if (COM_CheckParm ("-hipnotic") && !q_strcasecmp(p, "hipnotic")) p = NULL; - if (COM_CheckParm ("-quoth") && !q_strcasecmp(p, "quoth")) p = NULL; - if (p != NULL) { - COM_AddGameDirectory (com_basedir, p); + if(COM_CheckParm("-rogue") && !q_strcasecmp(p, "rogue")) p = NULL; + if(COM_CheckParm("-hipnotic") && !q_strcasecmp(p, "hipnotic")) p = NULL; + if(COM_CheckParm("-quoth") && !q_strcasecmp(p, "quoth")) p = NULL; + if(p != NULL) + { + COM_AddGameDirectory(com_basedir, p); // QuakeSpasm extension: treat '-game missionpack' as '-missionpack' - if (!q_strcasecmp(p,"rogue")) { + if(!q_strcasecmp(p, "rogue")) + { rogue = true; standard_quake = false; } - if (!q_strcasecmp(p,"hipnotic") || !q_strcasecmp(p,"quoth")) { + if(!q_strcasecmp(p, "hipnotic") || !q_strcasecmp(p, "quoth")) + { hipnotic = true; standard_quake = false; } } } - COM_CheckRegistered (); + COM_CheckRegistered(); } @@ -2304,21 +2329,24 @@ size_t FS_fread(void *ptr, size_t size, size_t nmemb, fshandle_t *fh) long bytes_read; size_t nmemb_read; - if (!fh) { + if(!fh) + { errno = EBADF; return 0; } - if (!ptr) { + if(!ptr) + { errno = EFAULT; return 0; } - if (!size || !nmemb) { /* no error, just zero bytes wanted */ + if(!size || !nmemb) /* no error, just zero bytes wanted */ + { errno = 0; return 0; } byte_size = nmemb * size; - if (byte_size > fh->length - fh->pos) /* just read to end */ + if(byte_size > fh->length - fh->pos) /* just read to end */ byte_size = fh->length - fh->pos; bytes_read = fread(ptr, 1, byte_size, fh->file); fh->pos += bytes_read; @@ -2328,7 +2356,7 @@ size_t FS_fread(void *ptr, size_t size, size_t nmemb, fshandle_t *fh) nmemb_read = bytes_read / size; /* even if the last member is only read partially * it is counted as a whole in the return value. */ - if (bytes_read % size) + if(bytes_read % size) nmemb_read++; return nmemb_read; @@ -2336,18 +2364,19 @@ size_t FS_fread(void *ptr, size_t size, size_t nmemb, fshandle_t *fh) int32_t FS_fseek(fshandle_t *fh, long offset, int32_t whence) { -/* I don't care about 64 bit off_t or fseeko() here. - * the quake/hexen2 file system is 32 bits, anyway. */ + /* I don't care about 64 bit off_t or fseeko() here. + * the quake/hexen2 file system is 32 bits, anyway. */ int32_t ret; - if (!fh) { + if(!fh) + { errno = EBADF; return -1; } /* the relative file position shouldn't be smaller * than zero or bigger than the filesize. */ - switch (whence) + switch(whence) { case SEEK_SET: break; @@ -2362,16 +2391,17 @@ int32_t FS_fseek(fshandle_t *fh, long offset, int32_t whence) return -1; } - if (offset < 0) { + if(offset < 0) + { errno = EINVAL; return -1; } - if (offset > fh->length) /* just seek to end */ + if(offset > fh->length) /* just seek to end */ offset = fh->length; ret = fseek(fh->file, fh->start + offset, SEEK_SET); - if (ret < 0) + if(ret < 0) return ret; fh->pos = offset; @@ -2380,7 +2410,8 @@ int32_t FS_fseek(fshandle_t *fh, long offset, int32_t whence) int32_t FS_fclose(fshandle_t *fh) { - if (!fh) { + if(!fh) + { errno = EBADF; return -1; } @@ -2389,7 +2420,8 @@ int32_t FS_fclose(fshandle_t *fh) long FS_ftell(fshandle_t *fh) { - if (!fh) { + if(!fh) + { errno = EBADF; return -1; } @@ -2398,7 +2430,7 @@ long FS_ftell(fshandle_t *fh) void FS_rewind(fshandle_t *fh) { - if (!fh) return; + if(!fh) return; clearerr(fh->file); fseek(fh->file, fh->start, SEEK_SET); fh->pos = 0; @@ -2406,18 +2438,20 @@ void FS_rewind(fshandle_t *fh) int32_t FS_feof(fshandle_t *fh) { - if (!fh) { + if(!fh) + { errno = EBADF; return -1; } - if (fh->pos >= fh->length) + if(fh->pos >= fh->length) return -1; return 0; } int32_t FS_ferror(fshandle_t *fh) { - if (!fh) { + if(!fh) + { errno = EBADF; return -1; } @@ -2426,11 +2460,12 @@ int32_t FS_ferror(fshandle_t *fh) int32_t FS_fgetc(fshandle_t *fh) { - if (!fh) { + if(!fh) + { errno = EBADF; return EOF; } - if (fh->pos >= fh->length) + if(fh->pos >= fh->length) return EOF; fh->pos += 1; return fgetc(fh->file); @@ -2440,10 +2475,10 @@ char *FS_fgets(char *s, int32_t size, fshandle_t *fh) { char *ret; - if (FS_feof(fh)) + if(FS_feof(fh)) return NULL; - if (size > (fh->length - fh->pos) + 1) + if(size > (fh->length - fh->pos) + 1) size = (fh->length - fh->pos) + 1; ret = fgets(s, size, fh->file); @@ -2452,9 +2487,10 @@ char *FS_fgets(char *s, int32_t size, fshandle_t *fh) return ret; } -long FS_filelength (fshandle_t *fh) +long FS_filelength(fshandle_t *fh) { - if (!fh) { + if(!fh) + { errno = EBADF; return -1; } diff --git a/source/common.h b/source/common.h index 8379192..881bfc3 100644 --- a/source/common.h +++ b/source/common.h @@ -28,166 +28,166 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #if defined(_WIN32) #ifdef _MSC_VER # pragma warning(disable:4244) - /* 'argument' : conversion from 'type1' to 'type2', - possible loss of data */ +/* 'argument' : conversion from 'type1' to 'type2', + possible loss of data */ # pragma warning(disable:4305) - /* 'identifier' : truncation from 'type1' to 'type2' */ - /* in our case, truncation from 'double' to 'float' */ +/* 'identifier' : truncation from 'type1' to 'type2' */ +/* in our case, truncation from 'double' to 'float' */ # pragma warning(disable:4267) - /* 'var' : conversion from 'size_t' to 'type', - possible loss of data (/Wp64 warning) */ -#endif /* _MSC_VER */ -#endif /* _WIN32 */ +/* 'var' : conversion from 'size_t' to 'type', + possible loss of data (/Wp64 warning) */ +#endif /* _MSC_VER */ +#endif /* _WIN32 */ -#undef min -#undef max -#define q_min(a, b) (((a) < (b)) ? (a) : (b)) -#define q_max(a, b) (((a) > (b)) ? (a) : (b)) -#define CLAMP(_minval, x, _maxval) \ - ((x) < (_minval) ? (_minval) : \ - (x) > (_maxval) ? (_maxval) : (x)) +#undef min +#undef max +#define q_min(a, b) (((a) < (b)) ? (a) : (b)) +#define q_max(a, b) (((a) > (b)) ? (a) : (b)) +#define CLAMP(_minval, x, _maxval) \ + ((x) < (_minval) ? (_minval) : \ + (x) > (_maxval) ? (_maxval) : (x)) typedef struct sizebuf_s { - bool allowoverflow; // if false, do a Sys_Error - bool overflowed; // set to true if the buffer size failed - byte *data; - int32_t maxsize; - int32_t cursize; + bool allowoverflow; // if false, do a Sys_Error + bool overflowed; // set to true if the buffer size failed + byte *data; + int32_t maxsize; + int32_t cursize; } sizebuf_t; -void SZ_Alloc (sizebuf_t *buf, int32_t startsize); -void SZ_Free (sizebuf_t *buf); -void SZ_Clear (sizebuf_t *buf); -void *SZ_GetSpace (sizebuf_t *buf, int32_t length); -void SZ_Write (sizebuf_t *buf, const void *data, int32_t length); -void SZ_Print (sizebuf_t *buf, const char *data); // strcats onto the sizebuf +void SZ_Alloc(sizebuf_t *buf, int32_t startsize); +void SZ_Free(sizebuf_t *buf); +void SZ_Clear(sizebuf_t *buf); +void *SZ_GetSpace(sizebuf_t *buf, int32_t length); +void SZ_Write(sizebuf_t *buf, const void *data, int32_t length); +void SZ_Print(sizebuf_t *buf, const char *data); // strcats onto the sizebuf //============================================================================ typedef struct link_s { - struct link_s *prev, *next; + struct link_s *prev, *next; } link_t; -void ClearLink (link_t *l); -void RemoveLink (link_t *l); -void InsertLinkBefore (link_t *l, link_t *before); -void InsertLinkAfter (link_t *l, link_t *after); +void ClearLink(link_t *l); +void RemoveLink(link_t *l); +void InsertLinkBefore(link_t *l, link_t *before); +void InsertLinkAfter(link_t *l, link_t *after); // (type *)STRUCT_FROM_LINK(link_t *link, type, member) // ent = STRUCT_FROM_LINK(link,entity_t,order) // FIXME: remove this mess! -#define STRUCT_FROM_LINK(l,t,m) ((t *)((byte *)l - (intptr_t)&(((t *)0)->m))) +#define STRUCT_FROM_LINK(l,t,m) ((t *)((byte *)l - (intptr_t)&(((t *)0)->m))) //============================================================================ -extern bool host_bigendian; +extern bool host_bigendian; -extern int16_t (*BigShort) (int16_t l); -extern int16_t (*LittleShort) (int16_t l); -extern int32_t (*BigLong) (int32_t l); -extern int32_t (*LittleLong) (int32_t l); -extern float (*BigFloat) (float l); -extern float (*LittleFloat) (float l); +extern int16_t (*BigShort)(int16_t l); +extern int16_t (*LittleShort)(int16_t l); +extern int32_t (*BigLong)(int32_t l); +extern int32_t (*LittleLong)(int32_t l); +extern float (*BigFloat)(float l); +extern float (*LittleFloat)(float l); //============================================================================ -void MSG_WriteChar (sizebuf_t *sb, int32_t c); -void MSG_WriteByte (sizebuf_t *sb, int32_t c); -void MSG_WriteShort (sizebuf_t *sb, int32_t c); -void MSG_WriteLong (sizebuf_t *sb, int32_t c); -void MSG_WriteFloat (sizebuf_t *sb, float f); -void MSG_WriteString (sizebuf_t *sb, const char *s); -void MSG_WriteCoord (sizebuf_t *sb, float f, uint32_t flags); -void MSG_WriteAngle (sizebuf_t *sb, float f, uint32_t flags); -void MSG_WriteAngle16 (sizebuf_t *sb, float f, uint32_t flags); //johnfitz +void MSG_WriteChar(sizebuf_t *sb, int32_t c); +void MSG_WriteByte(sizebuf_t *sb, int32_t c); +void MSG_WriteShort(sizebuf_t *sb, int32_t c); +void MSG_WriteLong(sizebuf_t *sb, int32_t c); +void MSG_WriteFloat(sizebuf_t *sb, float f); +void MSG_WriteString(sizebuf_t *sb, const char *s); +void MSG_WriteCoord(sizebuf_t *sb, float f, uint32_t flags); +void MSG_WriteAngle(sizebuf_t *sb, float f, uint32_t flags); +void MSG_WriteAngle16(sizebuf_t *sb, float f, uint32_t flags); //johnfitz -extern int32_t msg_readcount; -extern bool msg_badread; // set if a read goes beyond end of message +extern int32_t msg_readcount; +extern bool msg_badread; // set if a read goes beyond end of message -void MSG_BeginReading (void); -int32_t MSG_ReadChar (void); -int32_t MSG_ReadByte (void); -int32_t MSG_ReadShort (void); -int32_t MSG_ReadLong (void); -float MSG_ReadFloat (void); -const char *MSG_ReadString (void); +void MSG_BeginReading(void); +int32_t MSG_ReadChar(void); +int32_t MSG_ReadByte(void); +int32_t MSG_ReadShort(void); +int32_t MSG_ReadLong(void); +float MSG_ReadFloat(void); +const char *MSG_ReadString(void); -float MSG_ReadCoord (uint32_t flags); -float MSG_ReadAngle (uint32_t flags); -float MSG_ReadAngle16 (uint32_t flags); //johnfitz +float MSG_ReadCoord(uint32_t flags); +float MSG_ReadAngle(uint32_t flags); +float MSG_ReadAngle16(uint32_t flags); //johnfitz //============================================================================ -void Q_memset (void *dest, int32_t fill, size_t count); -void Q_memcpy (void *dest, const void *src, size_t count); -int32_t Q_memcmp (const void *m1, const void *m2, size_t count); -void Q_strcpy (char *dest, const char *src); -void Q_strncpy (char *dest, const char *src, int32_t count); -int32_t Q_strlen (const char *str); -char *Q_strrchr (const char *s, char c); -void Q_strcat (char *dest, const char *src); -int32_t Q_strcmp (const char *s1, const char *s2); -int32_t Q_strncmp (const char *s1, const char *s2, int32_t count); -int32_t Q_atoi (const char *str); -float Q_atof (const char *str); +void Q_memset(void *dest, int32_t fill, size_t count); +void Q_memcpy(void *dest, const void *src, size_t count); +int32_t Q_memcmp(const void *m1, const void *m2, size_t count); +void Q_strcpy(char *dest, const char *src); +void Q_strncpy(char *dest, const char *src, int32_t count); +int32_t Q_strlen(const char *str); +char *Q_strrchr(const char *s, char c); +void Q_strcat(char *dest, const char *src); +int32_t Q_strcmp(const char *s1, const char *s2); +int32_t Q_strncmp(const char *s1, const char *s2, int32_t count); +int32_t Q_atoi(const char *str); +float Q_atof(const char *str); #include "strl_fn.h" /* locale-insensitive strcasecmp replacement functions: */ -extern int32_t q_strcasecmp (const char * s1, const char * s2); -extern int32_t q_strncasecmp (const char *s1, const char *s2, size_t n); +extern int32_t q_strcasecmp(const char * s1, const char * s2); +extern int32_t q_strncasecmp(const char *s1, const char *s2, size_t n); /* locale-insensitive case-insensitive alternative to strstr */ extern char *q_strcasestr(const char *haystack, const char *needle); /* locale-insensitive strlwr/upr replacement functions: */ -extern char *q_strlwr (char *str); -extern char *q_strupr (char *str); +extern char *q_strlwr(char *str); +extern char *q_strupr(char *str); /* snprintf, vsnprintf : always use our versions. */ -extern int32_t q_snprintf (char *str, size_t size, const char *format, ...) FUNC_PRINTF(3,4); -extern int32_t q_vsnprintf(char *str, size_t size, const char *format, va_list args) FUNC_PRINTF(3,0); +extern int32_t q_snprintf(char *str, size_t size, const char *format, ...) FUNC_PRINTF(3, 4); +extern int32_t q_vsnprintf(char *str, size_t size, const char *format, va_list args) FUNC_PRINTF(3, 0); //============================================================================ -extern char com_token[1024]; -extern bool com_eof; +extern char com_token[1024]; +extern bool com_eof; -const char *COM_Parse (const char *data); +const char *COM_Parse(const char *data); -extern int32_t com_argc; -extern char **com_argv; +extern int32_t com_argc; +extern char **com_argv; -extern int32_t safemode; +extern int32_t safemode; /* safe mode: in true, the engine will behave as if one of these arguments were actually on the command line: -nosound, -nocdaudio, -nomidi, -stdvid, -dibonly, -nomouse, -nojoy, -nolan */ -int32_t COM_CheckParm (const char *parm); +int32_t COM_CheckParm(const char *parm); -void COM_Init (void); -void COM_InitArgv (int32_t argc, char **argv); -void COM_InitFilesystem (void); +void COM_Init(void); +void COM_InitArgv(int32_t argc, char **argv); +void COM_InitFilesystem(void); -const char *COM_SkipPath (const char *pathname); -void COM_StripExtension (const char *in, char *out, size_t outsize); -void COM_FileBase (const char *in, char *out, size_t outsize); -void COM_AddExtension (char *path, const char *extension, size_t len); +const char *COM_SkipPath(const char *pathname); +void COM_StripExtension(const char *in, char *out, size_t outsize); +void COM_FileBase(const char *in, char *out, size_t outsize); +void COM_AddExtension(char *path, const char *extension, size_t len); #if 0 /* COM_DefaultExtension can be dangerous */ -void COM_DefaultExtension (char *path, const char *extension, size_t len); +void COM_DefaultExtension(char *path, const char *extension, size_t len); #endif -const char *COM_FileGetExtension (const char *in); /* doesn't return NULL */ -void COM_ExtractExtension (const char *in, char *out, size_t outsize); -void COM_CreatePath (char *path); +const char *COM_FileGetExtension(const char *in); /* doesn't return NULL */ +void COM_ExtractExtension(const char *in, char *out, size_t outsize); +void COM_CreatePath(char *path); -char *va (const char *format, ...) FUNC_PRINTF(1,2); +char *va(const char *format, ...) FUNC_PRINTF(1, 2); // does a varargs printf into a temp buffer @@ -196,26 +196,26 @@ char *va (const char *format, ...) FUNC_PRINTF(1,2); // QUAKEFS typedef struct { - char name[MAX_QPATH]; - int32_t filepos, filelen; + char name[MAX_QPATH]; + int32_t filepos, filelen; } packfile_t; typedef struct pack_s { - char filename[MAX_OSPATH]; - int32_t handle; - int32_t numfiles; - packfile_t *files; + char filename[MAX_OSPATH]; + int32_t handle; + int32_t numfiles; + packfile_t *files; } pack_t; typedef struct searchpath_s { - uint32_t path_id; // identifier assigned to the game directory - // Note that /game1 and - // /game1 have the same id. - char filename[MAX_OSPATH]; - pack_t *pack; // only one of filename / pack will be used - struct searchpath_s *next; + uint32_t path_id; // identifier assigned to the game directory + // Note that /game1 and + // /game1 have the same id. + char filename[MAX_OSPATH]; + pack_t *pack; // only one of filename / pack will be used + struct searchpath_s *next; } searchpath_t; extern searchpath_t *com_searchpaths; @@ -224,40 +224,40 @@ extern searchpath_t *com_base_searchpaths; extern int32_t com_filesize; struct cache_user_s; -extern char com_basedir[MAX_OSPATH]; -extern char com_gamedir[MAX_OSPATH]; -extern int32_t file_from_pak; // global indicating that file came from a pak +extern char com_basedir[MAX_OSPATH]; +extern char com_gamedir[MAX_OSPATH]; +extern int32_t file_from_pak; // global indicating that file came from a pak -void COM_WriteFile (const char *filename, const void *data, int32_t len); -int32_t COM_OpenFile (const char *filename, int32_t *handle, uint32_t *path_id); -int32_t COM_FOpenFile (const char *filename, FILE **file, uint32_t *path_id); -bool COM_FileExists (const char *filename, uint32_t *path_id); -void COM_CloseFile (int32_t h); +void COM_WriteFile(const char *filename, const void *data, int32_t len); +int32_t COM_OpenFile(const char *filename, int32_t *handle, uint32_t *path_id); +int32_t COM_FOpenFile(const char *filename, FILE **file, uint32_t *path_id); +bool COM_FileExists(const char *filename, uint32_t *path_id); +void COM_CloseFile(int32_t h); // these procedures open a file using COM_FindFile and loads it into a proper // buffer. the buffer is allocated with a total size of com_filesize + 1. the // procedures differ by their buffer allocation method. -byte *COM_LoadStackFile (const char *path, void *buffer, int32_t bufsize, - uint32_t *path_id); - // uses the specified stack stack buffer with the specified size - // of bufsize. if bufsize is too short, uses temp hunk. the bufsize - // must include the +1 -byte *COM_LoadTempFile (const char *path, uint32_t *path_id); - // allocates the buffer on the temp hunk. -byte *COM_LoadHunkFile (const char *path, uint32_t *path_id); - // allocates the buffer on the hunk. -byte *COM_LoadZoneFile (const char *path, uint32_t *path_id); - // allocates the buffer on the zone. -void COM_LoadCacheFile (const char *path, struct cache_user_s *cu, - uint32_t *path_id); - // uses cache mem for allocating the buffer. -byte *COM_LoadMallocFile (const char *path, uint32_t *path_id); - // allocates the buffer on the system mem (malloc). +byte *COM_LoadStackFile(const char *path, void *buffer, int32_t bufsize, + uint32_t *path_id); +// uses the specified stack stack buffer with the specified size +// of bufsize. if bufsize is too short, uses temp hunk. the bufsize +// must include the +1 +byte *COM_LoadTempFile(const char *path, uint32_t *path_id); +// allocates the buffer on the temp hunk. +byte *COM_LoadHunkFile(const char *path, uint32_t *path_id); +// allocates the buffer on the hunk. +byte *COM_LoadZoneFile(const char *path, uint32_t *path_id); +// allocates the buffer on the zone. +void COM_LoadCacheFile(const char *path, struct cache_user_s *cu, + uint32_t *path_id); +// uses cache mem for allocating the buffer. +byte *COM_LoadMallocFile(const char *path, uint32_t *path_id); +// allocates the buffer on the system mem (malloc). // Opens the given path directly, ignoring search paths. // Returns NULL on failure, or else a '\0'-terminated malloc'ed buffer. // Loads in "t" mode so CRLF to LF translation is performed on Windows. -byte *COM_LoadMallocFile_TextMode_OSPath (const char *path, long *len_out); +byte *COM_LoadMallocFile_TextMode_OSPath(const char *path, long *len_out); // Attempts to parse an int32_t, followed by a newline. // Returns advanced buffer position. @@ -281,10 +281,10 @@ const char *COM_ParseStringNewline(const char *buffer); typedef struct _fshandle_t { FILE *file; - bool pak; /* is the file read from a pak */ - long start; /* file or data start position */ - long length; /* file or data size */ - long pos; /* current position relative to start */ + bool pak; /* is the file read from a pak */ + long start; /* file or data start position */ + long length; /* file or data size */ + long pos; /* current position relative to start */ } fshandle_t; size_t FS_fread(void *ptr, size_t size, size_t nmemb, fshandle_t *fh); @@ -296,13 +296,13 @@ int32_t FS_ferror(fshandle_t *fh); int32_t FS_fclose(fshandle_t *fh); int32_t FS_fgetc(fshandle_t *fh); char *FS_fgets(char *s, int32_t size, fshandle_t *fh); -long FS_filelength (fshandle_t *fh); +long FS_filelength(fshandle_t *fh); -extern struct cvar_s registered; -extern bool standard_quake, rogue, hipnotic; -extern bool fitzmode; - /* if true, run in fitzquake mode disabling custom quakespasm hacks */ +extern struct cvar_s registered; +extern bool standard_quake, rogue, hipnotic; +extern bool fitzmode; +/* if true, run in fitzquake mode disabling custom quakespasm hacks */ -#endif /* _Q_COMMON_H */ +#endif /* _Q_COMMON_H */ diff --git a/source/console.c b/source/console.c index 0f26852..d6a2fb2 100644 --- a/source/console.c +++ b/source/console.c @@ -32,37 +32,37 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #endif #include "quakedef.h" -int32_t con_linewidth; +int32_t con_linewidth; -float con_cursorspeed = 4; +float con_cursorspeed = 4; -#define CON_TEXTSIZE (1024 * 1024) //ericw -- was 65536. johnfitz -- new default size -#define CON_MINSIZE 16384 //johnfitz -- old default, now the minimum size +#define CON_TEXTSIZE (1024 * 1024) //ericw -- was 65536. johnfitz -- new default size +#define CON_MINSIZE 16384 //johnfitz -- old default, now the minimum size -int32_t con_buffersize; //johnfitz -- user can now override default +int32_t con_buffersize; //johnfitz -- user can now override default -bool con_forcedup; // because no entities to refresh +bool con_forcedup; // because no entities to refresh -int32_t con_totallines; // total lines in console scrollback -int32_t con_backscroll; // lines up from bottom to display -int32_t con_current; // where next message will be printed -int32_t con_x; // offset in current line for next print -char *con_text = NULL; +int32_t con_totallines; // total lines in console scrollback +int32_t con_backscroll; // lines up from bottom to display +int32_t con_current; // where next message will be printed +int32_t con_x; // offset in current line for next print +char *con_text = NULL; -cvar_t con_notifytime = {"con_notifytime","3",CVAR_NONE}; //seconds -cvar_t con_logcenterprint = {"con_logcenterprint", "1", CVAR_NONE}; //johnfitz +cvar_t con_notifytime = {"con_notifytime", "3", CVAR_NONE}; //seconds +cvar_t con_logcenterprint = {"con_logcenterprint", "1", CVAR_NONE}; //johnfitz -char con_lastcenterstring[1024]; //johnfitz +char con_lastcenterstring[1024]; //johnfitz -#define NUM_CON_TIMES 4 -float con_times[NUM_CON_TIMES]; // realtime time the line was generated - // for transparent notify lines +#define NUM_CON_TIMES 4 +float con_times[NUM_CON_TIMES]; // realtime time the line was generated +// for transparent notify lines -int32_t con_vislines; +int32_t con_vislines; -bool con_debuglog = false; +bool con_debuglog = false; -bool con_initialized; +bool con_initialized; /* @@ -72,7 +72,7 @@ Con_Quakebar -- johnfitz -- returns a bar of the desired length, but never wider includes a newline, unless len >= con_linewidth. ================ */ -const char *Con_Quakebar (int32_t len) +const char *Con_Quakebar(int32_t len) { static char bar[42]; int32_t i; @@ -81,14 +81,14 @@ const char *Con_Quakebar (int32_t len) len = q_min(len, con_linewidth); bar[0] = '\35'; - for (i = 1; i < len - 1; i++) + for(i = 1; i < len - 1; i++) bar[i] = '\36'; - bar[len-1] = '\37'; + bar[len - 1] = '\37'; - if (len < con_linewidth) + if(len < con_linewidth) { bar[len] = '\n'; - bar[len+1] = 0; + bar[len + 1] = 0; } else bar[len] = 0; @@ -103,23 +103,23 @@ Con_ToggleConsole_f */ extern int32_t history_line; //johnfitz -void Con_ToggleConsole_f (void) +void Con_ToggleConsole_f(void) { - if (key_dest == key_console/* || (key_dest == key_game && con_forcedup)*/) + if(key_dest == key_console/* || (key_dest == key_game && con_forcedup)*/) { - key_lines[edit_line][1] = 0; // clear any typing + key_lines[edit_line][1] = 0; // clear any typing key_linepos = 1; con_backscroll = 0; //johnfitz -- toggleconsole should return you to the bottom of the scrollback history_line = edit_line; //johnfitz -- it should also return you to the bottom of the command history - if (cls.state == ca_connected) + if(cls.state == ca_connected) { IN_Activate(); key_dest = key_game; } else { - M_Menu_Main_f (); + M_Menu_Main_f(); } } else @@ -128,8 +128,8 @@ void Con_ToggleConsole_f (void) key_dest = key_console; } - SCR_EndLoadingPlaque (); - memset (con_times, 0, sizeof(con_times)); + SCR_EndLoadingPlaque(); + memset(con_times, 0, sizeof(con_times)); } /* @@ -137,10 +137,10 @@ void Con_ToggleConsole_f (void) Con_Clear_f ================ */ -static void Con_Clear_f (void) +static void Con_Clear_f(void) { - if (con_text) - Q_memset (con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE + if(con_text) + Q_memset(con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE con_backscroll = 0; //johnfitz -- if console is empty, being scrolled up is confusing } @@ -149,55 +149,55 @@ static void Con_Clear_f (void) Con_Dump_f -- johnfitz -- adapted from quake2 source ================ */ -static void Con_Dump_f (void) +static void Con_Dump_f(void) { - int32_t l, x; - const char *line; - FILE *f; - char buffer[1024]; - char name[MAX_OSPATH]; + int32_t l, x; + const char *line; + FILE *f; + char buffer[1024]; + char name[MAX_OSPATH]; - q_snprintf (name, sizeof(name), "%s/condump.txt", com_gamedir); - COM_CreatePath (name); - f = fopen (name, "w"); - if (!f) + q_snprintf(name, sizeof(name), "%s/condump.txt", com_gamedir); + COM_CreatePath(name); + f = fopen(name, "w"); + if(!f) { - Con_Printf ("ERROR: couldn't open file %s.\n", name); + Con_Printf("ERROR: couldn't open file %s.\n", name); return; } // skip initial empty lines - for (l = con_current - con_totallines + 1; l <= con_current; l++) + for(l = con_current - con_totallines + 1; l <= con_current; l++) { - line = con_text + (l % con_totallines)*con_linewidth; - for (x = 0; x < con_linewidth; x++) - if (line[x] != ' ') + line = con_text + (l % con_totallines) * con_linewidth; + for(x = 0; x < con_linewidth; x++) + if(line[x] != ' ') break; - if (x != con_linewidth) + if(x != con_linewidth) break; } // write the remaining lines buffer[con_linewidth] = 0; - for ( ; l <= con_current; l++) + for(; l <= con_current; l++) { - line = con_text + (l%con_totallines)*con_linewidth; - strncpy (buffer, line, con_linewidth); - for (x = con_linewidth - 1; x >= 0; x--) + line = con_text + (l % con_totallines) * con_linewidth; + strncpy(buffer, line, con_linewidth); + for(x = con_linewidth - 1; x >= 0; x--) { - if (buffer[x] == ' ') + if(buffer[x] == ' ') buffer[x] = 0; else break; } - for (x = 0; buffer[x]; x++) + for(x = 0; buffer[x]; x++) buffer[x] &= 0x7f; - fprintf (f, "%s\n", buffer); + fprintf(f, "%s\n", buffer); } - fclose (f); - Con_Printf ("Dumped console text to %s.\n", name); + fclose(f); + Con_Printf("Dumped console text to %s.\n", name); } /* @@ -205,11 +205,11 @@ static void Con_Dump_f (void) Con_ClearNotify ================ */ -void Con_ClearNotify (void) +void Con_ClearNotify(void) { - int32_t i; + int32_t i; - for (i = 0; i < NUM_CON_TIMES; i++) + for(i = 0; i < NUM_CON_TIMES; i++) con_times[i] = 0; } @@ -219,9 +219,9 @@ void Con_ClearNotify (void) Con_MessageMode_f ================ */ -static void Con_MessageMode_f (void) +static void Con_MessageMode_f(void) { - if (cls.state != ca_connected || cls.demoplayback) + if(cls.state != ca_connected || cls.demoplayback) return; chat_team = false; key_dest = key_message; @@ -232,9 +232,9 @@ static void Con_MessageMode_f (void) Con_MessageMode2_f ================ */ -static void Con_MessageMode2_f (void) +static void Con_MessageMode2_f(void) { - if (cls.state != ca_connected || cls.demoplayback) + if(cls.state != ca_connected || cls.demoplayback) return; chat_team = true; key_dest = key_message; @@ -248,15 +248,15 @@ Con_CheckResize If the line width has changed, reformat the buffer. ================ */ -void Con_CheckResize (void) +void Con_CheckResize(void) { - int32_t i, j, width, oldwidth, oldtotallines, numlines, numchars; - char *tbuf; //johnfitz -- tbuf no longer a static array + int32_t i, j, width, oldwidth, oldtotallines, numlines, numchars; + char *tbuf; //johnfitz -- tbuf no longer a static array int32_t mark; //johnfitz width = (vid.conwidth >> 3) - 2; //johnfitz -- use vid.conwidth instead of vid.width - if (width == con_linewidth) + if(width == con_linewidth) return; oldwidth = con_linewidth; @@ -265,32 +265,32 @@ void Con_CheckResize (void) con_totallines = con_buffersize / con_linewidth; //johnfitz -- con_buffersize replaces CON_TEXTSIZE numlines = oldtotallines; - if (con_totallines < numlines) + if(con_totallines < numlines) numlines = con_totallines; numchars = oldwidth; - if (con_linewidth < numchars) + if(con_linewidth < numchars) numchars = con_linewidth; - mark = Hunk_LowMark (); //johnfitz - tbuf = (char *) Hunk_Alloc (con_buffersize); //johnfitz + mark = Hunk_LowMark(); //johnfitz + tbuf = (char *) Hunk_Alloc(con_buffersize); //johnfitz - Q_memcpy (tbuf, con_text, con_buffersize);//johnfitz -- con_buffersize replaces CON_TEXTSIZE - Q_memset (con_text, ' ', con_buffersize);//johnfitz -- con_buffersize replaces CON_TEXTSIZE + Q_memcpy(tbuf, con_text, con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE + Q_memset(con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE - for (i = 0; i < numlines; i++) + for(i = 0; i < numlines; i++) { - for (j = 0; j < numchars; j++) + for(j = 0; j < numchars; j++) { con_text[(con_totallines - 1 - i) * con_linewidth + j] = - tbuf[((con_current - i + oldtotallines) % oldtotallines) * oldwidth + j]; + tbuf[((con_current - i + oldtotallines) % oldtotallines) * oldwidth + j]; } } - Hunk_FreeToLowMark (mark); //johnfitz + Hunk_FreeToLowMark(mark); //johnfitz - Con_ClearNotify (); + Con_ClearNotify(); con_backscroll = 0; con_current = con_totallines - 1; @@ -302,20 +302,20 @@ void Con_CheckResize (void) Con_Init ================ */ -void Con_Init (void) +void Con_Init(void) { int32_t i; //johnfitz -- user settable console buffer size i = COM_CheckParm("-consize"); - if (i && i < com_argc-1) - con_buffersize = q_max(CON_MINSIZE,Q_atoi(com_argv[i+1])*1024); + if(i && i < com_argc - 1) + con_buffersize = q_max(CON_MINSIZE, Q_atoi(com_argv[i + 1]) * 1024); else con_buffersize = CON_TEXTSIZE; //johnfitz - con_text = (char *) Hunk_AllocName (con_buffersize, "context");//johnfitz -- con_buffersize replaces CON_TEXTSIZE - Q_memset (con_text, ' ', con_buffersize);//johnfitz -- con_buffersize replaces CON_TEXTSIZE + con_text = (char *) Hunk_AllocName(con_buffersize, "context"); //johnfitz -- con_buffersize replaces CON_TEXTSIZE + Q_memset(con_text, ' ', con_buffersize); //johnfitz -- con_buffersize replaces CON_TEXTSIZE con_linewidth = -1; //johnfitz -- no need to run Con_CheckResize here @@ -325,16 +325,16 @@ void Con_Init (void) con_current = con_totallines - 1; //johnfitz - Con_Printf ("Console initialized.\n"); + Con_Printf("Console initialized.\n"); - Cvar_RegisterVariable (&con_notifytime); - Cvar_RegisterVariable (&con_logcenterprint); //johnfitz + Cvar_RegisterVariable(&con_notifytime); + Cvar_RegisterVariable(&con_logcenterprint); //johnfitz - Cmd_AddCommand ("toggleconsole", Con_ToggleConsole_f); - Cmd_AddCommand ("messagemode", Con_MessageMode_f); - Cmd_AddCommand ("messagemode2", Con_MessageMode2_f); - Cmd_AddCommand ("clear", Con_Clear_f); - Cmd_AddCommand ("condump", Con_Dump_f); //johnfitz + Cmd_AddCommand("toggleconsole", Con_ToggleConsole_f); + Cmd_AddCommand("messagemode", Con_MessageMode_f); + Cmd_AddCommand("messagemode2", Con_MessageMode2_f); + Cmd_AddCommand("clear", Con_Clear_f); + Cmd_AddCommand("condump", Con_Dump_f); //johnfitz con_initialized = true; } @@ -344,18 +344,18 @@ void Con_Init (void) Con_Linefeed =============== */ -static void Con_Linefeed (void) +static void Con_Linefeed(void) { //johnfitz -- improved scrolling - if (con_backscroll) + if(con_backscroll) con_backscroll++; - if (con_backscroll > con_totallines - (glheight>>3) - 1) - con_backscroll = con_totallines - (glheight>>3) - 1; + if(con_backscroll > con_totallines - (glheight >> 3) - 1) + con_backscroll = con_totallines - (glheight >> 3) - 1; //johnfitz con_x = 0; con_current++; - Q_memset (&con_text[(con_current%con_totallines)*con_linewidth], ' ', con_linewidth); + Q_memset(&con_text[(con_current % con_totallines)*con_linewidth], ' ', con_linewidth); } /* @@ -367,25 +367,25 @@ All console printing must go through this in order to be logged to disk If no console is visible, the notify window will pop up. ================ */ -static void Con_Print (const char *txt) +static void Con_Print(const char *txt) { - int32_t y; - int32_t c, l; - static int32_t cr; - int32_t mask; - bool boundary; + int32_t y; + int32_t c, l; + static int32_t cr; + int32_t mask; + bool boundary; //con_backscroll = 0; //johnfitz -- better console scrolling - if (txt[0] == 1) + if(txt[0] == 1) { - mask = 128; // go to colored text - S_LocalSound ("misc/talk.wav"); // play talk wav + mask = 128; // go to colored text + S_LocalSound("misc/talk.wav"); // play talk wav txt++; } - else if (txt[0] == 2) + else if(txt[0] == 2) { - mask = 128; // go to colored text + mask = 128; // go to colored text txt++; } else @@ -393,21 +393,21 @@ static void Con_Print (const char *txt) boundary = true; - while ( (c = *txt) ) + while((c = *txt)) { - if (c <= ' ') + if(c <= ' ') { boundary = true; } - else if (boundary) + else if(boundary) { // count word length - for (l = 0; l < con_linewidth; l++) - if (txt[l] <= ' ') + for(l = 0; l < con_linewidth; l++) + if(txt[l] <= ' ') break; // word wrap - if (l != con_linewidth && (con_x + l > con_linewidth)) + if(l != con_linewidth && (con_x + l > con_linewidth)) con_x = 0; boundary = false; @@ -415,21 +415,21 @@ static void Con_Print (const char *txt) txt++; - if (cr) + if(cr) { con_current--; cr = false; } - if (!con_x) + if(!con_x) { - Con_Linefeed (); - // mark time for transparent overlay - if (con_current >= 0) + Con_Linefeed(); + // mark time for transparent overlay + if(con_current >= 0) con_times[con_current % NUM_CON_TIMES] = realtime; } - switch (c) + switch(c) { case '\n': con_x = 0; @@ -440,11 +440,11 @@ static void Con_Print (const char *txt) cr = 1; break; - default: // display character and advance + default: // display character and advance y = con_current % con_totallines; - con_text[y*con_linewidth+con_x] = c | mask; + con_text[y * con_linewidth + con_x] = c | mask; con_x++; - if (con_x >= con_linewidth) + if(con_x >= con_linewidth) con_x = 0; break; } @@ -454,8 +454,8 @@ static void Con_Print (const char *txt) // borrowed from uhexen2 by S.A. for new procs, LOG_Init, LOG_Close -static char logfilename[MAX_OSPATH]; // current logfile name -static int32_t log_fd = -1; // log file descriptor +static char logfilename[MAX_OSPATH]; // current logfile name +static int32_t log_fd = -1; // log file descriptor /* ================ @@ -464,7 +464,7 @@ Con_DebugLog */ void Con_DebugLog(const char *msg) { - if (log_fd == -1) + if(log_fd == -1) return; write(log_fd, msg, strlen(msg)); @@ -478,42 +478,42 @@ Con_Printf Handles cursor positioning, line wrapping, etc ================ */ -#define MAXPRINTMSG 4096 -void Con_Printf (const char *fmt, ...) +#define MAXPRINTMSG 4096 +void Con_Printf(const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; - static bool inupdate; + va_list argptr; + char msg[MAXPRINTMSG]; + static bool inupdate; - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); // also echo to debugging console - Sys_Printf ("%s", msg); + Sys_Printf("%s", msg); // log all messages to file - if (con_debuglog) + if(con_debuglog) Con_DebugLog(msg); - if (!con_initialized) + if(!con_initialized) return; - if (cls.state == ca_dedicated) - return; // no graphics mode + if(cls.state == ca_dedicated) + return; // no graphics mode // write it to the scrollable buffer - Con_Print (msg); + Con_Print(msg); // update the screen if the console is displayed - if (cls.signon != SIGNONS && !scr_disabled_for_loading ) + if(cls.signon != SIGNONS && !scr_disabled_for_loading) { - // protect against infinite loop if something in SCR_UpdateScreen calls - // Con_Printd - if (!inupdate) + // protect against infinite loop if something in SCR_UpdateScreen calls + // Con_Printd + if(!inupdate) { inupdate = true; - SCR_UpdateScreen (); + SCR_UpdateScreen(); inupdate = false; } } @@ -528,20 +528,20 @@ use for "exceeds standard limit of" messages, which are only relevant for develo targetting vanilla engines ================ */ -void Con_DWarning (const char *fmt, ...) +void Con_DWarning(const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; + va_list argptr; + char msg[MAXPRINTMSG]; - if (!developer.value) - return; // don't confuse non-developers with techie stuff... + if(!developer.value) + return; // don't confuse non-developers with techie stuff... - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - Con_SafePrintf ("\x02Warning: "); - Con_Printf ("%s", msg); + Con_SafePrintf("\x02Warning: "); + Con_Printf("%s", msg); } /* @@ -549,17 +549,17 @@ void Con_DWarning (const char *fmt, ...) Con_Warning -- johnfitz -- prints a warning to the console ================ */ -void Con_Warning (const char *fmt, ...) +void Con_Warning(const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; + va_list argptr; + char msg[MAXPRINTMSG]; - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - Con_SafePrintf ("\x02Warning: "); - Con_Printf ("%s", msg); + Con_SafePrintf("\x02Warning: "); + Con_Printf("%s", msg); } /* @@ -569,19 +569,19 @@ Con_DPrintf A Con_Printf that only shows up if the "developer" cvar is set ================ */ -void Con_DPrintf (const char *fmt, ...) +void Con_DPrintf(const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; + va_list argptr; + char msg[MAXPRINTMSG]; - if (!developer.value) - return; // don't confuse non-developers with techie stuff... + if(!developer.value) + return; // don't confuse non-developers with techie stuff... - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - Con_SafePrintf ("%s", msg); //johnfitz -- was Con_Printf + Con_SafePrintf("%s", msg); //johnfitz -- was Con_Printf } /* @@ -591,17 +591,17 @@ Con_DPrintf2 -- johnfitz -- only prints if "developer" >= 2 currently not used ================ */ -void Con_DPrintf2 (const char *fmt, ...) +void Con_DPrintf2(const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; + va_list argptr; + char msg[MAXPRINTMSG]; - if (developer.value >= 2) + if(developer.value >= 2) { - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); - Con_Printf ("%s", msg); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); + Con_Printf("%s", msg); } } @@ -613,19 +613,19 @@ Con_SafePrintf Okay to call even when the screen can't be updated ================== */ -void Con_SafePrintf (const char *fmt, ...) +void Con_SafePrintf(const char *fmt, ...) { - va_list argptr; - char msg[1024]; - int32_t temp; + va_list argptr; + char msg[1024]; + int32_t temp; - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); temp = scr_disabled_for_loading; scr_disabled_for_loading = true; - Con_Printf ("%s", msg); + Con_Printf("%s", msg); scr_disabled_for_loading = temp; } @@ -634,40 +634,40 @@ void Con_SafePrintf (const char *fmt, ...) Con_CenterPrintf -- johnfitz -- pad each line with spaces to make it appear centered ================ */ -void Con_CenterPrintf (int32_t linewidth, const char *fmt, ...) FUNC_PRINTF(2,3); -void Con_CenterPrintf (int32_t linewidth, const char *fmt, ...) +void Con_CenterPrintf(int32_t linewidth, const char *fmt, ...) FUNC_PRINTF(2, 3); +void Con_CenterPrintf(int32_t linewidth, const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; //the original message - char line[MAXPRINTMSG]; //one line from the message - char spaces[21]; //buffer for spaces - char *src, *dst; - int32_t len, s; + va_list argptr; + char msg[MAXPRINTMSG]; //the original message + char line[MAXPRINTMSG]; //one line from the message + char spaces[21]; //buffer for spaces + char *src, *dst; + int32_t len, s; - va_start (argptr, fmt); - q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); linewidth = q_min(linewidth, con_linewidth); - for (src = msg; *src; ) + for(src = msg; *src;) { dst = line; - while (*src && *src != '\n') + while(*src && *src != '\n') *dst++ = *src++; *dst = 0; - if (*src == '\n') + if(*src == '\n') src++; len = strlen(line); - if (len < linewidth) + if(len < linewidth) { - s = (linewidth-len)/2; - memset (spaces, ' ', s); + s = (linewidth - len) / 2; + memset(spaces, ' ', s); spaces[s] = 0; - Con_Printf ("%s%s\n", spaces, line); + Con_Printf("%s%s\n", spaces, line); } else - Con_Printf ("%s\n", line); + Con_Printf("%s\n", line); } } @@ -676,29 +676,29 @@ void Con_CenterPrintf (int32_t linewidth, const char *fmt, ...) Con_LogCenterPrint -- johnfitz -- echo centerprint message to the console ================== */ -void Con_LogCenterPrint (const char *str) +void Con_LogCenterPrint(const char *str) { - if (!strcmp(str, con_lastcenterstring)) + if(!strcmp(str, con_lastcenterstring)) return; //ignore duplicates - if (cl.gametype == GAME_DEATHMATCH && con_logcenterprint.value != 2) + if(cl.gametype == GAME_DEATHMATCH && con_logcenterprint.value != 2) return; //don't log in deathmatch strcpy(con_lastcenterstring, str); - if (con_logcenterprint.value) + if(con_logcenterprint.value) { - Con_Printf ("%s", Con_Quakebar(40)); - Con_CenterPrintf (40, "%s\n", str); - Con_Printf ("%s", Con_Quakebar(40)); - Con_ClearNotify (); + Con_Printf("%s", Con_Quakebar(40)); + Con_CenterPrintf(40, "%s\n", str); + Con_Printf("%s", Con_Quakebar(40)); + Con_ClearNotify(); } } /* ============================================================================== - TAB COMPLETION + TAB COMPLETION ============================================================================== */ @@ -708,30 +708,30 @@ void Con_LogCenterPrint (const char *str) char key_tabpartial[MAXCMDLINE]; typedef struct tab_s { - const char *name; - const char *type; - struct tab_s *next; - struct tab_s *prev; + const char *name; + const char *type; + struct tab_s *next; + struct tab_s *prev; } tab_t; -tab_t *tablist; +tab_t *tablist; //defs from elsewhere -extern bool keydown[256]; +extern bool keydown[256]; typedef struct cmd_function_s { - struct cmd_function_s *next; - const char *name; - xcommand_t function; + struct cmd_function_s *next; + const char *name; + xcommand_t function; } cmd_function_t; -extern cmd_function_t *cmd_functions; -#define MAX_ALIAS_NAME 32 +extern cmd_function_t *cmd_functions; +#define MAX_ALIAS_NAME 32 typedef struct cmdalias_s { - struct cmdalias_s *next; - char name[MAX_ALIAS_NAME]; - char *value; + struct cmdalias_s *next; + char name[MAX_ALIAS_NAME]; + char *value; } cmdalias_t; -extern cmdalias_t *cmd_alias; +extern cmdalias_t *cmd_alias; /* ============ @@ -743,18 +743,18 @@ tablist is a doubly-linked loop, alphabetized by name // bash_partial is the string that can be expanded, // aka Linux Bash shell. -- S.A. -static char bash_partial[80]; -static bool bash_singlematch; +static char bash_partial[80]; +static bool bash_singlematch; -void AddToTabList (const char *name, const char *type) +void AddToTabList(const char *name, const char *type) { - tab_t *t,*insert; - char *i_bash; + tab_t *t, *insert; + char *i_bash; const char *i_name; - if (!*bash_partial) + if(!*bash_partial) { - strncpy (bash_partial, name, 79); + strncpy(bash_partial, name, 79); bash_partial[79] = '\0'; } else @@ -763,7 +763,7 @@ void AddToTabList (const char *name, const char *type) // find max common between bash_partial and name i_bash = bash_partial; i_name = name; - while (*i_bash && (*i_bash == *i_name)) + while(*i_bash && (*i_bash == *i_name)) { i_bash++; i_name++; @@ -775,13 +775,13 @@ void AddToTabList (const char *name, const char *type) t->name = name; t->type = type; - if (!tablist) //create list + if(!tablist) //create list { tablist = t; t->next = t; t->prev = t; } - else if (strcmp(name, tablist->name) < 0) //insert at front + else if(strcmp(name, tablist->name) < 0) //insert at front { t->next = tablist; t->prev = tablist->prev; @@ -794,10 +794,11 @@ void AddToTabList (const char *name, const char *type) insert = tablist; do { - if (strcmp(name, insert->name) < 0) + if(strcmp(name, insert->name) < 0) break; insert = insert->next; - } while (insert != tablist); + } + while(insert != tablist); t->next = insert; t->prev = insert->prev; @@ -808,8 +809,8 @@ void AddToTabList (const char *name, const char *type) typedef struct arg_completion_type_s { - const char *command; - filelist_item_t **filelist; + const char *command; + filelist_item_t **filelist; } arg_completion_type_t; static const arg_completion_type_t arg_completion_types[] = @@ -823,39 +824,40 @@ static const arg_completion_type_t arg_completion_types[] = }; static const int32_t num_arg_completion_types = - sizeof(arg_completion_types)/sizeof(arg_completion_types[0]); + sizeof(arg_completion_types) / sizeof(arg_completion_types[0]); /* ============ FindCompletion -- stevenaaus ============ */ -const char *FindCompletion (const char *partial, filelist_item_t *filelist, int32_t *nummatches_out) +const char *FindCompletion(const char *partial, filelist_item_t *filelist, int32_t *nummatches_out) { static char matched[32]; char *i_matched, *i_name; - filelist_item_t *file; + filelist_item_t *file; int32_t init, match, plen; memset(matched, 0, sizeof(matched)); plen = strlen(partial); match = 0; - for (file = filelist, init = 0; file; file = file->next) + for(file = filelist, init = 0; file; file = file->next) { - if (!strncmp(file->name, partial, plen)) + if(!strncmp(file->name, partial, plen)) { - if (init == 0) + if(init == 0) { init = 1; - strncpy (matched, file->name, sizeof(matched)-1); - matched[sizeof(matched)-1] = '\0'; + strncpy(matched, file->name, sizeof(matched) - 1); + matched[sizeof(matched) - 1] = '\0'; } else - { // find max common + { + // find max common i_matched = matched; i_name = file->name; - while (*i_matched && (*i_matched == *i_name)) + while(*i_matched && (*i_matched == *i_name)) { i_matched++; i_name++; @@ -868,14 +870,14 @@ const char *FindCompletion (const char *partial, filelist_item_t *filelist, int3 *nummatches_out = match; - if (match > 1) + if(match > 1) { - for (file = filelist; file; file = file->next) + for(file = filelist; file; file = file->next) { - if (!strncmp(file->name, partial, plen)) - Con_SafePrintf (" %s\n", file->name); + if(!strncmp(file->name, partial, plen)) + Con_SafePrintf(" %s\n", file->name); } - Con_SafePrintf ("\n"); + Con_SafePrintf("\n"); } return matched; @@ -886,12 +888,12 @@ const char *FindCompletion (const char *partial, filelist_item_t *filelist, int3 BuildTabList -- johnfitz ============ */ -void BuildTabList (const char *partial) +void BuildTabList(const char *partial) { - cmdalias_t *alias; - cvar_t *cvar; - cmd_function_t *cmd; - int32_t len; + cmdalias_t *alias; + cvar_t *cvar; + cmd_function_t *cmd; + int32_t len; tablist = NULL; len = strlen(partial); @@ -899,18 +901,18 @@ void BuildTabList (const char *partial) bash_partial[0] = 0; bash_singlematch = 1; - cvar = Cvar_FindVarAfter ("", CVAR_NONE); - for ( ; cvar ; cvar=cvar->next) - if (!Q_strncmp (partial, cvar->name, len)) - AddToTabList (cvar->name, "cvar"); + cvar = Cvar_FindVarAfter("", CVAR_NONE); + for(; cvar ; cvar = cvar->next) + if(!Q_strncmp(partial, cvar->name, len)) + AddToTabList(cvar->name, "cvar"); - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - if (!Q_strncmp (partial,cmd->name, len)) - AddToTabList (cmd->name, "command"); + for(cmd = cmd_functions ; cmd ; cmd = cmd->next) + if(!Q_strncmp(partial, cmd->name, len)) + AddToTabList(cmd->name, "command"); - for (alias=cmd_alias ; alias ; alias=alias->next) - if (!Q_strncmp (partial, alias->name, len)) - AddToTabList (alias->name, "alias"); + for(alias = cmd_alias ; alias ; alias = alias->next) + if(!Q_strncmp(partial, alias->name, len)) + AddToTabList(alias->name, "alias"); } /* @@ -918,55 +920,55 @@ void BuildTabList (const char *partial) Con_TabComplete -- johnfitz ============ */ -void Con_TabComplete (void) +void Con_TabComplete(void) { - char partial[MAXCMDLINE]; - const char *match; - static char *c; - tab_t *t; - int32_t mark, i, j; + char partial[MAXCMDLINE]; + const char *match; + static char *c; + tab_t *t; + int32_t mark, i, j; // if editline is empty, return - if (key_lines[edit_line][1] == 0) + if(key_lines[edit_line][1] == 0) return; // get partial string (space -> cursor) - if (!key_tabpartial[0]) //first time through, find new insert point. (Otherwise, use previous.) + if(!key_tabpartial[0]) //first time through, find new insert point. (Otherwise, use previous.) { //work back from cursor until you find a space, quote, semicolon, or prompt c = key_lines[edit_line] + key_linepos - 1; //start one space left of cursor - while (*c!=' ' && *c!='\"' && *c!=';' && c!=key_lines[edit_line]) + while(*c != ' ' && *c != '\"' && *c != ';' && c != key_lines[edit_line]) c--; c++; //start 1 char after the separator we just found } - for (i = 0; c + i < key_lines[edit_line] + key_linepos; i++) + for(i = 0; c + i < key_lines[edit_line] + key_linepos; i++) partial[i] = c[i]; partial[i] = 0; // Map autocomplete function -- S.A // Since we don't have argument completion, this hack will do for now... - for (j=0; j= MAXCMDLINE) + if(key_linepos >= MAXCMDLINE) key_linepos = MAXCMDLINE - 1; // if only one match, append a space - if (key_linepos < MAXCMDLINE - 1 && - key_lines[edit_line][key_linepos] == 0 && (nummatches == 1)) + if(key_linepos < MAXCMDLINE - 1 && + key_lines[edit_line][key_linepos] == 0 && (nummatches == 1)) { key_lines[edit_line][key_linepos] = ' '; key_linepos++; @@ -978,25 +980,25 @@ void Con_TabComplete (void) } //if partial is empty, return - if (partial[0] == 0) + if(partial[0] == 0) return; //trim trailing space becuase it screws up string comparisons - if (i > 0 && partial[i-1] == ' ') - partial[i-1] = 0; + if(i > 0 && partial[i - 1] == ' ') + partial[i - 1] = 0; // find a match mark = Hunk_LowMark(); - if (!key_tabpartial[0]) //first time through + if(!key_tabpartial[0]) //first time through { - q_strlcpy (key_tabpartial, partial, MAXCMDLINE); - BuildTabList (key_tabpartial); + q_strlcpy(key_tabpartial, partial, MAXCMDLINE); + BuildTabList(key_tabpartial); - if (!tablist) + if(!tablist) return; // print list if length > 1 - if (tablist->next != tablist) + if(tablist->next != tablist) { t = tablist; Con_SafePrintf("\n"); @@ -1004,19 +1006,20 @@ void Con_TabComplete (void) { Con_SafePrintf(" %s (%s)\n", t->name, t->type); t = t->next; - } while (t != tablist); + } + while(t != tablist); Con_SafePrintf("\n"); } - // match = tablist->name; - // First time, just show maximum matching chars -- S.A. + // match = tablist->name; + // First time, just show maximum matching chars -- S.A. match = bash_partial; } else { - BuildTabList (key_tabpartial); + BuildTabList(key_tabpartial); - if (!tablist) + if(!tablist) return; //find current match -- can't save a pointer because the list will be rebuilt each time @@ -1024,36 +1027,37 @@ void Con_TabComplete (void) match = keydown[K_SHIFT] ? t->prev->name : t->name; do { - if (!Q_strcmp(t->name, partial)) + if(!Q_strcmp(t->name, partial)) { match = keydown[K_SHIFT] ? t->prev->name : t->next->name; break; } t = t->next; - } while (t != tablist); + } + while(t != tablist); } Hunk_FreeToLowMark(mark); //it's okay to free it here because match is a pointer to persistent data // insert new match into edit line - q_strlcpy (partial, match, MAXCMDLINE); //first copy match string - q_strlcat (partial, key_lines[edit_line] + key_linepos, MAXCMDLINE); //then add chars after cursor - *c = '\0'; //now copy all of this into edit line - q_strlcat (key_lines[edit_line], partial, MAXCMDLINE); + q_strlcpy(partial, match, MAXCMDLINE); //first copy match string + q_strlcat(partial, key_lines[edit_line] + key_linepos, MAXCMDLINE); //then add chars after cursor + *c = '\0'; //now copy all of this into edit line + q_strlcat(key_lines[edit_line], partial, MAXCMDLINE); key_linepos = c - key_lines[edit_line] + Q_strlen(match); //set new cursor position - if (key_linepos >= MAXCMDLINE) + if(key_linepos >= MAXCMDLINE) key_linepos = MAXCMDLINE - 1; // if cursor is at end of string, let's append a space to make life easier - if (key_linepos < MAXCMDLINE - 1 && - key_lines[edit_line][key_linepos] == 0 && bash_singlematch) + if(key_linepos < MAXCMDLINE - 1 && + key_lines[edit_line][key_linepos] == 0 && bash_singlematch) { key_lines[edit_line][key_linepos] = ' '; key_linepos++; key_lines[edit_line][key_linepos] = 0; - // S.A.: the map argument completion (may be in combination with the bash-style - // display behavior changes, causes weirdness when completing the arguments for - // the changelevel command. the line below "fixes" it, although I'm not sure about - // the reason, yet, neither do I know any possible side effects of it: + // S.A.: the map argument completion (may be in combination with the bash-style + // display behavior changes, causes weirdness when completing the arguments for + // the changelevel command. the line below "fixes" it, although I'm not sure about + // the reason, yet, neither do I know any possible side effects of it: c = key_lines[edit_line] + key_linepos; } } @@ -1073,65 +1077,65 @@ Con_DrawNotify Draws the last few lines of output transparently over the game top ================ */ -void Con_DrawNotify (void) +void Con_DrawNotify(void) { - int32_t i, x, v; - const char *text; - float time; + int32_t i, x, v; + const char *text; + float time; - GL_SetCanvas (CANVAS_CONSOLE); //johnfitz + GL_SetCanvas(CANVAS_CONSOLE); //johnfitz v = vid.conheight; //johnfitz - for (i = con_current-NUM_CON_TIMES+1; i <= con_current; i++) + for(i = con_current - NUM_CON_TIMES + 1; i <= con_current; i++) { - if (i < 0) + if(i < 0) continue; time = con_times[i % NUM_CON_TIMES]; - if (time == 0) + if(time == 0) continue; time = realtime - time; - if (time > con_notifytime.value) + if(time > con_notifytime.value) continue; - text = con_text + (i % con_totallines)*con_linewidth; + text = con_text + (i % con_totallines) * con_linewidth; clearnotify = 0; - for (x = 0; x < con_linewidth; x++) - Draw_Character ((x+1)<<3, v, text[x]); + for(x = 0; x < con_linewidth; x++) + Draw_Character((x + 1) << 3, v, text[x]); v += 8; scr_tileclear_updates = 0; //johnfitz } - if (key_dest == key_message) + if(key_dest == key_message) { clearnotify = 0; - if (chat_team) + if(chat_team) { - Draw_String (8, v, "say_team:"); + Draw_String(8, v, "say_team:"); x = 11; } else { - Draw_String (8, v, "say:"); + Draw_String(8, v, "say:"); x = 6; } text = Key_GetChatBuffer(); i = Key_GetChatMsgLen(); - if (i > con_linewidth - x - 1) + if(i > con_linewidth - x - 1) text += i - con_linewidth + x + 1; - while (*text) + while(*text) { - Draw_Character (x<<3, v, *text); + Draw_Character(x << 3, v, *text); x++; text++; } - Draw_Character (x<<3, v, 10 + ((int32_t)(realtime*con_cursorspeed)&1)); + Draw_Character(x << 3, v, 10 + ((int32_t)(realtime * con_cursorspeed) & 1)); v += 8; scr_tileclear_updates = 0; //johnfitz @@ -1145,30 +1149,30 @@ Con_DrawInput -- johnfitz -- modified to allow insert editing The input line scrolls horizontally if typing goes beyond the right edge ================ */ -extern qpic_t *pic_ovr, *pic_ins; //johnfitz -- new cursor handling +extern qpic_t *pic_ovr, *pic_ins; //johnfitz -- new cursor handling -void Con_DrawInput (void) +void Con_DrawInput(void) { - int32_t i, ofs; + int32_t i, ofs; - if (key_dest != key_console && !con_forcedup) - return; // don't draw anything + if(key_dest != key_console && !con_forcedup) + return; // don't draw anything // prestep if horizontally scrolling - if (key_linepos >= con_linewidth) + if(key_linepos >= con_linewidth) ofs = 1 + key_linepos - con_linewidth; else ofs = 0; // draw input string - for (i = 0; key_lines[edit_line][i+ofs] && i < con_linewidth; i++) - Draw_Character ((i+1)<<3, vid.conheight - 16, key_lines[edit_line][i+ofs]); + for(i = 0; key_lines[edit_line][i + ofs] && i < con_linewidth; i++) + Draw_Character((i + 1) << 3, vid.conheight - 16, key_lines[edit_line][i + ofs]); // johnfitz -- new cursor handling - if (!((int32_t)((realtime-key_blinktime)*con_cursorspeed) & 1)) + if(!((int32_t)((realtime - key_blinktime)*con_cursorspeed) & 1)) { i = key_linepos - ofs; - Draw_Pic ((i+1)<<3, vid.conheight - 16, key_insert ? pic_ins : pic_ovr); + Draw_Pic((i + 1) << 3, vid.conheight - 16, key_insert ? pic_ins : pic_ovr); } } @@ -1180,56 +1184,56 @@ Draws the console with the solid background The typing input line at the bottom should only be drawn if typing is allowed ================ */ -void Con_DrawConsole (int32_t lines, bool drawinput) +void Con_DrawConsole(int32_t lines, bool drawinput) { - int32_t i, x, y, j, sb, rows; - const char *text; - char ver[32]; + int32_t i, x, y, j, sb, rows; + const char *text; + char ver[32]; - if (lines <= 0) + if(lines <= 0) return; con_vislines = lines * vid.conheight / glheight; - GL_SetCanvas (CANVAS_CONSOLE); + GL_SetCanvas(CANVAS_CONSOLE); // draw the background - Draw_ConsoleBackground (); + Draw_ConsoleBackground(); // draw the buffer text - rows = (con_vislines +7)/8; - y = vid.conheight - rows*8; + rows = (con_vislines + 7) / 8; + y = vid.conheight - rows * 8; rows -= 2; //for input and version lines sb = (con_backscroll) ? 2 : 0; - for (i = con_current - rows + 1; i <= con_current - sb; i++, y += 8) + for(i = con_current - rows + 1; i <= con_current - sb; i++, y += 8) { j = i - con_backscroll; - if (j < 0) + if(j < 0) j = 0; - text = con_text + (j % con_totallines)*con_linewidth; + text = con_text + (j % con_totallines) * con_linewidth; - for (x = 0; x < con_linewidth; x++) - Draw_Character ( (x + 1)<<3, y, text[x]); + for(x = 0; x < con_linewidth; x++) + Draw_Character((x + 1) << 3, y, text[x]); } // draw scrollback arrows - if (con_backscroll) + if(con_backscroll) { y += 8; // blank line - for (x = 0; x < con_linewidth; x += 4) - Draw_Character ((x + 1)<<3, y, '^'); + for(x = 0; x < con_linewidth; x += 4) + Draw_Character((x + 1) << 3, y, '^'); y += 8; } // draw the input prompt, user text, and cursor - if (drawinput) - Con_DrawInput (); + if(drawinput) + Con_DrawInput(); //draw version number in bottom right y += 8; - q_snprintf (ver, sizeof(ver), "QuakeSpasm " QUAKESPASM_VERSION); - for (x = 0; x < (int32_t)strlen(ver); x++) - Draw_Character ((con_linewidth - strlen(ver) + x + 2)<<3, y, ver[x] /*+ 128*/); + q_snprintf(ver, sizeof(ver), "QuakeSpasm " QUAKESPASM_VERSION); + for(x = 0; x < (int32_t)strlen(ver); x++) + Draw_Character((con_linewidth - strlen(ver) + x + 2) << 3, y, ver[x] /*+ 128*/); } @@ -1238,71 +1242,72 @@ void Con_DrawConsole (int32_t lines, bool drawinput) Con_NotifyBox ================== */ -void Con_NotifyBox (const char *text) +void Con_NotifyBox(const char *text) { - double t1, t2; - int32_t lastkey, lastchar; + double t1, t2; + int32_t lastkey, lastchar; // during startup for sound / cd warnings - Con_Printf ("\n\n%s", Con_Quakebar(40)); //johnfitz - Con_Printf ("%s", text); - Con_Printf ("Press a key.\n"); - Con_Printf ("%s", Con_Quakebar(40)); //johnfitz + Con_Printf("\n\n%s", Con_Quakebar(40)); //johnfitz + Con_Printf("%s", text); + Con_Printf("Press a key.\n"); + Con_Printf("%s", Con_Quakebar(40)); //johnfitz IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_console; - Key_BeginInputGrab (); + Key_BeginInputGrab(); do { - t1 = Sys_DoubleTime (); - SCR_UpdateScreen (); - Sys_SendKeyEvents (); - Key_GetGrabbedInput (&lastkey, &lastchar); - Sys_Sleep (16); - t2 = Sys_DoubleTime (); - realtime += t2-t1; // make the cursor blink - } while (lastkey == -1 && lastchar == -1); - Key_EndInputGrab (); + t1 = Sys_DoubleTime(); + SCR_UpdateScreen(); + Sys_SendKeyEvents(); + Key_GetGrabbedInput(&lastkey, &lastchar); + Sys_Sleep(16); + t2 = Sys_DoubleTime(); + realtime += t2 - t1; // make the cursor blink + } + while(lastkey == -1 && lastchar == -1); + Key_EndInputGrab(); - Con_Printf ("\n"); + Con_Printf("\n"); IN_Activate(); key_dest = key_game; - realtime = 0; // put the cursor back to invisible + realtime = 0; // put the cursor back to invisible } -void LOG_Init (quakeparms_t *parms) +void LOG_Init(quakeparms_t *parms) { - time_t inittime; - char session[24]; + time_t inittime; + char session[24]; - if (!COM_CheckParm("-condebug")) + if(!COM_CheckParm("-condebug")) return; - inittime = time (NULL); - strftime (session, sizeof(session), "%m/%" PRIi32 "/%Y %H:%M:%S", localtime(&inittime)); - q_snprintf (logfilename, sizeof(logfilename), "%s/qconsole.log", parms->basedir); + inittime = time(NULL); + strftime(session, sizeof(session), "%m/%" PRIi32 "/%Y %H:%M:%S", localtime(&inittime)); + q_snprintf(logfilename, sizeof(logfilename), "%s/qconsole.log", parms->basedir); // unlink (logfilename); - log_fd = open (logfilename, O_WRONLY | O_CREAT | O_TRUNC, 0666); - if (log_fd == -1) + log_fd = open(logfilename, O_WRONLY | O_CREAT | O_TRUNC, 0666); + if(log_fd == -1) { - fprintf (stderr, "Error: Unable to create log file %s\n", logfilename); + fprintf(stderr, "Error: Unable to create log file %s\n", logfilename); return; } con_debuglog = true; - Con_DebugLog (va("LOG started on: %s \n", session)); + Con_DebugLog(va("LOG started on: %s \n", session)); } -void LOG_Close (void) +void LOG_Close(void) { - if (log_fd == -1) + if(log_fd == -1) return; - close (log_fd); + close(log_fd); log_fd = -1; } diff --git a/source/console.h b/source/console.h index fe58472..30c6685 100644 --- a/source/console.h +++ b/source/console.h @@ -28,42 +28,42 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // extern int32_t con_totallines; extern int32_t con_backscroll; -extern bool con_forcedup; // because no entities to refresh +extern bool con_forcedup; // because no entities to refresh extern bool con_initialized; extern byte *con_chars; extern char con_lastcenterstring[]; //johnfitz -void Con_DrawCharacter (int32_t cx, int32_t line, int32_t num); +void Con_DrawCharacter(int32_t cx, int32_t line, int32_t num); -void Con_CheckResize (void); -void Con_Init (void); -void Con_DrawConsole (int32_t lines, bool drawinput); -void Con_Printf (const char *fmt, ...) FUNC_PRINTF(1,2); -void Con_DWarning (const char *fmt, ...) FUNC_PRINTF(1,2); //ericw -void Con_Warning (const char *fmt, ...) FUNC_PRINTF(1,2); //johnfitz -void Con_DPrintf (const char *fmt, ...) FUNC_PRINTF(1,2); -void Con_DPrintf2 (const char *fmt, ...) FUNC_PRINTF(1,2); //johnfitz -void Con_SafePrintf (const char *fmt, ...) FUNC_PRINTF(1,2); -void Con_DrawNotify (void); -void Con_ClearNotify (void); -void Con_ToggleConsole_f (void); +void Con_CheckResize(void); +void Con_Init(void); +void Con_DrawConsole(int32_t lines, bool drawinput); +void Con_Printf(const char *fmt, ...) FUNC_PRINTF(1, 2); +void Con_DWarning(const char *fmt, ...) FUNC_PRINTF(1, 2); //ericw +void Con_Warning(const char *fmt, ...) FUNC_PRINTF(1, 2); //johnfitz +void Con_DPrintf(const char *fmt, ...) FUNC_PRINTF(1, 2); +void Con_DPrintf2(const char *fmt, ...) FUNC_PRINTF(1, 2); //johnfitz +void Con_SafePrintf(const char *fmt, ...) FUNC_PRINTF(1, 2); +void Con_DrawNotify(void); +void Con_ClearNotify(void); +void Con_ToggleConsole_f(void); -void Con_NotifyBox (const char *text); // during startup for sound / cd warnings +void Con_NotifyBox(const char *text); // during startup for sound / cd warnings -void Con_Show (void); -void Con_Hide (void); +void Con_Show(void); +void Con_Hide(void); -const char *Con_Quakebar (int32_t len); -void Con_TabComplete (void); -void Con_LogCenterPrint (const char *str); +const char *Con_Quakebar(int32_t len); +void Con_TabComplete(void); +void Con_LogCenterPrint(const char *str); // // debuglog // -void LOG_Init (quakeparms_t *parms); -void LOG_Close (void); -void Con_DebugLog (const char *msg); +void LOG_Init(quakeparms_t *parms); +void LOG_Close(void); +void Con_DebugLog(const char *msg); -#endif /* __CONSOLE_H */ +#endif /* __CONSOLE_H */ diff --git a/source/crc.c b/source/crc.c index 378008b..20795fa 100644 --- a/source/crc.c +++ b/source/crc.c @@ -27,43 +27,43 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // and the initial and final xor values shown below... in other words, the // CCITT standard CRC used by XMODEM -#define CRC_INIT_VALUE 0xffff -#define CRC_XOR_VALUE 0x0000 +#define CRC_INIT_VALUE 0xffff +#define CRC_XOR_VALUE 0x0000 static uint16_t crctable[256] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 }; void CRC_Init(uint16_t *crcvalue) @@ -82,12 +82,12 @@ uint16_t CRC_Value(uint16_t crcvalue) } //johnfitz -- texture crc -uint16_t CRC_Block (const byte *start, int32_t count) +uint16_t CRC_Block(const byte *start, int32_t count) { - uint16_t crc; + uint16_t crc; - CRC_Init (&crc); - while (count--) + CRC_Init(&crc); + while(count--) crc = (crc << 8) ^ crctable[(crc >> 8) ^ *start++]; return crc; diff --git a/source/crc.h b/source/crc.h index ced63e6..b510235 100644 --- a/source/crc.h +++ b/source/crc.h @@ -27,7 +27,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. void CRC_Init(uint16_t *crcvalue); void CRC_ProcessByte(uint16_t *crcvalue, byte data); uint16_t CRC_Value(uint16_t crcvalue); -uint16_t CRC_Block (const byte *start, int32_t count); //johnfitz -- texture crc +uint16_t CRC_Block(const byte *start, int32_t count); //johnfitz -- texture crc -#endif /* _QUAKE_CRC_H */ +#endif /* _QUAKE_CRC_H */ diff --git a/source/cvar.c b/source/cvar.c index 12d3f80..93c0b2f 100644 --- a/source/cvar.c +++ b/source/cvar.c @@ -23,8 +23,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -static cvar_t *cvar_vars; -static char cvar_null_string[] = ""; +static cvar_t *cvar_vars; +static char cvar_null_string[] = ""; //============================================================================== // @@ -32,22 +32,22 @@ static char cvar_null_string[] = ""; // //============================================================================== -void Cvar_Reset (const char *name); //johnfitz +void Cvar_Reset(const char *name); //johnfitz /* ============ Cvar_List_f -- johnfitz ============ */ -void Cvar_List_f (void) +void Cvar_List_f(void) { - cvar_t *cvar; - const char *partial; - int32_t len, count; + cvar_t *cvar; + const char *partial; + int32_t len, count; - if (Cmd_Argc() > 1) + if(Cmd_Argc() > 1) { - partial = Cmd_Argv (1); + partial = Cmd_Argv(1); len = Q_strlen(partial); } else @@ -57,26 +57,26 @@ void Cvar_List_f (void) } count = 0; - for (cvar = cvar_vars ; cvar ; cvar = cvar->next) + for(cvar = cvar_vars ; cvar ; cvar = cvar->next) { - if (partial && Q_strncmp(partial, cvar->name, len)) + if(partial && Q_strncmp(partial, cvar->name, len)) { continue; } - Con_SafePrintf ("%s%s %s \"%s\"\n", - (cvar->flags & CVAR_ARCHIVE) ? "*" : " ", - (cvar->flags & CVAR_NOTIFY) ? "s" : " ", - cvar->name, - cvar->string); + Con_SafePrintf("%s%s %s \"%s\"\n", + (cvar->flags & CVAR_ARCHIVE) ? "*" : " ", + (cvar->flags & CVAR_NOTIFY) ? "s" : " ", + cvar->name, + cvar->string); count++; } - Con_SafePrintf ("%" PRIi32 " cvars", count); - if (partial) + Con_SafePrintf("%" PRIi32 " cvars", count); + if(partial) { - Con_SafePrintf (" beginning with \"%s\"", partial); + Con_SafePrintf(" beginning with \"%s\"", partial); } - Con_SafePrintf ("\n"); + Con_SafePrintf("\n"); } /* @@ -84,19 +84,19 @@ void Cvar_List_f (void) Cvar_Inc_f -- johnfitz ============ */ -void Cvar_Inc_f (void) +void Cvar_Inc_f(void) { - switch (Cmd_Argc()) + switch(Cmd_Argc()) { default: case 1: Con_Printf("inc [amount] : increment cvar\n"); break; case 2: - Cvar_SetValue (Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) + 1); + Cvar_SetValue(Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) + 1); break; case 3: - Cvar_SetValue (Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) + Q_atof(Cmd_Argv(2))); + Cvar_SetValue(Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) + Q_atof(Cmd_Argv(2))); break; } } @@ -106,19 +106,19 @@ void Cvar_Inc_f (void) Cvar_Toggle_f -- johnfitz ============ */ -void Cvar_Toggle_f (void) +void Cvar_Toggle_f(void) { - switch (Cmd_Argc()) + switch(Cmd_Argc()) { default: case 1: Con_Printf("toggle : toggle cvar\n"); break; case 2: - if (Cvar_VariableValue(Cmd_Argv(1))) - Cvar_Set (Cmd_Argv(1), "0"); + if(Cvar_VariableValue(Cmd_Argv(1))) + Cvar_Set(Cmd_Argv(1), "0"); else - Cvar_Set (Cmd_Argv(1), "1"); + Cvar_Set(Cmd_Argv(1), "1"); break; } } @@ -128,11 +128,11 @@ void Cvar_Toggle_f (void) Cvar_Cycle_f -- johnfitz ============ */ -void Cvar_Cycle_f (void) +void Cvar_Cycle_f(void) { int32_t i; - if (Cmd_Argc() < 3) + if(Cmd_Argc() < 3) { Con_Printf("cycle : cycle cvar through a list of values\n"); return; @@ -141,29 +141,29 @@ void Cvar_Cycle_f (void) //loop through the args until you find one that matches the current cvar value. //yes, this will get stuck on a list that contains the same value twice. //it's not worth dealing with, and i'm not even sure it can be dealt with. - for (i = 2; i < Cmd_Argc(); i++) + for(i = 2; i < Cmd_Argc(); i++) { //zero is assumed to be a string, even though it could actually be zero. The worst case //is that the first time you call this command, it won't match on zero when it should, but after that, //it will be comparing strings that all had the same source (the user) so it will work. - if (Q_atof(Cmd_Argv(i)) == 0) + if(Q_atof(Cmd_Argv(i)) == 0) { - if (!strcmp(Cmd_Argv(i), Cvar_VariableString(Cmd_Argv(1)))) + if(!strcmp(Cmd_Argv(i), Cvar_VariableString(Cmd_Argv(1)))) break; } else { - if (Q_atof(Cmd_Argv(i)) == Cvar_VariableValue(Cmd_Argv(1))) + if(Q_atof(Cmd_Argv(i)) == Cvar_VariableValue(Cmd_Argv(1))) break; } } - if (i == Cmd_Argc()) - Cvar_Set (Cmd_Argv(1), Cmd_Argv(2)); // no match - else if (i + 1 == Cmd_Argc()) - Cvar_Set (Cmd_Argv(1), Cmd_Argv(2)); // matched last value in list + if(i == Cmd_Argc()) + Cvar_Set(Cmd_Argv(1), Cmd_Argv(2)); // no match + else if(i + 1 == Cmd_Argc()) + Cvar_Set(Cmd_Argv(1), Cmd_Argv(2)); // matched last value in list else - Cvar_Set (Cmd_Argv(1), Cmd_Argv(i+1)); // matched earlier in list + Cvar_Set(Cmd_Argv(1), Cmd_Argv(i + 1)); // matched earlier in list } /* @@ -171,16 +171,16 @@ void Cvar_Cycle_f (void) Cvar_Reset_f -- johnfitz ============ */ -void Cvar_Reset_f (void) +void Cvar_Reset_f(void) { - switch (Cmd_Argc()) + switch(Cmd_Argc()) { default: case 1: - Con_Printf ("reset : reset cvar to default\n"); + Con_Printf("reset : reset cvar to default\n"); break; case 2: - Cvar_Reset (Cmd_Argv(1)); + Cvar_Reset(Cmd_Argv(1)); break; } } @@ -190,12 +190,12 @@ void Cvar_Reset_f (void) Cvar_ResetAll_f -- johnfitz ============ */ -void Cvar_ResetAll_f (void) +void Cvar_ResetAll_f(void) { - cvar_t *var; + cvar_t *var; - for (var = cvar_vars ; var ; var = var->next) - Cvar_Reset (var->name); + for(var = cvar_vars ; var ; var = var->next) + Cvar_Reset(var->name); } /* @@ -203,12 +203,12 @@ void Cvar_ResetAll_f (void) Cvar_ResetCfg_f -- QuakeSpasm ============ */ -void Cvar_ResetCfg_f (void) +void Cvar_ResetCfg_f(void) { - cvar_t *var; + cvar_t *var; - for (var = cvar_vars ; var ; var = var->next) - if (var->flags & CVAR_ARCHIVE) Cvar_Reset (var->name); + for(var = cvar_vars ; var ; var = var->next) + if(var->flags & CVAR_ARCHIVE) Cvar_Reset(var->name); } //============================================================================== @@ -223,15 +223,15 @@ Cvar_Init -- johnfitz ============ */ -void Cvar_Init (void) +void Cvar_Init(void) { - Cmd_AddCommand ("cvarlist", Cvar_List_f); - Cmd_AddCommand ("toggle", Cvar_Toggle_f); - Cmd_AddCommand ("cycle", Cvar_Cycle_f); - Cmd_AddCommand ("inc", Cvar_Inc_f); - Cmd_AddCommand ("reset", Cvar_Reset_f); - Cmd_AddCommand ("resetall", Cvar_ResetAll_f); - Cmd_AddCommand ("resetcfg", Cvar_ResetCfg_f); + Cmd_AddCommand("cvarlist", Cvar_List_f); + Cmd_AddCommand("toggle", Cvar_Toggle_f); + Cmd_AddCommand("cycle", Cvar_Cycle_f); + Cmd_AddCommand("inc", Cvar_Inc_f); + Cmd_AddCommand("reset", Cvar_Reset_f); + Cmd_AddCommand("resetall", Cvar_ResetAll_f); + Cmd_AddCommand("resetcfg", Cvar_ResetCfg_f); } //============================================================================== @@ -245,27 +245,27 @@ void Cvar_Init (void) Cvar_FindVar ============ */ -cvar_t *Cvar_FindVar (const char *var_name) +cvar_t *Cvar_FindVar(const char *var_name) { - cvar_t *var; + cvar_t *var; - for (var = cvar_vars ; var ; var = var->next) + for(var = cvar_vars ; var ; var = var->next) { - if (!Q_strcmp(var_name, var->name)) + if(!Q_strcmp(var_name, var->name)) return var; } return NULL; } -cvar_t *Cvar_FindVarAfter (const char *prev_name, uint32_t with_flags) +cvar_t *Cvar_FindVarAfter(const char *prev_name, uint32_t with_flags) { - cvar_t *var; + cvar_t *var; - if (*prev_name) + if(*prev_name) { - var = Cvar_FindVar (prev_name); - if (!var) + var = Cvar_FindVar(prev_name); + if(!var) return NULL; var = var->next; } @@ -273,9 +273,9 @@ cvar_t *Cvar_FindVarAfter (const char *prev_name, uint32_t with_flags) var = cvar_vars; // search for the next cvar matching the needed flags - while (var) + while(var) { - if ((var->flags & with_flags) || !with_flags) + if((var->flags & with_flags) || !with_flags) break; var = var->next; } @@ -287,25 +287,25 @@ cvar_t *Cvar_FindVarAfter (const char *prev_name, uint32_t with_flags) Cvar_LockVar ============ */ -void Cvar_LockVar (const char *var_name) +void Cvar_LockVar(const char *var_name) { - cvar_t *var = Cvar_FindVar (var_name); - if (var) + cvar_t *var = Cvar_FindVar(var_name); + if(var) var->flags |= CVAR_LOCKED; } -void Cvar_UnlockVar (const char *var_name) +void Cvar_UnlockVar(const char *var_name) { - cvar_t *var = Cvar_FindVar (var_name); - if (var) + cvar_t *var = Cvar_FindVar(var_name); + if(var) var->flags &= ~CVAR_LOCKED; } -void Cvar_UnlockAll (void) +void Cvar_UnlockAll(void) { - cvar_t *var; + cvar_t *var; - for (var = cvar_vars ; var ; var = var->next) + for(var = cvar_vars ; var ; var = var->next) { var->flags &= ~CVAR_LOCKED; } @@ -316,14 +316,14 @@ void Cvar_UnlockAll (void) Cvar_VariableValue ============ */ -float Cvar_VariableValue (const char *var_name) +float Cvar_VariableValue(const char *var_name) { - cvar_t *var; + cvar_t *var; - var = Cvar_FindVar (var_name); - if (!var) + var = Cvar_FindVar(var_name); + if(!var) return 0; - return Q_atof (var->string); + return Q_atof(var->string); } @@ -332,12 +332,12 @@ float Cvar_VariableValue (const char *var_name) Cvar_VariableString ============ */ -const char *Cvar_VariableString (const char *var_name) +const char *Cvar_VariableString(const char *var_name) { cvar_t *var; - var = Cvar_FindVar (var_name); - if (!var) + var = Cvar_FindVar(var_name); + if(!var) return cvar_null_string; return var->string; } @@ -348,19 +348,19 @@ const char *Cvar_VariableString (const char *var_name) Cvar_CompleteVariable ============ */ -const char *Cvar_CompleteVariable (const char *partial) +const char *Cvar_CompleteVariable(const char *partial) { - cvar_t *cvar; - int32_t len; + cvar_t *cvar; + int32_t len; len = Q_strlen(partial); - if (!len) + if(!len) return NULL; // check functions - for (cvar = cvar_vars ; cvar ; cvar = cvar->next) + for(cvar = cvar_vars ; cvar ; cvar = cvar->next) { - if (!Q_strncmp(partial, cvar->name, len)) + if(!Q_strncmp(partial, cvar->name, len)) return cvar->name; } @@ -372,79 +372,79 @@ const char *Cvar_CompleteVariable (const char *partial) Cvar_Reset -- johnfitz ============ */ -void Cvar_Reset (const char *name) +void Cvar_Reset(const char *name) { - cvar_t *var; + cvar_t *var; - var = Cvar_FindVar (name); - if (!var) - Con_Printf ("variable \"%s\" not found\n", name); + var = Cvar_FindVar(name); + if(!var) + Con_Printf("variable \"%s\" not found\n", name); else - Cvar_SetQuick (var, var->default_string); + Cvar_SetQuick(var, var->default_string); } -void Cvar_SetQuick (cvar_t *var, const char *value) +void Cvar_SetQuick(cvar_t *var, const char *value) { - if (var->flags & (CVAR_ROM|CVAR_LOCKED)) + if(var->flags & (CVAR_ROM | CVAR_LOCKED)) return; - if (!(var->flags & CVAR_REGISTERED)) + if(!(var->flags & CVAR_REGISTERED)) return; - if (!var->string) - var->string = Z_Strdup (value); + if(!var->string) + var->string = Z_Strdup(value); else { - int32_t len; + int32_t len; - if (!strcmp(var->string, value)) - return; // no change + if(!strcmp(var->string, value)) + return; // no change var->flags |= CVAR_CHANGED; - len = Q_strlen (value); - if (len != Q_strlen(var->string)) + len = Q_strlen(value); + if(len != Q_strlen(var->string)) { - Z_Free ((void *)var->string); - var->string = (char *) Z_Malloc (len + 1); + Z_Free((void *)var->string); + var->string = (char *) Z_Malloc(len + 1); } - memcpy ((char *)var->string, value, len + 1); + memcpy((char *)var->string, value, len + 1); } - var->value = Q_atof (var->string); + var->value = Q_atof(var->string); //johnfitz -- save initial value for "reset" command - if (!var->default_string) - var->default_string = Z_Strdup (var->string); + if(!var->default_string) + var->default_string = Z_Strdup(var->string); //johnfitz -- during initialization, update default too - else if (!host_initialized) + else if(!host_initialized) { - // Sys_Printf("changing default of %s: %s -> %s\n", - // var->name, var->default_string, var->string); - Z_Free ((void *)var->default_string); - var->default_string = Z_Strdup (var->string); + // Sys_Printf("changing default of %s: %s -> %s\n", + // var->name, var->default_string, var->string); + Z_Free((void *)var->default_string); + var->default_string = Z_Strdup(var->string); } //johnfitz - if (var->callback) - var->callback (var); + if(var->callback) + var->callback(var); } -void Cvar_SetValueQuick (cvar_t *var, const float value) +void Cvar_SetValueQuick(cvar_t *var, const float value) { - char val[32], *ptr = val; + char val[32], *ptr = val; - if (value == (float)((int32_t)value)) - q_snprintf (val, sizeof(val), "%" PRIi32 "", (int32_t)value); + if(value == (float)((int32_t)value)) + q_snprintf(val, sizeof(val), "%" PRIi32 "", (int32_t)value); else { - q_snprintf (val, sizeof(val), "%f", value); + q_snprintf(val, sizeof(val), "%f", value); // kill trailing zeroes - while (*ptr) + while(*ptr) ptr++; - while (--ptr > val && *ptr == '0' && ptr[-1] != '.') + while(--ptr > val && *ptr == '0' && ptr[-1] != '.') *ptr = '\0'; } - Cvar_SetQuick (var, val); + Cvar_SetQuick(var, val); } /* @@ -452,18 +452,19 @@ void Cvar_SetValueQuick (cvar_t *var, const float value) Cvar_Set ============ */ -void Cvar_Set (const char *var_name, const char *value) +void Cvar_Set(const char *var_name, const char *value) { - cvar_t *var; + cvar_t *var; - var = Cvar_FindVar (var_name); - if (!var) - { // there is an error in C code if this happens - Con_Printf ("Cvar_Set: variable %s not found\n", var_name); + var = Cvar_FindVar(var_name); + if(!var) + { + // there is an error in C code if this happens + Con_Printf("Cvar_Set: variable %s not found\n", var_name); return; } - Cvar_SetQuick (var, value); + Cvar_SetQuick(var, value); } /* @@ -471,23 +472,23 @@ void Cvar_Set (const char *var_name, const char *value) Cvar_SetValue ============ */ -void Cvar_SetValue (const char *var_name, const float value) +void Cvar_SetValue(const char *var_name, const float value) { - char val[32], *ptr = val; + char val[32], *ptr = val; - if (value == (float)((int32_t)value)) - q_snprintf (val, sizeof(val), "%" PRIi32 "", (int32_t)value); + if(value == (float)((int32_t)value)) + q_snprintf(val, sizeof(val), "%" PRIi32 "", (int32_t)value); else { - q_snprintf (val, sizeof(val), "%f", value); + q_snprintf(val, sizeof(val), "%f", value); // kill trailing zeroes - while (*ptr) + while(*ptr) ptr++; - while (--ptr > val && *ptr == '0' && ptr[-1] != '.') + while(--ptr > val && *ptr == '0' && ptr[-1] != '.') *ptr = '\0'; } - Cvar_Set (var_name, val); + Cvar_Set(var_name, val); } /* @@ -495,13 +496,13 @@ void Cvar_SetValue (const char *var_name, const float value) Cvar_SetROM ============ */ -void Cvar_SetROM (const char *var_name, const char *value) +void Cvar_SetROM(const char *var_name, const char *value) { - cvar_t *var = Cvar_FindVar (var_name); - if (var) + cvar_t *var = Cvar_FindVar(var_name); + if(var) { var->flags &= ~CVAR_ROM; - Cvar_SetQuick (var, value); + Cvar_SetQuick(var, value); var->flags |= CVAR_ROM; } } @@ -511,13 +512,13 @@ void Cvar_SetROM (const char *var_name, const char *value) Cvar_SetValueROM ============ */ -void Cvar_SetValueROM (const char *var_name, const float value) +void Cvar_SetValueROM(const char *var_name, const float value) { - cvar_t *var = Cvar_FindVar (var_name); - if (var) + cvar_t *var = Cvar_FindVar(var_name); + if(var) { var->flags &= ~CVAR_ROM; - Cvar_SetValueQuick (var, value); + Cvar_SetValueQuick(var, value); var->flags |= CVAR_ROM; } } @@ -529,30 +530,30 @@ Cvar_RegisterVariable Adds a freestanding variable to the variable list. ============ */ -void Cvar_RegisterVariable (cvar_t *variable) +void Cvar_RegisterVariable(cvar_t *variable) { - char value[512]; - bool set_rom; - cvar_t *cursor,*prev; //johnfitz -- sorted list insert + char value[512]; + bool set_rom; + cvar_t *cursor, *prev; //johnfitz -- sorted list insert // first check to see if it has already been defined - if (Cvar_FindVar (variable->name)) + if(Cvar_FindVar(variable->name)) { - Con_Printf ("Can't register variable %s, already defined\n", variable->name); + Con_Printf("Can't register variable %s, already defined\n", variable->name); return; } // check for overlap with a command - if (Cmd_Exists (variable->name)) + if(Cmd_Exists(variable->name)) { - Con_Printf ("Cvar_RegisterVariable: %s is a command\n", variable->name); + Con_Printf("Cvar_RegisterVariable: %s is a command\n", variable->name); return; } // link the variable in //johnfitz -- insert each entry in alphabetical order - if (cvar_vars == NULL || - strcmp(variable->name, cvar_vars->name) < 0) // insert at front + if(cvar_vars == NULL || + strcmp(variable->name, cvar_vars->name) < 0) // insert at front { variable->next = cvar_vars; cvar_vars = variable; @@ -561,7 +562,7 @@ void Cvar_RegisterVariable (cvar_t *variable) { prev = cvar_vars; cursor = cvar_vars->next; - while (cursor && (strcmp(variable->name, cursor->name) > 0)) + while(cursor && (strcmp(variable->name, cursor->name) > 0)) { prev = cursor; cursor = cursor->next; @@ -573,18 +574,18 @@ void Cvar_RegisterVariable (cvar_t *variable) variable->flags |= CVAR_REGISTERED; // copy the value off, because future sets will Z_Free it - q_strlcpy (value, variable->string, sizeof(value)); + q_strlcpy(value, variable->string, sizeof(value)); variable->string = NULL; variable->default_string = NULL; - if (!(variable->flags & CVAR_CALLBACK)) + if(!(variable->flags & CVAR_CALLBACK)) variable->callback = NULL; // set it through the function to be consistent set_rom = (variable->flags & CVAR_ROM); variable->flags &= ~CVAR_ROM; - Cvar_SetQuick (variable, value); - if (set_rom) + Cvar_SetQuick(variable, value); + if(set_rom) variable->flags |= CVAR_ROM; } @@ -595,12 +596,12 @@ Cvar_SetCallback Set a callback function to the var ============ */ -void Cvar_SetCallback (cvar_t *var, cvarcallback_t func) +void Cvar_SetCallback(cvar_t *var, cvarcallback_t func) { var->callback = func; - if (func) + if(func) var->flags |= CVAR_CALLBACK; - else var->flags &= ~CVAR_CALLBACK; + else var->flags &= ~CVAR_CALLBACK; } /* @@ -610,23 +611,23 @@ Cvar_Command Handles variable inspection and changing from the console ============ */ -bool Cvar_Command (void) +bool Cvar_Command(void) { - cvar_t *v; + cvar_t *v; // check variables - v = Cvar_FindVar (Cmd_Argv(0)); - if (!v) + v = Cvar_FindVar(Cmd_Argv(0)); + if(!v) return false; // perform a variable print or set - if (Cmd_Argc() == 1) + if(Cmd_Argc() == 1) { - Con_Printf ("\"%s\" is \"%s\"\n", v->name, v->string); + Con_Printf("\"%s\" is \"%s\"\n", v->name, v->string); return true; } - Cvar_Set (v->name, Cmd_Argv(1)); + Cvar_Set(v->name, Cmd_Argv(1)); return true; } @@ -639,14 +640,14 @@ Writes lines containing "set variable value" for all variables with the archive flag set to true. ============ */ -void Cvar_WriteVariables (FILE *f) +void Cvar_WriteVariables(FILE *f) { - cvar_t *var; + cvar_t *var; - for (var = cvar_vars ; var ; var = var->next) + for(var = cvar_vars ; var ; var = var->next) { - if (var->flags & CVAR_ARCHIVE) - fprintf (f, "%s \"%s\"\n", var->name, var->string); + if(var->flags & CVAR_ARCHIVE) + fprintf(f, "%s \"%s\"\n", var->name, var->string); } } diff --git a/source/cvar.h b/source/cvar.h index fdf4571..d1e00cd 100644 --- a/source/cvar.h +++ b/source/cvar.h @@ -32,8 +32,8 @@ it is sufficient to initialize a cvar_t with just the first two fields, or you can add a ,true flag for variables that you want saved to the configuration file when the game is quit: -cvar_t r_draworder = {"r_draworder","1"}; -cvar_t scr_screensize = {"screensize","1",true}; +cvar_t r_draworder = {"r_draworder","1"}; +cvar_t scr_screensize = {"screensize","1",true}; Cvars must be registered before use, or they will have a 0 value instead of the float interpretation of the string. @@ -55,89 +55,89 @@ teamplay = cvar("teamplay"); cvar_set ("registered", "1"); The user can access cvars from the console in two ways: -r_draworder prints the current value -r_draworder 0 sets the current value to 0 +r_draworder prints the current value +r_draworder 0 sets the current value to 0 Cvars are restricted from having the same names as commands to keep this interface from being ambiguous. */ -#define CVAR_NONE 0 -#define CVAR_ARCHIVE (1U << 0) // if set, causes it to be saved to config -#define CVAR_NOTIFY (1U << 1) // changes will be broadcasted to all players (q1) -#define CVAR_SERVERINFO (1U << 2) // added to serverinfo will be sent to clients (q1/net_dgrm.c and qwsv) -#define CVAR_USERINFO (1U << 3) // added to userinfo, will be sent to server (qwcl) -#define CVAR_CHANGED (1U << 4) -#define CVAR_ROM (1U << 6) -#define CVAR_LOCKED (1U << 8) // locked temporarily -#define CVAR_REGISTERED (1U << 10) // the var is added to the list of variables -#define CVAR_CALLBACK (1U << 16) // var has a callback +#define CVAR_NONE 0 +#define CVAR_ARCHIVE (1U << 0) // if set, causes it to be saved to config +#define CVAR_NOTIFY (1U << 1) // changes will be broadcasted to all players (q1) +#define CVAR_SERVERINFO (1U << 2) // added to serverinfo will be sent to clients (q1/net_dgrm.c and qwsv) +#define CVAR_USERINFO (1U << 3) // added to userinfo, will be sent to server (qwcl) +#define CVAR_CHANGED (1U << 4) +#define CVAR_ROM (1U << 6) +#define CVAR_LOCKED (1U << 8) // locked temporarily +#define CVAR_REGISTERED (1U << 10) // the var is added to the list of variables +#define CVAR_CALLBACK (1U << 16) // var has a callback -typedef void (*cvarcallback_t) (struct cvar_s *); +typedef void (*cvarcallback_t)(struct cvar_s *); typedef struct cvar_s { - const char *name; - const char *string; - uint32_t flags; - float value; - const char *default_string; //johnfitz -- remember defaults for reset function - cvarcallback_t callback; - struct cvar_s *next; + const char *name; + const char *string; + uint32_t flags; + float value; + const char *default_string; //johnfitz -- remember defaults for reset function + cvarcallback_t callback; + struct cvar_s *next; } cvar_t; -void Cvar_RegisterVariable (cvar_t *variable); +void Cvar_RegisterVariable(cvar_t *variable); // registers a cvar that already has the name, string, and optionally // the archive elements set. -void Cvar_SetCallback (cvar_t *var, cvarcallback_t func); +void Cvar_SetCallback(cvar_t *var, cvarcallback_t func); // set a callback function to the var -void Cvar_Set (const char *var_name, const char *value); +void Cvar_Set(const char *var_name, const char *value); // equivelant to " " typed at the console -void Cvar_SetValue (const char *var_name, const float value); +void Cvar_SetValue(const char *var_name, const float value); // expands value to a string and calls Cvar_Set -void Cvar_SetROM (const char *var_name, const char *value); -void Cvar_SetValueROM (const char *var_name, const float value); +void Cvar_SetROM(const char *var_name, const char *value); +void Cvar_SetValueROM(const char *var_name, const float value); // sets a CVAR_ROM variable from within the engine -void Cvar_SetQuick (cvar_t *var, const char *value); -void Cvar_SetValueQuick (cvar_t *var, const float value); +void Cvar_SetQuick(cvar_t *var, const char *value); +void Cvar_SetValueQuick(cvar_t *var, const float value); // these two accept a cvar pointer instead of a var name, // but are otherwise identical to the "non-Quick" versions. // the cvar MUST be registered. -float Cvar_VariableValue (const char *var_name); +float Cvar_VariableValue(const char *var_name); // returns 0 if not defined or non numeric -const char *Cvar_VariableString (const char *var_name); +const char *Cvar_VariableString(const char *var_name); // returns an empty string if not defined -bool Cvar_Command (void); +bool Cvar_Command(void); // called by Cmd_ExecuteString when Cmd_Argv(0) doesn't match a known // command. Returns true if the command was a variable reference that // was handled. (print or change) -void Cvar_WriteVariables (FILE *f); +void Cvar_WriteVariables(FILE *f); // Writes lines containing "set variable value" for all variables // with the CVAR_ARCHIVE flag set -cvar_t *Cvar_FindVar (const char *var_name); -cvar_t *Cvar_FindVarAfter (const char *prev_name, uint32_t with_flags); +cvar_t *Cvar_FindVar(const char *var_name); +cvar_t *Cvar_FindVarAfter(const char *prev_name, uint32_t with_flags); -void Cvar_LockVar (const char *var_name); -void Cvar_UnlockVar (const char *var_name); -void Cvar_UnlockAll (void); +void Cvar_LockVar(const char *var_name); +void Cvar_UnlockVar(const char *var_name); +void Cvar_UnlockAll(void); -void Cvar_Init (void); +void Cvar_Init(void); -const char *Cvar_CompleteVariable (const char *partial); +const char *Cvar_CompleteVariable(const char *partial); // attempts to match a partial variable name for command line completion // returns NULL if nothing fits -#endif /* __CVAR_H__ */ +#endif /* __CVAR_H__ */ diff --git a/source/draw.h b/source/draw.h index 23a8c3c..dc6a557 100644 --- a/source/draw.h +++ b/source/draw.h @@ -26,23 +26,23 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // draw.h -- these are the only functions outside the refresh allowed // to touch the vid buffer -extern qpic_t *draw_disc; // also used on sbar +extern qpic_t *draw_disc; // also used on sbar -void Draw_Init (void); -void Draw_Character (int32_t x, int32_t y, int32_t num); -void Draw_DebugChar (char num); -void Draw_Pic (int32_t x, int32_t y, qpic_t *pic); -void Draw_TransPicTranslate (int32_t x, int32_t y, qpic_t *pic, int32_t top, int32_t bottom); //johnfitz -- more parameters -void Draw_ConsoleBackground (void); //johnfitz -- removed parameter int32_t lines -void Draw_TileClear (int32_t x, int32_t y, int32_t w, int32_t h); -void Draw_Fill (int32_t x, int32_t y, int32_t w, int32_t h, int32_t c, float alpha); //johnfitz -- added alpha -void Draw_FadeScreen (void); -void Draw_String (int32_t x, int32_t y, const char *str); -qpic_t *Draw_PicFromWad (const char *name); -qpic_t *Draw_CachePic (const char *path); -void Draw_NewGame (void); +void Draw_Init(void); +void Draw_Character(int32_t x, int32_t y, int32_t num); +void Draw_DebugChar(char num); +void Draw_Pic(int32_t x, int32_t y, qpic_t *pic); +void Draw_TransPicTranslate(int32_t x, int32_t y, qpic_t *pic, int32_t top, int32_t bottom); //johnfitz -- more parameters +void Draw_ConsoleBackground(void); //johnfitz -- removed parameter int32_t lines +void Draw_TileClear(int32_t x, int32_t y, int32_t w, int32_t h); +void Draw_Fill(int32_t x, int32_t y, int32_t w, int32_t h, int32_t c, float alpha); //johnfitz -- added alpha +void Draw_FadeScreen(void); +void Draw_String(int32_t x, int32_t y, const char *str); +qpic_t *Draw_PicFromWad(const char *name); +qpic_t *Draw_CachePic(const char *path); +void Draw_NewGame(void); -void GL_SetCanvas (canvastype newcanvas); //johnfitz +void GL_SetCanvas(canvastype newcanvas); //johnfitz -#endif /* _QUAKE_DRAW_H */ +#endif /* _QUAKE_DRAW_H */ diff --git a/source/filenames.h b/source/filenames.h index 9e4c78f..fc23515 100644 --- a/source/filenames.h +++ b/source/filenames.h @@ -38,153 +38,171 @@ #define HAVE_DOS_BASED_FILE_SYSTEM 1 #define HAVE_CASE_INSENSITIVE_FILE_SYSTEM 1 -#define HAS_DRIVE_SPEC(f) ((f)[0] && ((f)[1] == ':')) -#define STRIP_DRIVE_SPEC(f) ((f) + 2) -#define IS_DIR_SEPARATOR(c) ((c) == '/' || (c) == '\\') +#define HAS_DRIVE_SPEC(f) ((f)[0] && ((f)[1] == ':')) +#define STRIP_DRIVE_SPEC(f) ((f) + 2) +#define IS_DIR_SEPARATOR(c) ((c) == '/' || (c) == '\\') /* both '/' and '\\' work as dir separator. djgpp likes changing * '\\' into '/', so I define DIR_SEPARATOR_CHAR as '/' for djgpp, * '\\' otherwise. */ #ifdef __DJGPP__ -#define DIR_SEPARATOR_CHAR '/' -#define DIR_SEPARATOR_STR "/" +#define DIR_SEPARATOR_CHAR '/' +#define DIR_SEPARATOR_STR "/" #else -#define DIR_SEPARATOR_CHAR '\\' -#define DIR_SEPARATOR_STR "\\" +#define DIR_SEPARATOR_CHAR '\\' +#define DIR_SEPARATOR_STR "\\" #endif /* Note that IS_ABSOLUTE_PATH accepts d:foo as well, although it is only semi-absolute. This is because the users of IS_ABSOLUTE_PATH want to know whether to prepend the current working directory to a file name, which should not be done with a name like d:foo. */ -#define IS_ABSOLUTE_PATH(f) (IS_DIR_SEPARATOR((f)[0]) || HAS_DRIVE_SPEC((f))) +#define IS_ABSOLUTE_PATH(f) (IS_DIR_SEPARATOR((f)[0]) || HAS_DRIVE_SPEC((f))) #ifdef __cplusplus -static inline char *FIND_FIRST_DIRSEP(char *_the_path) { -/* FIXME: What about C:FOO ? */ - char *p1 = strchr(_the_path, '/'); - char *p2 = strchr(_the_path, '\\'); - if (p1 == NULL) return p2; - if (p2 == NULL) return p1; - return (p1 < p2)? p1 : p2; +static inline char *FIND_FIRST_DIRSEP(char *_the_path) +{ + /* FIXME: What about C:FOO ? */ + char *p1 = strchr(_the_path, '/'); + char *p2 = strchr(_the_path, '\\'); + if(p1 == NULL) return p2; + if(p2 == NULL) return p1; + return (p1 < p2) ? p1 : p2; } -static inline char *FIND_LAST_DIRSEP (char *_the_path) { -/* FIXME: What about C:FOO ? */ - char *p1 = strrchr(_the_path, '/'); - char *p2 = strrchr(_the_path, '\\'); - if (p1 == NULL) return p2; - if (p2 == NULL) return p1; - return (p1 > p2)? p1 : p2; +static inline char *FIND_LAST_DIRSEP(char *_the_path) +{ + /* FIXME: What about C:FOO ? */ + char *p1 = strrchr(_the_path, '/'); + char *p2 = strrchr(_the_path, '\\'); + if(p1 == NULL) return p2; + if(p2 == NULL) return p1; + return (p1 > p2) ? p1 : p2; } -static inline const char *FIND_FIRST_DIRSEP(const char *_the_path) { -/* FIXME: What about C:FOO ? */ - const char *p1 = strchr(_the_path, '/'); - const char *p2 = strchr(_the_path, '\\'); - if (p1 == NULL) return p2; - if (p2 == NULL) return p1; - return (p1 < p2)? p1 : p2; +static inline const char *FIND_FIRST_DIRSEP(const char *_the_path) +{ + /* FIXME: What about C:FOO ? */ + const char *p1 = strchr(_the_path, '/'); + const char *p2 = strchr(_the_path, '\\'); + if(p1 == NULL) return p2; + if(p2 == NULL) return p1; + return (p1 < p2) ? p1 : p2; } -static inline const char *FIND_LAST_DIRSEP (const char *_the_path) { -/* FIXME: What about C:FOO ? */ - const char *p1 = strrchr(_the_path, '/'); - const char *p2 = strrchr(_the_path, '\\'); - if (p1 == NULL) return p2; - if (p2 == NULL) return p1; - return (p1 > p2)? p1 : p2; +static inline const char *FIND_LAST_DIRSEP(const char *_the_path) +{ + /* FIXME: What about C:FOO ? */ + const char *p1 = strrchr(_the_path, '/'); + const char *p2 = strrchr(_the_path, '\\'); + if(p1 == NULL) return p2; + if(p2 == NULL) return p1; + return (p1 > p2) ? p1 : p2; } #else -static inline char *FIND_FIRST_DIRSEP(const char *_the_path) { -/* FIXME: What about C:FOO ? */ - char *p1 = strchr(_the_path, '/'); - char *p2 = strchr(_the_path, '\\'); - if (p1 == NULL) return p2; - if (p2 == NULL) return p1; - return (p1 < p2)? p1 : p2; +static inline char *FIND_FIRST_DIRSEP(const char *_the_path) +{ + /* FIXME: What about C:FOO ? */ + char *p1 = strchr(_the_path, '/'); + char *p2 = strchr(_the_path, '\\'); + if(p1 == NULL) return p2; + if(p2 == NULL) return p1; + return (p1 < p2) ? p1 : p2; } -static inline char *FIND_LAST_DIRSEP (const char *_the_path) { -/* FIXME: What about C:FOO ? */ - char *p1 = strrchr(_the_path, '/'); - char *p2 = strrchr(_the_path, '\\'); - if (p1 == NULL) return p2; - if (p2 == NULL) return p1; - return (p1 > p2)? p1 : p2; +static inline char *FIND_LAST_DIRSEP(const char *_the_path) +{ + /* FIXME: What about C:FOO ? */ + char *p1 = strrchr(_the_path, '/'); + char *p2 = strrchr(_the_path, '\\'); + if(p1 == NULL) return p2; + if(p2 == NULL) return p1; + return (p1 > p2) ? p1 : p2; } #endif /* C++ */ /* ----------------- AmigaOS, MorphOS, AROS, etc: ----------------- */ -#elif defined(__MORPHOS__) || defined(__AROS__) || defined(AMIGAOS) || \ +#elif defined(__MORPHOS__) || defined(__AROS__) || defined(AMIGAOS) || \ defined(__amigaos__) || defined(__amigaos4__) ||defined(__amigados__) || \ defined(AMIGA) || defined(_AMIGA) || defined(__AMIGA__) -#define HAS_DRIVE_SPEC(f) (0) /* */ -#define STRIP_DRIVE_SPEC(f) (f) /* */ -#define IS_DIR_SEPARATOR(c) ((c) == '/' || (c) == ':') -#define DIR_SEPARATOR_CHAR '/' -#define DIR_SEPARATOR_STR "/" -#define IS_ABSOLUTE_PATH(f) (IS_DIR_SEPARATOR((f)[0]) || (strchr((f), ':'))) +#define HAS_DRIVE_SPEC(f) (0) /* */ +#define STRIP_DRIVE_SPEC(f) (f) /* */ +#define IS_DIR_SEPARATOR(c) ((c) == '/' || (c) == ':') +#define DIR_SEPARATOR_CHAR '/' +#define DIR_SEPARATOR_STR "/" +#define IS_ABSOLUTE_PATH(f) (IS_DIR_SEPARATOR((f)[0]) || (strchr((f), ':'))) #define HAVE_CASE_INSENSITIVE_FILE_SYSTEM 1 #ifdef __cplusplus -static inline char *FIND_FIRST_DIRSEP(char *_the_path) { - char *p = strchr(_the_path, ':'); - if (p != NULL) return p; - return strchr(_the_path, '/'); +static inline char *FIND_FIRST_DIRSEP(char *_the_path) +{ + char *p = strchr(_the_path, ':'); + if(p != NULL) return p; + return strchr(_the_path, '/'); } -static inline char *FIND_LAST_DIRSEP (char *_the_path) { - char *p = strrchr(_the_path, '/'); - if (p != NULL) return p; - return strchr(_the_path, ':'); +static inline char *FIND_LAST_DIRSEP(char *_the_path) +{ + char *p = strrchr(_the_path, '/'); + if(p != NULL) return p; + return strchr(_the_path, ':'); } -static inline const char *FIND_FIRST_DIRSEP(const char *_the_path) { - const char *p = strchr(_the_path, ':'); - if (p != NULL) return p; - return strchr(_the_path, '/'); +static inline const char *FIND_FIRST_DIRSEP(const char *_the_path) +{ + const char *p = strchr(_the_path, ':'); + if(p != NULL) return p; + return strchr(_the_path, '/'); } -static inline const char *FIND_LAST_DIRSEP (const char *_the_path) { - const char *p = strrchr(_the_path, '/'); - if (p != NULL) return p; - return strchr(_the_path, ':'); +static inline const char *FIND_LAST_DIRSEP(const char *_the_path) +{ + const char *p = strrchr(_the_path, '/'); + if(p != NULL) return p; + return strchr(_the_path, ':'); } #else -static inline char *FIND_FIRST_DIRSEP(const char *_the_path) { - char *p = strchr(_the_path, ':'); - if (p != NULL) return p; - return strchr(_the_path, '/'); +static inline char *FIND_FIRST_DIRSEP(const char *_the_path) +{ + char *p = strchr(_the_path, ':'); + if(p != NULL) return p; + return strchr(_the_path, '/'); } -static inline char *FIND_LAST_DIRSEP (const char *_the_path) { - char *p = strrchr(_the_path, '/'); - if (p != NULL) return p; - return strchr(_the_path, ':'); +static inline char *FIND_LAST_DIRSEP(const char *_the_path) +{ + char *p = strrchr(_the_path, '/'); + if(p != NULL) return p; + return strchr(_the_path, ':'); } #endif /* C++ */ /* ---------------------- assumed UNIX-ish : ---------------------- */ #else /* */ -#define IS_DIR_SEPARATOR(c) ((c) == '/') -#define DIR_SEPARATOR_CHAR '/' -#define DIR_SEPARATOR_STR "/" -#define IS_ABSOLUTE_PATH(f) (IS_DIR_SEPARATOR((f)[0])) -#define HAS_DRIVE_SPEC(f) (0) -#define STRIP_DRIVE_SPEC(f) (f) +#define IS_DIR_SEPARATOR(c) ((c) == '/') +#define DIR_SEPARATOR_CHAR '/' +#define DIR_SEPARATOR_STR "/" +#define IS_ABSOLUTE_PATH(f) (IS_DIR_SEPARATOR((f)[0])) +#define HAS_DRIVE_SPEC(f) (0) +#define STRIP_DRIVE_SPEC(f) (f) #ifdef __cplusplus -static inline char *FIND_FIRST_DIRSEP(char *_the_path) { - return strchr(_the_path, '/'); +static inline char *FIND_FIRST_DIRSEP(char *_the_path) +{ + return strchr(_the_path, '/'); } -static inline char *FIND_LAST_DIRSEP (char *_the_path) { - return strrchr(_the_path, '/'); +static inline char *FIND_LAST_DIRSEP(char *_the_path) +{ + return strrchr(_the_path, '/'); } -static inline const char *FIND_FIRST_DIRSEP(const char *_the_path) { - return strchr(_the_path, '/'); +static inline const char *FIND_FIRST_DIRSEP(const char *_the_path) +{ + return strchr(_the_path, '/'); } -static inline const char *FIND_LAST_DIRSEP (const char *_the_path) { - return strrchr(_the_path, '/'); +static inline const char *FIND_LAST_DIRSEP(const char *_the_path) +{ + return strrchr(_the_path, '/'); } #else -static inline char *FIND_FIRST_DIRSEP(const char *_the_path) { - return strchr(_the_path, '/'); +static inline char *FIND_FIRST_DIRSEP(const char *_the_path) +{ + return strchr(_the_path, '/'); } -static inline char *FIND_LAST_DIRSEP (const char *_the_path) { - return strrchr(_the_path, '/'); +static inline char *FIND_LAST_DIRSEP(const char *_the_path) +{ + return strrchr(_the_path, '/'); } #endif /* C++ */ diff --git a/source/gl_draw.c b/source/gl_draw.c index 9499702..1ddb1d9 100644 --- a/source/gl_draw.c +++ b/source/gl_draw.c @@ -27,82 +27,82 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //extern uint8_t d_15to8table[65536]; //johnfitz -- never used -cvar_t scr_conalpha = {"scr_conalpha", "0.5", CVAR_ARCHIVE}; //johnfitz +cvar_t scr_conalpha = {"scr_conalpha", "0.5", CVAR_ARCHIVE}; //johnfitz -qpic_t *draw_disc; -qpic_t *draw_backtile; +qpic_t *draw_disc; +qpic_t *draw_backtile; gltexture_t *char_texture; //johnfitz -qpic_t *pic_ovr, *pic_ins; //johnfitz -- new cursor handling -qpic_t *pic_nul; //johnfitz -- for missing gfx, don't crash +qpic_t *pic_ovr, *pic_ins; //johnfitz -- new cursor handling +qpic_t *pic_nul; //johnfitz -- for missing gfx, don't crash //johnfitz -- new pics byte pic_ovr_data[8][8] = { - {255,255,255,255,255,255,255,255}, - {255, 15, 15, 15, 15, 15, 15,255}, + {255, 255, 255, 255, 255, 255, 255, 255}, + {255, 15, 15, 15, 15, 15, 15, 255}, {255, 15, 15, 15, 15, 15, 15, 2}, {255, 15, 15, 15, 15, 15, 15, 2}, {255, 15, 15, 15, 15, 15, 15, 2}, {255, 15, 15, 15, 15, 15, 15, 2}, {255, 15, 15, 15, 15, 15, 15, 2}, - {255,255, 2, 2, 2, 2, 2, 2}, + {255, 255, 2, 2, 2, 2, 2, 2}, }; byte pic_ins_data[9][8] = { - { 15, 15,255,255,255,255,255,255}, - { 15, 15, 2,255,255,255,255,255}, - { 15, 15, 2,255,255,255,255,255}, - { 15, 15, 2,255,255,255,255,255}, - { 15, 15, 2,255,255,255,255,255}, - { 15, 15, 2,255,255,255,255,255}, - { 15, 15, 2,255,255,255,255,255}, - { 15, 15, 2,255,255,255,255,255}, - {255, 2, 2,255,255,255,255,255}, + { 15, 15, 255, 255, 255, 255, 255, 255}, + { 15, 15, 2, 255, 255, 255, 255, 255}, + { 15, 15, 2, 255, 255, 255, 255, 255}, + { 15, 15, 2, 255, 255, 255, 255, 255}, + { 15, 15, 2, 255, 255, 255, 255, 255}, + { 15, 15, 2, 255, 255, 255, 255, 255}, + { 15, 15, 2, 255, 255, 255, 255, 255}, + { 15, 15, 2, 255, 255, 255, 255, 255}, + {255, 2, 2, 255, 255, 255, 255, 255}, }; byte pic_nul_data[8][8] = { - {252,252,252,252, 0, 0, 0, 0}, - {252,252,252,252, 0, 0, 0, 0}, - {252,252,252,252, 0, 0, 0, 0}, - {252,252,252,252, 0, 0, 0, 0}, - { 0, 0, 0, 0,252,252,252,252}, - { 0, 0, 0, 0,252,252,252,252}, - { 0, 0, 0, 0,252,252,252,252}, - { 0, 0, 0, 0,252,252,252,252}, + {252, 252, 252, 252, 0, 0, 0, 0}, + {252, 252, 252, 252, 0, 0, 0, 0}, + {252, 252, 252, 252, 0, 0, 0, 0}, + {252, 252, 252, 252, 0, 0, 0, 0}, + { 0, 0, 0, 0, 252, 252, 252, 252}, + { 0, 0, 0, 0, 252, 252, 252, 252}, + { 0, 0, 0, 0, 252, 252, 252, 252}, + { 0, 0, 0, 0, 252, 252, 252, 252}, }; byte pic_stipple_data[8][8] = { - {255, 0, 0, 0,255, 0, 0, 0}, - { 0, 0,255, 0, 0, 0,255, 0}, - {255, 0, 0, 0,255, 0, 0, 0}, - { 0, 0,255, 0, 0, 0,255, 0}, - {255, 0, 0, 0,255, 0, 0, 0}, - { 0, 0,255, 0, 0, 0,255, 0}, - {255, 0, 0, 0,255, 0, 0, 0}, - { 0, 0,255, 0, 0, 0,255, 0}, + {255, 0, 0, 0, 255, 0, 0, 0}, + { 0, 0, 255, 0, 0, 0, 255, 0}, + {255, 0, 0, 0, 255, 0, 0, 0}, + { 0, 0, 255, 0, 0, 0, 255, 0}, + {255, 0, 0, 0, 255, 0, 0, 0}, + { 0, 0, 255, 0, 0, 0, 255, 0}, + {255, 0, 0, 0, 255, 0, 0, 0}, + { 0, 0, 255, 0, 0, 0, 255, 0}, }; byte pic_crosshair_data[8][8] = { - {255,255,255,255,255,255,255,255}, - {255,255,255, 8, 9,255,255,255}, - {255,255,255, 6, 8, 2,255,255}, - {255, 6, 8, 8, 6, 8, 8,255}, - {255,255, 2, 8, 8, 2, 2, 2}, - {255,255,255, 7, 8, 2,255,255}, - {255,255,255,255, 2, 2,255,255}, - {255,255,255,255,255,255,255,255}, + {255, 255, 255, 255, 255, 255, 255, 255}, + {255, 255, 255, 8, 9, 255, 255, 255}, + {255, 255, 255, 6, 8, 2, 255, 255}, + {255, 6, 8, 8, 6, 8, 8, 255}, + {255, 255, 2, 8, 8, 2, 2, 2}, + {255, 255, 255, 7, 8, 2, 255, 255}, + {255, 255, 255, 255, 2, 2, 255, 255}, + {255, 255, 255, 255, 255, 255, 255, 255}, }; //johnfitz typedef struct { gltexture_t *gltexture; - float sl, tl, sh, th; + float sl, tl, sh, th; } glpic_t; canvastype currentcanvas = CANVAS_NONE; //johnfitz -- for GL_SetCanvas @@ -115,29 +115,29 @@ canvastype currentcanvas = CANVAS_NONE; //johnfitz -- for GL_SetCanvas typedef struct cachepic_s { - char name[MAX_QPATH]; - qpic_t pic; - byte padding[32]; // for appended glpic + char name[MAX_QPATH]; + qpic_t pic; + byte padding[32]; // for appended glpic } cachepic_t; -#define MAX_CACHED_PICS 128 -cachepic_t menu_cachepics[MAX_CACHED_PICS]; -int32_t menu_numcachepics; +#define MAX_CACHED_PICS 128 +cachepic_t menu_cachepics[MAX_CACHED_PICS]; +int32_t menu_numcachepics; -byte menuplyr_pixels[4096]; +byte menuplyr_pixels[4096]; // scrap allocation // Allocate all the little status bar obejcts into a single texture // to crutch up stupid hardware / drivers -#define MAX_SCRAPS 2 -#define BLOCK_WIDTH 256 -#define BLOCK_HEIGHT 256 +#define MAX_SCRAPS 2 +#define BLOCK_WIDTH 256 +#define BLOCK_HEIGHT 256 -int32_t scrap_allocated[MAX_SCRAPS][BLOCK_WIDTH]; -byte scrap_texels[MAX_SCRAPS][BLOCK_WIDTH*BLOCK_HEIGHT]; //johnfitz -- removed *4 after BLOCK_HEIGHT -bool scrap_dirty; -gltexture_t *scrap_textures[MAX_SCRAPS]; //johnfitz +int32_t scrap_allocated[MAX_SCRAPS][BLOCK_WIDTH]; +byte scrap_texels[MAX_SCRAPS][BLOCK_WIDTH * BLOCK_HEIGHT]; //johnfitz -- removed *4 after BLOCK_HEIGHT +bool scrap_dirty; +gltexture_t *scrap_textures[MAX_SCRAPS]; //johnfitz /* @@ -147,44 +147,45 @@ Scrap_AllocBlock returns an index into scrap_texnums[] and the position inside it ================ */ -int32_t Scrap_AllocBlock (int32_t w, int32_t h, int32_t *x, int32_t *y) +int32_t Scrap_AllocBlock(int32_t w, int32_t h, int32_t *x, int32_t *y) { - int32_t i, j; - int32_t best, best2; - int32_t texnum; + int32_t i, j; + int32_t best, best2; + int32_t texnum; - for (texnum=0 ; texnum= best) + if(scrap_allocated[texnum][i + j] >= best) break; - if (scrap_allocated[texnum][i+j] > best2) - best2 = scrap_allocated[texnum][i+j]; + if(scrap_allocated[texnum][i + j] > best2) + best2 = scrap_allocated[texnum][i + j]; } - if (j == w) - { // this is a valid spot + if(j == w) + { + // this is a valid spot *x = i; *y = best = best2; } } - if (best + h > BLOCK_HEIGHT) + if(best + h > BLOCK_HEIGHT) continue; - for (i=0 ; iwidth < 64 && p->height < 64) + if(p->width < 64 && p->height < 64) { - int32_t x, y; - int32_t i, j, k; - int32_t texnum; + int32_t x, y; + int32_t i, j, k; + int32_t texnum; - texnum = Scrap_AllocBlock (p->width, p->height, &x, &y); + texnum = Scrap_AllocBlock(p->width, p->height, &x, &y); scrap_dirty = true; k = 0; - for (i=0 ; iheight ; i++) + for(i = 0 ; i < p->height ; i++) { - for (j=0 ; jwidth ; j++, k++) - scrap_texels[texnum][(y+i)*BLOCK_WIDTH + x + j] = p->data[k]; + for(j = 0 ; j < p->width ; j++, k++) + scrap_texels[texnum][(y + i)*BLOCK_WIDTH + x + j] = p->data[k]; } gl.gltexture = scrap_textures[texnum]; //johnfitz -- changed to an array //johnfitz -- no longer go from 0.01 to 0.99 - gl.sl = x/(float)BLOCK_WIDTH; - gl.sh = (x+p->width)/(float)BLOCK_WIDTH; - gl.tl = y/(float)BLOCK_WIDTH; - gl.th = (y+p->height)/(float)BLOCK_WIDTH; + gl.sl = x / (float)BLOCK_WIDTH; + gl.sh = (x + p->width) / (float)BLOCK_WIDTH; + gl.tl = y / (float)BLOCK_WIDTH; + gl.th = (y + p->height) / (float)BLOCK_WIDTH; } else { char texturename[64]; //johnfitz - q_snprintf (texturename, sizeof(texturename), "%s:%s", WADFILENAME, name); //johnfitz + q_snprintf(texturename, sizeof(texturename), "%s:%s", WADFILENAME, name); //johnfitz - offset = (src_offset_t)p - (src_offset_t)wad_base + sizeof(int32_t)*2; //johnfitz + offset = (src_offset_t)p - (src_offset_t)wad_base + sizeof(int32_t) * 2; //johnfitz - gl.gltexture = TexMgr_LoadImage (NULL, texturename, p->width, p->height, SRC_INDEXED, p->data, WADFILENAME, - offset, TEXPREF_ALPHA | TEXPREF_PAD | TEXPREF_NOPICMIP); //johnfitz -- TexMgr + gl.gltexture = TexMgr_LoadImage(NULL, texturename, p->width, p->height, SRC_INDEXED, p->data, WADFILENAME, + offset, TEXPREF_ALPHA | TEXPREF_PAD | TEXPREF_NOPICMIP); //johnfitz -- TexMgr gl.sl = 0; - gl.sh = (float)p->width/(float)TexMgr_PadConditional(p->width); //johnfitz + gl.sh = (float)p->width / (float)TexMgr_PadConditional(p->width); //johnfitz gl.tl = 0; - gl.th = (float)p->height/(float)TexMgr_PadConditional(p->height); //johnfitz + gl.th = (float)p->height / (float)TexMgr_PadConditional(p->height); //johnfitz } - memcpy (p->data, &gl, sizeof(glpic_t)); + memcpy(p->data, &gl, sizeof(glpic_t)); return p; } @@ -269,47 +270,47 @@ qpic_t *Draw_PicFromWad (const char *name) Draw_CachePic ================ */ -qpic_t *Draw_CachePic (const char *path) +qpic_t *Draw_CachePic(const char *path) { - cachepic_t *pic; - int32_t i; - qpic_t *dat; - glpic_t gl; + cachepic_t *pic; + int32_t i; + qpic_t *dat; + glpic_t gl; - for (pic=menu_cachepics, i=0 ; iname)) + if(!strcmp(path, pic->name)) return &pic->pic; } - if (menu_numcachepics == MAX_CACHED_PICS) - Sys_Error ("menu_numcachepics == MAX_CACHED_PICS"); + if(menu_numcachepics == MAX_CACHED_PICS) + Sys_Error("menu_numcachepics == MAX_CACHED_PICS"); menu_numcachepics++; - strcpy (pic->name, path); + strcpy(pic->name, path); // // load the pic from disk // - dat = (qpic_t *)COM_LoadTempFile (path, NULL); - if (!dat) - Sys_Error ("Draw_CachePic: failed to load %s", path); - SwapPic (dat); + dat = (qpic_t *)COM_LoadTempFile(path, NULL); + if(!dat) + Sys_Error("Draw_CachePic: failed to load %s", path); + SwapPic(dat); // HACK HACK HACK --- we need to keep the bytes for // the translatable player picture just for the menu // configuration dialog - if (!strcmp (path, "gfx/menuplyr.lmp")) - memcpy (menuplyr_pixels, dat->data, dat->width*dat->height); + if(!strcmp(path, "gfx/menuplyr.lmp")) + memcpy(menuplyr_pixels, dat->data, dat->width * dat->height); pic->pic.width = dat->width; pic->pic.height = dat->height; - gl.gltexture = TexMgr_LoadImage (NULL, path, dat->width, dat->height, SRC_INDEXED, dat->data, path, - sizeof(int32_t)*2, TEXPREF_ALPHA | TEXPREF_PAD | TEXPREF_NOPICMIP); //johnfitz -- TexMgr + gl.gltexture = TexMgr_LoadImage(NULL, path, dat->width, dat->height, SRC_INDEXED, dat->data, path, + sizeof(int32_t) * 2, TEXPREF_ALPHA | TEXPREF_PAD | TEXPREF_NOPICMIP); //johnfitz -- TexMgr gl.sl = 0; - gl.sh = (float)dat->width/(float)TexMgr_PadConditional(dat->width); //johnfitz + gl.sh = (float)dat->width / (float)TexMgr_PadConditional(dat->width); //johnfitz gl.tl = 0; - gl.th = (float)dat->height/(float)TexMgr_PadConditional(dat->height); //johnfitz - memcpy (pic->pic.data, &gl, sizeof(glpic_t)); + gl.th = (float)dat->height / (float)TexMgr_PadConditional(dat->height); //johnfitz + memcpy(pic->pic.data, &gl, sizeof(glpic_t)); return &pic->pic; } @@ -319,22 +320,22 @@ qpic_t *Draw_CachePic (const char *path) Draw_MakePic -- johnfitz -- generate pics from internal data ================ */ -qpic_t *Draw_MakePic (const char *name, int32_t width, int32_t height, byte *data) +qpic_t *Draw_MakePic(const char *name, int32_t width, int32_t height, byte *data) { int32_t flags = TEXPREF_NEAREST | TEXPREF_ALPHA | TEXPREF_PERSIST | TEXPREF_NOPICMIP | TEXPREF_PAD; - qpic_t *pic; - glpic_t gl; + qpic_t *pic; + glpic_t gl; - pic = (qpic_t *) Hunk_Alloc (sizeof(qpic_t) - 4 + sizeof (glpic_t)); + pic = (qpic_t *) Hunk_Alloc(sizeof(qpic_t) - 4 + sizeof(glpic_t)); pic->width = width; pic->height = height; - gl.gltexture = TexMgr_LoadImage (NULL, name, width, height, SRC_INDEXED, data, "", (src_offset_t)data, flags); + gl.gltexture = TexMgr_LoadImage(NULL, name, width, height, SRC_INDEXED, data, "", (src_offset_t)data, flags); gl.sl = 0; - gl.sh = (float)width/(float)TexMgr_PadConditional(width); + gl.sh = (float)width / (float)TexMgr_PadConditional(width); gl.tl = 0; - gl.th = (float)height/(float)TexMgr_PadConditional(height); - memcpy (pic->data, &gl, sizeof(glpic_t)); + gl.th = (float)height / (float)TexMgr_PadConditional(height); + memcpy(pic->data, &gl, sizeof(glpic_t)); return pic; } @@ -350,19 +351,19 @@ qpic_t *Draw_MakePic (const char *name, int32_t width, int32_t height, byte *dat Draw_LoadPics -- johnfitz =============== */ -void Draw_LoadPics (void) +void Draw_LoadPics(void) { - byte *data; - src_offset_t offset; + byte *data; + src_offset_t offset; - data = (byte *) W_GetLumpName ("conchars"); - if (!data) Sys_Error ("Draw_LoadPics: couldn't load conchars"); + data = (byte *) W_GetLumpName("conchars"); + if(!data) Sys_Error("Draw_LoadPics: couldn't load conchars"); offset = (src_offset_t)data - (src_offset_t)wad_base; - char_texture = TexMgr_LoadImage (NULL, WADFILENAME":conchars", 128, 128, SRC_INDEXED, data, - WADFILENAME, offset, TEXPREF_ALPHA | TEXPREF_NEAREST | TEXPREF_NOPICMIP | TEXPREF_CONCHARS); + char_texture = TexMgr_LoadImage(NULL, WADFILENAME":conchars", 128, 128, SRC_INDEXED, data, + WADFILENAME, offset, TEXPREF_ALPHA | TEXPREF_NEAREST | TEXPREF_NOPICMIP | TEXPREF_CONCHARS); - draw_disc = Draw_PicFromWad ("disc"); - draw_backtile = Draw_PicFromWad ("backtile"); + draw_disc = Draw_PicFromWad("disc"); + draw_backtile = Draw_PicFromWad("backtile"); } /* @@ -370,25 +371,25 @@ void Draw_LoadPics (void) Draw_NewGame -- johnfitz =============== */ -void Draw_NewGame (void) +void Draw_NewGame(void) { - cachepic_t *pic; - int32_t i; + cachepic_t *pic; + int32_t i; // empty scrap and reallocate gltextures memset(scrap_allocated, 0, sizeof(scrap_allocated)); memset(scrap_texels, 255, sizeof(scrap_texels)); - Scrap_Upload (); //creates 2 empty gltextures + Scrap_Upload(); //creates 2 empty gltextures // reload wad pics - W_LoadWadFile (); //johnfitz -- filename is now hard-coded for honesty - Draw_LoadPics (); - SCR_LoadPics (); - Sbar_LoadPics (); + W_LoadWadFile(); //johnfitz -- filename is now hard-coded for honesty + Draw_LoadPics(); + SCR_LoadPics(); + Sbar_LoadPics(); // empty lmp cache - for (pic = menu_cachepics, i = 0; i < menu_numcachepics; pic++, i++) + for(pic = menu_cachepics, i = 0; i < menu_numcachepics; pic++, i++) pic->name[0] = 0; menu_numcachepics = 0; } @@ -398,23 +399,23 @@ void Draw_NewGame (void) Draw_Init -- johnfitz -- rewritten =============== */ -void Draw_Init (void) +void Draw_Init(void) { - Cvar_RegisterVariable (&scr_conalpha); + Cvar_RegisterVariable(&scr_conalpha); // clear scrap and allocate gltextures memset(scrap_allocated, 0, sizeof(scrap_allocated)); memset(scrap_texels, 255, sizeof(scrap_texels)); - Scrap_Upload (); //creates 2 empty textures + Scrap_Upload(); //creates 2 empty textures // create internal pics - pic_ins = Draw_MakePic ("ins", 8, 9, &pic_ins_data[0][0]); - pic_ovr = Draw_MakePic ("ovr", 8, 8, &pic_ovr_data[0][0]); - pic_nul = Draw_MakePic ("nul", 8, 8, &pic_nul_data[0][0]); + pic_ins = Draw_MakePic("ins", 8, 9, &pic_ins_data[0][0]); + pic_ovr = Draw_MakePic("ovr", 8, 8, &pic_ovr_data[0][0]); + pic_nul = Draw_MakePic("nul", 8, 8, &pic_nul_data[0][0]); // load game pics - Draw_LoadPics (); + Draw_LoadPics(); } //============================================================================== @@ -428,26 +429,26 @@ void Draw_Init (void) Draw_CharacterQuad -- johnfitz -- seperate function to spit out verts ================ */ -void Draw_CharacterQuad (int32_t x, int32_t y, char num) +void Draw_CharacterQuad(int32_t x, int32_t y, char num) { - int32_t row, col; - float frow, fcol, size; + int32_t row, col; + float frow, fcol, size; - row = num>>4; - col = num&15; + row = num >> 4; + col = num & 15; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.0625; - glTexCoord2f (fcol, frow); - glVertex2f (x, y); - glTexCoord2f (fcol + size, frow); - glVertex2f (x+8, y); - glTexCoord2f (fcol + size, frow + size); - glVertex2f (x+8, y+8); - glTexCoord2f (fcol, frow + size); - glVertex2f (x, y+8); + glTexCoord2f(fcol, frow); + glVertex2f(x, y); + glTexCoord2f(fcol + size, frow); + glVertex2f(x + 8, y); + glTexCoord2f(fcol + size, frow + size); + glVertex2f(x + 8, y + 8); + glTexCoord2f(fcol, frow + size); + glVertex2f(x, y + 8); } /* @@ -455,22 +456,22 @@ void Draw_CharacterQuad (int32_t x, int32_t y, char num) Draw_Character -- johnfitz -- modified to call Draw_CharacterQuad ================ */ -void Draw_Character (int32_t x, int32_t y, int32_t num) +void Draw_Character(int32_t x, int32_t y, int32_t num) { - if (y <= -8) - return; // totally off screen + if(y <= -8) + return; // totally off screen num &= 255; - if (num == 32) + if(num == 32) return; //don't waste verts on spaces - GL_Bind (char_texture); - glBegin (GL_QUADS); + GL_Bind(char_texture); + glBegin(GL_QUADS); - Draw_CharacterQuad (x, y, (char) num); + Draw_CharacterQuad(x, y, (char) num); - glEnd (); + glEnd(); } /* @@ -478,23 +479,23 @@ void Draw_Character (int32_t x, int32_t y, int32_t num) Draw_String -- johnfitz -- modified to call Draw_CharacterQuad ================ */ -void Draw_String (int32_t x, int32_t y, const char *str) +void Draw_String(int32_t x, int32_t y, const char *str) { - if (y <= -8) - return; // totally off screen + if(y <= -8) + return; // totally off screen - GL_Bind (char_texture); - glBegin (GL_QUADS); + GL_Bind(char_texture); + glBegin(GL_QUADS); - while (*str) + while(*str) { - if (*str != 32) //don't waste verts on spaces - Draw_CharacterQuad (x, y, *str); + if(*str != 32) //don't waste verts on spaces + Draw_CharacterQuad(x, y, *str); str++; x += 8; } - glEnd (); + glEnd(); } /* @@ -502,24 +503,24 @@ void Draw_String (int32_t x, int32_t y, const char *str) Draw_Pic -- johnfitz -- modified ============= */ -void Draw_Pic (int32_t x, int32_t y, qpic_t *pic) +void Draw_Pic(int32_t x, int32_t y, qpic_t *pic) { - glpic_t *gl; + glpic_t *gl; - if (scrap_dirty) - Scrap_Upload (); + if(scrap_dirty) + Scrap_Upload(); gl = (glpic_t *)pic->data; - GL_Bind (gl->gltexture); - glBegin (GL_QUADS); - glTexCoord2f (gl->sl, gl->tl); - glVertex2f (x, y); - glTexCoord2f (gl->sh, gl->tl); - glVertex2f (x+pic->width, y); - glTexCoord2f (gl->sh, gl->th); - glVertex2f (x+pic->width, y+pic->height); - glTexCoord2f (gl->sl, gl->th); - glVertex2f (x, y+pic->height); - glEnd (); + GL_Bind(gl->gltexture); + glBegin(GL_QUADS); + glTexCoord2f(gl->sl, gl->tl); + glVertex2f(x, y); + glTexCoord2f(gl->sh, gl->tl); + glVertex2f(x + pic->width, y); + glTexCoord2f(gl->sh, gl->th); + glVertex2f(x + pic->width, y + pic->height); + glTexCoord2f(gl->sl, gl->th); + glVertex2f(x, y + pic->height); + glEnd(); } /* @@ -529,20 +530,20 @@ Draw_TransPicTranslate -- johnfitz -- rewritten to use texmgr to do translation Only used for the player color selection menu ============= */ -void Draw_TransPicTranslate (int32_t x, int32_t y, qpic_t *pic, int32_t top, int32_t bottom) +void Draw_TransPicTranslate(int32_t x, int32_t y, qpic_t *pic, int32_t top, int32_t bottom) { static int32_t oldtop = -2; static int32_t oldbottom = -2; - if (top != oldtop || bottom != oldbottom) + if(top != oldtop || bottom != oldbottom) { glpic_t *p = (glpic_t *)pic->data; gltexture_t *glt = p->gltexture; oldtop = top; oldbottom = bottom; - TexMgr_ReloadImage (glt, top, bottom); + TexMgr_ReloadImage(glt, top, bottom); } - Draw_Pic (x, y, pic); + Draw_Pic(x, y, pic); } /* @@ -550,37 +551,37 @@ void Draw_TransPicTranslate (int32_t x, int32_t y, qpic_t *pic, int32_t top, int Draw_ConsoleBackground -- johnfitz -- rewritten ================ */ -void Draw_ConsoleBackground (void) +void Draw_ConsoleBackground(void) { qpic_t *pic; float alpha; - pic = Draw_CachePic ("gfx/conback.lmp"); + pic = Draw_CachePic("gfx/conback.lmp"); pic->width = vid.conwidth; pic->height = vid.conheight; alpha = (con_forcedup) ? 1.0 : scr_conalpha.value; - GL_SetCanvas (CANVAS_CONSOLE); //in case this is called from weird places + GL_SetCanvas(CANVAS_CONSOLE); //in case this is called from weird places - if (alpha > 0.0) + if(alpha > 0.0) { - if (alpha < 1.0) + if(alpha < 1.0) { - glEnable (GL_BLEND); - glColor4f (1,1,1,alpha); - glDisable (GL_ALPHA_TEST); + glEnable(GL_BLEND); + glColor4f(1, 1, 1, alpha); + glDisable(GL_ALPHA_TEST); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } - Draw_Pic (0, 0, pic); + Draw_Pic(0, 0, pic); - if (alpha < 1.0) + if(alpha < 1.0) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glEnable (GL_ALPHA_TEST); - glDisable (GL_BLEND); - glColor4f (1,1,1,1); + glEnable(GL_ALPHA_TEST); + glDisable(GL_BLEND); + glColor4f(1, 1, 1, 1); } } } @@ -594,24 +595,24 @@ This repeats a 64*64 tile graphic to fill the screen around a sized down refresh window. ============= */ -void Draw_TileClear (int32_t x, int32_t y, int32_t w, int32_t h) +void Draw_TileClear(int32_t x, int32_t y, int32_t w, int32_t h) { - glpic_t *gl; + glpic_t *gl; gl = (glpic_t *)draw_backtile->data; - glColor3f (1,1,1); - GL_Bind (gl->gltexture); - glBegin (GL_QUADS); - glTexCoord2f (x/64.0, y/64.0); - glVertex2f (x, y); - glTexCoord2f ( (x+w)/64.0, y/64.0); - glVertex2f (x+w, y); - glTexCoord2f ( (x+w)/64.0, (y+h)/64.0); - glVertex2f (x+w, y+h); - glTexCoord2f ( x/64.0, (y+h)/64.0 ); - glVertex2f (x, y+h); - glEnd (); + glColor3f(1, 1, 1); + GL_Bind(gl->gltexture); + glBegin(GL_QUADS); + glTexCoord2f(x / 64.0, y / 64.0); + glVertex2f(x, y); + glTexCoord2f((x + w) / 64.0, y / 64.0); + glVertex2f(x + w, y); + glTexCoord2f((x + w) / 64.0, (y + h) / 64.0); + glVertex2f(x + w, y + h); + glTexCoord2f(x / 64.0, (y + h) / 64.0); + glVertex2f(x, y + h); + glEnd(); } /* @@ -621,26 +622,26 @@ Draw_Fill Fills a box of pixels with a single color ============= */ -void Draw_Fill (int32_t x, int32_t y, int32_t w, int32_t h, int32_t c, float alpha) //johnfitz -- added alpha +void Draw_Fill(int32_t x, int32_t y, int32_t w, int32_t h, int32_t c, float alpha) //johnfitz -- added alpha { byte *pal = (byte *)d_8to24table; //johnfitz -- use d_8to24table instead of host_basepal - glDisable (GL_TEXTURE_2D); - glEnable (GL_BLEND); //johnfitz -- for alpha - glDisable (GL_ALPHA_TEST); //johnfitz -- for alpha - glColor4f (pal[c*4]/255.0, pal[c*4+1]/255.0, pal[c*4+2]/255.0, alpha); //johnfitz -- added alpha + glDisable(GL_TEXTURE_2D); + glEnable(GL_BLEND); //johnfitz -- for alpha + glDisable(GL_ALPHA_TEST); //johnfitz -- for alpha + glColor4f(pal[c * 4] / 255.0, pal[c * 4 + 1] / 255.0, pal[c * 4 + 2] / 255.0, alpha); //johnfitz -- added alpha - glBegin (GL_QUADS); - glVertex2f (x,y); - glVertex2f (x+w, y); - glVertex2f (x+w, y+h); - glVertex2f (x, y+h); - glEnd (); + glBegin(GL_QUADS); + glVertex2f(x, y); + glVertex2f(x + w, y); + glVertex2f(x + w, y + h); + glVertex2f(x, y + h); + glEnd(); - glColor3f (1,1,1); - glDisable (GL_BLEND); //johnfitz -- for alpha - glEnable (GL_ALPHA_TEST); //johnfitz -- for alpha - glEnable (GL_TEXTURE_2D); + glColor3f(1, 1, 1); + glDisable(GL_BLEND); //johnfitz -- for alpha + glEnable(GL_ALPHA_TEST); //johnfitz -- for alpha + glEnable(GL_TEXTURE_2D); } /* @@ -648,26 +649,26 @@ void Draw_Fill (int32_t x, int32_t y, int32_t w, int32_t h, int32_t c, float alp Draw_FadeScreen -- johnfitz -- revised ================ */ -void Draw_FadeScreen (void) +void Draw_FadeScreen(void) { - GL_SetCanvas (CANVAS_DEFAULT); + GL_SetCanvas(CANVAS_DEFAULT); - glEnable (GL_BLEND); - glDisable (GL_ALPHA_TEST); - glDisable (GL_TEXTURE_2D); - glColor4f (0, 0, 0, 0.5); - glBegin (GL_QUADS); + glEnable(GL_BLEND); + glDisable(GL_ALPHA_TEST); + glDisable(GL_TEXTURE_2D); + glColor4f(0, 0, 0, 0.5); + glBegin(GL_QUADS); - glVertex2f (0,0); - glVertex2f (glwidth, 0); - glVertex2f (glwidth, glheight); - glVertex2f (0, glheight); + glVertex2f(0, 0); + glVertex2f(glwidth, 0); + glVertex2f(glwidth, glheight); + glVertex2f(0, glheight); - glEnd (); - glColor4f (1,1,1,1); - glEnable (GL_TEXTURE_2D); - glEnable (GL_ALPHA_TEST); - glDisable (GL_BLEND); + glEnd(); + glColor4f(1, 1, 1, 1); + glEnable(GL_TEXTURE_2D); + glEnable(GL_ALPHA_TEST); + glDisable(GL_BLEND); Sbar_Changed(); } @@ -677,81 +678,81 @@ void Draw_FadeScreen (void) GL_SetCanvas -- johnfitz -- support various canvas types ================ */ -void GL_SetCanvas (canvastype newcanvas) +void GL_SetCanvas(canvastype newcanvas) { extern vrect_t scr_vrect; float s; int32_t lines; - if (newcanvas == currentcanvas) + if(newcanvas == currentcanvas) return; currentcanvas = newcanvas; glMatrixMode(GL_PROJECTION); - glLoadIdentity (); + glLoadIdentity(); switch(newcanvas) { case CANVAS_DEFAULT: - glOrtho (0, glwidth, glheight, 0, -99999, 99999); - glViewport (glx, gly, glwidth, glheight); + glOrtho(0, glwidth, glheight, 0, -99999, 99999); + glViewport(glx, gly, glwidth, glheight); break; case CANVAS_CONSOLE: lines = vid.conheight - (scr_con_current * vid.conheight / glheight); - glOrtho (0, vid.conwidth, vid.conheight + lines, lines, -99999, 99999); - glViewport (glx, gly, glwidth, glheight); + glOrtho(0, vid.conwidth, vid.conheight + lines, lines, -99999, 99999); + glViewport(glx, gly, glwidth, glheight); break; case CANVAS_MENU: s = q_min((float)glwidth / 320.0, (float)glheight / 200.0); - s = CLAMP (1.0, scr_menuscale.value, s); + s = CLAMP(1.0, scr_menuscale.value, s); // ericw -- doubled width to 640 to accommodate long keybindings - glOrtho (0, 640, 200, 0, -99999, 99999); - glViewport (glx + (glwidth - 320*s) / 2, gly + (glheight - 200*s) / 2, 640*s, 200*s); + glOrtho(0, 640, 200, 0, -99999, 99999); + glViewport(glx + (glwidth - 320 * s) / 2, gly + (glheight - 200 * s) / 2, 640 * s, 200 * s); break; case CANVAS_SBAR: - s = CLAMP (1.0, scr_sbarscale.value, (float)glwidth / 320.0); - if (cl.gametype == GAME_DEATHMATCH) + s = CLAMP(1.0, scr_sbarscale.value, (float)glwidth / 320.0); + if(cl.gametype == GAME_DEATHMATCH) { - glOrtho (0, glwidth / s, 48, 0, -99999, 99999); - glViewport (glx, gly, glwidth, 48*s); + glOrtho(0, glwidth / s, 48, 0, -99999, 99999); + glViewport(glx, gly, glwidth, 48 * s); } else { - glOrtho (0, 320, 48, 0, -99999, 99999); - glViewport (glx + (glwidth - 320*s) / 2, gly, 320*s, 48*s); + glOrtho(0, 320, 48, 0, -99999, 99999); + glViewport(glx + (glwidth - 320 * s) / 2, gly, 320 * s, 48 * s); } break; case CANVAS_WARPIMAGE: - glOrtho (0, 128, 0, 128, -99999, 99999); - glViewport (glx, gly+glheight-gl_warpimagesize, gl_warpimagesize, gl_warpimagesize); + glOrtho(0, 128, 0, 128, -99999, 99999); + glViewport(glx, gly + glheight - gl_warpimagesize, gl_warpimagesize, gl_warpimagesize); break; case CANVAS_CROSSHAIR: //0,0 is center of viewport - s = CLAMP (1.0, scr_crosshairscale.value, 10.0); - glOrtho (scr_vrect.width/-2/s, scr_vrect.width/2/s, scr_vrect.height/2/s, scr_vrect.height/-2/s, -99999, 99999); - glViewport (scr_vrect.x, glheight - scr_vrect.y - scr_vrect.height, scr_vrect.width & ~1, scr_vrect.height & ~1); + s = CLAMP(1.0, scr_crosshairscale.value, 10.0); + glOrtho(scr_vrect.width / -2 / s, scr_vrect.width / 2 / s, scr_vrect.height / 2 / s, scr_vrect.height / -2 / s, -99999, 99999); + glViewport(scr_vrect.x, glheight - scr_vrect.y - scr_vrect.height, scr_vrect.width & ~1, scr_vrect.height & ~1); break; case CANVAS_BOTTOMLEFT: //used by devstats - s = (float)glwidth/vid.conwidth; //use console scale - glOrtho (0, 320, 200, 0, -99999, 99999); - glViewport (glx, gly, 320*s, 200*s); + s = (float)glwidth / vid.conwidth; //use console scale + glOrtho(0, 320, 200, 0, -99999, 99999); + glViewport(glx, gly, 320 * s, 200 * s); break; case CANVAS_BOTTOMRIGHT: //used by fps/clock - s = (float)glwidth/vid.conwidth; //use console scale - glOrtho (0, 320, 200, 0, -99999, 99999); - glViewport (glx+glwidth-320*s, gly, 320*s, 200*s); + s = (float)glwidth / vid.conwidth; //use console scale + glOrtho(0, 320, 200, 0, -99999, 99999); + glViewport(glx + glwidth - 320 * s, gly, 320 * s, 200 * s); break; case CANVAS_TOPRIGHT: //used by disc s = 1; - glOrtho (0, 320, 200, 0, -99999, 99999); - glViewport (glx+glwidth-320*s, gly+glheight-200*s, 320*s, 200*s); + glOrtho(0, 320, 200, 0, -99999, 99999); + glViewport(glx + glwidth - 320 * s, gly + glheight - 200 * s, 320 * s, 200 * s); break; default: - Sys_Error ("GL_SetCanvas: bad canvas type"); + Sys_Error("GL_SetCanvas: bad canvas type"); } glMatrixMode(GL_MODELVIEW); - glLoadIdentity (); + glLoadIdentity(); } /* @@ -759,14 +760,14 @@ void GL_SetCanvas (canvastype newcanvas) GL_Set2D -- johnfitz -- rewritten ================ */ -void GL_Set2D (void) +void GL_Set2D(void) { currentcanvas = CANVAS_INVALID; - GL_SetCanvas (CANVAS_DEFAULT); + GL_SetCanvas(CANVAS_DEFAULT); - glDisable (GL_DEPTH_TEST); - glDisable (GL_CULL_FACE); - glDisable (GL_BLEND); - glEnable (GL_ALPHA_TEST); - glColor4f (1,1,1,1); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glEnable(GL_ALPHA_TEST); + glColor4f(1, 1, 1, 1); } diff --git a/source/gl_fog.c b/source/gl_fog.c index 746e0e3..7540391 100644 --- a/source/gl_fog.c +++ b/source/gl_fog.c @@ -52,13 +52,13 @@ Fog_Update update internal variables ============= */ -void Fog_Update (float density, float red, float green, float blue, float time) +void Fog_Update(float density, float red, float green, float blue, float time) { //save previous settings for fade - if (time > 0) + if(time > 0) { //check for a fade in progress - if (fade_done > cl.time) + if(fade_done > cl.time) { float f; @@ -92,7 +92,7 @@ Fog_ParseServerMessage handle an SVC_FOG message from server ============= */ -void Fog_ParseServerMessage (void) +void Fog_ParseServerMessage(void) { float density, red, green, blue, time; @@ -102,7 +102,7 @@ void Fog_ParseServerMessage (void) blue = MSG_ReadByte() / 255.0; time = q_max(0.0, MSG_ReadShort() / 100.0); - Fog_Update (density, red, green, blue, time); + Fog_Update(density, red, green, blue, time); } /* @@ -112,9 +112,9 @@ Fog_FogCommand_f handle the 'fog' console command ============= */ -void Fog_FogCommand_f (void) +void Fog_FogCommand_f(void) { - switch (Cmd_Argc()) + switch(Cmd_Argc()) { default: case 1: @@ -130,38 +130,38 @@ void Fog_FogCommand_f (void) break; case 2: Fog_Update(q_max(0.0, atof(Cmd_Argv(1))), - fog_red, - fog_green, - fog_blue, - 0.0); + fog_red, + fog_green, + fog_blue, + 0.0); break; case 3: //TEST Fog_Update(q_max(0.0, atof(Cmd_Argv(1))), - fog_red, - fog_green, - fog_blue, - atof(Cmd_Argv(2))); + fog_red, + fog_green, + fog_blue, + atof(Cmd_Argv(2))); break; case 4: Fog_Update(fog_density, - CLAMP(0.0, atof(Cmd_Argv(1)), 1.0), - CLAMP(0.0, atof(Cmd_Argv(2)), 1.0), - CLAMP(0.0, atof(Cmd_Argv(3)), 1.0), - 0.0); + CLAMP(0.0, atof(Cmd_Argv(1)), 1.0), + CLAMP(0.0, atof(Cmd_Argv(2)), 1.0), + CLAMP(0.0, atof(Cmd_Argv(3)), 1.0), + 0.0); break; case 5: Fog_Update(q_max(0.0, atof(Cmd_Argv(1))), - CLAMP(0.0, atof(Cmd_Argv(2)), 1.0), - CLAMP(0.0, atof(Cmd_Argv(3)), 1.0), - CLAMP(0.0, atof(Cmd_Argv(4)), 1.0), - 0.0); + CLAMP(0.0, atof(Cmd_Argv(2)), 1.0), + CLAMP(0.0, atof(Cmd_Argv(3)), 1.0), + CLAMP(0.0, atof(Cmd_Argv(4)), 1.0), + 0.0); break; case 6: //TEST Fog_Update(q_max(0.0, atof(Cmd_Argv(1))), - CLAMP(0.0, atof(Cmd_Argv(2)), 1.0), - CLAMP(0.0, atof(Cmd_Argv(3)), 1.0), - CLAMP(0.0, atof(Cmd_Argv(4)), 1.0), - atof(Cmd_Argv(5))); + CLAMP(0.0, atof(Cmd_Argv(2)), 1.0), + CLAMP(0.0, atof(Cmd_Argv(3)), 1.0), + CLAMP(0.0, atof(Cmd_Argv(4)), 1.0), + atof(Cmd_Argv(5))); break; } } @@ -173,7 +173,7 @@ Fog_ParseWorldspawn called at map load ============= */ -void Fog_ParseWorldspawn (void) +void Fog_ParseWorldspawn(void) { char key[128], value[4096]; const char *data; @@ -193,29 +193,29 @@ void Fog_ParseWorldspawn (void) fade_done = 0.0; data = COM_Parse(cl.worldmodel->entities); - if (!data) + if(!data) return; // error - if (com_token[0] != '{') + if(com_token[0] != '{') return; // error - while (1) + while(1) { data = COM_Parse(data); - if (!data) + if(!data) return; // error - if (com_token[0] == '}') + if(com_token[0] == '}') break; // end of worldspawn - if (com_token[0] == '_') + if(com_token[0] == '_') strcpy(key, com_token + 1); else strcpy(key, com_token); - while (key[strlen(key)-1] == ' ') // remove trailing spaces - key[strlen(key)-1] = 0; + while(key[strlen(key) - 1] == ' ') // remove trailing spaces + key[strlen(key) - 1] = 0; data = COM_Parse(data); - if (!data) + if(!data) return; // error strcpy(value, com_token); - if (!strcmp("fog", key)) + if(!strcmp("fog", key)) { sscanf(value, "%f %f %f %f", &fog_density, &fog_red, &fog_green, &fog_blue); } @@ -229,13 +229,13 @@ Fog_GetColor calculates fog color for this frame, taking into account fade times ============= */ -float *Fog_GetColor (void) +float *Fog_GetColor(void) { static float c[4]; float f; int32_t i; - if (fade_done > cl.time) + if(fade_done > cl.time) { f = (fade_done - cl.time) / fade_time; c[0] = f * old_red + (1.0 - f) * fog_red; @@ -252,7 +252,7 @@ float *Fog_GetColor (void) } //find closest 24-bit RGB value, so solid-colored sky can match the fog perfectly - for (i=0;i<3;i++) + for(i = 0; i < 3; i++) c[i] = (float)(Q_rint(c[i] * 255)) / 255.0f; return c; @@ -265,11 +265,11 @@ Fog_GetDensity returns current density of fog ============= */ -float Fog_GetDensity (void) +float Fog_GetDensity(void) { float f; - if (fade_done > cl.time) + if(fade_done > cl.time) { f = (fade_done - cl.time) / fade_time; return f * old_density + (1.0 - f) * fog_density; @@ -285,7 +285,7 @@ Fog_SetupFrame called at the beginning of each frame ============= */ -void Fog_SetupFrame (void) +void Fog_SetupFrame(void) { glFogfv(GL_FOG_COLOR, Fog_GetColor()); glFogf(GL_FOG_DENSITY, Fog_GetDensity() / 64.0); @@ -298,9 +298,9 @@ Fog_EnableGFog called before drawing stuff that should be fogged ============= */ -void Fog_EnableGFog (void) +void Fog_EnableGFog(void) { - if (Fog_GetDensity() > 0) + if(Fog_GetDensity() > 0) glEnable(GL_FOG); } @@ -311,9 +311,9 @@ Fog_DisableGFog called after drawing stuff that should be fogged ============= */ -void Fog_DisableGFog (void) +void Fog_DisableGFog(void) { - if (Fog_GetDensity() > 0) + if(Fog_GetDensity() > 0) glDisable(GL_FOG); } @@ -324,11 +324,11 @@ Fog_StartAdditive called before drawing stuff that is additive blended -- sets fog color to black ============= */ -void Fog_StartAdditive (void) +void Fog_StartAdditive(void) { - vec3_t color = {0,0,0}; + vec3_t color = {0, 0, 0}; - if (Fog_GetDensity() > 0) + if(Fog_GetDensity() > 0) glFogfv(GL_FOG_COLOR, color); } @@ -339,9 +339,9 @@ Fog_StopAdditive called after drawing stuff that is additive blended -- restores fog color ============= */ -void Fog_StopAdditive (void) +void Fog_StopAdditive(void) { - if (Fog_GetDensity() > 0) + if(Fog_GetDensity() > 0) glFogfv(GL_FOG_COLOR, Fog_GetColor()); } @@ -353,8 +353,8 @@ void Fog_StopAdditive (void) cvar_t r_vfog = {"r_vfog", "1", CVAR_NONE}; -void Fog_DrawVFog (void){} -void Fog_MarkModels (void){} +void Fog_DrawVFog(void) {} +void Fog_MarkModels(void) {} //============================================================================== // @@ -369,10 +369,10 @@ Fog_NewMap called whenever a map is loaded ============= */ -void Fog_NewMap (void) +void Fog_NewMap(void) { - Fog_ParseWorldspawn (); //for global fog - Fog_MarkModels (); //for volumetric fog + Fog_ParseWorldspawn(); //for global fog + Fog_MarkModels(); //for volumetric fog } /* @@ -382,9 +382,9 @@ Fog_Init called when quake initializes ============= */ -void Fog_Init (void) +void Fog_Init(void) { - Cmd_AddCommand ("fog",Fog_FogCommand_f); + Cmd_AddCommand("fog", Fog_FogCommand_f); //Cvar_RegisterVariable (&r_vfog); @@ -394,17 +394,17 @@ void Fog_Init (void) fog_green = DEFAULT_GRAY; fog_blue = DEFAULT_GRAY; - Fog_SetupState (); + Fog_SetupState(); } /* ============= Fog_SetupState - + ericw -- moved from Fog_Init, state that needs to be setup when a new context is created ============= */ -void Fog_SetupState (void) +void Fog_SetupState(void) { glFogi(GL_FOG_MODE, GL_EXP2); } diff --git a/source/gl_mesh.c b/source/gl_mesh.c index e0e934d..1135118 100644 --- a/source/gl_mesh.c +++ b/source/gl_mesh.c @@ -32,79 +32,79 @@ ALIAS MODEL DISPLAY LIST GENERATION ================================================================= */ -qmodel_t *aliasmodel; -aliashdr_t *paliashdr; +qmodel_t *aliasmodel; +aliashdr_t *paliashdr; -int32_t used[8192]; // bool +int32_t used[8192]; // bool // the command list holds counts and s/t values that are valid for // every frame -int32_t commands[8192]; -int32_t numcommands; +int32_t commands[8192]; +int32_t numcommands; // all frames will have their vertexes rearranged and expanded // so they are in the order expected by the command list -int32_t vertexorder[8192]; -int32_t numorder; +int32_t vertexorder[8192]; +int32_t numorder; -int32_t allverts, alltris; +int32_t allverts, alltris; -int32_t stripverts[128]; -int32_t striptris[128]; -int32_t stripcount; +int32_t stripverts[128]; +int32_t striptris[128]; +int32_t stripcount; /* ================ StripLength ================ */ -int32_t StripLength (int32_t starttri, int32_t startv) +int32_t StripLength(int32_t starttri, int32_t startv) { - int32_t m1, m2; - int32_t j; - mtriangle_t *last, *check; - int32_t k; + int32_t m1, m2; + int32_t j; + mtriangle_t *last, *check; + int32_t k; used[starttri] = 2; last = &triangles[starttri]; - stripverts[0] = last->vertindex[(startv)%3]; - stripverts[1] = last->vertindex[(startv+1)%3]; - stripverts[2] = last->vertindex[(startv+2)%3]; + stripverts[0] = last->vertindex[(startv) % 3]; + stripverts[1] = last->vertindex[(startv + 1) % 3]; + stripverts[2] = last->vertindex[(startv + 2) % 3]; striptris[0] = starttri; stripcount = 1; - m1 = last->vertindex[(startv+2)%3]; - m2 = last->vertindex[(startv+1)%3]; + m1 = last->vertindex[(startv + 2) % 3]; + m2 = last->vertindex[(startv + 1) % 3]; // look for a matching triangle nexttri: - for (j=starttri+1, check=&triangles[starttri+1] ; jnumtris ; j++, check++) + for(j = starttri + 1, check = &triangles[starttri + 1] ; j < pheader->numtris ; j++, check++) { - if (check->facesfront != last->facesfront) + if(check->facesfront != last->facesfront) continue; - for (k=0 ; k<3 ; k++) + for(k = 0 ; k < 3 ; k++) { - if (check->vertindex[k] != m1) + if(check->vertindex[k] != m1) continue; - if (check->vertindex[ (k+1)%3 ] != m2) + if(check->vertindex[(k + 1) % 3 ] != m2) continue; // this is the next part of the fan // if we can't use this triangle, this tristrip is done - if (used[j]) + if(used[j]) goto done; // the new edge - if (stripcount & 1) - m2 = check->vertindex[ (k+2)%3 ]; + if(stripcount & 1) + m2 = check->vertindex[(k + 2) % 3 ]; else - m1 = check->vertindex[ (k+2)%3 ]; + m1 = check->vertindex[(k + 2) % 3 ]; - stripverts[stripcount+2] = check->vertindex[ (k+2)%3 ]; + stripverts[stripcount + 2] = check->vertindex[(k + 2) % 3 ]; striptris[stripcount] = j; stripcount++; @@ -115,8 +115,8 @@ nexttri: done: // clear the temp used flags - for (j=starttri+1 ; jnumtris ; j++) - if (used[j] == 2) + for(j = starttri + 1 ; j < pheader->numtris ; j++) + if(used[j] == 2) used[j] = 0; return stripcount; @@ -127,51 +127,51 @@ done: FanLength =========== */ -int32_t FanLength (int32_t starttri, int32_t startv) +int32_t FanLength(int32_t starttri, int32_t startv) { - int32_t m1, m2; - int32_t j; - mtriangle_t *last, *check; - int32_t k; + int32_t m1, m2; + int32_t j; + mtriangle_t *last, *check; + int32_t k; used[starttri] = 2; last = &triangles[starttri]; - stripverts[0] = last->vertindex[(startv)%3]; - stripverts[1] = last->vertindex[(startv+1)%3]; - stripverts[2] = last->vertindex[(startv+2)%3]; + stripverts[0] = last->vertindex[(startv) % 3]; + stripverts[1] = last->vertindex[(startv + 1) % 3]; + stripverts[2] = last->vertindex[(startv + 2) % 3]; striptris[0] = starttri; stripcount = 1; - m1 = last->vertindex[(startv+0)%3]; - m2 = last->vertindex[(startv+2)%3]; + m1 = last->vertindex[(startv + 0) % 3]; + m2 = last->vertindex[(startv + 2) % 3]; // look for a matching triangle nexttri: - for (j=starttri+1, check=&triangles[starttri+1] ; jnumtris ; j++, check++) + for(j = starttri + 1, check = &triangles[starttri + 1] ; j < pheader->numtris ; j++, check++) { - if (check->facesfront != last->facesfront) + if(check->facesfront != last->facesfront) continue; - for (k=0 ; k<3 ; k++) + for(k = 0 ; k < 3 ; k++) { - if (check->vertindex[k] != m1) + if(check->vertindex[k] != m1) continue; - if (check->vertindex[ (k+1)%3 ] != m2) + if(check->vertindex[(k + 1) % 3 ] != m2) continue; // this is the next part of the fan // if we can't use this triangle, this tristrip is done - if (used[j]) + if(used[j]) goto done; // the new edge - m2 = check->vertindex[ (k+2)%3 ]; + m2 = check->vertindex[(k + 2) % 3 ]; - stripverts[stripcount+2] = m2; + stripverts[stripcount + 2] = m2; striptris[stripcount] = j; stripcount++; @@ -182,8 +182,8 @@ nexttri: done: // clear the temp used flags - for (j=starttri+1 ; jnumtris ; j++) - if (used[j] == 2) + for(j = starttri + 1 ; j < pheader->numtris ; j++) + if(used[j] == 2) used[j] = 0; return stripcount; @@ -198,63 +198,63 @@ Generate a list of trifans or strips for the model, which holds for all frames ================ */ -void BuildTris (void) +void BuildTris(void) { - int32_t i, j, k; - int32_t startv; - float s, t; - int32_t len, bestlen, besttype; - int32_t bestverts[1024]; - int32_t besttris[1024]; - int32_t type; + int32_t i, j, k; + int32_t startv; + float s, t; + int32_t len, bestlen, besttype; + int32_t bestverts[1024]; + int32_t besttris[1024]; + int32_t type; // // build tristrips // numorder = 0; numcommands = 0; - memset (used, 0, sizeof(used)); - for (i = 0; i < pheader->numtris; i++) + memset(used, 0, sizeof(used)); + for(i = 0; i < pheader->numtris; i++) { // pick an unused triangle and start the trifan - if (used[i]) + if(used[i]) continue; bestlen = 0; besttype = 0; - for (type = 0 ; type < 2 ; type++) + for(type = 0 ; type < 2 ; type++) // type = 1; { - for (startv = 0; startv < 3; startv++) + for(startv = 0; startv < 3; startv++) { - if (type == 1) - len = StripLength (i, startv); + if(type == 1) + len = StripLength(i, startv); else - len = FanLength (i, startv); - if (len > bestlen) + len = FanLength(i, startv); + if(len > bestlen) { besttype = type; bestlen = len; - for (j = 0; j < bestlen+2; j++) + for(j = 0; j < bestlen + 2; j++) bestverts[j] = stripverts[j]; - for (j = 0; j < bestlen; j++) + for(j = 0; j < bestlen; j++) besttris[j] = striptris[j]; } } } // mark the tris on the best strip as used - for (j = 0; j < bestlen; j++) + for(j = 0; j < bestlen; j++) used[besttris[j]] = 1; - if (besttype == 1) - commands[numcommands++] = (bestlen+2); + if(besttype == 1) + commands[numcommands++] = (bestlen + 2); else - commands[numcommands++] = -(bestlen+2); + commands[numcommands++] = -(bestlen + 2); - for (j = 0; j < bestlen+2; j++) + for(j = 0; j < bestlen + 2; j++) { - int32_t tmp; + int32_t tmp; // emit a vertex into the reorder buffer k = bestverts[j]; @@ -263,64 +263,64 @@ void BuildTris (void) // emit s/t coords into the commands stream s = stverts[k].s; t = stverts[k].t; - if (!triangles[besttris[0]].facesfront && stverts[k].onseam) - s += pheader->skinwidth / 2; // on back side + if(!triangles[besttris[0]].facesfront && stverts[k].onseam) + s += pheader->skinwidth / 2; // on back side s = (s + 0.5) / pheader->skinwidth; t = (t + 0.5) / pheader->skinheight; - // *(float *)&commands[numcommands++] = s; - // *(float *)&commands[numcommands++] = t; + // *(float *)&commands[numcommands++] = s; + // *(float *)&commands[numcommands++] = t; // NOTE: 4 == sizeof(int32_t) - // == sizeof(float) - memcpy (&tmp, &s, 4); + // == sizeof(float) + memcpy(&tmp, &s, 4); commands[numcommands++] = tmp; - memcpy (&tmp, &t, 4); + memcpy(&tmp, &t, 4); commands[numcommands++] = tmp; } } - commands[numcommands++] = 0; // end of list marker + commands[numcommands++] = 0; // end of list marker - Con_DPrintf2 ("%3" PRIi32 " tri %3" PRIi32 " vert %3" PRIi32 " cmd\n", pheader->numtris, numorder, numcommands); + Con_DPrintf2("%3" PRIi32 " tri %3" PRIi32 " vert %3" PRIi32 " cmd\n", pheader->numtris, numorder, numcommands); allverts += numorder; alltris += pheader->numtris; } -static void GL_MakeAliasModelDisplayLists_VBO (void); -static void GLMesh_LoadVertexBuffer (qmodel_t *m, const aliashdr_t *hdr); +static void GL_MakeAliasModelDisplayLists_VBO(void); +static void GLMesh_LoadVertexBuffer(qmodel_t *m, const aliashdr_t *hdr); /* ================ GL_MakeAliasModelDisplayLists ================ */ -void GL_MakeAliasModelDisplayLists (qmodel_t *m, aliashdr_t *hdr) +void GL_MakeAliasModelDisplayLists(qmodel_t *m, aliashdr_t *hdr) { - int32_t i, j; - int32_t *cmds; - trivertx_t *verts; - float hscale, vscale; //johnfitz -- padded skins - int32_t count; //johnfitz -- precompute texcoords for padded skins - int32_t *loadcmds; //johnfitz + int32_t i, j; + int32_t *cmds; + trivertx_t *verts; + float hscale, vscale; //johnfitz -- padded skins + int32_t count; //johnfitz -- precompute texcoords for padded skins + int32_t *loadcmds; //johnfitz //johnfitz -- padded skins - hscale = (float)hdr->skinwidth/(float)TexMgr_PadConditional(hdr->skinwidth); - vscale = (float)hdr->skinheight/(float)TexMgr_PadConditional(hdr->skinheight); + hscale = (float)hdr->skinwidth / (float)TexMgr_PadConditional(hdr->skinwidth); + vscale = (float)hdr->skinheight / (float)TexMgr_PadConditional(hdr->skinheight); //johnfitz aliasmodel = m; - paliashdr = hdr; // (aliashdr_t *)Mod_Extradata (m); + paliashdr = hdr; // (aliashdr_t *)Mod_Extradata (m); //johnfitz -- generate meshes - Con_DPrintf2 ("meshing %s...\n",m->name); - BuildTris (); + Con_DPrintf2("meshing %s...\n", m->name); + BuildTris(); // save the data out paliashdr->poseverts = numorder; - cmds = (int32_t *) Hunk_Alloc (numcommands * 4); + cmds = (int32_t *) Hunk_Alloc(numcommands * 4); paliashdr->commands = (byte *)cmds - (byte *)paliashdr; //johnfitz -- precompute texcoords for padded skins @@ -329,28 +329,29 @@ void GL_MakeAliasModelDisplayLists (qmodel_t *m, aliashdr_t *hdr) { *cmds++ = count = *loadcmds++; - if (!count) + if(!count) break; - if (count < 0) + if(count < 0) count = -count; do { *(float *)cmds++ = hscale * (*(float *)loadcmds++); *(float *)cmds++ = vscale * (*(float *)loadcmds++); - } while (--count); + } + while(--count); } //johnfitz - verts = (trivertx_t *) Hunk_Alloc (paliashdr->numposes * paliashdr->poseverts * sizeof(trivertx_t)); + verts = (trivertx_t *) Hunk_Alloc(paliashdr->numposes * paliashdr->poseverts * sizeof(trivertx_t)); paliashdr->posedata = (byte *)verts - (byte *)paliashdr; - for (i=0 ; inumposes ; i++) - for (j=0 ; jnumposes ; i++) + for(j = 0 ; j < numorder ; j++) *verts++ = poseverts[i][vertexorder[j]]; // ericw - GL_MakeAliasModelDisplayLists_VBO (); + GL_MakeAliasModelDisplayLists_VBO(); } uint32_t r_meshindexbuffer = 0; @@ -366,7 +367,7 @@ is copied to Mod_Extradata. Original code by MH from RMQEngine ================ */ -void GL_MakeAliasModelDisplayLists_VBO (void) +void GL_MakeAliasModelDisplayLists_VBO(void) { int32_t i, j; int32_t maxverts_vbo; @@ -374,31 +375,31 @@ void GL_MakeAliasModelDisplayLists_VBO (void) uint16_t *indexes; aliasmesh_t *desc; - if (!gl_glsl_alias_able) + if(!gl_glsl_alias_able) return; // first, copy the verts onto the hunk - verts = (trivertx_t *) Hunk_Alloc (paliashdr->numposes * paliashdr->numverts * sizeof(trivertx_t)); + verts = (trivertx_t *) Hunk_Alloc(paliashdr->numposes * paliashdr->numverts * sizeof(trivertx_t)); paliashdr->vertexes = (byte *)verts - (byte *)paliashdr; - for (i=0 ; inumposes ; i++) - for (j=0 ; jnumverts ; j++) - verts[i*paliashdr->numverts + j] = poseverts[i][j]; + for(i = 0 ; i < paliashdr->numposes ; i++) + for(j = 0 ; j < paliashdr->numverts ; j++) + verts[i * paliashdr->numverts + j] = poseverts[i][j]; // there can never be more than this number of verts and we just put them all on the hunk maxverts_vbo = pheader->numtris * 3; - desc = (aliasmesh_t *) Hunk_Alloc (sizeof (aliasmesh_t) * maxverts_vbo); + desc = (aliasmesh_t *) Hunk_Alloc(sizeof(aliasmesh_t) * maxverts_vbo); // there will always be this number of indexes - indexes = (uint16_t *) Hunk_Alloc (sizeof (uint16_t) * maxverts_vbo); + indexes = (uint16_t *) Hunk_Alloc(sizeof(uint16_t) * maxverts_vbo); pheader->indexes = (intptr_t) indexes - (intptr_t) pheader; pheader->meshdesc = (intptr_t) desc - (intptr_t) pheader; pheader->numindexes = 0; pheader->numverts_vbo = 0; - for (i = 0; i < pheader->numtris; i++) + for(i = 0; i < pheader->numtris; i++) { - for (j = 0; j < 3; j++) + for(j = 0; j < 3; j++) { int32_t v; @@ -410,13 +411,13 @@ void GL_MakeAliasModelDisplayLists_VBO (void) int32_t t = stverts[vertindex].t; // check for back side and adjust texcoord s - if (!triangles[i].facesfront && stverts[vertindex].onseam) s += pheader->skinwidth / 2; + if(!triangles[i].facesfront && stverts[vertindex].onseam) s += pheader->skinwidth / 2; // see does this vert already exist - for (v = 0; v < pheader->numverts_vbo; v++) + for(v = 0; v < pheader->numverts_vbo; v++) { // it could use the same xyz but have different s and t - if (desc[v].vertindex == vertindex && (int32_t) desc[v].st[0] == s && (int32_t) desc[v].st[1] == t) + if(desc[v].vertindex == vertindex && (int32_t) desc[v].st[0] == s && (int32_t) desc[v].st[1] == t) { // exists; emit an index for it indexes[pheader->numindexes++] = v; @@ -426,7 +427,7 @@ void GL_MakeAliasModelDisplayLists_VBO (void) } } - if (v == pheader->numverts_vbo) + if(v == pheader->numverts_vbo) { // doesn't exist; emit a new vert and index indexes[pheader->numindexes++] = pheader->numverts_vbo; @@ -439,11 +440,11 @@ void GL_MakeAliasModelDisplayLists_VBO (void) } // upload immediately - GLMesh_LoadVertexBuffer (aliasmodel, pheader); + GLMesh_LoadVertexBuffer(aliasmodel, pheader); } -#define NUMVERTEXNORMALS 162 -extern float r_avertexnormals[NUMVERTEXNORMALS][3]; +#define NUMVERTEXNORMALS 162 +extern float r_avertexnormals[NUMVERTEXNORMALS][3]; /* ================ @@ -454,7 +455,7 @@ Upload the given alias model's mesh to a VBO Original code by MH from RMQEngine ================ */ -static void GLMesh_LoadVertexBuffer (qmodel_t *m, const aliashdr_t *hdr) +static void GLMesh_LoadVertexBuffer(qmodel_t *m, const aliashdr_t *hdr) { int32_t totalvbosize = 0; const aliasmesh_t *desc; @@ -463,7 +464,7 @@ static void GLMesh_LoadVertexBuffer (qmodel_t *m, const aliashdr_t *hdr) byte *vbodata; int32_t f; - if (!gl_glsl_alias_able) + if(!gl_glsl_alias_able) return; // count the sizes we need @@ -474,26 +475,26 @@ static void GLMesh_LoadVertexBuffer (qmodel_t *m, const aliashdr_t *hdr) m->vboindexofs = 0; m->vboxyzofs = 0; - totalvbosize += (hdr->numposes * hdr->numverts_vbo * sizeof (meshxyz_t)); // ericw -- what RMQEngine called nummeshframes is called numposes in QuakeSpasm + totalvbosize += (hdr->numposes * hdr->numverts_vbo * sizeof(meshxyz_t)); // ericw -- what RMQEngine called nummeshframes is called numposes in QuakeSpasm m->vbostofs = totalvbosize; - totalvbosize += (hdr->numverts_vbo * sizeof (meshst_t)); + totalvbosize += (hdr->numverts_vbo * sizeof(meshst_t)); - if (!hdr->numindexes) return; - if (!totalvbosize) return; + if(!hdr->numindexes) return; + if(!totalvbosize) return; // grab the pointers to data in the extradata - desc = (aliasmesh_t *) ((byte *) hdr + hdr->meshdesc); - indexes = (int16_t *) ((byte *) hdr + hdr->indexes); - trivertexes = (trivertx_t *) ((byte *)hdr + hdr->vertexes); + desc = (aliasmesh_t *)((byte *) hdr + hdr->meshdesc); + indexes = (int16_t *)((byte *) hdr + hdr->indexes); + trivertexes = (trivertx_t *)((byte *)hdr + hdr->vertexes); // upload indices buffer - GL_DeleteBuffersFunc (1, &m->meshindexesvbo); - GL_GenBuffersFunc (1, &m->meshindexesvbo); - GL_BindBufferFunc (GL_ELEMENT_ARRAY_BUFFER, m->meshindexesvbo); - GL_BufferDataFunc (GL_ELEMENT_ARRAY_BUFFER, hdr->numindexes * sizeof (uint16_t), indexes, GL_STATIC_DRAW); + GL_DeleteBuffersFunc(1, &m->meshindexesvbo); + GL_GenBuffersFunc(1, &m->meshindexesvbo); + GL_BindBufferFunc(GL_ELEMENT_ARRAY_BUFFER, m->meshindexesvbo); + GL_BufferDataFunc(GL_ELEMENT_ARRAY_BUFFER, hdr->numindexes * sizeof(uint16_t), indexes, GL_STATIC_DRAW); // create the vertex buffer (empty) @@ -501,20 +502,20 @@ static void GLMesh_LoadVertexBuffer (qmodel_t *m, const aliashdr_t *hdr) memset(vbodata, 0, totalvbosize); // fill in the vertices at the start of the buffer - for (f = 0; f < hdr->numposes; f++) // ericw -- what RMQEngine called nummeshframes is called numposes in QuakeSpasm + for(f = 0; f < hdr->numposes; f++) // ericw -- what RMQEngine called nummeshframes is called numposes in QuakeSpasm { int32_t v; - meshxyz_t *xyz = (meshxyz_t *) (vbodata + (f * hdr->numverts_vbo * sizeof (meshxyz_t))); + meshxyz_t *xyz = (meshxyz_t *)(vbodata + (f * hdr->numverts_vbo * sizeof(meshxyz_t))); const trivertx_t *tv = trivertexes + (hdr->numverts * f); - for (v = 0; v < hdr->numverts_vbo; v++) + for(v = 0; v < hdr->numverts_vbo; v++) { trivertx_t trivert = tv[desc[v].vertindex]; xyz[v].xyz[0] = trivert.v[0]; xyz[v].xyz[1] = trivert.v[1]; xyz[v].xyz[2] = trivert.v[2]; - xyz[v].xyz[3] = 1; // need w 1 for 4 byte vertex compression + xyz[v].xyz[3] = 1; // need w 1 for 4 byte vertex compression // map the normal coordinates in [-1..1] to [-127..127] and store in an uint8_t. // this introduces some error (less than 0.004), but the normals were very coarse @@ -522,7 +523,7 @@ static void GLMesh_LoadVertexBuffer (qmodel_t *m, const aliashdr_t *hdr) xyz[v].normal[0] = 127 * r_avertexnormals[trivert.lightnormalindex][0]; xyz[v].normal[1] = 127 * r_avertexnormals[trivert.lightnormalindex][1]; xyz[v].normal[2] = 127 * r_avertexnormals[trivert.lightnormalindex][2]; - xyz[v].normal[3] = 0; // unused; for 4-byte alignment + xyz[v].normal[3] = 0; // unused; for 4-byte alignment } } @@ -532,12 +533,12 @@ static void GLMesh_LoadVertexBuffer (qmodel_t *m, const aliashdr_t *hdr) float hscale, vscale; //johnfitz -- padded skins - hscale = (float)hdr->skinwidth/(float)TexMgr_PadConditional(hdr->skinwidth); - vscale = (float)hdr->skinheight/(float)TexMgr_PadConditional(hdr->skinheight); + hscale = (float)hdr->skinwidth / (float)TexMgr_PadConditional(hdr->skinwidth); + vscale = (float)hdr->skinheight / (float)TexMgr_PadConditional(hdr->skinheight); //johnfitz - st = (meshst_t *) (vbodata + m->vbostofs); - for (f = 0; f < hdr->numverts_vbo; f++) + st = (meshst_t *)(vbodata + m->vbostofs); + for(f = 0; f < hdr->numverts_vbo; f++) { st[f].st[0] = hscale * ((float) desc[f].st[0] + 0.5f) / (float) hdr->skinwidth; st[f].st[1] = vscale * ((float) desc[f].st[1] + 0.5f) / (float) hdr->skinheight; @@ -545,15 +546,15 @@ static void GLMesh_LoadVertexBuffer (qmodel_t *m, const aliashdr_t *hdr) } // upload vertexes buffer - GL_DeleteBuffersFunc (1, &m->meshvbo); - GL_GenBuffersFunc (1, &m->meshvbo); - GL_BindBufferFunc (GL_ARRAY_BUFFER, m->meshvbo); - GL_BufferDataFunc (GL_ARRAY_BUFFER, totalvbosize, vbodata, GL_STATIC_DRAW); + GL_DeleteBuffersFunc(1, &m->meshvbo); + GL_GenBuffersFunc(1, &m->meshvbo); + GL_BindBufferFunc(GL_ARRAY_BUFFER, m->meshvbo); + GL_BufferDataFunc(GL_ARRAY_BUFFER, totalvbosize, vbodata, GL_STATIC_DRAW); - free (vbodata); + free(vbodata); // invalidate the cached bindings - GL_ClearBufferBindings (); + GL_ClearBufferBindings(); } /* @@ -563,23 +564,23 @@ GLMesh_LoadVertexBuffers Loop over all precached alias models, and upload each one to a VBO. ================ */ -void GLMesh_LoadVertexBuffers (void) +void GLMesh_LoadVertexBuffers(void) { int32_t j; qmodel_t *m; const aliashdr_t *hdr; - if (!gl_glsl_alias_able) + if(!gl_glsl_alias_able) return; - for (j = 1; j < MAX_MODELS; j++) + for(j = 1; j < MAX_MODELS; j++) { - if (!(m = cl.model_precache[j])) break; - if (m->type != mod_alias) continue; + if(!(m = cl.model_precache[j])) break; + if(m->type != mod_alias) continue; - hdr = (const aliashdr_t *) Mod_Extradata (m); + hdr = (const aliashdr_t *) Mod_Extradata(m); - GLMesh_LoadVertexBuffer (m, hdr); + GLMesh_LoadVertexBuffer(m, hdr); } } @@ -590,25 +591,25 @@ GLMesh_DeleteVertexBuffers Delete VBOs for all loaded alias models ================ */ -void GLMesh_DeleteVertexBuffers (void) +void GLMesh_DeleteVertexBuffers(void) { int32_t j; qmodel_t *m; - if (!gl_glsl_alias_able) + if(!gl_glsl_alias_able) return; - for (j = 1; j < MAX_MODELS; j++) + for(j = 1; j < MAX_MODELS; j++) { - if (!(m = cl.model_precache[j])) break; - if (m->type != mod_alias) continue; + if(!(m = cl.model_precache[j])) break; + if(m->type != mod_alias) continue; - GL_DeleteBuffersFunc (1, &m->meshvbo); + GL_DeleteBuffersFunc(1, &m->meshvbo); m->meshvbo = 0; - GL_DeleteBuffersFunc (1, &m->meshindexesvbo); + GL_DeleteBuffersFunc(1, &m->meshindexesvbo); m->meshindexesvbo = 0; } - GL_ClearBufferBindings (); + GL_ClearBufferBindings(); } diff --git a/source/gl_model.c b/source/gl_model.c index 233b7da..20464de 100644 --- a/source/gl_model.c +++ b/source/gl_model.c @@ -26,46 +26,46 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -qmodel_t *loadmodel; -char loadname[32]; // for hunk tags +qmodel_t *loadmodel; +char loadname[32]; // for hunk tags -void Mod_LoadSpriteModel (qmodel_t *mod, void *buffer); -void Mod_LoadBrushModel (qmodel_t *mod, void *buffer); -void Mod_LoadAliasModel (qmodel_t *mod, void *buffer); -qmodel_t *Mod_LoadModel (qmodel_t *mod, bool crash); +void Mod_LoadSpriteModel(qmodel_t *mod, void *buffer); +void Mod_LoadBrushModel(qmodel_t *mod, void *buffer); +void Mod_LoadAliasModel(qmodel_t *mod, void *buffer); +qmodel_t *Mod_LoadModel(qmodel_t *mod, bool crash); -cvar_t external_ents = {"external_ents", "1", CVAR_ARCHIVE}; +cvar_t external_ents = {"external_ents", "1", CVAR_ARCHIVE}; -static byte *mod_novis; -static int32_t mod_novis_capacity; +static byte *mod_novis; +static int32_t mod_novis_capacity; -static byte *mod_decompressed; -static int32_t mod_decompressed_capacity; +static byte *mod_decompressed; +static int32_t mod_decompressed_capacity; -#define MAX_MOD_KNOWN 2048 /*johnfitz -- was 512 */ -qmodel_t mod_known[MAX_MOD_KNOWN]; -int32_t mod_numknown; +#define MAX_MOD_KNOWN 2048 /*johnfitz -- was 512 */ +qmodel_t mod_known[MAX_MOD_KNOWN]; +int32_t mod_numknown; -texture_t *r_notexture_mip; //johnfitz -- moved here from r_main.c -texture_t *r_notexture_mip2; //johnfitz -- used for non-lightmapped surfs with a missing texture +texture_t *r_notexture_mip; //johnfitz -- moved here from r_main.c +texture_t *r_notexture_mip2; //johnfitz -- used for non-lightmapped surfs with a missing texture /* =============== Mod_Init =============== */ -void Mod_Init (void) +void Mod_Init(void) { - Cvar_RegisterVariable (&gl_subdivide_size); - Cvar_RegisterVariable (&external_ents); + Cvar_RegisterVariable(&gl_subdivide_size); + Cvar_RegisterVariable(&external_ents); //johnfitz -- create notexture miptex - r_notexture_mip = (texture_t *) Hunk_AllocName (sizeof(texture_t), "r_notexture_mip"); - strcpy (r_notexture_mip->name, "notexture"); + r_notexture_mip = (texture_t *) Hunk_AllocName(sizeof(texture_t), "r_notexture_mip"); + strcpy(r_notexture_mip->name, "notexture"); r_notexture_mip->height = r_notexture_mip->width = 32; - r_notexture_mip2 = (texture_t *) Hunk_AllocName (sizeof(texture_t), "r_notexture_mip2"); - strcpy (r_notexture_mip2->name, "notexture2"); + r_notexture_mip2 = (texture_t *) Hunk_AllocName(sizeof(texture_t), "r_notexture_mip2"); + strcpy(r_notexture_mip2->name, "notexture2"); r_notexture_mip2->height = r_notexture_mip2->width = 32; //johnfitz } @@ -77,18 +77,18 @@ Mod_Extradata Caches the data if needed =============== */ -void *Mod_Extradata (qmodel_t *mod) +void *Mod_Extradata(qmodel_t *mod) { - void *r; + void *r; - r = Cache_Check (&mod->cache); - if (r) + r = Cache_Check(&mod->cache); + if(r) return r; - Mod_LoadModel (mod, true); + Mod_LoadModel(mod, true); - if (!mod->cache.data) - Sys_Error ("Mod_Extradata: caching failed"); + if(!mod->cache.data) + Sys_Error("Mod_Extradata: caching failed"); return mod->cache.data; } @@ -97,29 +97,29 @@ void *Mod_Extradata (qmodel_t *mod) Mod_PointInLeaf =============== */ -mleaf_t *Mod_PointInLeaf (vec3_t p, qmodel_t *model) +mleaf_t *Mod_PointInLeaf(vec3_t p, qmodel_t *model) { - mnode_t *node; - float d; - mplane_t *plane; + mnode_t *node; + float d; + mplane_t *plane; - if (!model || !model->nodes) - Sys_Error ("Mod_PointInLeaf: bad model"); + if(!model || !model->nodes) + Sys_Error("Mod_PointInLeaf: bad model"); node = model->nodes; - while (1) + while(1) { - if (node->contents < 0) + if(node->contents < 0) return (mleaf_t *)node; plane = node->plane; - d = DotProduct (p,plane->normal) - plane->dist; - if (d > 0) + d = DotProduct(p, plane->normal) - plane->dist; + if(d > 0) node = node->children[0]; else node = node->children[1]; } - return NULL; // never reached + return NULL; // never reached } @@ -128,27 +128,28 @@ mleaf_t *Mod_PointInLeaf (vec3_t p, qmodel_t *model) Mod_DecompressVis =================== */ -byte *Mod_DecompressVis (byte *in, qmodel_t *model) +byte *Mod_DecompressVis(byte *in, qmodel_t *model) { - int32_t c; - byte *out; - byte *outend; - int32_t row; + int32_t c; + byte *out; + byte *outend; + int32_t row; - row = (model->numleafs+7)>>3; - if (mod_decompressed == NULL || row > mod_decompressed_capacity) + row = (model->numleafs + 7) >> 3; + if(mod_decompressed == NULL || row > mod_decompressed_capacity) { mod_decompressed_capacity = row; - mod_decompressed = (byte *) realloc (mod_decompressed, mod_decompressed_capacity); - if (!mod_decompressed) - Sys_Error ("Mod_DecompressVis: realloc() failed on %" PRIi32 " bytes", mod_decompressed_capacity); + mod_decompressed = (byte *) realloc(mod_decompressed, mod_decompressed_capacity); + if(!mod_decompressed) + Sys_Error("Mod_DecompressVis: realloc() failed on %" PRIi32 " bytes", mod_decompressed_capacity); } out = mod_decompressed; outend = mod_decompressed + row; - if (!in) - { // no vis info, so make all visible - while (row) + if(!in) + { + // no vis info, so make all visible + while(row) { *out++ = 0xff; row--; @@ -158,7 +159,7 @@ byte *Mod_DecompressVis (byte *in, qmodel_t *model) do { - if (*in) + if(*in) { *out++ = *in++; continue; @@ -166,11 +167,12 @@ byte *Mod_DecompressVis (byte *in, qmodel_t *model) c = in[1]; in += 2; - while (c) + while(c) { - if (out == outend) + if(out == outend) { - if(!model->viswarn) { + if(!model->viswarn) + { model->viswarn = true; Con_Warning("Mod_DecompressVis: output overrun on model \"%s\"\n", model->name); } @@ -179,30 +181,31 @@ byte *Mod_DecompressVis (byte *in, qmodel_t *model) *out++ = 0; c--; } - } while (out - mod_decompressed < row); + } + while(out - mod_decompressed < row); return mod_decompressed; } -byte *Mod_LeafPVS (mleaf_t *leaf, qmodel_t *model) +byte *Mod_LeafPVS(mleaf_t *leaf, qmodel_t *model) { - if (leaf == model->leafs) - return Mod_NoVisPVS (model); - return Mod_DecompressVis (leaf->compressed_vis, model); + if(leaf == model->leafs) + return Mod_NoVisPVS(model); + return Mod_DecompressVis(leaf->compressed_vis, model); } -byte *Mod_NoVisPVS (qmodel_t *model) +byte *Mod_NoVisPVS(qmodel_t *model) { int32_t pvsbytes; - - pvsbytes = (model->numleafs+7)>>3; - if (mod_novis == NULL || pvsbytes > mod_novis_capacity) + + pvsbytes = (model->numleafs + 7) >> 3; + if(mod_novis == NULL || pvsbytes > mod_novis_capacity) { mod_novis_capacity = pvsbytes; - mod_novis = (byte *) realloc (mod_novis, mod_novis_capacity); - if (!mod_novis) - Sys_Error ("Mod_NoVisPVS: realloc() failed on %" PRIi32 " bytes", mod_novis_capacity); - + mod_novis = (byte *) realloc(mod_novis, mod_novis_capacity); + if(!mod_novis) + Sys_Error("Mod_NoVisPVS: realloc() failed on %" PRIi32 " bytes", mod_novis_capacity); + memset(mod_novis, 0xff, mod_novis_capacity); } return mod_novis; @@ -213,31 +216,31 @@ byte *Mod_NoVisPVS (qmodel_t *model) Mod_ClearAll =================== */ -void Mod_ClearAll (void) +void Mod_ClearAll(void) { - int32_t i; - qmodel_t *mod; + int32_t i; + qmodel_t *mod; - for (i=0 , mod=mod_known ; itype != mod_alias) + for(i = 0, mod = mod_known ; i < mod_numknown ; i++, mod++) + if(mod->type != mod_alias) { mod->needload = true; - TexMgr_FreeTexturesForOwner (mod); //johnfitz + TexMgr_FreeTexturesForOwner(mod); //johnfitz } } -void Mod_ResetAll (void) +void Mod_ResetAll(void) { - int32_t i; - qmodel_t *mod; + int32_t i; + qmodel_t *mod; //ericw -- free alias model VBOs - GLMesh_DeleteVertexBuffers (); - - for (i=0 , mod=mod_known ; ineedload) //otherwise Mod_ClearAll() did it already - TexMgr_FreeTexturesForOwner (mod); + if(!mod->needload) //otherwise Mod_ClearAll() did it already + TexMgr_FreeTexturesForOwner(mod); memset(mod, 0, sizeof(qmodel_t)); } mod_numknown = 0; @@ -249,26 +252,26 @@ Mod_FindName ================== */ -qmodel_t *Mod_FindName (const char *name) +qmodel_t *Mod_FindName(const char *name) { - int32_t i; - qmodel_t *mod; + int32_t i; + qmodel_t *mod; - if (!name[0]) - Sys_Error ("Mod_FindName: NULL name"); //johnfitz -- was "Mod_ForName" + if(!name[0]) + Sys_Error("Mod_FindName: NULL name"); //johnfitz -- was "Mod_ForName" // // search the currently loaded models // - for (i=0 , mod=mod_known ; iname, name) ) + for(i = 0, mod = mod_known ; i < mod_numknown ; i++, mod++) + if(!strcmp(mod->name, name)) break; - if (i == mod_numknown) + if(i == mod_numknown) { - if (mod_numknown == MAX_MOD_KNOWN) - Sys_Error ("mod_numknown == MAX_MOD_KNOWN"); - q_strlcpy (mod->name, name, MAX_QPATH); + if(mod_numknown == MAX_MOD_KNOWN) + Sys_Error("mod_numknown == MAX_MOD_KNOWN"); + q_strlcpy(mod->name, name, MAX_QPATH); mod->needload = true; mod_numknown++; } @@ -282,16 +285,16 @@ Mod_TouchModel ================== */ -void Mod_TouchModel (const char *name) +void Mod_TouchModel(const char *name) { - qmodel_t *mod; + qmodel_t *mod; - mod = Mod_FindName (name); + mod = Mod_FindName(name); - if (!mod->needload) + if(!mod->needload) { - if (mod->type == mod_alias) - Cache_Check (&mod->cache); + if(mod->type == mod_alias) + Cache_Check(&mod->cache); } } @@ -302,27 +305,27 @@ Mod_LoadModel Loads a model into the cache ================== */ -qmodel_t *Mod_LoadModel (qmodel_t *mod, bool crash) +qmodel_t *Mod_LoadModel(qmodel_t *mod, bool crash) { - byte *buf; - byte stackbuf[1024]; // avoid dirtying the cache heap - int32_t mod_type; + byte *buf; + byte stackbuf[1024]; // avoid dirtying the cache heap + int32_t mod_type; - if (!mod->needload) + if(!mod->needload) { - if (mod->type == mod_alias) + if(mod->type == mod_alias) { - if (Cache_Check (&mod->cache)) + if(Cache_Check(&mod->cache)) return mod; } else - return mod; // not cached at all + return mod; // not cached at all } // // because the world is so huge, load it one piece at a time // - if (!crash) + if(!crash) { } @@ -330,18 +333,18 @@ qmodel_t *Mod_LoadModel (qmodel_t *mod, bool crash) // // load the file // - buf = COM_LoadStackFile (mod->name, stackbuf, sizeof(stackbuf), & mod->path_id); - if (!buf) + buf = COM_LoadStackFile(mod->name, stackbuf, sizeof(stackbuf), & mod->path_id); + if(!buf) { - if (crash) - Host_Error ("Mod_LoadModel: %s not found", mod->name); //johnfitz -- was "Mod_NumForName" + if(crash) + Host_Error("Mod_LoadModel: %s not found", mod->name); //johnfitz -- was "Mod_NumForName" return NULL; } // // allocate a new model // - COM_FileBase (mod->name, loadname, sizeof(loadname)); + COM_FileBase(mod->name, loadname, sizeof(loadname)); loadmodel = mod; @@ -353,18 +356,18 @@ qmodel_t *Mod_LoadModel (qmodel_t *mod, bool crash) mod->needload = false; mod_type = (buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24)); - switch (mod_type) + switch(mod_type) { case IDPOLYHEADER: - Mod_LoadAliasModel (mod, buf); + Mod_LoadAliasModel(mod, buf); break; case IDSPRITEHEADER: - Mod_LoadSpriteModel (mod, buf); + Mod_LoadSpriteModel(mod, buf); break; default: - Mod_LoadBrushModel (mod, buf); + Mod_LoadBrushModel(mod, buf); break; } @@ -378,36 +381,36 @@ Mod_ForName Loads in a model for the given name ================== */ -qmodel_t *Mod_ForName (const char *name, bool crash) +qmodel_t *Mod_ForName(const char *name, bool crash) { - qmodel_t *mod; + qmodel_t *mod; - mod = Mod_FindName (name); + mod = Mod_FindName(name); - return Mod_LoadModel (mod, crash); + return Mod_LoadModel(mod, crash); } /* =============================================================================== - BRUSHMODEL LOADING + BRUSHMODEL LOADING =============================================================================== */ -byte *mod_base; +byte *mod_base; /* ================= Mod_CheckFullbrights -- johnfitz ================= */ -bool Mod_CheckFullbrights (byte *pixels, int32_t count) +bool Mod_CheckFullbrights(byte *pixels, int32_t count) { int32_t i; - for (i = 0; i < count; i++) - if (*pixels++ > 223) + for(i = 0; i < count; i++) + if(*pixels++ > 223) return true; return false; } @@ -417,63 +420,63 @@ bool Mod_CheckFullbrights (byte *pixels, int32_t count) Mod_LoadTextures ================= */ -void Mod_LoadTextures (lump_t *l) +void Mod_LoadTextures(lump_t *l) { - int32_t i, j, pixels, num, maxanim, altmax; - miptex_t *mt; - texture_t *tx, *tx2; - texture_t *anims[10]; - texture_t *altanims[10]; - dmiptexlump_t *m; + int32_t i, j, pixels, num, maxanim, altmax; + miptex_t *mt; + texture_t *tx, *tx2; + texture_t *anims[10]; + texture_t *altanims[10]; + dmiptexlump_t *m; //johnfitz -- more variables - char texturename[64]; - int32_t nummiptex; - src_offset_t offset; - int32_t mark, fwidth, fheight; - char filename[MAX_OSPATH], filename2[MAX_OSPATH], mapname[MAX_OSPATH]; - byte *data; + char texturename[64]; + int32_t nummiptex; + src_offset_t offset; + int32_t mark, fwidth, fheight; + char filename[MAX_OSPATH], filename2[MAX_OSPATH], mapname[MAX_OSPATH]; + byte *data; extern byte *hunk_base; //johnfitz //johnfitz -- don't return early if no textures; still need to create dummy texture - if (!l->filelen) + if(!l->filelen) { - Con_Printf ("Mod_LoadTextures: no textures in bsp file\n"); + Con_Printf("Mod_LoadTextures: no textures in bsp file\n"); nummiptex = 0; m = NULL; // avoid bogus compiler warning } else { m = (dmiptexlump_t *)(mod_base + l->fileofs); - m->nummiptex = LittleLong (m->nummiptex); + m->nummiptex = LittleLong(m->nummiptex); nummiptex = m->nummiptex; } //johnfitz loadmodel->numtextures = nummiptex + 2; //johnfitz -- need 2 dummy texture chains for missing textures - loadmodel->textures = (texture_t **) Hunk_AllocName (loadmodel->numtextures * sizeof(*loadmodel->textures) , loadname); + loadmodel->textures = (texture_t **) Hunk_AllocName(loadmodel->numtextures * sizeof(*loadmodel->textures), loadname); - for (i=0 ; idataofs[i] = LittleLong(m->dataofs[i]); - if (m->dataofs[i] == -1) + if(m->dataofs[i] == -1) continue; mt = (miptex_t *)((byte *)m + m->dataofs[i]); - mt->width = LittleLong (mt->width); - mt->height = LittleLong (mt->height); - for (j=0 ; joffsets[j] = LittleLong (mt->offsets[j]); + mt->width = LittleLong(mt->width); + mt->height = LittleLong(mt->height); + for(j = 0 ; j < MIPLEVELS ; j++) + mt->offsets[j] = LittleLong(mt->offsets[j]); - if ( (mt->width & 15) || (mt->height & 15) ) - Sys_Error ("Texture %s is not 16 aligned", mt->name); - pixels = mt->width*mt->height/64*85; - tx = (texture_t *) Hunk_AllocName (sizeof(texture_t) +pixels, loadname ); + if((mt->width & 15) || (mt->height & 15)) + Sys_Error("Texture %s is not 16 aligned", mt->name); + pixels = mt->width * mt->height / 64 * 85; + tx = (texture_t *) Hunk_AllocName(sizeof(texture_t) + pixels, loadname); loadmodel->textures[i] = tx; - memcpy (tx->name, mt->name, sizeof(tx->name)); + memcpy(tx->name, mt->name, sizeof(tx->name)); tx->width = mt->width; tx->height = mt->height; - for (j=0 ; joffsets[j] = mt->offsets[j] + sizeof(texture_t) - sizeof(miptex_t); // the pixels immediately follow the structures @@ -481,154 +484,154 @@ void Mod_LoadTextures (lump_t *l) // appears in the wild; e.g. jam2_tronyn.bsp (func_mapjam2), // kellbase1.bsp (quoth), and can lead to a segfault if we read past // the end of the .bsp file buffer - if (((byte*)(mt+1) + pixels) > (mod_base + l->fileofs + l->filelen)) + if(((byte*)(mt + 1) + pixels) > (mod_base + l->fileofs + l->filelen)) { Con_DPrintf("Texture %s extends past end of lump\n", mt->name); - pixels = q_max(0, (mod_base + l->fileofs + l->filelen) - (byte*)(mt+1)); + pixels = q_max(0, (mod_base + l->fileofs + l->filelen) - (byte*)(mt + 1)); } - memcpy ( tx+1, mt+1, pixels); + memcpy(tx + 1, mt + 1, pixels); tx->update_warp = false; //johnfitz tx->warpimage = NULL; //johnfitz tx->fullbright = NULL; //johnfitz //johnfitz -- lots of changes - if (!isDedicated) //no texture uploading for dedicated server + if(!isDedicated) //no texture uploading for dedicated server { - if (!q_strncasecmp(tx->name,"sky",3)) //sky texture //also note -- was Q_strncmp, changed to match qbsp - Sky_LoadTexture (tx); - else if (tx->name[0] == '*') //warping texture + if(!q_strncasecmp(tx->name, "sky", 3)) //sky texture //also note -- was Q_strncmp, changed to match qbsp + Sky_LoadTexture(tx); + else if(tx->name[0] == '*') //warping texture { //external textures -- first look in "textures/mapname/" then look in "textures/" mark = Hunk_LowMark(); - COM_StripExtension (loadmodel->name + 5, mapname, sizeof(mapname)); - q_snprintf (filename, sizeof(filename), "textures/%s/#%s", mapname, tx->name+1); //this also replaces the '*' with a '#' - data = Image_LoadImage (filename, &fwidth, &fheight); - if (!data) + COM_StripExtension(loadmodel->name + 5, mapname, sizeof(mapname)); + q_snprintf(filename, sizeof(filename), "textures/%s/#%s", mapname, tx->name + 1); //this also replaces the '*' with a '#' + data = Image_LoadImage(filename, &fwidth, &fheight); + if(!data) { - q_snprintf (filename, sizeof(filename), "textures/#%s", tx->name+1); - data = Image_LoadImage (filename, &fwidth, &fheight); + q_snprintf(filename, sizeof(filename), "textures/#%s", tx->name + 1); + data = Image_LoadImage(filename, &fwidth, &fheight); } //now load whatever we found - if (data) //load external image + if(data) //load external image { - q_strlcpy (texturename, filename, sizeof(texturename)); - tx->gltexture = TexMgr_LoadImage (loadmodel, texturename, fwidth, fheight, - SRC_RGBA, data, filename, 0, TEXPREF_NONE); + q_strlcpy(texturename, filename, sizeof(texturename)); + tx->gltexture = TexMgr_LoadImage(loadmodel, texturename, fwidth, fheight, + SRC_RGBA, data, filename, 0, TEXPREF_NONE); } else //use the texture from the bsp file { - q_snprintf (texturename, sizeof(texturename), "%s:%s", loadmodel->name, tx->name); - offset = (src_offset_t)(mt+1) - (src_offset_t)mod_base; - tx->gltexture = TexMgr_LoadImage (loadmodel, texturename, tx->width, tx->height, - SRC_INDEXED, (byte *)(tx+1), loadmodel->name, offset, TEXPREF_NONE); + q_snprintf(texturename, sizeof(texturename), "%s:%s", loadmodel->name, tx->name); + offset = (src_offset_t)(mt + 1) - (src_offset_t)mod_base; + tx->gltexture = TexMgr_LoadImage(loadmodel, texturename, tx->width, tx->height, + SRC_INDEXED, (byte *)(tx + 1), loadmodel->name, offset, TEXPREF_NONE); } //now create the warpimage, using dummy data from the hunk to create the initial image - Hunk_Alloc (gl_warpimagesize*gl_warpimagesize*4); //make sure hunk is big enough so we don't reach an illegal address - Hunk_FreeToLowMark (mark); - q_snprintf (texturename, sizeof(texturename), "%s_warp", texturename); - tx->warpimage = TexMgr_LoadImage (loadmodel, texturename, gl_warpimagesize, - gl_warpimagesize, SRC_RGBA, hunk_base, "", (src_offset_t)hunk_base, TEXPREF_NOPICMIP | TEXPREF_WARPIMAGE); + Hunk_Alloc(gl_warpimagesize * gl_warpimagesize * 4); //make sure hunk is big enough so we don't reach an illegal address + Hunk_FreeToLowMark(mark); + q_snprintf(texturename, sizeof(texturename), "%s_warp", texturename); + tx->warpimage = TexMgr_LoadImage(loadmodel, texturename, gl_warpimagesize, + gl_warpimagesize, SRC_RGBA, hunk_base, "", (src_offset_t)hunk_base, TEXPREF_NOPICMIP | TEXPREF_WARPIMAGE); tx->update_warp = true; } else //regular texture { // ericw -- fence textures - int32_t extraflags; + int32_t extraflags; extraflags = 0; - if (tx->name[0] == '{') + if(tx->name[0] == '{') extraflags |= TEXPREF_ALPHA; // ericw //external textures -- first look in "textures/mapname/" then look in "textures/" - mark = Hunk_LowMark (); - COM_StripExtension (loadmodel->name + 5, mapname, sizeof(mapname)); - q_snprintf (filename, sizeof(filename), "textures/%s/%s", mapname, tx->name); - data = Image_LoadImage (filename, &fwidth, &fheight); - if (!data) + mark = Hunk_LowMark(); + COM_StripExtension(loadmodel->name + 5, mapname, sizeof(mapname)); + q_snprintf(filename, sizeof(filename), "textures/%s/%s", mapname, tx->name); + data = Image_LoadImage(filename, &fwidth, &fheight); + if(!data) { - q_snprintf (filename, sizeof(filename), "textures/%s", tx->name); - data = Image_LoadImage (filename, &fwidth, &fheight); + q_snprintf(filename, sizeof(filename), "textures/%s", tx->name); + data = Image_LoadImage(filename, &fwidth, &fheight); } //now load whatever we found - if (data) //load external image + if(data) //load external image { - tx->gltexture = TexMgr_LoadImage (loadmodel, filename, fwidth, fheight, - SRC_RGBA, data, filename, 0, TEXPREF_MIPMAP | extraflags ); + tx->gltexture = TexMgr_LoadImage(loadmodel, filename, fwidth, fheight, + SRC_RGBA, data, filename, 0, TEXPREF_MIPMAP | extraflags); //now try to load glow/luma image from the same place - Hunk_FreeToLowMark (mark); - q_snprintf (filename2, sizeof(filename2), "%s_glow", filename); - data = Image_LoadImage (filename2, &fwidth, &fheight); - if (!data) + Hunk_FreeToLowMark(mark); + q_snprintf(filename2, sizeof(filename2), "%s_glow", filename); + data = Image_LoadImage(filename2, &fwidth, &fheight); + if(!data) { - q_snprintf (filename2, sizeof(filename2), "%s_luma", filename); - data = Image_LoadImage (filename2, &fwidth, &fheight); + q_snprintf(filename2, sizeof(filename2), "%s_luma", filename); + data = Image_LoadImage(filename2, &fwidth, &fheight); } - if (data) - tx->fullbright = TexMgr_LoadImage (loadmodel, filename2, fwidth, fheight, - SRC_RGBA, data, filename, 0, TEXPREF_MIPMAP | extraflags ); + if(data) + tx->fullbright = TexMgr_LoadImage(loadmodel, filename2, fwidth, fheight, + SRC_RGBA, data, filename, 0, TEXPREF_MIPMAP | extraflags); } else //use the texture from the bsp file { - q_snprintf (texturename, sizeof(texturename), "%s:%s", loadmodel->name, tx->name); - offset = (src_offset_t)(mt+1) - (src_offset_t)mod_base; - if (Mod_CheckFullbrights ((byte *)(tx+1), pixels)) + q_snprintf(texturename, sizeof(texturename), "%s:%s", loadmodel->name, tx->name); + offset = (src_offset_t)(mt + 1) - (src_offset_t)mod_base; + if(Mod_CheckFullbrights((byte *)(tx + 1), pixels)) { - tx->gltexture = TexMgr_LoadImage (loadmodel, texturename, tx->width, tx->height, - SRC_INDEXED, (byte *)(tx+1), loadmodel->name, offset, TEXPREF_MIPMAP | TEXPREF_NOBRIGHT | extraflags); - q_snprintf (texturename, sizeof(texturename), "%s:%s_glow", loadmodel->name, tx->name); - tx->fullbright = TexMgr_LoadImage (loadmodel, texturename, tx->width, tx->height, - SRC_INDEXED, (byte *)(tx+1), loadmodel->name, offset, TEXPREF_MIPMAP | TEXPREF_FULLBRIGHT | extraflags); + tx->gltexture = TexMgr_LoadImage(loadmodel, texturename, tx->width, tx->height, + SRC_INDEXED, (byte *)(tx + 1), loadmodel->name, offset, TEXPREF_MIPMAP | TEXPREF_NOBRIGHT | extraflags); + q_snprintf(texturename, sizeof(texturename), "%s:%s_glow", loadmodel->name, tx->name); + tx->fullbright = TexMgr_LoadImage(loadmodel, texturename, tx->width, tx->height, + SRC_INDEXED, (byte *)(tx + 1), loadmodel->name, offset, TEXPREF_MIPMAP | TEXPREF_FULLBRIGHT | extraflags); } else { - tx->gltexture = TexMgr_LoadImage (loadmodel, texturename, tx->width, tx->height, - SRC_INDEXED, (byte *)(tx+1), loadmodel->name, offset, TEXPREF_MIPMAP | extraflags); + tx->gltexture = TexMgr_LoadImage(loadmodel, texturename, tx->width, tx->height, + SRC_INDEXED, (byte *)(tx + 1), loadmodel->name, offset, TEXPREF_MIPMAP | extraflags); } } - Hunk_FreeToLowMark (mark); + Hunk_FreeToLowMark(mark); } } //johnfitz } //johnfitz -- last 2 slots in array should be filled with dummy textures - loadmodel->textures[loadmodel->numtextures-2] = r_notexture_mip; //for lightmapped surfs - loadmodel->textures[loadmodel->numtextures-1] = r_notexture_mip2; //for SURF_DRAWTILED surfs + loadmodel->textures[loadmodel->numtextures - 2] = r_notexture_mip; //for lightmapped surfs + loadmodel->textures[loadmodel->numtextures - 1] = r_notexture_mip2; //for SURF_DRAWTILED surfs // // sequence the animations // - for (i=0 ; itextures[i]; - if (!tx || tx->name[0] != '+') + if(!tx || tx->name[0] != '+') continue; - if (tx->anim_next) - continue; // allready sequenced + if(tx->anim_next) + continue; // allready sequenced - // find the number of frames in the animation - memset (anims, 0, sizeof(anims)); - memset (altanims, 0, sizeof(altanims)); + // find the number of frames in the animation + memset(anims, 0, sizeof(anims)); + memset(altanims, 0, sizeof(altanims)); maxanim = tx->name[1]; altmax = 0; - if (maxanim >= 'a' && maxanim <= 'z') + if(maxanim >= 'a' && maxanim <= 'z') maxanim -= 'a' - 'A'; - if (maxanim >= '0' && maxanim <= '9') + if(maxanim >= '0' && maxanim <= '9') { maxanim -= '0'; altmax = 0; anims[maxanim] = tx; maxanim++; } - else if (maxanim >= 'A' && maxanim <= 'J') + else if(maxanim >= 'A' && maxanim <= 'J') { altmax = maxanim - 'A'; maxanim = 0; @@ -636,61 +639,61 @@ void Mod_LoadTextures (lump_t *l) altmax++; } else - Sys_Error ("Bad animating texture %s", tx->name); + Sys_Error("Bad animating texture %s", tx->name); - for (j=i+1 ; jtextures[j]; - if (!tx2 || tx2->name[0] != '+') + if(!tx2 || tx2->name[0] != '+') continue; - if (strcmp (tx2->name+2, tx->name+2)) + if(strcmp(tx2->name + 2, tx->name + 2)) continue; num = tx2->name[1]; - if (num >= 'a' && num <= 'z') + if(num >= 'a' && num <= 'z') num -= 'a' - 'A'; - if (num >= '0' && num <= '9') + if(num >= '0' && num <= '9') { num -= '0'; anims[num] = tx2; - if (num+1 > maxanim) + if(num + 1 > maxanim) maxanim = num + 1; } - else if (num >= 'A' && num <= 'J') + else if(num >= 'A' && num <= 'J') { num = num - 'A'; altanims[num] = tx2; - if (num+1 > altmax) - altmax = num+1; + if(num + 1 > altmax) + altmax = num + 1; } else - Sys_Error ("Bad animating texture %s", tx->name); + Sys_Error("Bad animating texture %s", tx->name); } -#define ANIM_CYCLE 2 - // link them all together - for (j=0 ; jname); + if(!tx2) + Sys_Error("Missing frame %" PRIi32 " of %s", j, tx->name); tx2->anim_total = maxanim * ANIM_CYCLE; tx2->anim_min = j * ANIM_CYCLE; - tx2->anim_max = (j+1) * ANIM_CYCLE; - tx2->anim_next = anims[ (j+1)%maxanim ]; - if (altmax) + tx2->anim_max = (j + 1) * ANIM_CYCLE; + tx2->anim_next = anims[(j + 1) % maxanim ]; + if(altmax) tx2->alternate_anims = altanims[0]; } - for (j=0 ; jname); + if(!tx2) + Sys_Error("Missing frame %" PRIi32 " of %s", j, tx->name); tx2->anim_total = altmax * ANIM_CYCLE; tx2->anim_min = j * ANIM_CYCLE; - tx2->anim_max = (j+1) * ANIM_CYCLE; - tx2->anim_next = altanims[ (j+1)%altmax ]; - if (maxanim) + tx2->anim_max = (j + 1) * ANIM_CYCLE; + tx2->anim_next = altanims[(j + 1) % altmax ]; + if(maxanim) tx2->alternate_anims = anims[0]; } } @@ -701,7 +704,7 @@ void Mod_LoadTextures (lump_t *l) Mod_LoadLighting -- johnfitz -- replaced with lit support code via lordhavoc ================= */ -void Mod_LoadLighting (lump_t *l) +void Mod_LoadLighting(lump_t *l) { int32_t i, mark; byte *in, *out, *data; @@ -715,21 +718,20 @@ void Mod_LoadLighting (lump_t *l) COM_StripExtension(litfilename, litfilename, sizeof(litfilename)); q_strlcat(litfilename, ".lit", sizeof(litfilename)); mark = Hunk_LowMark(); - data = (byte*) COM_LoadHunkFile (litfilename, &path_id); - if (data) + data = (byte*) COM_LoadHunkFile(litfilename, &path_id); + if(data) { // use lit file only from the same gamedir as the map // itself or from a searchpath with higher priority. - if (path_id < loadmodel->path_id) + if(path_id < loadmodel->path_id) { Hunk_FreeToLowMark(mark); Con_DPrintf("ignored %s from a gamedir with lower priority\n", litfilename); } - else - if (data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T') + else if(data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T') { i = LittleLong(((int32_t *)data)[1]); - if (i == 1) + if(i == 1) { Con_DPrintf2("%s loaded\n", litfilename); loadmodel->lightdata = data + 8; @@ -748,13 +750,13 @@ void Mod_LoadLighting (lump_t *l) } } // LordHavoc: no .lit found, expand the white lighting data to color - if (!l->filelen) + if(!l->filelen) return; - loadmodel->lightdata = (byte *) Hunk_AllocName ( l->filelen*3, litfilename); - in = loadmodel->lightdata + l->filelen*2; // place the file at the end, so it will not be overwritten until the very last write + loadmodel->lightdata = (byte *) Hunk_AllocName(l->filelen * 3, litfilename); + in = loadmodel->lightdata + l->filelen * 2; // place the file at the end, so it will not be overwritten until the very last write out = loadmodel->lightdata; - memcpy (in, mod_base + l->fileofs, l->filelen); - for (i = 0;i < l->filelen;i++) + memcpy(in, mod_base + l->fileofs, l->filelen); + for(i = 0; i < l->filelen; i++) { d = *in++; *out++ = d; @@ -769,16 +771,16 @@ void Mod_LoadLighting (lump_t *l) Mod_LoadVisibility ================= */ -void Mod_LoadVisibility (lump_t *l) +void Mod_LoadVisibility(lump_t *l) { loadmodel->viswarn = false; - if (!l->filelen) + if(!l->filelen) { loadmodel->visdata = NULL; return; } - loadmodel->visdata = (byte *) Hunk_AllocName ( l->filelen, loadname); - memcpy (loadmodel->visdata, mod_base + l->fileofs, l->filelen); + loadmodel->visdata = (byte *) Hunk_AllocName(l->filelen, loadname); + memcpy(loadmodel->visdata, mod_base + l->fileofs, l->filelen); } @@ -787,14 +789,14 @@ void Mod_LoadVisibility (lump_t *l) Mod_LoadEntities ================= */ -void Mod_LoadEntities (lump_t *l) +void Mod_LoadEntities(lump_t *l) { - char entfilename[MAX_QPATH]; - char *ents; - int32_t mark; - uint32_t path_id; + char entfilename[MAX_QPATH]; + char *ents; + int32_t mark; + uint32_t path_id; - if (! external_ents.value) + if(! external_ents.value) goto _load_embedded; q_strlcpy(entfilename, loadmodel->name, sizeof(entfilename)); @@ -802,12 +804,12 @@ void Mod_LoadEntities (lump_t *l) q_strlcat(entfilename, ".ent", sizeof(entfilename)); Con_DPrintf2("trying to load %s\n", entfilename); mark = Hunk_LowMark(); - ents = (char *) COM_LoadHunkFile (entfilename, &path_id); - if (ents) + ents = (char *) COM_LoadHunkFile(entfilename, &path_id); + if(ents) { // use ent file only from the same gamedir as the map // itself or from a searchpath with higher priority. - if (path_id < loadmodel->path_id) + if(path_id < loadmodel->path_id) { Hunk_FreeToLowMark(mark); Con_DPrintf("ignored %s from a gamedir with lower priority\n", entfilename); @@ -821,13 +823,13 @@ void Mod_LoadEntities (lump_t *l) } _load_embedded: - if (!l->filelen) + if(!l->filelen) { loadmodel->entities = NULL; return; } - loadmodel->entities = (char *) Hunk_AllocName ( l->filelen, loadname); - memcpy (loadmodel->entities, mod_base + l->fileofs, l->filelen); + loadmodel->entities = (char *) Hunk_AllocName(l->filelen, loadname); + memcpy(loadmodel->entities, mod_base + l->fileofs, l->filelen); } @@ -836,26 +838,26 @@ _load_embedded: Mod_LoadVertexes ================= */ -void Mod_LoadVertexes (lump_t *l) +void Mod_LoadVertexes(lump_t *l) { - dvertex_t *in; - mvertex_t *out; - int32_t i, count; + dvertex_t *in; + mvertex_t *out; + int32_t i, count; in = (dvertex_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (mvertex_t *) Hunk_AllocName ( count*sizeof(*out), loadname); + out = (mvertex_t *) Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->vertexes = out; loadmodel->numvertexes = count; - for (i=0 ; iposition[0] = LittleFloat (in->point[0]); - out->position[1] = LittleFloat (in->point[1]); - out->position[2] = LittleFloat (in->point[2]); + out->position[0] = LittleFloat(in->point[0]); + out->position[1] = LittleFloat(in->point[1]); + out->position[2] = LittleFloat(in->point[2]); } } @@ -864,25 +866,25 @@ void Mod_LoadVertexes (lump_t *l) Mod_LoadEdges ================= */ -void Mod_LoadEdges (lump_t *l, int32_t bsp2) +void Mod_LoadEdges(lump_t *l, int32_t bsp2) { medge_t *out; - int32_t i, count; + int32_t i, count; - if (bsp2) + if(bsp2) { dledge_t *in = (dledge_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (medge_t *) Hunk_AllocName ( (count + 1) * sizeof(*out), loadname); + out = (medge_t *) Hunk_AllocName((count + 1) * sizeof(*out), loadname); loadmodel->edges = out; loadmodel->numedges = count; - for (i=0 ; iv[0] = LittleLong(in->v[0]); out->v[1] = LittleLong(in->v[1]); @@ -892,16 +894,16 @@ void Mod_LoadEdges (lump_t *l, int32_t bsp2) { dsedge_t *in = (dsedge_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (medge_t *) Hunk_AllocName ( (count + 1) * sizeof(*out), loadname); + out = (medge_t *) Hunk_AllocName((count + 1) * sizeof(*out), loadname); loadmodel->edges = out; loadmodel->numedges = count; - for (i=0 ; iv[0] = (uint16_t)LittleShort(in->v[0]); out->v[1] = (uint16_t)LittleShort(in->v[1]); @@ -914,58 +916,58 @@ void Mod_LoadEdges (lump_t *l, int32_t bsp2) Mod_LoadTexinfo ================= */ -void Mod_LoadTexinfo (lump_t *l) +void Mod_LoadTexinfo(lump_t *l) { texinfo_t *in; mtexinfo_t *out; - int32_t i, j, count, miptex; - float len1, len2; + int32_t i, j, count, miptex; + float len1, len2; int32_t missing = 0; //johnfitz in = (texinfo_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (mtexinfo_t *) Hunk_AllocName ( count*sizeof(*out), loadname); + out = (mtexinfo_t *) Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->texinfo = out; loadmodel->numtexinfo = count; - for (i=0 ; ivecs[0][j] = LittleFloat (in->vecs[0][j]); - out->vecs[1][j] = LittleFloat (in->vecs[1][j]); + out->vecs[0][j] = LittleFloat(in->vecs[0][j]); + out->vecs[1][j] = LittleFloat(in->vecs[1][j]); } - len1 = VectorLength (out->vecs[0]); - len2 = VectorLength (out->vecs[1]); - len1 = (len1 + len2)/2; - if (len1 < 0.32) + len1 = VectorLength(out->vecs[0]); + len2 = VectorLength(out->vecs[1]); + len1 = (len1 + len2) / 2; + if(len1 < 0.32) out->mipadjust = 4; - else if (len1 < 0.49) + else if(len1 < 0.49) out->mipadjust = 3; - else if (len1 < 0.99) + else if(len1 < 0.99) out->mipadjust = 2; else out->mipadjust = 1; #if 0 - if (len1 + len2 < 0.001) - out->mipadjust = 1; // don't crash + if(len1 + len2 < 0.001) + out->mipadjust = 1; // don't crash else - out->mipadjust = 1 / floor((len1+len2)/2 + 0.1); + out->mipadjust = 1 / floor((len1 + len2) / 2 + 0.1); #endif - miptex = LittleLong (in->miptex); - out->flags = LittleLong (in->flags); + miptex = LittleLong(in->miptex); + out->flags = LittleLong(in->flags); //johnfitz -- rewrote this section - if (miptex >= loadmodel->numtextures-1 || !loadmodel->textures[miptex]) + if(miptex >= loadmodel->numtextures - 1 || !loadmodel->textures[miptex]) { - if (out->flags & TEX_SPECIAL) - out->texture = loadmodel->textures[loadmodel->numtextures-1]; + if(out->flags & TEX_SPECIAL) + out->texture = loadmodel->textures[loadmodel->numtextures - 1]; else - out->texture = loadmodel->textures[loadmodel->numtextures-2]; + out->texture = loadmodel->textures[loadmodel->numtextures - 2]; out->flags |= TEX_MISSING; missing++; } @@ -977,8 +979,8 @@ void Mod_LoadTexinfo (lump_t *l) } //johnfitz: report missing textures - if (missing && loadmodel->numtextures > 1) - Con_Printf ("Mod_LoadTexinfo: %" PRIi32 " texture(s) missing from BSP file\n", missing); + if(missing && loadmodel->numtextures > 1) + Con_Printf("Mod_LoadTexinfo: %" PRIi32 " texture(s) missing from BSP file\n", missing); //johnfitz } @@ -989,28 +991,28 @@ CalcSurfaceExtents Fills in s->texturemins[] and s->extents[] ================ */ -void CalcSurfaceExtents (msurface_t *s) +void CalcSurfaceExtents(msurface_t *s) { - float mins[2], maxs[2], val; - int32_t i,j, e; - mvertex_t *v; - mtexinfo_t *tex; - int32_t bmins[2], bmaxs[2]; + float mins[2], maxs[2], val; + int32_t i, j, e; + mvertex_t *v; + mtexinfo_t *tex; + int32_t bmins[2], bmaxs[2]; mins[0] = mins[1] = 999999; maxs[0] = maxs[1] = -99999; tex = s->texinfo; - for (i=0 ; inumedges ; i++) + for(i = 0 ; i < s->numedges ; i++) { - e = loadmodel->surfedges[s->firstedge+i]; - if (e >= 0) + e = loadmodel->surfedges[s->firstedge + i]; + if(e >= 0) v = &loadmodel->vertexes[loadmodel->edges[e].v[0]]; else v = &loadmodel->vertexes[loadmodel->edges[-e].v[1]]; - for (j=0 ; j<2 ; j++) + for(j = 0 ; j < 2 ; j++) { /* The following calculation is sensitive to floating-point * precision. It needs to produce the same result that the @@ -1027,28 +1029,28 @@ void CalcSurfaceExtents (msurface_t *s) * and using SSE2 floating-point. A potential trouble spot * is the hallway at the beginning of mfxsp17. -- ericw */ - val = ((double)v->position[0] * (double)tex->vecs[j][0]) + - ((double)v->position[1] * (double)tex->vecs[j][1]) + - ((double)v->position[2] * (double)tex->vecs[j][2]) + - (double)tex->vecs[j][3]; + val = ((double)v->position[0] * (double)tex->vecs[j][0]) + + ((double)v->position[1] * (double)tex->vecs[j][1]) + + ((double)v->position[2] * (double)tex->vecs[j][2]) + + (double)tex->vecs[j][3]; - if (val < mins[j]) + if(val < mins[j]) mins[j] = val; - if (val > maxs[j]) + if(val > maxs[j]) maxs[j] = val; } } - for (i=0 ; i<2 ; i++) + for(i = 0 ; i < 2 ; i++) { - bmins[i] = floor(mins[i]/16); - bmaxs[i] = ceil(maxs[i]/16); + bmins[i] = floor(mins[i] / 16); + bmaxs[i] = ceil(maxs[i] / 16); s->texturemins[i] = bmins[i] * 16; s->extents[i] = (bmaxs[i] - bmins[i]) * 16; - if ( !(tex->flags & TEX_SPECIAL) && s->extents[i] > 2000) //johnfitz -- was 512 in glquake, 256 in winquake - Sys_Error ("Bad surface extents"); + if(!(tex->flags & TEX_SPECIAL) && s->extents[i] > 2000) //johnfitz -- was 512 in glquake, 256 in winquake + Sys_Error("Bad surface extents"); } } @@ -1059,41 +1061,41 @@ Mod_PolyForUnlitSurface -- johnfitz -- creates polys for unlightmapped surfaces TODO: merge this into BuildSurfaceDisplayList? ================ */ -void Mod_PolyForUnlitSurface (msurface_t *fa) +void Mod_PolyForUnlitSurface(msurface_t *fa) { - vec3_t verts[64]; - int32_t numverts, i, lindex; - float *vec; - glpoly_t *poly; - float texscale; + vec3_t verts[64]; + int32_t numverts, i, lindex; + float *vec; + glpoly_t *poly; + float texscale; - if (fa->flags & (SURF_DRAWTURB | SURF_DRAWSKY)) - texscale = (1.0/128.0); //warp animation repeats every 128 + if(fa->flags & (SURF_DRAWTURB | SURF_DRAWSKY)) + texscale = (1.0 / 128.0); //warp animation repeats every 128 else - texscale = (1.0/32.0); //to match r_notexture_mip + texscale = (1.0 / 32.0); //to match r_notexture_mip // convert edges back to a normal polygon numverts = 0; - for (i=0 ; inumedges ; i++) + for(i = 0 ; i < fa->numedges ; i++) { lindex = loadmodel->surfedges[fa->firstedge + i]; - if (lindex > 0) + if(lindex > 0) vec = loadmodel->vertexes[loadmodel->edges[lindex].v[0]].position; else vec = loadmodel->vertexes[loadmodel->edges[-lindex].v[1]].position; - VectorCopy (vec, verts[numverts]); + VectorCopy(vec, verts[numverts]); numverts++; } //create the poly - poly = (glpoly_t *) Hunk_Alloc (sizeof(glpoly_t) + (numverts-4) * VERTEXSIZE*sizeof(float)); + poly = (glpoly_t *) Hunk_Alloc(sizeof(glpoly_t) + (numverts - 4) * VERTEXSIZE * sizeof(float)); poly->next = NULL; fa->polys = poly; poly->numverts = numverts; - for (i=0, vec=(float *)verts; iverts[i]); + VectorCopy(vec, poly->verts[i]); poly->verts[i][3] = DotProduct(vec, fa->texinfo->vecs[0]) * texscale; poly->verts[i][4] = DotProduct(vec, fa->texinfo->vecs[1]) * texscale; } @@ -1104,34 +1106,34 @@ void Mod_PolyForUnlitSurface (msurface_t *fa) Mod_CalcSurfaceBounds -- johnfitz -- calculate bounding box for per-surface frustum culling ================= */ -void Mod_CalcSurfaceBounds (msurface_t *s) +void Mod_CalcSurfaceBounds(msurface_t *s) { - int32_t i, e; - mvertex_t *v; + int32_t i, e; + mvertex_t *v; s->mins[0] = s->mins[1] = s->mins[2] = 9999; s->maxs[0] = s->maxs[1] = s->maxs[2] = -9999; - for (i=0 ; inumedges ; i++) + for(i = 0 ; i < s->numedges ; i++) { - e = loadmodel->surfedges[s->firstedge+i]; - if (e >= 0) + e = loadmodel->surfedges[s->firstedge + i]; + if(e >= 0) v = &loadmodel->vertexes[loadmodel->edges[e].v[0]]; else v = &loadmodel->vertexes[loadmodel->edges[-e].v[1]]; - if (s->mins[0] > v->position[0]) + if(s->mins[0] > v->position[0]) s->mins[0] = v->position[0]; - if (s->mins[1] > v->position[1]) + if(s->mins[1] > v->position[1]) s->mins[1] = v->position[1]; - if (s->mins[2] > v->position[2]) + if(s->mins[2] > v->position[2]) s->mins[2] = v->position[2]; - if (s->maxs[0] < v->position[0]) + if(s->maxs[0] < v->position[0]) s->maxs[0] = v->position[0]; - if (s->maxs[1] < v->position[1]) + if(s->maxs[1] < v->position[1]) s->maxs[1] = v->position[1]; - if (s->maxs[2] < v->position[2]) + if(s->maxs[2] < v->position[2]) s->maxs[2] = v->position[2]; } } @@ -1141,50 +1143,50 @@ void Mod_CalcSurfaceBounds (msurface_t *s) Mod_LoadFaces ================= */ -void Mod_LoadFaces (lump_t *l, bool bsp2) +void Mod_LoadFaces(lump_t *l, bool bsp2) { - dsface_t *ins; - dlface_t *inl; - msurface_t *out; - int32_t i, count, surfnum, lofs; - int32_t planenum, side, texinfon; + dsface_t *ins; + dlface_t *inl; + msurface_t *out; + int32_t i, count, surfnum, lofs; + int32_t planenum, side, texinfon; - if (bsp2) + if(bsp2) { ins = NULL; inl = (dlface_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*inl)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*inl)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*inl); } else { ins = (dsface_t *)(mod_base + l->fileofs); inl = NULL; - if (l->filelen % sizeof(*ins)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*ins)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*ins); } - out = (msurface_t *)Hunk_AllocName ( count*sizeof(*out), loadname); + out = (msurface_t *)Hunk_AllocName(count * sizeof(*out), loadname); //johnfitz -- warn mappers about exceeding old limits - if (count > 32767 && !bsp2) - Con_DWarning ("%" PRIi32 " faces exceeds standard limit of 32767.\n", count); + if(count > 32767 && !bsp2) + Con_DWarning("%" PRIi32 " faces exceeds standard limit of 32767.\n", count); //johnfitz loadmodel->surfaces = out; loadmodel->numsurfaces = count; - for (surfnum=0 ; surfnumfirstedge = LittleLong(inl->firstedge); out->numedges = LittleLong(inl->numedges); planenum = LittleLong(inl->planenum); side = LittleLong(inl->side); - texinfon = LittleLong (inl->texinfo); - for (i=0 ; itexinfo); + for(i = 0 ; i < MAXLIGHTMAPS ; i++) out->styles[i] = inl->styles[i]; lofs = LittleLong(inl->lightofs); inl++; @@ -1195,8 +1197,8 @@ void Mod_LoadFaces (lump_t *l, bool bsp2) out->numedges = LittleShort(ins->numedges); planenum = LittleShort(ins->planenum); side = LittleShort(ins->side); - texinfon = LittleShort (ins->texinfo); - for (i=0 ; itexinfo); + for(i = 0 ; i < MAXLIGHTMAPS ; i++) out->styles[i] = ins->styles[i]; lofs = LittleLong(ins->lightofs); ins++; @@ -1204,59 +1206,59 @@ void Mod_LoadFaces (lump_t *l, bool bsp2) out->flags = 0; - if (side) + if(side) out->flags |= SURF_PLANEBACK; out->plane = loadmodel->planes + planenum; out->texinfo = loadmodel->texinfo + texinfon; - CalcSurfaceExtents (out); + CalcSurfaceExtents(out); - Mod_CalcSurfaceBounds (out); //johnfitz -- for per-surface frustum culling + Mod_CalcSurfaceBounds(out); //johnfitz -- for per-surface frustum culling - // lighting info - if (lofs == -1) + // lighting info + if(lofs == -1) out->samples = NULL; else out->samples = loadmodel->lightdata + (lofs * 3); //johnfitz -- lit support via lordhavoc (was "+ i") //johnfitz -- this section rewritten - if (!q_strncasecmp(out->texinfo->texture->name,"sky",3)) // sky surface //also note -- was Q_strncmp, changed to match qbsp + if(!q_strncasecmp(out->texinfo->texture->name, "sky", 3)) // sky surface //also note -- was Q_strncmp, changed to match qbsp { out->flags |= (SURF_DRAWSKY | SURF_DRAWTILED); - Mod_PolyForUnlitSurface (out); //no more subdivision + Mod_PolyForUnlitSurface(out); //no more subdivision } - else if (out->texinfo->texture->name[0] == '*') // warp surface + else if(out->texinfo->texture->name[0] == '*') // warp surface { out->flags |= (SURF_DRAWTURB | SURF_DRAWTILED); - // detect special liquid types - if (!strncmp (out->texinfo->texture->name, "*lava", 5)) + // detect special liquid types + if(!strncmp(out->texinfo->texture->name, "*lava", 5)) out->flags |= SURF_DRAWLAVA; - else if (!strncmp (out->texinfo->texture->name, "*slime", 6)) + else if(!strncmp(out->texinfo->texture->name, "*slime", 6)) out->flags |= SURF_DRAWSLIME; - else if (!strncmp (out->texinfo->texture->name, "*tele", 5)) + else if(!strncmp(out->texinfo->texture->name, "*tele", 5)) out->flags |= SURF_DRAWTELE; else out->flags |= SURF_DRAWWATER; - Mod_PolyForUnlitSurface (out); - GL_SubdivideSurface (out); + Mod_PolyForUnlitSurface(out); + GL_SubdivideSurface(out); } - else if (out->texinfo->texture->name[0] == '{') // ericw -- fence textures + else if(out->texinfo->texture->name[0] == '{') // ericw -- fence textures { out->flags |= SURF_DRAWFENCE; } - else if (out->texinfo->flags & TEX_MISSING) // texture is missing from bsp + else if(out->texinfo->flags & TEX_MISSING) // texture is missing from bsp { - if (out->samples) //lightmapped + if(out->samples) //lightmapped { out->flags |= SURF_NOTEXTURE; } else // not lightmapped { out->flags |= (SURF_NOTEXTURE | SURF_DRAWTILED); - Mod_PolyForUnlitSurface (out); + Mod_PolyForUnlitSurface(out); } } //johnfitz @@ -1269,13 +1271,13 @@ void Mod_LoadFaces (lump_t *l, bool bsp2) Mod_SetParent ================= */ -void Mod_SetParent (mnode_t *node, mnode_t *parent) +void Mod_SetParent(mnode_t *node, mnode_t *parent) { node->parent = parent; - if (node->contents < 0) + if(node->contents < 0) return; - Mod_SetParent (node->children[0], node); - Mod_SetParent (node->children[1], node); + Mod_SetParent(node->children[0], node); + Mod_SetParent(node->children[1], node); } /* @@ -1283,50 +1285,50 @@ void Mod_SetParent (mnode_t *node, mnode_t *parent) Mod_LoadNodes ================= */ -void Mod_LoadNodes_S (lump_t *l) +void Mod_LoadNodes_S(lump_t *l) { - int32_t i, j, count, p; - dsnode_t *in; - mnode_t *out; + int32_t i, j, count, p; + dsnode_t *in; + mnode_t *out; in = (dsnode_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (mnode_t *) Hunk_AllocName ( count*sizeof(*out), loadname); + out = (mnode_t *) Hunk_AllocName(count * sizeof(*out), loadname); //johnfitz -- warn mappers about exceeding old limits - if (count > 32767) - Con_DWarning ("%" PRIi32 " nodes exceeds standard limit of 32767.\n", count); + if(count > 32767) + Con_DWarning("%" PRIi32 " nodes exceeds standard limit of 32767.\n", count); //johnfitz loadmodel->nodes = out; loadmodel->numnodes = count; - for (i=0 ; iminmaxs[j] = LittleShort (in->mins[j]); - out->minmaxs[3+j] = LittleShort (in->maxs[j]); + out->minmaxs[j] = LittleShort(in->mins[j]); + out->minmaxs[3 + j] = LittleShort(in->maxs[j]); } p = LittleLong(in->planenum); out->plane = loadmodel->planes + p; - out->firstsurface = (uint16_t)LittleShort (in->firstface); //johnfitz -- explicit cast as uint16_t - out->numsurfaces = (uint16_t)LittleShort (in->numfaces); //johnfitz -- explicit cast as uint16_t + out->firstsurface = (uint16_t)LittleShort(in->firstface); //johnfitz -- explicit cast as uint16_t + out->numsurfaces = (uint16_t)LittleShort(in->numfaces); //johnfitz -- explicit cast as uint16_t - for (j=0 ; j<2 ; j++) + for(j = 0 ; j < 2 ; j++) { //johnfitz -- hack to handle nodes > 32k, adapted from darkplaces p = (uint16_t)LittleShort(in->children[j]); - if (p < count) + if(p < count) out->children[j] = loadmodel->nodes + p; else { p = 65535 - p; //note this uses 65535 intentionally, -1 is leaf 0 - if (p < loadmodel->numleafs) + if(p < loadmodel->numleafs) out->children[j] = (mnode_t *)(loadmodel->leafs + p); else { @@ -1339,46 +1341,46 @@ void Mod_LoadNodes_S (lump_t *l) } } -void Mod_LoadNodes_L1 (lump_t *l) +void Mod_LoadNodes_L1(lump_t *l) { - int32_t i, j, count, p; - dl1node_t *in; - mnode_t *out; + int32_t i, j, count, p; + dl1node_t *in; + mnode_t *out; in = (dl1node_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("Mod_LoadNodes: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("Mod_LoadNodes: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (mnode_t *)Hunk_AllocName ( count*sizeof(*out), loadname); + out = (mnode_t *)Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->nodes = out; loadmodel->numnodes = count; - for (i=0 ; iminmaxs[j] = LittleShort (in->mins[j]); - out->minmaxs[3+j] = LittleShort (in->maxs[j]); + out->minmaxs[j] = LittleShort(in->mins[j]); + out->minmaxs[3 + j] = LittleShort(in->maxs[j]); } p = LittleLong(in->planenum); out->plane = loadmodel->planes + p; - out->firstsurface = LittleLong (in->firstface); //johnfitz -- explicit cast as uint16_t - out->numsurfaces = LittleLong (in->numfaces); //johnfitz -- explicit cast as uint16_t + out->firstsurface = LittleLong(in->firstface); //johnfitz -- explicit cast as uint16_t + out->numsurfaces = LittleLong(in->numfaces); //johnfitz -- explicit cast as uint16_t - for (j=0 ; j<2 ; j++) + for(j = 0 ; j < 2 ; j++) { //johnfitz -- hack to handle nodes > 32k, adapted from darkplaces p = LittleLong(in->children[j]); - if (p >= 0 && p < count) + if(p >= 0 && p < count) out->children[j] = loadmodel->nodes + p; else { p = 0xffffffff - p; //note this uses 65535 intentionally, -1 is leaf 0 - if (p >= 0 && p < loadmodel->numleafs) + if(p >= 0 && p < loadmodel->numleafs) out->children[j] = (mnode_t *)(loadmodel->leafs + p); else { @@ -1391,46 +1393,46 @@ void Mod_LoadNodes_L1 (lump_t *l) } } -void Mod_LoadNodes_L2 (lump_t *l) +void Mod_LoadNodes_L2(lump_t *l) { - int32_t i, j, count, p; - dl2node_t *in; - mnode_t *out; + int32_t i, j, count, p; + dl2node_t *in; + mnode_t *out; in = (dl2node_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("Mod_LoadNodes: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("Mod_LoadNodes: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (mnode_t *)Hunk_AllocName ( count*sizeof(*out), loadname); + out = (mnode_t *)Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->nodes = out; loadmodel->numnodes = count; - for (i=0 ; iminmaxs[j] = LittleFloat (in->mins[j]); - out->minmaxs[3+j] = LittleFloat (in->maxs[j]); + out->minmaxs[j] = LittleFloat(in->mins[j]); + out->minmaxs[3 + j] = LittleFloat(in->maxs[j]); } p = LittleLong(in->planenum); out->plane = loadmodel->planes + p; - out->firstsurface = LittleLong (in->firstface); //johnfitz -- explicit cast as uint16_t - out->numsurfaces = LittleLong (in->numfaces); //johnfitz -- explicit cast as uint16_t + out->firstsurface = LittleLong(in->firstface); //johnfitz -- explicit cast as uint16_t + out->numsurfaces = LittleLong(in->numfaces); //johnfitz -- explicit cast as uint16_t - for (j=0 ; j<2 ; j++) + for(j = 0 ; j < 2 ; j++) { //johnfitz -- hack to handle nodes > 32k, adapted from darkplaces p = LittleLong(in->children[j]); - if (p > 0 && p < count) + if(p > 0 && p < count) out->children[j] = loadmodel->nodes + p; else { p = 0xffffffff - p; //note this uses 65535 intentionally, -1 is leaf 0 - if (p >= 0 && p < loadmodel->numleafs) + if(p >= 0 && p < loadmodel->numleafs) out->children[j] = (mnode_t *)(loadmodel->leafs + p); else { @@ -1443,42 +1445,42 @@ void Mod_LoadNodes_L2 (lump_t *l) } } -void Mod_LoadNodes (lump_t *l, int32_t bsp2) +void Mod_LoadNodes(lump_t *l, int32_t bsp2) { - if (bsp2 == 2) + if(bsp2 == 2) Mod_LoadNodes_L2(l); - else if (bsp2) + else if(bsp2) Mod_LoadNodes_L1(l); else Mod_LoadNodes_S(l); - Mod_SetParent (loadmodel->nodes, NULL); // sets nodes and leafs + Mod_SetParent(loadmodel->nodes, NULL); // sets nodes and leafs } -void Mod_ProcessLeafs_S (dsleaf_t *in, int32_t filelen) +void Mod_ProcessLeafs_S(dsleaf_t *in, int32_t filelen) { - mleaf_t *out; - int32_t i, j, count, p; + mleaf_t *out; + int32_t i, j, count, p; - if (filelen % sizeof(*in)) - Sys_Error ("Mod_ProcessLeafs: funny lump size in %s", loadmodel->name); + if(filelen % sizeof(*in)) + Sys_Error("Mod_ProcessLeafs: funny lump size in %s", loadmodel->name); count = filelen / sizeof(*in); - out = (mleaf_t *) Hunk_AllocName ( count*sizeof(*out), loadname); + out = (mleaf_t *) Hunk_AllocName(count * sizeof(*out), loadname); //johnfitz - if (count > 32767) - Host_Error ("Mod_LoadLeafs: %" PRIi32 " leafs exceeds limit of 32767.\n", count); + if(count > 32767) + Host_Error("Mod_LoadLeafs: %" PRIi32 " leafs exceeds limit of 32767.\n", count); //johnfitz loadmodel->leafs = out; loadmodel->numleafs = count; - for (i=0 ; iminmaxs[j] = LittleShort (in->mins[j]); - out->minmaxs[3+j] = LittleShort (in->maxs[j]); + out->minmaxs[j] = LittleShort(in->mins[j]); + out->minmaxs[3 + j] = LittleShort(in->maxs[j]); } p = LittleLong(in->contents); @@ -1488,40 +1490,40 @@ void Mod_ProcessLeafs_S (dsleaf_t *in, int32_t filelen) out->nummarksurfaces = (uint16_t)LittleShort(in->nummarksurfaces); //johnfitz -- uint16_t p = LittleLong(in->visofs); - if (p == -1) + if(p == -1) out->compressed_vis = NULL; else out->compressed_vis = loadmodel->visdata + p; out->efrags = NULL; - for (j=0 ; j<4 ; j++) + for(j = 0 ; j < 4 ; j++) out->ambient_sound_level[j] = in->ambient_level[j]; //johnfitz -- removed code to mark surfaces as SURF_UNDERWATER } } -void Mod_ProcessLeafs_L1 (dl1leaf_t *in, int32_t filelen) +void Mod_ProcessLeafs_L1(dl1leaf_t *in, int32_t filelen) { - mleaf_t *out; - int32_t i, j, count, p; + mleaf_t *out; + int32_t i, j, count, p; - if (filelen % sizeof(*in)) - Sys_Error ("Mod_ProcessLeafs: funny lump size in %s", loadmodel->name); + if(filelen % sizeof(*in)) + Sys_Error("Mod_ProcessLeafs: funny lump size in %s", loadmodel->name); count = filelen / sizeof(*in); - out = (mleaf_t *) Hunk_AllocName (count * sizeof(*out), loadname); + out = (mleaf_t *) Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->leafs = out; loadmodel->numleafs = count; - for (i=0 ; iminmaxs[j] = LittleShort (in->mins[j]); - out->minmaxs[3+j] = LittleShort (in->maxs[j]); + out->minmaxs[j] = LittleShort(in->mins[j]); + out->minmaxs[3 + j] = LittleShort(in->maxs[j]); } p = LittleLong(in->contents); @@ -1531,40 +1533,40 @@ void Mod_ProcessLeafs_L1 (dl1leaf_t *in, int32_t filelen) out->nummarksurfaces = LittleLong(in->nummarksurfaces); //johnfitz -- uint16_t p = LittleLong(in->visofs); - if (p == -1) + if(p == -1) out->compressed_vis = NULL; else out->compressed_vis = loadmodel->visdata + p; out->efrags = NULL; - for (j=0 ; j<4 ; j++) + for(j = 0 ; j < 4 ; j++) out->ambient_sound_level[j] = in->ambient_level[j]; //johnfitz -- removed code to mark surfaces as SURF_UNDERWATER } } -void Mod_ProcessLeafs_L2 (dl2leaf_t *in, int32_t filelen) +void Mod_ProcessLeafs_L2(dl2leaf_t *in, int32_t filelen) { - mleaf_t *out; - int32_t i, j, count, p; + mleaf_t *out; + int32_t i, j, count, p; - if (filelen % sizeof(*in)) - Sys_Error ("Mod_ProcessLeafs: funny lump size in %s", loadmodel->name); + if(filelen % sizeof(*in)) + Sys_Error("Mod_ProcessLeafs: funny lump size in %s", loadmodel->name); count = filelen / sizeof(*in); - out = (mleaf_t *) Hunk_AllocName (count * sizeof(*out), loadname); + out = (mleaf_t *) Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->leafs = out; loadmodel->numleafs = count; - for (i=0 ; iminmaxs[j] = LittleFloat (in->mins[j]); - out->minmaxs[3+j] = LittleFloat (in->maxs[j]); + out->minmaxs[j] = LittleFloat(in->mins[j]); + out->minmaxs[3 + j] = LittleFloat(in->maxs[j]); } p = LittleLong(in->contents); @@ -1574,13 +1576,13 @@ void Mod_ProcessLeafs_L2 (dl2leaf_t *in, int32_t filelen) out->nummarksurfaces = LittleLong(in->nummarksurfaces); //johnfitz -- uint16_t p = LittleLong(in->visofs); - if (p == -1) + if(p == -1) out->compressed_vis = NULL; else out->compressed_vis = loadmodel->visdata + p; out->efrags = NULL; - for (j=0 ; j<4 ; j++) + for(j = 0 ; j < 4 ; j++) out->ambient_sound_level[j] = in->ambient_level[j]; //johnfitz -- removed code to mark surfaces as SURF_UNDERWATER @@ -1592,16 +1594,16 @@ void Mod_ProcessLeafs_L2 (dl2leaf_t *in, int32_t filelen) Mod_LoadLeafs ================= */ -void Mod_LoadLeafs (lump_t *l, int32_t bsp2) +void Mod_LoadLeafs(lump_t *l, int32_t bsp2) { void *in = (void *)(mod_base + l->fileofs); - if (bsp2 == 2) - Mod_ProcessLeafs_L2 ((dl2leaf_t *)in, l->filelen); - else if (bsp2) - Mod_ProcessLeafs_L1 ((dl1leaf_t *)in, l->filelen); + if(bsp2 == 2) + Mod_ProcessLeafs_L2((dl2leaf_t *)in, l->filelen); + else if(bsp2) + Mod_ProcessLeafs_L1((dl1leaf_t *)in, l->filelen); else - Mod_ProcessLeafs_S ((dsleaf_t *) in, l->filelen); + Mod_ProcessLeafs_S((dsleaf_t *) in, l->filelen); } /* @@ -1609,21 +1611,21 @@ void Mod_LoadLeafs (lump_t *l, int32_t bsp2) Mod_LoadClipnodes ================= */ -void Mod_LoadClipnodes (lump_t *l, bool bsp2) +void Mod_LoadClipnodes(lump_t *l, bool bsp2) { dsclipnode_t *ins; dlclipnode_t *inl; mclipnode_t *out; //johnfitz -- was dclipnode_t - int32_t i, count; - hull_t *hull; + int32_t i, count; + hull_t *hull; - if (bsp2) + if(bsp2) { ins = NULL; inl = (dlclipnode_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*inl)) - Sys_Error ("Mod_LoadClipnodes: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*inl)) + Sys_Error("Mod_LoadClipnodes: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*inl); } @@ -1631,16 +1633,16 @@ void Mod_LoadClipnodes (lump_t *l, bool bsp2) { ins = (dsclipnode_t *)(mod_base + l->fileofs); inl = NULL; - if (l->filelen % sizeof(*ins)) - Sys_Error ("Mod_LoadClipnodes: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*ins)) + Sys_Error("Mod_LoadClipnodes: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*ins); } - out = (mclipnode_t *) Hunk_AllocName ( count*sizeof(*out), loadname); + out = (mclipnode_t *) Hunk_AllocName(count * sizeof(*out), loadname); //johnfitz -- warn about exceeding old limits - if (count > 32767 && !bsp2) - Con_DWarning ("%" PRIi32 " clipnodes exceeds standard limit of 32767.\n", count); + if(count > 32767 && !bsp2) + Con_DWarning("%" PRIi32 " clipnodes exceeds standard limit of 32767.\n", count); //johnfitz loadmodel->clipnodes = out; @@ -1649,7 +1651,7 @@ void Mod_LoadClipnodes (lump_t *l, bool bsp2) hull = &loadmodel->hulls[1]; hull->clipnodes = out; hull->firstclipnode = 0; - hull->lastclipnode = count-1; + hull->lastclipnode = count - 1; hull->planes = loadmodel->planes; hull->clip_mins[0] = -16; hull->clip_mins[1] = -16; @@ -1661,7 +1663,7 @@ void Mod_LoadClipnodes (lump_t *l, bool bsp2) hull = &loadmodel->hulls[2]; hull->clipnodes = out; hull->firstclipnode = 0; - hull->lastclipnode = count-1; + hull->lastclipnode = count - 1; hull->planes = loadmodel->planes; hull->clip_mins[0] = -32; hull->clip_mins[1] = -32; @@ -1670,15 +1672,15 @@ void Mod_LoadClipnodes (lump_t *l, bool bsp2) hull->clip_maxs[1] = 32; hull->clip_maxs[2] = 64; - if (bsp2) + if(bsp2) { - for (i=0 ; iplanenum = LittleLong(inl->planenum); //johnfitz -- bounds check - if (out->planenum < 0 || out->planenum >= loadmodel->numplanes) - Host_Error ("Mod_LoadClipnodes: planenum out of bounds"); + if(out->planenum < 0 || out->planenum >= loadmodel->numplanes) + Host_Error("Mod_LoadClipnodes: planenum out of bounds"); //johnfitz out->children[0] = LittleLong(inl->children[0]); @@ -1688,22 +1690,22 @@ void Mod_LoadClipnodes (lump_t *l, bool bsp2) } else { - for (i=0 ; iplanenum = LittleLong(ins->planenum); - //johnfitz -- bounds check - if (out->planenum < 0 || out->planenum >= loadmodel->numplanes) - Host_Error ("Mod_LoadClipnodes: planenum out of bounds"); - //johnfitz + //johnfitz -- bounds check + if(out->planenum < 0 || out->planenum >= loadmodel->numplanes) + Host_Error("Mod_LoadClipnodes: planenum out of bounds"); + //johnfitz //johnfitz -- support clipnodes > 32k out->children[0] = (uint16_t)LittleShort(ins->children[0]); out->children[1] = (uint16_t)LittleShort(ins->children[1]); - if (out->children[0] >= count) + if(out->children[0] >= count) out->children[0] -= 65536; - if (out->children[1] >= count) + if(out->children[1] >= count) out->children[1] -= 65536; //johnfitz } @@ -1717,31 +1719,31 @@ Mod_MakeHull0 Duplicate the drawing hull structure as a clipping hull ================= */ -void Mod_MakeHull0 (void) +void Mod_MakeHull0(void) { - mnode_t *in, *child; + mnode_t *in, *child; mclipnode_t *out; //johnfitz -- was dclipnode_t - int32_t i, j, count; - hull_t *hull; + int32_t i, j, count; + hull_t *hull; hull = &loadmodel->hulls[0]; in = loadmodel->nodes; count = loadmodel->numnodes; - out = (mclipnode_t *) Hunk_AllocName ( count*sizeof(*out), loadname); + out = (mclipnode_t *) Hunk_AllocName(count * sizeof(*out), loadname); hull->clipnodes = out; hull->firstclipnode = 0; - hull->lastclipnode = count-1; + hull->lastclipnode = count - 1; hull->planes = loadmodel->planes; - for (i=0 ; iplanenum = in->plane - loadmodel->planes; - for (j=0 ; j<2 ; j++) + for(j = 0 ; j < 2 ; j++) { child = in->children[j]; - if (child->contents < 0) + if(child->contents < 0) out->children[j] = child->contents; else out->children[j] = child - loadmodel->nodes; @@ -1754,28 +1756,28 @@ void Mod_MakeHull0 (void) Mod_LoadMarksurfaces ================= */ -void Mod_LoadMarksurfaces (lump_t *l, int32_t bsp2) +void Mod_LoadMarksurfaces(lump_t *l, int32_t bsp2) { - int32_t i, j, count; + int32_t i, j, count; msurface_t **out; - if (bsp2) + if(bsp2) { uint32_t *in = (uint32_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Host_Error ("Mod_LoadMarksurfaces: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Host_Error("Mod_LoadMarksurfaces: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (msurface_t **)Hunk_AllocName ( count*sizeof(*out), loadname); + out = (msurface_t **)Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->marksurfaces = out; loadmodel->nummarksurfaces = count; - for (i=0 ; i= loadmodel->numsurfaces) - Host_Error ("Mod_LoadMarksurfaces: bad surface number"); + if(j >= loadmodel->numsurfaces) + Host_Error("Mod_LoadMarksurfaces: bad surface number"); out[i] = loadmodel->surfaces + j; } } @@ -1783,25 +1785,25 @@ void Mod_LoadMarksurfaces (lump_t *l, int32_t bsp2) { int16_t *in = (int16_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Host_Error ("Mod_LoadMarksurfaces: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Host_Error("Mod_LoadMarksurfaces: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (msurface_t **)Hunk_AllocName ( count*sizeof(*out), loadname); + out = (msurface_t **)Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->marksurfaces = out; loadmodel->nummarksurfaces = count; //johnfitz -- warn mappers about exceeding old limits - if (count > 32767) - Con_DWarning ("%" PRIi32 " marksurfaces exceeds standard limit of 32767.\n", count); + if(count > 32767) + Con_DWarning("%" PRIi32 " marksurfaces exceeds standard limit of 32767.\n", count); //johnfitz - for (i=0 ; i= loadmodel->numsurfaces) - Sys_Error ("Mod_LoadMarksurfaces: bad surface number"); + if(j >= loadmodel->numsurfaces) + Sys_Error("Mod_LoadMarksurfaces: bad surface number"); out[i] = loadmodel->surfaces + j; } } @@ -1812,22 +1814,22 @@ void Mod_LoadMarksurfaces (lump_t *l, int32_t bsp2) Mod_LoadSurfedges ================= */ -void Mod_LoadSurfedges (lump_t *l) +void Mod_LoadSurfedges(lump_t *l) { - int32_t i, count; - int32_t *in, *out; + int32_t i, count; + int32_t *in, *out; in = (int32_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (int32_t *) Hunk_AllocName ( count*sizeof(*out), loadname); + out = (int32_t *) Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->surfedges = out; loadmodel->numsurfedges = count; - for (i=0 ; ifileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (mplane_t *) Hunk_AllocName ( count*2*sizeof(*out), loadname); + out = (mplane_t *) Hunk_AllocName(count * 2 * sizeof(*out), loadname); loadmodel->planes = out; loadmodel->numplanes = count; - for (i=0 ; inormal[j] = LittleFloat (in->normal[j]); - if (out->normal[j] < 0) - bits |= 1<normal[j] = LittleFloat(in->normal[j]); + if(out->normal[j] < 0) + bits |= 1 << j; } - out->dist = LittleFloat (in->dist); - out->type = LittleLong (in->type); + out->dist = LittleFloat(in->dist); + out->type = LittleLong(in->type); out->signbits = bits; } } @@ -1874,17 +1876,17 @@ void Mod_LoadPlanes (lump_t *l) RadiusFromBounds ================= */ -float RadiusFromBounds (vec3_t mins, vec3_t maxs) +float RadiusFromBounds(vec3_t mins, vec3_t maxs) { - int32_t i; - vec3_t corner; + int32_t i; + vec3_t corner; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { corner[i] = fabs(mins[i]) > fabs(maxs[i]) ? fabs(mins[i]) : fabs(maxs[i]); } - return VectorLength (corner); + return VectorLength(corner); } /* @@ -1892,41 +1894,42 @@ float RadiusFromBounds (vec3_t mins, vec3_t maxs) Mod_LoadSubmodels ================= */ -void Mod_LoadSubmodels (lump_t *l) +void Mod_LoadSubmodels(lump_t *l) { - dmodel_t *in; - dmodel_t *out; - int32_t i, j, count; + dmodel_t *in; + dmodel_t *out; + int32_t i, j, count; in = (dmodel_t *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - Sys_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); + if(l->filelen % sizeof(*in)) + Sys_Error("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); count = l->filelen / sizeof(*in); - out = (dmodel_t *) Hunk_AllocName ( count*sizeof(*out), loadname); + out = (dmodel_t *) Hunk_AllocName(count * sizeof(*out), loadname); loadmodel->submodels = out; loadmodel->numsubmodels = count; - for (i=0 ; imins[j] = LittleFloat (in->mins[j]) - 1; - out->maxs[j] = LittleFloat (in->maxs[j]) + 1; - out->origin[j] = LittleFloat (in->origin[j]); + for(j = 0 ; j < 3 ; j++) + { + // spread the mins / maxs by a pixel + out->mins[j] = LittleFloat(in->mins[j]) - 1; + out->maxs[j] = LittleFloat(in->maxs[j]) + 1; + out->origin[j] = LittleFloat(in->origin[j]); } - for (j=0 ; jheadnode[j] = LittleLong (in->headnode[j]); - out->visleafs = LittleLong (in->visleafs); - out->firstface = LittleLong (in->firstface); - out->numfaces = LittleLong (in->numfaces); + for(j = 0 ; j < MAX_MAP_HULLS ; j++) + out->headnode[j] = LittleLong(in->headnode[j]); + out->visleafs = LittleLong(in->visleafs); + out->firstface = LittleLong(in->firstface); + out->numfaces = LittleLong(in->numfaces); } // johnfitz -- check world visleafs -- adapted from bjp out = loadmodel->submodels; - if (out->visleafs > 8192) - Con_DWarning ("%" PRIi32 " visleafs exceeds standard limit of 8192.\n", out->visleafs); + if(out->visleafs > 8192) + Con_DWarning("%" PRIi32 " visleafs exceeds standard limit of 8192.\n", out->visleafs); //johnfitz } @@ -1942,33 +1945,33 @@ Therefore, the bounding box of the hull can be constructed entirely from axial planes found in the clipnodes for that hull. ================= */ -void Mod_BoundsFromClipNode (qmodel_t *mod, int32_t hull, int32_t nodenum) +void Mod_BoundsFromClipNode(qmodel_t *mod, int32_t hull, int32_t nodenum) { - mplane_t *plane; - mclipnode_t *node; + mplane_t *plane; + mclipnode_t *node; - if (nodenum < 0) + if(nodenum < 0) return; //hit a leafnode node = &mod->clipnodes[nodenum]; plane = mod->hulls[hull].planes + node->planenum; - switch (plane->type) + switch(plane->type) { case PLANE_X: - if (plane->signbits == 1) + if(plane->signbits == 1) mod->clipmins[0] = q_min(mod->clipmins[0], -plane->dist - mod->hulls[hull].clip_mins[0]); else mod->clipmaxs[0] = q_max(mod->clipmaxs[0], plane->dist - mod->hulls[hull].clip_maxs[0]); break; case PLANE_Y: - if (plane->signbits == 2) + if(plane->signbits == 2) mod->clipmins[1] = q_min(mod->clipmins[1], -plane->dist - mod->hulls[hull].clip_mins[1]); else mod->clipmaxs[1] = q_max(mod->clipmaxs[1], plane->dist - mod->hulls[hull].clip_maxs[1]); break; case PLANE_Z: - if (plane->signbits == 4) + if(plane->signbits == 4) mod->clipmins[2] = q_min(mod->clipmins[2], -plane->dist - mod->hulls[hull].clip_mins[2]); else mod->clipmaxs[2] = q_max(mod->clipmaxs[2], plane->dist - mod->hulls[hull].clip_maxs[2]); @@ -1978,8 +1981,8 @@ void Mod_BoundsFromClipNode (qmodel_t *mod, int32_t hull, int32_t nodenum) break; } - Mod_BoundsFromClipNode (mod, hull, node->children[0]); - Mod_BoundsFromClipNode (mod, hull, node->children[1]); + Mod_BoundsFromClipNode(mod, hull, node->children[0]); + Mod_BoundsFromClipNode(mod, hull, node->children[1]); } /* @@ -1987,19 +1990,19 @@ void Mod_BoundsFromClipNode (qmodel_t *mod, int32_t hull, int32_t nodenum) Mod_LoadBrushModel ================= */ -void Mod_LoadBrushModel (qmodel_t *mod, void *buffer) +void Mod_LoadBrushModel(qmodel_t *mod, void *buffer) { - int32_t i, j; - int32_t bsp2; - dheader_t *header; - dmodel_t *bm; - float radius; //johnfitz + int32_t i, j; + int32_t bsp2; + dheader_t *header; + dmodel_t *bm; + float radius; //johnfitz loadmodel->type = mod_brush; header = (dheader_t *)buffer; - mod->bspversion = LittleLong (header->version); + mod->bspversion = LittleLong(header->version); switch(mod->bspversion) { @@ -2007,43 +2010,43 @@ void Mod_LoadBrushModel (qmodel_t *mod, void *buffer) bsp2 = false; break; case BSP2VERSION_2PSB: - bsp2 = 1; //first iteration + bsp2 = 1; //first iteration break; case BSP2VERSION_BSP2: - bsp2 = 2; //sanitised revision + bsp2 = 2; //sanitised revision break; default: - Sys_Error ("Mod_LoadBrushModel: %s has wrong version number (%" PRIi32 " should be %" PRIi32 ")", mod->name, mod->bspversion, BSPVERSION); + Sys_Error("Mod_LoadBrushModel: %s has wrong version number (%" PRIi32 " should be %" PRIi32 ")", mod->name, mod->bspversion, BSPVERSION); break; } // swap all the lumps mod_base = (byte *)header; - for (i = 0; i < (int32_t) sizeof(dheader_t) / 4; i++) - ((int32_t *)header)[i] = LittleLong ( ((int32_t *)header)[i]); + for(i = 0; i < (int32_t) sizeof(dheader_t) / 4; i++) + ((int32_t *)header)[i] = LittleLong(((int32_t *)header)[i]); // load into heap - Mod_LoadVertexes (&header->lumps[LUMP_VERTEXES]); - Mod_LoadEdges (&header->lumps[LUMP_EDGES], bsp2); - Mod_LoadSurfedges (&header->lumps[LUMP_SURFEDGES]); - Mod_LoadTextures (&header->lumps[LUMP_TEXTURES]); - Mod_LoadLighting (&header->lumps[LUMP_LIGHTING]); - Mod_LoadPlanes (&header->lumps[LUMP_PLANES]); - Mod_LoadTexinfo (&header->lumps[LUMP_TEXINFO]); - Mod_LoadFaces (&header->lumps[LUMP_FACES], bsp2); - Mod_LoadMarksurfaces (&header->lumps[LUMP_MARKSURFACES], bsp2); - Mod_LoadVisibility (&header->lumps[LUMP_VISIBILITY]); - Mod_LoadLeafs (&header->lumps[LUMP_LEAFS], bsp2); - Mod_LoadNodes (&header->lumps[LUMP_NODES], bsp2); - Mod_LoadClipnodes (&header->lumps[LUMP_CLIPNODES], bsp2); - Mod_LoadEntities (&header->lumps[LUMP_ENTITIES]); - Mod_LoadSubmodels (&header->lumps[LUMP_MODELS]); + Mod_LoadVertexes(&header->lumps[LUMP_VERTEXES]); + Mod_LoadEdges(&header->lumps[LUMP_EDGES], bsp2); + Mod_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]); + Mod_LoadTextures(&header->lumps[LUMP_TEXTURES]); + Mod_LoadLighting(&header->lumps[LUMP_LIGHTING]); + Mod_LoadPlanes(&header->lumps[LUMP_PLANES]); + Mod_LoadTexinfo(&header->lumps[LUMP_TEXINFO]); + Mod_LoadFaces(&header->lumps[LUMP_FACES], bsp2); + Mod_LoadMarksurfaces(&header->lumps[LUMP_MARKSURFACES], bsp2); + Mod_LoadVisibility(&header->lumps[LUMP_VISIBILITY]); + Mod_LoadLeafs(&header->lumps[LUMP_LEAFS], bsp2); + Mod_LoadNodes(&header->lumps[LUMP_NODES], bsp2); + Mod_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], bsp2); + Mod_LoadEntities(&header->lumps[LUMP_ENTITIES]); + Mod_LoadSubmodels(&header->lumps[LUMP_MODELS]); - Mod_MakeHull0 (); + Mod_MakeHull0(); - mod->numframes = 2; // regular and alternate animation + mod->numframes = 2; // regular and alternate animation // // set up the submodels (FIXME: this is confusing) @@ -2053,35 +2056,35 @@ void Mod_LoadBrushModel (qmodel_t *mod, void *buffer) // we're looping through the submodels starting at 0. Submodel 0 is the main model, so we don't have to // worry about clobbering data the first time through, since it's the same data. At the end of the loop, // we create a new copy of the data to use the next time through. - for (i=0 ; inumsubmodels ; i++) + for(i = 0 ; i < mod->numsubmodels ; i++) { bm = &mod->submodels[i]; mod->hulls[0].firstclipnode = bm->headnode[0]; - for (j=1 ; jhulls[j].firstclipnode = bm->headnode[j]; - mod->hulls[j].lastclipnode = mod->numclipnodes-1; + mod->hulls[j].lastclipnode = mod->numclipnodes - 1; } mod->firstmodelsurface = bm->firstface; mod->nummodelsurfaces = bm->numfaces; - VectorCopy (bm->maxs, mod->maxs); - VectorCopy (bm->mins, mod->mins); + VectorCopy(bm->maxs, mod->maxs); + VectorCopy(bm->mins, mod->mins); //johnfitz -- calculate rotate bounds and yaw bounds - radius = RadiusFromBounds (mod->mins, mod->maxs); + radius = RadiusFromBounds(mod->mins, mod->maxs); mod->rmaxs[0] = mod->rmaxs[1] = mod->rmaxs[2] = mod->ymaxs[0] = mod->ymaxs[1] = mod->ymaxs[2] = radius; mod->rmins[0] = mod->rmins[1] = mod->rmins[2] = mod->ymins[0] = mod->ymins[1] = mod->ymins[2] = -radius; //johnfitz //johnfitz -- correct physics cullboxes so that outlying clip brushes on doors and stuff are handled right - if (i > 0 || strcmp(mod->name, sv.modelname) != 0) //skip submodel 0 of sv.worldmodel, which is the actual world + if(i > 0 || strcmp(mod->name, sv.modelname) != 0) //skip submodel 0 of sv.worldmodel, which is the actual world { // start with the hull0 bounds - VectorCopy (mod->maxs, mod->clipmaxs); - VectorCopy (mod->mins, mod->clipmins); + VectorCopy(mod->maxs, mod->clipmaxs); + VectorCopy(mod->mins, mod->clipmins); // process hull1 (we don't need to process hull2 becuase there's // no such thing as a brush that appears in hull2 but not hull1) @@ -2091,14 +2094,15 @@ void Mod_LoadBrushModel (qmodel_t *mod, void *buffer) mod->numleafs = bm->visleafs; - if (i < mod->numsubmodels-1) - { // duplicate the basic information - char name[10]; + if(i < mod->numsubmodels - 1) + { + // duplicate the basic information + char name[10]; - sprintf (name, "*%" PRIi32 "", i+1); - loadmodel = Mod_FindName (name); + sprintf(name, "*%" PRIi32 "", i + 1); + loadmodel = Mod_FindName(name); *loadmodel = *mod; - strcpy (loadmodel->name, name); + strcpy(loadmodel->name, name); mod = loadmodel; } } @@ -2112,37 +2116,37 @@ ALIAS MODELS ============================================================================== */ -aliashdr_t *pheader; +aliashdr_t *pheader; -stvert_t stverts[MAXALIASVERTS]; -mtriangle_t triangles[MAXALIASTRIS]; +stvert_t stverts[MAXALIASVERTS]; +mtriangle_t triangles[MAXALIASTRIS]; // a pose is a single set of vertexes. a frame may be // an animating sequence of poses -trivertx_t *poseverts[MAXALIASFRAMES]; -int32_t posenum; +trivertx_t *poseverts[MAXALIASFRAMES]; +int32_t posenum; -byte **player_8bit_texels_tbl; -byte *player_8bit_texels; +byte **player_8bit_texels_tbl; +byte *player_8bit_texels; /* ================= Mod_LoadAliasFrame ================= */ -void * Mod_LoadAliasFrame (void * pin, maliasframedesc_t *frame) +void * Mod_LoadAliasFrame(void * pin, maliasframedesc_t *frame) { - trivertx_t *pinframe; - int32_t i; - daliasframe_t *pdaliasframe; + trivertx_t *pinframe; + int32_t i; + daliasframe_t *pdaliasframe; pdaliasframe = (daliasframe_t *)pin; - strcpy (frame->name, pdaliasframe->name); + strcpy(frame->name, pdaliasframe->name); frame->firstpose = posenum; frame->numposes = 1; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { // these are byte values, so we don't have to worry about // endianness @@ -2167,21 +2171,21 @@ void * Mod_LoadAliasFrame (void * pin, maliasframedesc_t *frame) Mod_LoadAliasGroup ================= */ -void *Mod_LoadAliasGroup (void * pin, maliasframedesc_t *frame) +void *Mod_LoadAliasGroup(void * pin, maliasframedesc_t *frame) { - daliasgroup_t *pingroup; - int32_t i, numframes; - daliasinterval_t *pin_intervals; - void *ptemp; + daliasgroup_t *pingroup; + int32_t i, numframes; + daliasinterval_t *pin_intervals; + void *ptemp; pingroup = (daliasgroup_t *)pin; - numframes = LittleLong (pingroup->numframes); + numframes = LittleLong(pingroup->numframes); frame->firstpose = posenum; frame->numposes = numframes; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { // these are byte values, so we don't have to worry about endianness frame->bboxmin.v[i] = pingroup->bboxmin.v[i]; @@ -2191,13 +2195,13 @@ void *Mod_LoadAliasGroup (void * pin, maliasframedesc_t *frame) pin_intervals = (daliasinterval_t *)(pingroup + 1); - frame->interval = LittleFloat (pin_intervals->interval); + frame->interval = LittleFloat(pin_intervals->interval); pin_intervals += numframes; ptemp = (void *)pin_intervals; - for (i=0 ; i 0) FLOODFILL_STEP( -1, -1, 0 ); - if (x < skinwidth - 1) FLOODFILL_STEP( 1, 1, 0 ); - if (y > 0) FLOODFILL_STEP( -skinwidth, 0, -1 ); - if (y < skinheight - 1) FLOODFILL_STEP( skinwidth, 0, 1 ); + if(x > 0) FLOODFILL_STEP(-1, -1, 0); + if(x < skinwidth - 1) FLOODFILL_STEP(1, 1, 0); + if(y > 0) FLOODFILL_STEP(-skinwidth, 0, -1); + if(y < skinheight - 1) FLOODFILL_STEP(skinwidth, 0, 1); skin[x + skinwidth * y] = fdc; } } @@ -2290,53 +2294,53 @@ void Mod_FloodFillSkin( byte *skin, int32_t skinwidth, int32_t skinheight ) Mod_LoadAllSkins =============== */ -void *Mod_LoadAllSkins (int32_t numskins, daliasskintype_t *pskintype) +void *Mod_LoadAllSkins(int32_t numskins, daliasskintype_t *pskintype) { - int32_t i, j, k, size, groupskins; - char name[MAX_QPATH]; - byte *skin, *texels; - daliasskingroup_t *pinskingroup; - daliasskininterval_t *pinskinintervals; - char fbr_mask_name[MAX_QPATH]; //johnfitz -- added for fullbright support - src_offset_t offset; //johnfitz - uint32_t texflags = TEXPREF_PAD; + int32_t i, j, k, size, groupskins; + char name[MAX_QPATH]; + byte *skin, *texels; + daliasskingroup_t *pinskingroup; + daliasskininterval_t *pinskinintervals; + char fbr_mask_name[MAX_QPATH]; //johnfitz -- added for fullbright support + src_offset_t offset; //johnfitz + uint32_t texflags = TEXPREF_PAD; skin = (byte *)(pskintype + 1); - if (numskins < 1 || numskins > MAX_SKINS) - Sys_Error ("Mod_LoadAliasModel: Invalid # of skins: %" PRIi32 "\n", numskins); + if(numskins < 1 || numskins > MAX_SKINS) + Sys_Error("Mod_LoadAliasModel: Invalid # of skins: %" PRIi32 "\n", numskins); size = pheader->skinwidth * pheader->skinheight; - if (loadmodel->flags & MF_HOLEY) + if(loadmodel->flags & MF_HOLEY) texflags |= TEXPREF_ALPHA; - for (i=0 ; itype == ALIAS_SKIN_SINGLE) + if(pskintype->type == ALIAS_SKIN_SINGLE) { - Mod_FloodFillSkin( skin, pheader->skinwidth, pheader->skinheight ); + Mod_FloodFillSkin(skin, pheader->skinwidth, pheader->skinheight); // save 8 bit texels for the player model to remap texels = (byte *) Hunk_AllocName(size, loadname); pheader->texels[i] = texels - (byte *)pheader; - memcpy (texels, (byte *)(pskintype + 1), size); + memcpy(texels, (byte *)(pskintype + 1), size); //johnfitz -- rewritten - q_snprintf (name, sizeof(name), "%s:frame%" PRIi32 "", loadmodel->name, i); - offset = (src_offset_t)(pskintype+1) - (src_offset_t)mod_base; - if (Mod_CheckFullbrights ((byte *)(pskintype+1), size)) + q_snprintf(name, sizeof(name), "%s:frame%" PRIi32 "", loadmodel->name, i); + offset = (src_offset_t)(pskintype + 1) - (src_offset_t)mod_base; + if(Mod_CheckFullbrights((byte *)(pskintype + 1), size)) { - pheader->gltextures[i][0] = TexMgr_LoadImage (loadmodel, name, pheader->skinwidth, pheader->skinheight, - SRC_INDEXED, (byte *)(pskintype+1), loadmodel->name, offset, texflags | TEXPREF_NOBRIGHT); - q_snprintf (fbr_mask_name, sizeof(fbr_mask_name), "%s:frame%" PRIi32 "_glow", loadmodel->name, i); - pheader->fbtextures[i][0] = TexMgr_LoadImage (loadmodel, fbr_mask_name, pheader->skinwidth, pheader->skinheight, - SRC_INDEXED, (byte *)(pskintype+1), loadmodel->name, offset, texflags | TEXPREF_FULLBRIGHT); + pheader->gltextures[i][0] = TexMgr_LoadImage(loadmodel, name, pheader->skinwidth, pheader->skinheight, + SRC_INDEXED, (byte *)(pskintype + 1), loadmodel->name, offset, texflags | TEXPREF_NOBRIGHT); + q_snprintf(fbr_mask_name, sizeof(fbr_mask_name), "%s:frame%" PRIi32 "_glow", loadmodel->name, i); + pheader->fbtextures[i][0] = TexMgr_LoadImage(loadmodel, fbr_mask_name, pheader->skinwidth, pheader->skinheight, + SRC_INDEXED, (byte *)(pskintype + 1), loadmodel->name, offset, texflags | TEXPREF_FULLBRIGHT); } else { - pheader->gltextures[i][0] = TexMgr_LoadImage (loadmodel, name, pheader->skinwidth, pheader->skinheight, - SRC_INDEXED, (byte *)(pskintype+1), loadmodel->name, offset, texflags); + pheader->gltextures[i][0] = TexMgr_LoadImage(loadmodel, name, pheader->skinwidth, pheader->skinheight, + SRC_INDEXED, (byte *)(pskintype + 1), loadmodel->name, offset, texflags); pheader->fbtextures[i][0] = NULL; } @@ -2344,51 +2348,52 @@ void *Mod_LoadAllSkins (int32_t numskins, daliasskintype_t *pskintype) pheader->fbtextures[i][3] = pheader->fbtextures[i][2] = pheader->fbtextures[i][1] = pheader->fbtextures[i][0]; //johnfitz - pskintype = (daliasskintype_t *)((byte *)(pskintype+1) + size); + pskintype = (daliasskintype_t *)((byte *)(pskintype + 1) + size); } else { // animating skin group. yuck. pskintype++; pinskingroup = (daliasskingroup_t *)pskintype; - groupskins = LittleLong (pinskingroup->numskins); + groupskins = LittleLong(pinskingroup->numskins); pinskinintervals = (daliasskininterval_t *)(pinskingroup + 1); pskintype = (daliasskintype_t *)(pinskinintervals + groupskins); - for (j=0 ; jskinwidth, pheader->skinheight ); - if (j == 0) { + Mod_FloodFillSkin(skin, pheader->skinwidth, pheader->skinheight); + if(j == 0) + { texels = (byte *) Hunk_AllocName(size, loadname); pheader->texels[i] = texels - (byte *)pheader; - memcpy (texels, (byte *)(pskintype), size); + memcpy(texels, (byte *)(pskintype), size); } //johnfitz -- rewritten - q_snprintf (name, sizeof(name), "%s:frame%" PRIi32 "_%" PRIi32 "", loadmodel->name, i,j); + q_snprintf(name, sizeof(name), "%s:frame%" PRIi32 "_%" PRIi32 "", loadmodel->name, i, j); offset = (src_offset_t)(pskintype) - (src_offset_t)mod_base; //johnfitz - if (Mod_CheckFullbrights ((byte *)(pskintype), size)) + if(Mod_CheckFullbrights((byte *)(pskintype), size)) { - pheader->gltextures[i][j&3] = TexMgr_LoadImage (loadmodel, name, pheader->skinwidth, pheader->skinheight, - SRC_INDEXED, (byte *)(pskintype), loadmodel->name, offset, texflags | TEXPREF_NOBRIGHT); - q_snprintf (fbr_mask_name, sizeof(fbr_mask_name), "%s:frame%" PRIi32 "_%" PRIi32 "_glow", loadmodel->name, i,j); - pheader->fbtextures[i][j&3] = TexMgr_LoadImage (loadmodel, fbr_mask_name, pheader->skinwidth, pheader->skinheight, - SRC_INDEXED, (byte *)(pskintype), loadmodel->name, offset, texflags | TEXPREF_FULLBRIGHT); + pheader->gltextures[i][j & 3] = TexMgr_LoadImage(loadmodel, name, pheader->skinwidth, pheader->skinheight, + SRC_INDEXED, (byte *)(pskintype), loadmodel->name, offset, texflags | TEXPREF_NOBRIGHT); + q_snprintf(fbr_mask_name, sizeof(fbr_mask_name), "%s:frame%" PRIi32 "_%" PRIi32 "_glow", loadmodel->name, i, j); + pheader->fbtextures[i][j & 3] = TexMgr_LoadImage(loadmodel, fbr_mask_name, pheader->skinwidth, pheader->skinheight, + SRC_INDEXED, (byte *)(pskintype), loadmodel->name, offset, texflags | TEXPREF_FULLBRIGHT); } else { - pheader->gltextures[i][j&3] = TexMgr_LoadImage (loadmodel, name, pheader->skinwidth, pheader->skinheight, - SRC_INDEXED, (byte *)(pskintype), loadmodel->name, offset, texflags); - pheader->fbtextures[i][j&3] = NULL; + pheader->gltextures[i][j & 3] = TexMgr_LoadImage(loadmodel, name, pheader->skinwidth, pheader->skinheight, + SRC_INDEXED, (byte *)(pskintype), loadmodel->name, offset, texflags); + pheader->fbtextures[i][j & 3] = NULL; } //johnfitz pskintype = (daliasskintype_t *)((byte *)(pskintype) + size); } k = j; - for (/**/; j < 4; j++) - pheader->gltextures[i][j&3] = pheader->gltextures[i][j - k]; + for(/**/; j < 4; j++) + pheader->gltextures[i][j & 3] = pheader->gltextures[i][j - k]; } } @@ -2402,14 +2407,14 @@ void *Mod_LoadAllSkins (int32_t numskins, daliasskintype_t *pskintype) Mod_CalcAliasBounds -- johnfitz -- calculate bounds of alias model for nonrotated, yawrotated, and fullrotated cases ================= */ -void Mod_CalcAliasBounds (aliashdr_t *a) +void Mod_CalcAliasBounds(aliashdr_t *a) { - int32_t i,j,k; - float dist, yawradius, radius; - vec3_t v; + int32_t i, j, k; + float dist, yawradius, radius; + vec3_t v; //clear out all data - for (i=0; i<3;i++) + for(i = 0; i < 3; i++) { loadmodel->mins[i] = loadmodel->ymins[i] = loadmodel->rmins[i] = 999999; loadmodel->maxs[i] = loadmodel->ymaxs[i] = loadmodel->rmaxs[i] = -999999; @@ -2417,22 +2422,22 @@ void Mod_CalcAliasBounds (aliashdr_t *a) } //process verts - for (i=0 ; inumposes; i++) - for (j=0; jnumverts; j++) + for(i = 0 ; i < a->numposes; i++) + for(j = 0; j < a->numverts; j++) { - for (k=0; k<3;k++) + for(k = 0; k < 3; k++) v[k] = poseverts[i][j].v[k] * pheader->scale[k] + pheader->scale_origin[k]; - for (k=0; k<3;k++) + for(k = 0; k < 3; k++) { loadmodel->mins[k] = q_min(loadmodel->mins[k], v[k]); loadmodel->maxs[k] = q_max(loadmodel->maxs[k], v[k]); } dist = v[0] * v[0] + v[1] * v[1]; - if (yawradius < dist) + if(yawradius < dist) yawradius = dist; dist += v[2] * v[2]; - if (radius < dist) + if(radius < dist) radius = dist; } @@ -2458,24 +2463,24 @@ nameInList(const char *list, const char *name) s = list; - while (*s) + while(*s) { // make a copy until the next comma or end of string i = 0; - while (*s && *s != ',') + while(*s && *s != ',') { - if (i < MAX_QPATH - 1) + if(i < MAX_QPATH - 1) tmp[i++] = *s; s++; } tmp[i] = '\0'; //compare it to the model name - if (!strcmp(name, tmp)) + if(!strcmp(name, tmp)) { return true; } //search forwards to the next comma or end of string - while (*s && *s == ',') + while(*s && *s == ',') s++; } return false; @@ -2486,27 +2491,27 @@ nameInList(const char *list, const char *name) Mod_SetExtraFlags -- johnfitz -- set up extra flags that aren't in the mdl ================= */ -void Mod_SetExtraFlags (qmodel_t *mod) +void Mod_SetExtraFlags(qmodel_t *mod) { extern cvar_t r_nolerp_list, r_noshadow_list; - if (!mod || mod->type != mod_alias) + if(!mod || mod->type != mod_alias) return; mod->flags &= (0xFF | MF_HOLEY); //only preserve first byte, plus MF_HOLEY // nolerp flag - if (nameInList(r_nolerp_list.string, mod->name)) + if(nameInList(r_nolerp_list.string, mod->name)) mod->flags |= MOD_NOLERP; // noshadow flag - if (nameInList(r_noshadow_list.string, mod->name)) + if(nameInList(r_noshadow_list.string, mod->name)) mod->flags |= MOD_NOSHADOW; // fullbright hack (TODO: make this a cvar list) - if (!strcmp (mod->name, "progs/flame2.mdl") || - !strcmp (mod->name, "progs/flame.mdl") || - !strcmp (mod->name, "progs/boss.mdl")) + if(!strcmp(mod->name, "progs/flame2.mdl") || + !strcmp(mod->name, "progs/flame.mdl") || + !strcmp(mod->name, "progs/boss.mdl")) mod->flags |= MOD_FBRIGHTHACK; } @@ -2515,77 +2520,77 @@ void Mod_SetExtraFlags (qmodel_t *mod) Mod_LoadAliasModel ================= */ -void Mod_LoadAliasModel (qmodel_t *mod, void *buffer) +void Mod_LoadAliasModel(qmodel_t *mod, void *buffer) { - int32_t i, j; - mdl_t *pinmodel; - stvert_t *pinstverts; - dtriangle_t *pintriangles; - int32_t version, numframes; - int32_t size; - daliasframetype_t *pframetype; - daliasskintype_t *pskintype; - int32_t start, end, total; + int32_t i, j; + mdl_t *pinmodel; + stvert_t *pinstverts; + dtriangle_t *pintriangles; + int32_t version, numframes; + int32_t size; + daliasframetype_t *pframetype; + daliasskintype_t *pskintype; + int32_t start, end, total; - start = Hunk_LowMark (); + start = Hunk_LowMark(); pinmodel = (mdl_t *)buffer; mod_base = (byte *)buffer; //johnfitz - version = LittleLong (pinmodel->version); - if (version != ALIAS_VERSION) - Sys_Error ("%s has wrong version number (%" PRIi32 " should be %" PRIi32 ")", - mod->name, version, ALIAS_VERSION); + version = LittleLong(pinmodel->version); + if(version != ALIAS_VERSION) + Sys_Error("%s has wrong version number (%" PRIi32 " should be %" PRIi32 ")", + mod->name, version, ALIAS_VERSION); // // allocate space for a working header, plus all the data except the frames, // skin and group info // - size = sizeof(aliashdr_t) + - (LittleLong (pinmodel->numframes) - 1) * sizeof (pheader->frames[0]); - pheader = (aliashdr_t *) Hunk_AllocName (size, loadname); + size = sizeof(aliashdr_t) + + (LittleLong(pinmodel->numframes) - 1) * sizeof(pheader->frames[0]); + pheader = (aliashdr_t *) Hunk_AllocName(size, loadname); - mod->flags = LittleLong (pinmodel->flags); + mod->flags = LittleLong(pinmodel->flags); // // endian-adjust and copy the data, starting with the alias model header // - pheader->boundingradius = LittleFloat (pinmodel->boundingradius); - pheader->numskins = LittleLong (pinmodel->numskins); - pheader->skinwidth = LittleLong (pinmodel->skinwidth); - pheader->skinheight = LittleLong (pinmodel->skinheight); + pheader->boundingradius = LittleFloat(pinmodel->boundingradius); + pheader->numskins = LittleLong(pinmodel->numskins); + pheader->skinwidth = LittleLong(pinmodel->skinwidth); + pheader->skinheight = LittleLong(pinmodel->skinheight); - if (pheader->skinheight > MAX_LBM_HEIGHT) - Sys_Error ("model %s has a skin taller than %" PRIi32 "", mod->name, - MAX_LBM_HEIGHT); + if(pheader->skinheight > MAX_LBM_HEIGHT) + Sys_Error("model %s has a skin taller than %" PRIi32 "", mod->name, + MAX_LBM_HEIGHT); - pheader->numverts = LittleLong (pinmodel->numverts); + pheader->numverts = LittleLong(pinmodel->numverts); - if (pheader->numverts <= 0) - Sys_Error ("model %s has no vertices", mod->name); + if(pheader->numverts <= 0) + Sys_Error("model %s has no vertices", mod->name); - if (pheader->numverts > MAXALIASVERTS) - Sys_Error ("model %s has too many vertices", mod->name); + if(pheader->numverts > MAXALIASVERTS) + Sys_Error("model %s has too many vertices", mod->name); - pheader->numtris = LittleLong (pinmodel->numtris); + pheader->numtris = LittleLong(pinmodel->numtris); - if (pheader->numtris <= 0) - Sys_Error ("model %s has no triangles", mod->name); + if(pheader->numtris <= 0) + Sys_Error("model %s has no triangles", mod->name); - pheader->numframes = LittleLong (pinmodel->numframes); + pheader->numframes = LittleLong(pinmodel->numframes); numframes = pheader->numframes; - if (numframes < 1) - Sys_Error ("Mod_LoadAliasModel: Invalid # of frames: %" PRIi32 "\n", numframes); + if(numframes < 1) + Sys_Error("Mod_LoadAliasModel: Invalid # of frames: %" PRIi32 "\n", numframes); - pheader->size = LittleFloat (pinmodel->size) * ALIAS_BASE_SIZE_RATIO; - mod->synctype = (synctype_t) LittleLong (pinmodel->synctype); + pheader->size = LittleFloat(pinmodel->size) * ALIAS_BASE_SIZE_RATIO; + mod->synctype = (synctype_t) LittleLong(pinmodel->synctype); mod->numframes = pheader->numframes; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { - pheader->scale[i] = LittleFloat (pinmodel->scale[i]); - pheader->scale_origin[i] = LittleFloat (pinmodel->scale_origin[i]); - pheader->eyeposition[i] = LittleFloat (pinmodel->eyeposition[i]); + pheader->scale[i] = LittleFloat(pinmodel->scale[i]); + pheader->scale_origin[i] = LittleFloat(pinmodel->scale_origin[i]); + pheader->eyeposition[i] = LittleFloat(pinmodel->eyeposition[i]); } @@ -2593,18 +2598,18 @@ void Mod_LoadAliasModel (qmodel_t *mod, void *buffer) // load the skins // pskintype = (daliasskintype_t *)&pinmodel[1]; - pskintype = (daliasskintype_t *) Mod_LoadAllSkins (pheader->numskins, pskintype); + pskintype = (daliasskintype_t *) Mod_LoadAllSkins(pheader->numskins, pskintype); // // load base s and t vertices // pinstverts = (stvert_t *)pskintype; - for (i=0 ; inumverts ; i++) + for(i = 0 ; i < pheader->numverts ; i++) { - stverts[i].onseam = LittleLong (pinstverts[i].onseam); - stverts[i].s = LittleLong (pinstverts[i].s); - stverts[i].t = LittleLong (pinstverts[i].t); + stverts[i].onseam = LittleLong(pinstverts[i].onseam); + stverts[i].s = LittleLong(pinstverts[i].s); + stverts[i].t = LittleLong(pinstverts[i].t); } // @@ -2612,14 +2617,14 @@ void Mod_LoadAliasModel (qmodel_t *mod, void *buffer) // pintriangles = (dtriangle_t *)&pinstverts[pheader->numverts]; - for (i=0 ; inumtris ; i++) + for(i = 0 ; i < pheader->numtris ; i++) { - triangles[i].facesfront = LittleLong (pintriangles[i].facesfront); + triangles[i].facesfront = LittleLong(pintriangles[i].facesfront); - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { triangles[i].vertindex[j] = - LittleLong (pintriangles[i].vertindex[j]); + LittleLong(pintriangles[i].vertindex[j]); } } @@ -2629,41 +2634,41 @@ void Mod_LoadAliasModel (qmodel_t *mod, void *buffer) posenum = 0; pframetype = (daliasframetype_t *)&pintriangles[pheader->numtris]; - for (i=0 ; itype); - if (frametype == ALIAS_SINGLE) - pframetype = (daliasframetype_t *) Mod_LoadAliasFrame (pframetype + 1, &pheader->frames[i]); + aliasframetype_t frametype; + frametype = (aliasframetype_t) LittleLong(pframetype->type); + if(frametype == ALIAS_SINGLE) + pframetype = (daliasframetype_t *) Mod_LoadAliasFrame(pframetype + 1, &pheader->frames[i]); else - pframetype = (daliasframetype_t *) Mod_LoadAliasGroup (pframetype + 1, &pheader->frames[i]); + pframetype = (daliasframetype_t *) Mod_LoadAliasGroup(pframetype + 1, &pheader->frames[i]); } pheader->numposes = posenum; mod->type = mod_alias; - Mod_SetExtraFlags (mod); //johnfitz + Mod_SetExtraFlags(mod); //johnfitz - Mod_CalcAliasBounds (pheader); //johnfitz + Mod_CalcAliasBounds(pheader); //johnfitz // // build the draw lists // - GL_MakeAliasModelDisplayLists (mod, pheader); + GL_MakeAliasModelDisplayLists(mod, pheader); // // move the complete, relocatable alias model to the cache // - end = Hunk_LowMark (); + end = Hunk_LowMark(); total = end - start; - Cache_Alloc (&mod->cache, total, loadname); - if (!mod->cache.data) + Cache_Alloc(&mod->cache, total, loadname); + if(!mod->cache.data) return; - memcpy (mod->cache.data, pheader, total); + memcpy(mod->cache.data, pheader, total); - Hunk_FreeToLowMark (start); + Hunk_FreeToLowMark(start); } //============================================================================= @@ -2673,27 +2678,27 @@ void Mod_LoadAliasModel (qmodel_t *mod, void *buffer) Mod_LoadSpriteFrame ================= */ -void * Mod_LoadSpriteFrame (void * pin, mspriteframe_t **ppframe, int32_t framenum) +void * Mod_LoadSpriteFrame(void * pin, mspriteframe_t **ppframe, int32_t framenum) { - dspriteframe_t *pinframe; - mspriteframe_t *pspriteframe; - int32_t width, height, size, origin[2]; - char name[64]; - src_offset_t offset; //johnfitz + dspriteframe_t *pinframe; + mspriteframe_t *pspriteframe; + int32_t width, height, size, origin[2]; + char name[64]; + src_offset_t offset; //johnfitz pinframe = (dspriteframe_t *)pin; - width = LittleLong (pinframe->width); - height = LittleLong (pinframe->height); + width = LittleLong(pinframe->width); + height = LittleLong(pinframe->height); size = width * height; - pspriteframe = (mspriteframe_t *) Hunk_AllocName (sizeof (mspriteframe_t),loadname); + pspriteframe = (mspriteframe_t *) Hunk_AllocName(sizeof(mspriteframe_t), loadname); *ppframe = pspriteframe; pspriteframe->width = width; pspriteframe->height = height; - origin[0] = LittleLong (pinframe->origin[0]); - origin[1] = LittleLong (pinframe->origin[1]); + origin[0] = LittleLong(pinframe->origin[0]); + origin[1] = LittleLong(pinframe->origin[1]); pspriteframe->up = origin[1]; pspriteframe->down = origin[1] - height; @@ -2701,18 +2706,18 @@ void * Mod_LoadSpriteFrame (void * pin, mspriteframe_t **ppframe, int32_t framen pspriteframe->right = width + origin[0]; //johnfitz -- image might be padded - pspriteframe->smax = (float)width/(float)TexMgr_PadConditional(width); - pspriteframe->tmax = (float)height/(float)TexMgr_PadConditional(height); + pspriteframe->smax = (float)width / (float)TexMgr_PadConditional(width); + pspriteframe->tmax = (float)height / (float)TexMgr_PadConditional(height); //johnfitz - q_snprintf (name, sizeof(name), "%s:frame%" PRIi32 "", loadmodel->name, framenum); - offset = (src_offset_t)(pinframe+1) - (src_offset_t)mod_base; //johnfitz + q_snprintf(name, sizeof(name), "%s:frame%" PRIi32 "", loadmodel->name, framenum); + offset = (src_offset_t)(pinframe + 1) - (src_offset_t)mod_base; //johnfitz pspriteframe->gltexture = - TexMgr_LoadImage (loadmodel, name, width, height, SRC_INDEXED, - (byte *)(pinframe + 1), loadmodel->name, offset, - TEXPREF_PAD | TEXPREF_ALPHA | TEXPREF_NOPICMIP); //johnfitz -- TexMgr + TexMgr_LoadImage(loadmodel, name, width, height, SRC_INDEXED, + (byte *)(pinframe + 1), loadmodel->name, offset, + TEXPREF_PAD | TEXPREF_ALPHA | TEXPREF_NOPICMIP); //johnfitz -- TexMgr - return (void *)((byte *)pinframe + sizeof (dspriteframe_t) + size); + return (void *)((byte *)pinframe + sizeof(dspriteframe_t) + size); } @@ -2721,21 +2726,21 @@ void * Mod_LoadSpriteFrame (void * pin, mspriteframe_t **ppframe, int32_t framen Mod_LoadSpriteGroup ================= */ -void * Mod_LoadSpriteGroup (void * pin, mspriteframe_t **ppframe, int32_t framenum) +void * Mod_LoadSpriteGroup(void * pin, mspriteframe_t **ppframe, int32_t framenum) { - dspritegroup_t *pingroup; - mspritegroup_t *pspritegroup; - int32_t i, numframes; - dspriteinterval_t *pin_intervals; - float *poutintervals; - void *ptemp; + dspritegroup_t *pingroup; + mspritegroup_t *pspritegroup; + int32_t i, numframes; + dspriteinterval_t *pin_intervals; + float *poutintervals; + void *ptemp; pingroup = (dspritegroup_t *)pin; - numframes = LittleLong (pingroup->numframes); + numframes = LittleLong(pingroup->numframes); - pspritegroup = (mspritegroup_t *) Hunk_AllocName (sizeof (mspritegroup_t) + - (numframes - 1) * sizeof (pspritegroup->frames[0]), loadname); + pspritegroup = (mspritegroup_t *) Hunk_AllocName(sizeof(mspritegroup_t) + + (numframes - 1) * sizeof(pspritegroup->frames[0]), loadname); pspritegroup->numframes = numframes; @@ -2743,15 +2748,15 @@ void * Mod_LoadSpriteGroup (void * pin, mspriteframe_t **ppframe, int32_t framen pin_intervals = (dspriteinterval_t *)(pingroup + 1); - poutintervals = (float *) Hunk_AllocName (numframes * sizeof (float), loadname); + poutintervals = (float *) Hunk_AllocName(numframes * sizeof(float), loadname); pspritegroup->intervals = poutintervals; - for (i=0 ; iinterval); - if (*poutintervals <= 0.0) - Sys_Error ("Mod_LoadSpriteGroup: interval<=0"); + *poutintervals = LittleFloat(pin_intervals->interval); + if(*poutintervals <= 0.0) + Sys_Error("Mod_LoadSpriteGroup: interval<=0"); poutintervals++; pin_intervals++; @@ -2759,9 +2764,9 @@ void * Mod_LoadSpriteGroup (void * pin, mspriteframe_t **ppframe, int32_t framen ptemp = (void *)pin_intervals; - for (i=0 ; iframes[i], framenum * 100 + i); + ptemp = Mod_LoadSpriteFrame(ptemp, &pspritegroup->frames[i], framenum * 100 + i); } return ptemp; @@ -2773,70 +2778,70 @@ void * Mod_LoadSpriteGroup (void * pin, mspriteframe_t **ppframe, int32_t framen Mod_LoadSpriteModel ================= */ -void Mod_LoadSpriteModel (qmodel_t *mod, void *buffer) +void Mod_LoadSpriteModel(qmodel_t *mod, void *buffer) { - int32_t i; - int32_t version; - dsprite_t *pin; - msprite_t *psprite; - int32_t numframes; - int32_t size; - dspriteframetype_t *pframetype; + int32_t i; + int32_t version; + dsprite_t *pin; + msprite_t *psprite; + int32_t numframes; + int32_t size; + dspriteframetype_t *pframetype; pin = (dsprite_t *)buffer; mod_base = (byte *)buffer; //johnfitz - version = LittleLong (pin->version); - if (version != SPRITE_VERSION) - Sys_Error ("%s has wrong version number " - "(%" PRIi32 " should be %" PRIi32 ")", mod->name, version, SPRITE_VERSION); + version = LittleLong(pin->version); + if(version != SPRITE_VERSION) + Sys_Error("%s has wrong version number " + "(%" PRIi32 " should be %" PRIi32 ")", mod->name, version, SPRITE_VERSION); - numframes = LittleLong (pin->numframes); + numframes = LittleLong(pin->numframes); - size = sizeof (msprite_t) + (numframes - 1) * sizeof (psprite->frames); + size = sizeof(msprite_t) + (numframes - 1) * sizeof(psprite->frames); - psprite = (msprite_t *) Hunk_AllocName (size, loadname); + psprite = (msprite_t *) Hunk_AllocName(size, loadname); mod->cache.data = psprite; - psprite->type = LittleLong (pin->type); - psprite->maxwidth = LittleLong (pin->width); - psprite->maxheight = LittleLong (pin->height); - psprite->beamlength = LittleFloat (pin->beamlength); - mod->synctype = (synctype_t) LittleLong (pin->synctype); + psprite->type = LittleLong(pin->type); + psprite->maxwidth = LittleLong(pin->width); + psprite->maxheight = LittleLong(pin->height); + psprite->beamlength = LittleFloat(pin->beamlength); + mod->synctype = (synctype_t) LittleLong(pin->synctype); psprite->numframes = numframes; - mod->mins[0] = mod->mins[1] = -psprite->maxwidth/2; - mod->maxs[0] = mod->maxs[1] = psprite->maxwidth/2; - mod->mins[2] = -psprite->maxheight/2; - mod->maxs[2] = psprite->maxheight/2; + mod->mins[0] = mod->mins[1] = -psprite->maxwidth / 2; + mod->maxs[0] = mod->maxs[1] = psprite->maxwidth / 2; + mod->mins[2] = -psprite->maxheight / 2; + mod->maxs[2] = psprite->maxheight / 2; // // load the frames // - if (numframes < 1) - Sys_Error ("Mod_LoadSpriteModel: Invalid # of frames: %" PRIi32 "\n", numframes); + if(numframes < 1) + Sys_Error("Mod_LoadSpriteModel: Invalid # of frames: %" PRIi32 "\n", numframes); mod->numframes = numframes; pframetype = (dspriteframetype_t *)(pin + 1); - for (i=0 ; itype); + frametype = (spriteframetype_t) LittleLong(pframetype->type); psprite->frames[i].type = frametype; - if (frametype == SPR_SINGLE) + if(frametype == SPR_SINGLE) { pframetype = (dspriteframetype_t *) - Mod_LoadSpriteFrame (pframetype + 1, &psprite->frames[i].frameptr, i); + Mod_LoadSpriteFrame(pframetype + 1, &psprite->frames[i].frameptr, i); } else { pframetype = (dspriteframetype_t *) - Mod_LoadSpriteGroup (pframetype + 1, &psprite->frames[i].frameptr, i); + Mod_LoadSpriteGroup(pframetype + 1, &psprite->frames[i].frameptr, i); } } @@ -2850,16 +2855,16 @@ void Mod_LoadSpriteModel (qmodel_t *mod, void *buffer) Mod_Print ================ */ -void Mod_Print (void) +void Mod_Print(void) { - int32_t i; - qmodel_t *mod; + int32_t i; + qmodel_t *mod; - Con_SafePrintf ("Cached models:\n"); //johnfitz -- safeprint instead of print - for (i=0, mod=mod_known ; i < mod_numknown ; i++, mod++) + Con_SafePrintf("Cached models:\n"); //johnfitz -- safeprint instead of print + for(i = 0, mod = mod_known ; i < mod_numknown ; i++, mod++) { - Con_SafePrintf ("%8p : %s\n", mod->cache.data, mod->name); //johnfitz -- safeprint instead of print + Con_SafePrintf("%8p : %s\n", mod->cache.data, mod->name); //johnfitz -- safeprint instead of print } - Con_Printf ("%" PRIi32 " models\n",mod_numknown); //johnfitz -- print the total too + Con_Printf("%" PRIi32 " models\n", mod_numknown); //johnfitz -- print the total too } diff --git a/source/gl_model.h b/source/gl_model.h index 19ef10a..3e61a88 100644 --- a/source/gl_model.h +++ b/source/gl_model.h @@ -35,10 +35,10 @@ m*_t structures are in-memory // entity effects -#define EF_BRIGHTFIELD 1 -#define EF_MUZZLEFLASH 2 -#define EF_BRIGHTLIGHT 4 -#define EF_DIMLIGHT 8 +#define EF_BRIGHTFIELD 1 +#define EF_MUZZLEFLASH 2 +#define EF_BRIGHTLIGHT 4 +#define EF_DIMLIGHT 8 /* @@ -56,141 +56,142 @@ BRUSH MODELS // !!! if this is changed, it must be changed in asm_draw.h too !!! typedef struct { - vec3_t position; + vec3_t position; } mvertex_t; -#define SIDE_FRONT 0 -#define SIDE_BACK 1 -#define SIDE_ON 2 +#define SIDE_FRONT 0 +#define SIDE_BACK 1 +#define SIDE_ON 2 // plane_t structure // !!! if this is changed, it must be changed in asm_i386.h too !!! typedef struct mplane_s { - vec3_t normal; - float dist; - byte type; // for texture axis selection and fast side tests - byte signbits; // signx + signy<<1 + signz<<1 - byte pad[2]; + vec3_t normal; + float dist; + byte type; // for texture axis selection and fast side tests + byte signbits; // signx + signy<<1 + signz<<1 + byte pad[2]; } mplane_t; // ericw -- each texture has two chains, so we can clear the model chains // without affecting the world -typedef enum { +typedef enum +{ chain_world = 0, chain_model = 1 } texchain_t; typedef struct texture_s { - char name[16]; - unsigned width, height; - struct gltexture_s *gltexture; //johnfitz -- pointer to gltexture - struct gltexture_s *fullbright; //johnfitz -- fullbright mask texture - struct gltexture_s *warpimage; //johnfitz -- for water animation - bool update_warp; //johnfitz -- update warp this frame - struct msurface_s *texturechains[2]; // for texture chains - int32_t anim_total; // total tenths in sequence ( 0 = no) - int32_t anim_min, anim_max; // time for this frame min <=time< max - struct texture_s *anim_next; // in the animation sequence - struct texture_s *alternate_anims; // bmodels in frmae 1 use these - unsigned offsets[MIPLEVELS]; // four mip maps stored + char name[16]; + unsigned width, height; + struct gltexture_s *gltexture; //johnfitz -- pointer to gltexture + struct gltexture_s *fullbright; //johnfitz -- fullbright mask texture + struct gltexture_s *warpimage; //johnfitz -- for water animation + bool update_warp; //johnfitz -- update warp this frame + struct msurface_s *texturechains[2]; // for texture chains + int32_t anim_total; // total tenths in sequence ( 0 = no) + int32_t anim_min, anim_max; // time for this frame min <=time< max + struct texture_s *anim_next; // in the animation sequence + struct texture_s *alternate_anims; // bmodels in frmae 1 use these + unsigned offsets[MIPLEVELS]; // four mip maps stored } texture_t; -#define SURF_PLANEBACK 2 -#define SURF_DRAWSKY 4 -#define SURF_DRAWSPRITE 8 -#define SURF_DRAWTURB 0x10 -#define SURF_DRAWTILED 0x20 -#define SURF_DRAWBACKGROUND 0x40 -#define SURF_UNDERWATER 0x80 -#define SURF_NOTEXTURE 0x100 //johnfitz -#define SURF_DRAWFENCE 0x200 -#define SURF_DRAWLAVA 0x400 -#define SURF_DRAWSLIME 0x800 -#define SURF_DRAWTELE 0x1000 -#define SURF_DRAWWATER 0x2000 +#define SURF_PLANEBACK 2 +#define SURF_DRAWSKY 4 +#define SURF_DRAWSPRITE 8 +#define SURF_DRAWTURB 0x10 +#define SURF_DRAWTILED 0x20 +#define SURF_DRAWBACKGROUND 0x40 +#define SURF_UNDERWATER 0x80 +#define SURF_NOTEXTURE 0x100 //johnfitz +#define SURF_DRAWFENCE 0x200 +#define SURF_DRAWLAVA 0x400 +#define SURF_DRAWSLIME 0x800 +#define SURF_DRAWTELE 0x1000 +#define SURF_DRAWWATER 0x2000 // !!! if this is changed, it must be changed in asm_draw.h too !!! typedef struct { - uint32_t v[2]; - uint32_t cachededgeoffset; + uint32_t v[2]; + uint32_t cachededgeoffset; } medge_t; typedef struct { - float vecs[2][4]; - float mipadjust; - texture_t *texture; - int32_t flags; + float vecs[2][4]; + float mipadjust; + texture_t *texture; + int32_t flags; } mtexinfo_t; -#define VERTEXSIZE 7 +#define VERTEXSIZE 7 typedef struct glpoly_s { - struct glpoly_s *next; - struct glpoly_s *chain; - int32_t numverts; - float verts[4][VERTEXSIZE]; // variable sized (xyz s1t1 s2t2) + struct glpoly_s *next; + struct glpoly_s *chain; + int32_t numverts; + float verts[4][VERTEXSIZE]; // variable sized (xyz s1t1 s2t2) } glpoly_t; typedef struct msurface_s { - int32_t visframe; // should be drawn when node is crossed - bool culled; // johnfitz -- for frustum culling - float mins[3]; // johnfitz -- for frustum culling - float maxs[3]; // johnfitz -- for frustum culling + int32_t visframe; // should be drawn when node is crossed + bool culled; // johnfitz -- for frustum culling + float mins[3]; // johnfitz -- for frustum culling + float maxs[3]; // johnfitz -- for frustum culling - mplane_t *plane; - int32_t flags; + mplane_t *plane; + int32_t flags; - int32_t firstedge; // look up in model->surfedges[], negative numbers - int32_t numedges; // are backwards edges + int32_t firstedge; // look up in model->surfedges[], negative numbers + int32_t numedges; // are backwards edges - int16_t texturemins[2]; - int16_t extents[2]; + int16_t texturemins[2]; + int16_t extents[2]; - int32_t light_s, light_t; // gl lightmap coordinates + int32_t light_s, light_t; // gl lightmap coordinates - glpoly_t *polys; // multiple if warped - struct msurface_s *texturechain; + glpoly_t *polys; // multiple if warped + struct msurface_s *texturechain; - mtexinfo_t *texinfo; + mtexinfo_t *texinfo; - int32_t vbo_firstvert; // index of this surface's first vert in the VBO + int32_t vbo_firstvert; // index of this surface's first vert in the VBO // lighting info - int32_t dlightframe; - uint32_t dlightbits[(MAX_DLIGHTS + 31) >> 5]; - // int32_t is 32 bits, need an array for MAX_DLIGHTS > 32 + int32_t dlightframe; + uint32_t dlightbits[(MAX_DLIGHTS + 31) >> 5]; + // int32_t is 32 bits, need an array for MAX_DLIGHTS > 32 - int32_t lightmaptexturenum; - byte styles[MAXLIGHTMAPS]; - int32_t cached_light[MAXLIGHTMAPS]; // values currently used in lightmap - bool cached_dlight; // true if dynamic light in cache - byte *samples; // [numstyles*surfsize] + int32_t lightmaptexturenum; + byte styles[MAXLIGHTMAPS]; + int32_t cached_light[MAXLIGHTMAPS]; // values currently used in lightmap + bool cached_dlight; // true if dynamic light in cache + byte *samples; // [numstyles*surfsize] } msurface_t; typedef struct mnode_s { // common with leaf - int32_t contents; // 0, to differentiate from leafs - int32_t visframe; // node needs to be traversed if current + int32_t contents; // 0, to differentiate from leafs + int32_t visframe; // node needs to be traversed if current - float minmaxs[6]; // for bounding box culling + float minmaxs[6]; // for bounding box culling - struct mnode_s *parent; + struct mnode_s *parent; // node specific - mplane_t *plane; - struct mnode_s *children[2]; + mplane_t *plane; + struct mnode_s *children[2]; - int32_t firstsurface; - int32_t numsurfaces; + int32_t firstsurface; + int32_t numsurfaces; } mnode_t; @@ -198,40 +199,40 @@ typedef struct mnode_s typedef struct mleaf_s { // common with node - int32_t contents; // wil be a negative contents number - int32_t visframe; // node needs to be traversed if current + int32_t contents; // wil be a negative contents number + int32_t visframe; // node needs to be traversed if current - float minmaxs[6]; // for bounding box culling + float minmaxs[6]; // for bounding box culling - struct mnode_s *parent; + struct mnode_s *parent; // leaf specific - byte *compressed_vis; - efrag_t *efrags; + byte *compressed_vis; + efrag_t *efrags; - msurface_t **firstmarksurface; - int32_t nummarksurfaces; - int32_t key; // BSP sequence number for leaf's contents - byte ambient_sound_level[NUM_AMBIENTS]; + msurface_t **firstmarksurface; + int32_t nummarksurfaces; + int32_t key; // BSP sequence number for leaf's contents + byte ambient_sound_level[NUM_AMBIENTS]; } mleaf_t; //johnfitz -- for clipnodes>32k typedef struct mclipnode_s { - int32_t planenum; - int32_t children[2]; // negative numbers are contents + int32_t planenum; + int32_t children[2]; // negative numbers are contents } mclipnode_t; //johnfitz // !!! if this is changed, it must be changed in asm_i386.h too !!! typedef struct { - mclipnode_t *clipnodes; //johnfitz -- was dclipnode_t - mplane_t *planes; - int32_t firstclipnode; - int32_t lastclipnode; - vec3_t clip_mins; - vec3_t clip_maxs; + mclipnode_t *clipnodes; //johnfitz -- was dclipnode_t + mplane_t *planes; + int32_t firstclipnode; + int32_t lastclipnode; + vec3_t clip_mins; + vec3_t clip_maxs; } hull_t; /* @@ -246,34 +247,34 @@ SPRITE MODELS // FIXME: shorten these? typedef struct mspriteframe_s { - int32_t width, height; - float up, down, left, right; - float smax, tmax; //johnfitz -- image might be padded - struct gltexture_s *gltexture; + int32_t width, height; + float up, down, left, right; + float smax, tmax; //johnfitz -- image might be padded + struct gltexture_s *gltexture; } mspriteframe_t; typedef struct { - int32_t numframes; - float *intervals; - mspriteframe_t *frames[1]; + int32_t numframes; + float *intervals; + mspriteframe_t *frames[1]; } mspritegroup_t; typedef struct { - spriteframetype_t type; - mspriteframe_t *frameptr; + spriteframetype_t type; + mspriteframe_t *frameptr; } mspriteframedesc_t; typedef struct { - int32_t type; - int32_t maxwidth; - int32_t maxheight; - int32_t numframes; - float beamlength; // remove? - void *cachespot; // remove? - mspriteframedesc_t frames[1]; + int32_t type; + int32_t maxwidth; + int32_t maxheight; + int32_t numframes; + float beamlength; // remove? + void *cachespot; // remove? + mspriteframedesc_t frames[1]; } msprite_t; @@ -308,79 +309,81 @@ typedef struct meshst_s typedef struct { - int32_t firstpose; - int32_t numposes; - float interval; - trivertx_t bboxmin; - trivertx_t bboxmax; - int32_t frame; - char name[16]; + int32_t firstpose; + int32_t numposes; + float interval; + trivertx_t bboxmin; + trivertx_t bboxmax; + int32_t frame; + char name[16]; } maliasframedesc_t; typedef struct { - trivertx_t bboxmin; - trivertx_t bboxmax; - int32_t frame; + trivertx_t bboxmin; + trivertx_t bboxmax; + int32_t frame; } maliasgroupframedesc_t; typedef struct { - int32_t numframes; - int32_t intervals; - maliasgroupframedesc_t frames[1]; + int32_t numframes; + int32_t intervals; + maliasgroupframedesc_t frames[1]; } maliasgroup_t; // !!! if this is changed, it must be changed in asm_draw.h too !!! -typedef struct mtriangle_s { - int32_t facesfront; - int32_t vertindex[3]; +typedef struct mtriangle_s +{ + int32_t facesfront; + int32_t vertindex[3]; } mtriangle_t; -#define MAX_SKINS 32 -typedef struct { - int32_t ident; - int32_t version; - vec3_t scale; - vec3_t scale_origin; - float boundingradius; - vec3_t eyeposition; - int32_t numskins; - int32_t skinwidth; - int32_t skinheight; - int32_t numverts; - int32_t numtris; - int32_t numframes; - synctype_t synctype; - int32_t flags; - float size; +#define MAX_SKINS 32 +typedef struct +{ + int32_t ident; + int32_t version; + vec3_t scale; + vec3_t scale_origin; + float boundingradius; + vec3_t eyeposition; + int32_t numskins; + int32_t skinwidth; + int32_t skinheight; + int32_t numverts; + int32_t numtris; + int32_t numframes; + synctype_t synctype; + int32_t flags; + float size; //ericw -- used to populate vbo - int32_t numverts_vbo; // number of verts with unique x,y,z,s,t - intptr_t meshdesc; // offset into extradata: numverts_vbo aliasmesh_t - int32_t numindexes; - intptr_t indexes; // offset into extradata: numindexes unsigned shorts - intptr_t vertexes; // offset into extradata: numposes*vertsperframe trivertx_t + int32_t numverts_vbo; // number of verts with unique x,y,z,s,t + intptr_t meshdesc; // offset into extradata: numverts_vbo aliasmesh_t + int32_t numindexes; + intptr_t indexes; // offset into extradata: numindexes unsigned shorts + intptr_t vertexes; // offset into extradata: numposes*vertsperframe trivertx_t //ericw -- - int32_t numposes; - int32_t poseverts; - int32_t posedata; // numposes*poseverts trivert_t - int32_t commands; // gl command list with embedded s/t - struct gltexture_s *gltextures[MAX_SKINS][4]; //johnfitz - struct gltexture_s *fbtextures[MAX_SKINS][4]; //johnfitz - int32_t texels[MAX_SKINS]; // only for player skins - maliasframedesc_t frames[1]; // variable sized + int32_t numposes; + int32_t poseverts; + int32_t posedata; // numposes*poseverts trivert_t + int32_t commands; // gl command list with embedded s/t + struct gltexture_s *gltextures[MAX_SKINS][4]; //johnfitz + struct gltexture_s *fbtextures[MAX_SKINS][4]; //johnfitz + int32_t texels[MAX_SKINS]; // only for player skins + maliasframedesc_t frames[1]; // variable sized } aliashdr_t; -#define MAXALIASVERTS 2000 //johnfitz -- was 1024 -#define MAXALIASFRAMES 256 -#define MAXALIASTRIS 2048 -extern aliashdr_t *pheader; -extern stvert_t stverts[MAXALIASVERTS]; -extern mtriangle_t triangles[MAXALIASTRIS]; -extern trivertx_t *poseverts[MAXALIASFRAMES]; +#define MAXALIASVERTS 2000 //johnfitz -- was 1024 +#define MAXALIASFRAMES 256 +#define MAXALIASTRIS 2048 +extern aliashdr_t *pheader; +extern stvert_t stverts[MAXALIASVERTS]; +extern mtriangle_t triangles[MAXALIASTRIS]; +extern trivertx_t *poseverts[MAXALIASFRAMES]; //=================================================================== @@ -390,130 +393,130 @@ extern trivertx_t *poseverts[MAXALIASFRAMES]; typedef enum {mod_brush, mod_sprite, mod_alias} modtype_t; -#define EF_ROCKET 1 // leave a trail -#define EF_GRENADE 2 // leave a trail -#define EF_GIB 4 // leave a trail -#define EF_ROTATE 8 // rotate (bonus items) -#define EF_TRACER 16 // green split trail -#define EF_ZOMGIB 32 // small blood trail -#define EF_TRACER2 64 // orange split trail + rotate -#define EF_TRACER3 128 // purple trail -#define MF_HOLEY (1u<<14) // MarkV/QSS -- make index 255 transparent on mdl's +#define EF_ROCKET 1 // leave a trail +#define EF_GRENADE 2 // leave a trail +#define EF_GIB 4 // leave a trail +#define EF_ROTATE 8 // rotate (bonus items) +#define EF_TRACER 16 // green split trail +#define EF_ZOMGIB 32 // small blood trail +#define EF_TRACER2 64 // orange split trail + rotate +#define EF_TRACER3 128 // purple trail +#define MF_HOLEY (1u<<14) // MarkV/QSS -- make index 255 transparent on mdl's //johnfitz -- extra flags for rendering -#define MOD_NOLERP 256 //don't lerp when animating -#define MOD_NOSHADOW 512 //don't cast a shadow -#define MOD_FBRIGHTHACK 1024 //when fullbrights are disabled, use a hack to render this model brighter +#define MOD_NOLERP 256 //don't lerp when animating +#define MOD_NOSHADOW 512 //don't cast a shadow +#define MOD_FBRIGHTHACK 1024 //when fullbrights are disabled, use a hack to render this model brighter //johnfitz typedef struct qmodel_s { - char name[MAX_QPATH]; - uint32_t path_id; // path id of the game directory - // that this model came from - bool needload; // bmodels and sprites don't cache normally + char name[MAX_QPATH]; + uint32_t path_id; // path id of the game directory + // that this model came from + bool needload; // bmodels and sprites don't cache normally - modtype_t type; - int32_t numframes; - synctype_t synctype; + modtype_t type; + int32_t numframes; + synctype_t synctype; - int32_t flags; + int32_t flags; // // volume occupied by the model graphics // - vec3_t mins, maxs; - vec3_t ymins, ymaxs; //johnfitz -- bounds for entities with nonzero yaw - vec3_t rmins, rmaxs; //johnfitz -- bounds for entities with nonzero pitch or roll + vec3_t mins, maxs; + vec3_t ymins, ymaxs; //johnfitz -- bounds for entities with nonzero yaw + vec3_t rmins, rmaxs; //johnfitz -- bounds for entities with nonzero pitch or roll //johnfitz -- removed float radius; // // solid volume for clipping // - bool clipbox; - vec3_t clipmins, clipmaxs; + bool clipbox; + vec3_t clipmins, clipmaxs; // // brush model // - int32_t firstmodelsurface, nummodelsurfaces; + int32_t firstmodelsurface, nummodelsurfaces; - int32_t numsubmodels; - dmodel_t *submodels; + int32_t numsubmodels; + dmodel_t *submodels; - int32_t numplanes; - mplane_t *planes; + int32_t numplanes; + mplane_t *planes; - int32_t numleafs; // number of visible leafs, not counting 0 - mleaf_t *leafs; + int32_t numleafs; // number of visible leafs, not counting 0 + mleaf_t *leafs; - int32_t numvertexes; - mvertex_t *vertexes; + int32_t numvertexes; + mvertex_t *vertexes; - int32_t numedges; - medge_t *edges; + int32_t numedges; + medge_t *edges; - int32_t numnodes; - mnode_t *nodes; + int32_t numnodes; + mnode_t *nodes; - int32_t numtexinfo; - mtexinfo_t *texinfo; + int32_t numtexinfo; + mtexinfo_t *texinfo; - int32_t numsurfaces; - msurface_t *surfaces; + int32_t numsurfaces; + msurface_t *surfaces; - int32_t numsurfedges; - int32_t *surfedges; + int32_t numsurfedges; + int32_t *surfedges; - int32_t numclipnodes; - mclipnode_t *clipnodes; //johnfitz -- was dclipnode_t + int32_t numclipnodes; + mclipnode_t *clipnodes; //johnfitz -- was dclipnode_t - int32_t nummarksurfaces; - msurface_t **marksurfaces; + int32_t nummarksurfaces; + msurface_t **marksurfaces; - hull_t hulls[MAX_MAP_HULLS]; + hull_t hulls[MAX_MAP_HULLS]; - int32_t numtextures; - texture_t **textures; + int32_t numtextures; + texture_t **textures; - byte *visdata; - byte *lightdata; - char *entities; + byte *visdata; + byte *lightdata; + char *entities; - bool viswarn; // for Mod_DecompressVis() + bool viswarn; // for Mod_DecompressVis() - int32_t bspversion; + int32_t bspversion; // // alias model // - GLuint meshvbo; - GLuint meshindexesvbo; - int32_t vboindexofs; // offset in vbo of the hdr->numindexes unsigned shorts - int32_t vboxyzofs; // offset in vbo of hdr->numposes*hdr->numverts_vbo meshxyz_t - int32_t vbostofs; // offset in vbo of hdr->numverts_vbo meshst_t + GLuint meshvbo; + GLuint meshindexesvbo; + int32_t vboindexofs; // offset in vbo of the hdr->numindexes unsigned shorts + int32_t vboxyzofs; // offset in vbo of hdr->numposes*hdr->numverts_vbo meshxyz_t + int32_t vbostofs; // offset in vbo of hdr->numverts_vbo meshst_t // // additional model data // - cache_user_t cache; // only access through Mod_Extradata + cache_user_t cache; // only access through Mod_Extradata } qmodel_t; //============================================================================ -void Mod_Init (void); -void Mod_ClearAll (void); -void Mod_ResetAll (void); // for gamedir changes (Host_Game_f) -qmodel_t *Mod_ForName (const char *name, bool crash); -void *Mod_Extradata (qmodel_t *mod); // handles caching -void Mod_TouchModel (const char *name); +void Mod_Init(void); +void Mod_ClearAll(void); +void Mod_ResetAll(void); // for gamedir changes (Host_Game_f) +qmodel_t *Mod_ForName(const char *name, bool crash); +void *Mod_Extradata(qmodel_t *mod); // handles caching +void Mod_TouchModel(const char *name); -mleaf_t *Mod_PointInLeaf (float *p, qmodel_t *model); -byte *Mod_LeafPVS (mleaf_t *leaf, qmodel_t *model); -byte *Mod_NoVisPVS (qmodel_t *model); +mleaf_t *Mod_PointInLeaf(float *p, qmodel_t *model); +byte *Mod_LeafPVS(mleaf_t *leaf, qmodel_t *model); +byte *Mod_NoVisPVS(qmodel_t *model); -void Mod_SetExtraFlags (qmodel_t *mod); +void Mod_SetExtraFlags(qmodel_t *mod); -#endif // __MODEL__ +#endif // __MODEL__ diff --git a/source/gl_refrag.c b/source/gl_refrag.c index 8d457e3..1ac9ab5 100644 --- a/source/gl_refrag.c +++ b/source/gl_refrag.c @@ -23,7 +23,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -mnode_t *r_pefragtopnode; +mnode_t *r_pefragtopnode; //=========================================================================== @@ -31,7 +31,7 @@ mnode_t *r_pefragtopnode; /* =============================================================================== - ENTITY FRAGMENT FUNCTIONS + ENTITY FRAGMENT FUNCTIONS ericw -- GLQuake only uses efrags for static entities, and they're never removed, so I trimmed out unused functionality and fields in efrag_t. @@ -39,50 +39,50 @@ removed, so I trimmed out unused functionality and fields in efrag_t. Now, efrags are just a linked list for each leaf of the static entities that touch that leaf. The efrags are hunk-allocated so there is no fixed limit. - + This is inspired by MH's tutorial, and code from RMQEngine. http://forums.insideqc.com/viewtopic.php?t=1930 - + =============================================================================== */ -vec3_t r_emins, r_emaxs; +vec3_t r_emins, r_emaxs; -entity_t *r_addent; +entity_t *r_addent; -#define EXTRA_EFRAGS 128 +#define EXTRA_EFRAGS 128 // based on RMQEngine -static efrag_t *R_GetEfrag (void) +static efrag_t *R_GetEfrag(void) { // we could just Hunk_Alloc a single efrag_t and return it, but since // the struct is so small (2 pointers) allocate groups of them // to avoid wasting too much space on the hunk allocation headers. - - if (cl.free_efrags) + + if(cl.free_efrags) { efrag_t *ef = cl.free_efrags; cl.free_efrags = ef->leafnext; ef->leafnext = NULL; - + cl.num_efrags++; - + return ef; } else { int32_t i; - - cl.free_efrags = (efrag_t *) Hunk_AllocName (EXTRA_EFRAGS * sizeof (efrag_t), "efrags"); - - for (i = 0; i < EXTRA_EFRAGS - 1; i++) + + cl.free_efrags = (efrag_t *) Hunk_AllocName(EXTRA_EFRAGS * sizeof(efrag_t), "efrags"); + + for(i = 0; i < EXTRA_EFRAGS - 1; i++) cl.free_efrags[i].leafnext = &cl.free_efrags[i + 1]; - + cl.free_efrags[i].leafnext = NULL; - + // call recursively to get a newly allocated free efrag - return R_GetEfrag (); + return R_GetEfrag(); } } @@ -91,23 +91,23 @@ static efrag_t *R_GetEfrag (void) R_SplitEntityOnNode =================== */ -void R_SplitEntityOnNode (mnode_t *node) +void R_SplitEntityOnNode(mnode_t *node) { - efrag_t *ef; - mplane_t *splitplane; - mleaf_t *leaf; - int32_t sides; + efrag_t *ef; + mplane_t *splitplane; + mleaf_t *leaf; + int32_t sides; - if (node->contents == CONTENTS_SOLID) + if(node->contents == CONTENTS_SOLID) { return; } // add an efrag if the node is a leaf - if ( node->contents < 0) + if(node->contents < 0) { - if (!r_pefragtopnode) + if(!r_pefragtopnode) r_pefragtopnode = node; leaf = (mleaf_t *)node; @@ -128,20 +128,20 @@ void R_SplitEntityOnNode (mnode_t *node) splitplane = node->plane; sides = BOX_ON_PLANE_SIDE(r_emins, r_emaxs, splitplane); - if (sides == 3) + if(sides == 3) { - // split on this plane - // if this is the first splitter of this bmodel, remember it - if (!r_pefragtopnode) + // split on this plane + // if this is the first splitter of this bmodel, remember it + if(!r_pefragtopnode) r_pefragtopnode = node; } // recurse down the contacted sides - if (sides & 1) - R_SplitEntityOnNode (node->children[0]); + if(sides & 1) + R_SplitEntityOnNode(node->children[0]); - if (sides & 2) - R_SplitEntityOnNode (node->children[1]); + if(sides & 2) + R_SplitEntityOnNode(node->children[1]); } /* @@ -149,13 +149,13 @@ void R_SplitEntityOnNode (mnode_t *node) R_CheckEfrags -- johnfitz -- check for excessive efrag count =========== */ -void R_CheckEfrags (void) +void R_CheckEfrags(void) { - if (cls.signon < 2) + if(cls.signon < 2) return; //don't spam when still parsing signon packet full of static ents - if (cl.num_efrags > 640 && dev_peakstats.efrags <= 640) - Con_DWarning ("%" PRIi32 " efrags exceeds standard limit of 640.\n", cl.num_efrags); + if(cl.num_efrags > 640 && dev_peakstats.efrags <= 640) + Con_DWarning("%" PRIi32 " efrags exceeds standard limit of 640.\n", cl.num_efrags); dev_stats.efrags = cl.num_efrags; dev_peakstats.efrags = q_max(cl.num_efrags, dev_peakstats.efrags); @@ -166,12 +166,12 @@ void R_CheckEfrags (void) R_AddEfrags =========== */ -void R_AddEfrags (entity_t *ent) +void R_AddEfrags(entity_t *ent) { - qmodel_t *entmodel; - int32_t i; + qmodel_t *entmodel; + int32_t i; - if (!ent->model) + if(!ent->model) return; r_addent = ent; @@ -180,17 +180,17 @@ void R_AddEfrags (entity_t *ent) entmodel = ent->model; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { r_emins[i] = ent->origin[i] + entmodel->mins[i]; r_emaxs[i] = ent->origin[i] + entmodel->maxs[i]; } - R_SplitEntityOnNode (cl.worldmodel->nodes); + R_SplitEntityOnNode(cl.worldmodel->nodes); ent->topnode = r_pefragtopnode; - R_CheckEfrags (); //johnfitz + R_CheckEfrags(); //johnfitz } @@ -199,16 +199,16 @@ void R_AddEfrags (entity_t *ent) R_StoreEfrags -- johnfitz -- pointless switch statement removed. ================ */ -void R_StoreEfrags (efrag_t **ppefrag) +void R_StoreEfrags(efrag_t **ppefrag) { - entity_t *pent; - efrag_t *pefrag; + entity_t *pent; + efrag_t *pefrag; - while ((pefrag = *ppefrag) != NULL) + while((pefrag = *ppefrag) != NULL) { pent = pefrag->entity; - if ((pent->visframe != r_framecount) && (cl_numvisedicts < MAX_VISEDICTS)) + if((pent->visframe != r_framecount) && (cl_numvisedicts < MAX_VISEDICTS)) { cl_visedicts[cl_numvisedicts++] = pent; pent->visframe = r_framecount; diff --git a/source/gl_rlight.c b/source/gl_rlight.c index eac751f..75b4d99 100644 --- a/source/gl_rlight.c +++ b/source/gl_rlight.c @@ -23,7 +23,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -int32_t r_dlightframecount; +int32_t r_dlightframecount; extern cvar_t r_flatlightstyles; //johnfitz @@ -32,32 +32,32 @@ extern cvar_t r_flatlightstyles; //johnfitz R_AnimateLight ================== */ -void R_AnimateLight (void) +void R_AnimateLight(void) { - int32_t i,j,k; + int32_t i, j, k; // // light animations // 'm' is normal light, 'a' is no light, 'z' is double bright - i = (int32_t)(cl.time*10); - for (j=0 ; jradius * 0.35; - VectorSubtract (light->origin, r_origin, v); - if (VectorLength (v) < rad) - { // view is inside the dlight - AddLightBlend (1, 0.5, 0, light->radius * 0.0003); + VectorSubtract(light->origin, r_origin, v); + if(VectorLength(v) < rad) + { + // view is inside the dlight + AddLightBlend(1, 0.5, 0, light->radius * 0.0003); return; } - glBegin (GL_TRIANGLE_FAN); - glColor3f (0.2,0.1,0.0); - for (i=0 ; i<3 ; i++) - v[i] = light->origin[i] - vpn[i]*rad; - glVertex3fv (v); - glColor3f (0,0,0); - for (i=16 ; i>=0 ; i--) + glBegin(GL_TRIANGLE_FAN); + glColor3f(0.2, 0.1, 0.0); + for(i = 0 ; i < 3 ; i++) + v[i] = light->origin[i] - vpn[i] * rad; + glVertex3fv(v); + glColor3f(0, 0, 0); + for(i = 16 ; i >= 0 ; i--) { - a = i/16.0 * M_PI*2; - for (j=0 ; j<3 ; j++) - v[j] = light->origin[j] + vright[j]*cos(a)*rad - + vup[j]*sin(a)*rad; - glVertex3fv (v); + a = i / 16.0 * M_PI * 2; + for(j = 0 ; j < 3 ; j++) + v[j] = light->origin[j] + vright[j] * cos(a) * rad + + vup[j] * sin(a) * rad; + glVertex3fv(v); } - glEnd (); + glEnd(); } /* @@ -121,35 +122,35 @@ void R_RenderDlight (dlight_t *light) R_RenderDlights ============= */ -void R_RenderDlights (void) +void R_RenderDlights(void) { - int32_t i; - dlight_t *l; + int32_t i; + dlight_t *l; - if (!gl_flashblend.value) + if(!gl_flashblend.value) return; - r_dlightframecount = r_framecount + 1; // because the count hasn't - // advanced yet for this frame - glDepthMask (0); - glDisable (GL_TEXTURE_2D); - glShadeModel (GL_SMOOTH); - glEnable (GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE); + r_dlightframecount = r_framecount + 1; // because the count hasn't + // advanced yet for this frame + glDepthMask(0); + glDisable(GL_TEXTURE_2D); + glShadeModel(GL_SMOOTH); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE); l = cl_dlights; - for (i=0 ; idie < cl.time || !l->radius) + if(l->die < cl.time || !l->radius) continue; - R_RenderDlight (l); + R_RenderDlight(l); } - glColor3f (1,1,1); - glDisable (GL_BLEND); - glEnable (GL_TEXTURE_2D); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthMask (1); + glColor3f(1, 1, 1); + glDisable(GL_BLEND); + glEnable(GL_TEXTURE_2D); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDepthMask(1); } @@ -166,54 +167,58 @@ DYNAMIC LIGHTS R_MarkLights -- johnfitz -- rewritten to use LordHavoc's lighting speedup ============= */ -void R_MarkLights (dlight_t *light, int32_t num, mnode_t *node) +void R_MarkLights(dlight_t *light, int32_t num, mnode_t *node) { - mplane_t *splitplane; - msurface_t *surf; - vec3_t impact; - float dist, l, maxdist; - int32_t i, j, s, t; + mplane_t *splitplane; + msurface_t *surf; + vec3_t impact; + float dist, l, maxdist; + int32_t i, j, s, t; start: - if (node->contents < 0) + if(node->contents < 0) return; splitplane = node->plane; - if (splitplane->type < 3) + if(splitplane->type < 3) dist = light->origin[splitplane->type] - splitplane->dist; else - dist = DotProduct (light->origin, splitplane->normal) - splitplane->dist; + dist = DotProduct(light->origin, splitplane->normal) - splitplane->dist; - if (dist > light->radius) + if(dist > light->radius) { node = node->children[0]; goto start; } - if (dist < -light->radius) + if(dist < -light->radius) { node = node->children[1]; goto start; } - maxdist = light->radius*light->radius; + maxdist = light->radius * light->radius; // mark the polygons surf = cl.worldmodel->surfaces + node->firstsurface; - for (i=0 ; inumsurfaces ; i++, surf++) + for(i = 0 ; i < node->numsurfaces ; i++, surf++) { - for (j=0 ; j<3 ; j++) - impact[j] = light->origin[j] - surf->plane->normal[j]*dist; + for(j = 0 ; j < 3 ; j++) + impact[j] = light->origin[j] - surf->plane->normal[j] * dist; // clamp center of light to corner and check brightness - l = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0]; - s = l+0.5;if (s < 0) s = 0;else if (s > surf->extents[0]) s = surf->extents[0]; + l = DotProduct(impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0]; + s = l + 0.5; + if(s < 0) s = 0; + else if(s > surf->extents[0]) s = surf->extents[0]; s = l - s; - l = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1]; - t = l+0.5;if (t < 0) t = 0;else if (t > surf->extents[1]) t = surf->extents[1]; + l = DotProduct(impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1]; + t = l + 0.5; + if(t < 0) t = 0; + else if(t > surf->extents[1]) t = surf->extents[1]; t = l - t; // compare to minimum light - if ((s*s+t*t+dist*dist) < maxdist) + if((s * s + t * t + dist * dist) < maxdist) { - if (surf->dlightframe != r_dlightframecount) // not dynamic until now + if(surf->dlightframe != r_dlightframecount) // not dynamic until now { surf->dlightbits[num >> 5] = 1U << (num & 31); surf->dlightframe = r_dlightframecount; @@ -223,10 +228,10 @@ start: } } - if (node->children[0]->contents >= 0) - R_MarkLights (light, num, node->children[0]); - if (node->children[1]->contents >= 0) - R_MarkLights (light, num, node->children[1]); + if(node->children[0]->contents >= 0) + R_MarkLights(light, num, node->children[0]); + if(node->children[1]->contents >= 0) + R_MarkLights(light, num, node->children[1]); } /* @@ -234,23 +239,23 @@ start: R_PushDlights ============= */ -void R_PushDlights (void) +void R_PushDlights(void) { - int32_t i; - dlight_t *l; + int32_t i; + dlight_t *l; - if (gl_flashblend.value) + if(gl_flashblend.value) return; - r_dlightframecount = r_framecount + 1; // because the count hasn't - // advanced yet for this frame + r_dlightframecount = r_framecount + 1; // because the count hasn't + // advanced yet for this frame l = cl_dlights; - for (i=0 ; idie < cl.time || !l->radius) + if(l->die < cl.time || !l->radius) continue; - R_MarkLights (l, i, cl.worldmodel->nodes); + R_MarkLights(l, i, cl.worldmodel->nodes); } } @@ -263,26 +268,26 @@ LIGHT SAMPLING ============================================================================= */ -mplane_t *lightplane; -vec3_t lightspot; -vec3_t lightcolor; //johnfitz -- lit support via lordhavoc +mplane_t *lightplane; +vec3_t lightspot; +vec3_t lightcolor; //johnfitz -- lit support via lordhavoc /* ============= RecursiveLightPoint -- johnfitz -- replaced entire function for lit support via lordhavoc ============= */ -int32_t RecursiveLightPoint (vec3_t color, mnode_t *node, vec3_t start, vec3_t end) +int32_t RecursiveLightPoint(vec3_t color, mnode_t *node, vec3_t start, vec3_t end) { - float front, back, frac; - vec3_t mid; + float front, back, frac; + vec3_t mid; loc0: - if (node->contents < 0) - return false; // didn't hit anything + if(node->contents < 0) + return false; // didn't hit anything // calculate mid point - if (node->plane->type < 3) + if(node->plane->type < 3) { front = start[node->plane->type] - node->plane->dist; back = end[node->plane->type] - node->plane->dist; @@ -294,79 +299,87 @@ loc0: } // LordHavoc: optimized recursion - if ((back < 0) == (front < 0)) + if((back < 0) == (front < 0)) // return RecursiveLightPoint (color, node->children[front < 0], start, end); { node = node->children[front < 0]; goto loc0; } - frac = front / (front-back); - mid[0] = start[0] + (end[0] - start[0])*frac; - mid[1] = start[1] + (end[1] - start[1])*frac; - mid[2] = start[2] + (end[2] - start[2])*frac; + frac = front / (front - back); + mid[0] = start[0] + (end[0] - start[0]) * frac; + mid[1] = start[1] + (end[1] - start[1]) * frac; + mid[2] = start[2] + (end[2] - start[2]) * frac; // go down front side - if (RecursiveLightPoint (color, node->children[front < 0], start, mid)) - return true; // hit something + if(RecursiveLightPoint(color, node->children[front < 0], start, mid)) + return true; // hit something else { int32_t i, ds, dt; msurface_t *surf; - // check for impact on this node - VectorCopy (mid, lightspot); + // check for impact on this node + VectorCopy(mid, lightspot); lightplane = node->plane; surf = cl.worldmodel->surfaces + node->firstsurface; - for (i = 0;i < node->numsurfaces;i++, surf++) + for(i = 0; i < node->numsurfaces; i++, surf++) { - if (surf->flags & SURF_DRAWTILED) - continue; // no lightmaps + if(surf->flags & SURF_DRAWTILED) + continue; // no lightmaps - // ericw -- added double casts to force 64-bit precision. - // Without them the zombie at the start of jam3_ericw.bsp was - // incorrectly being lit up in SSE builds. - ds = (int32_t) ((double) DoublePrecisionDotProduct (mid, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3]); - dt = (int32_t) ((double) DoublePrecisionDotProduct (mid, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3]); + // ericw -- added double casts to force 64-bit precision. + // Without them the zombie at the start of jam3_ericw.bsp was + // incorrectly being lit up in SSE builds. + ds = (int32_t)((double) DoublePrecisionDotProduct(mid, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3]); + dt = (int32_t)((double) DoublePrecisionDotProduct(mid, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3]); - if (ds < surf->texturemins[0] || dt < surf->texturemins[1]) + if(ds < surf->texturemins[0] || dt < surf->texturemins[1]) continue; ds -= surf->texturemins[0]; dt -= surf->texturemins[1]; - if (ds > surf->extents[0] || dt > surf->extents[1]) + if(ds > surf->extents[0] || dt > surf->extents[1]) continue; - if (surf->samples) + if(surf->samples) { // LordHavoc: enhanced to interpolate lighting byte *lightmap; int32_t maps, line3, dsfrac = ds & 15, dtfrac = dt & 15, r00 = 0, g00 = 0, b00 = 0, r01 = 0, g01 = 0, b01 = 0, r10 = 0, g10 = 0, b10 = 0, r11 = 0, g11 = 0, b11 = 0; float scale; - line3 = ((surf->extents[0]>>4)+1)*3; + line3 = ((surf->extents[0] >> 4) + 1) * 3; - lightmap = surf->samples + ((dt>>4) * ((surf->extents[0]>>4)+1) + (ds>>4))*3; // LordHavoc: *3 for color + lightmap = surf->samples + ((dt >> 4) * ((surf->extents[0] >> 4) + 1) + (ds >> 4)) * 3; // LordHavoc: *3 for color - for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++) + for(maps = 0; maps < MAXLIGHTMAPS && surf->styles[maps] != 255; maps++) { scale = (float) d_lightstylevalue[surf->styles[maps]] * 1.0 / 256.0; - r00 += (float) lightmap[ 0] * scale;g00 += (float) lightmap[ 1] * scale;b00 += (float) lightmap[2] * scale; - r01 += (float) lightmap[ 3] * scale;g01 += (float) lightmap[ 4] * scale;b01 += (float) lightmap[5] * scale; - r10 += (float) lightmap[line3+0] * scale;g10 += (float) lightmap[line3+1] * scale;b10 += (float) lightmap[line3+2] * scale; - r11 += (float) lightmap[line3+3] * scale;g11 += (float) lightmap[line3+4] * scale;b11 += (float) lightmap[line3+5] * scale; - lightmap += ((surf->extents[0]>>4)+1) * ((surf->extents[1]>>4)+1)*3; // LordHavoc: *3 for colored lighting + r00 += (float) lightmap[ 0] * scale; + g00 += (float) lightmap[ 1] * scale; + b00 += (float) lightmap[2] * scale; + r01 += (float) lightmap[ 3] * scale; + g01 += (float) lightmap[ 4] * scale; + b01 += (float) lightmap[5] * scale; + r10 += (float) lightmap[line3 + 0] * scale; + g10 += (float) lightmap[line3 + 1] * scale; + b10 += (float) lightmap[line3 + 2] * scale; + r11 += (float) lightmap[line3 + 3] * scale; + g11 += (float) lightmap[line3 + 4] * scale; + b11 += (float) lightmap[line3 + 5] * scale; + lightmap += ((surf->extents[0] >> 4) + 1) * ((surf->extents[1] >> 4) + 1) * 3; // LordHavoc: *3 for colored lighting } - color[0] += (float) ((int32_t) ((((((((r11-r10) * dsfrac) >> 4) + r10)-((((r01-r00) * dsfrac) >> 4) + r00)) * dtfrac) >> 4) + ((((r01-r00) * dsfrac) >> 4) + r00))); - color[1] += (float) ((int32_t) ((((((((g11-g10) * dsfrac) >> 4) + g10)-((((g01-g00) * dsfrac) >> 4) + g00)) * dtfrac) >> 4) + ((((g01-g00) * dsfrac) >> 4) + g00))); - color[2] += (float) ((int32_t) ((((((((b11-b10) * dsfrac) >> 4) + b10)-((((b01-b00) * dsfrac) >> 4) + b00)) * dtfrac) >> 4) + ((((b01-b00) * dsfrac) >> 4) + b00))); + color[0] += (float)((int32_t)((((((((r11 - r10) * dsfrac) >> 4) + r10) - ((((r01 - r00) * dsfrac) >> 4) + r00)) * dtfrac) >> 4) + ((((r01 - r00) * dsfrac) >> 4) + r00))); + color[1] += (float)((int32_t)((((((((g11 - g10) * dsfrac) >> 4) + g10) - ((((g01 - g00) * dsfrac) >> 4) + g00)) * dtfrac) >> 4) + ((((g01 - g00) * dsfrac) >> 4) + g00))); + color[2] += (float)((int32_t)((((((((b11 - b10) * dsfrac) >> 4) + b10) - ((((b01 - b00) * dsfrac) >> 4) + b00)) * dtfrac) >> 4) + ((((b01 - b00) * dsfrac) >> 4) + b00))); } return true; // success } - // go down back side - return RecursiveLightPoint (color, node->children[front >= 0], mid, end); + // go down back side + return RecursiveLightPoint(color, node->children[front >= 0], mid, end); } } @@ -375,11 +388,11 @@ loc0: R_LightPoint -- johnfitz -- replaced entire function for lit support via lordhavoc ============= */ -int32_t R_LightPoint (vec3_t p) +int32_t R_LightPoint(vec3_t p) { - vec3_t end; + vec3_t end; - if (!cl.worldmodel->lightdata) + if(!cl.worldmodel->lightdata) { lightcolor[0] = lightcolor[1] = lightcolor[2] = 255; return 255; @@ -390,6 +403,6 @@ int32_t R_LightPoint (vec3_t p) end[2] = p[2] - 8192; //johnfitz -- was 2048 lightcolor[0] = lightcolor[1] = lightcolor[2] = 0; - RecursiveLightPoint (lightcolor, cl.worldmodel->nodes, p, end); + RecursiveLightPoint(lightcolor, cl.worldmodel->nodes, p, end); return ((lightcolor[0] + lightcolor[1] + lightcolor[2]) * (1.0f / 3.0f)); } diff --git a/source/gl_rmain.c b/source/gl_rmain.c index 917dcf8..b5a3786 100644 --- a/source/gl_rmain.c +++ b/source/gl_rmain.c @@ -23,15 +23,15 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -bool r_cache_thrash; // compatability +bool r_cache_thrash; // compatability -vec3_t modelorg, r_entorigin; -entity_t *currententity; +vec3_t modelorg, r_entorigin; +entity_t *currententity; -int32_t r_visframecount; // bumped when going to a new PVS -int32_t r_framecount; // used for dlight push checking +int32_t r_visframecount; // bumped when going to a new PVS +int32_t r_framecount; // used for dlight push checking -mplane_t frustum[4]; +mplane_t frustum[4]; //johnfitz -- rendering statistics int32_t rs_brushpolys, rs_aliaspolys, rs_skypolys, rs_particles, rs_fogpolys; @@ -41,78 +41,78 @@ float rs_megatexels; // // view origin // -vec3_t vup; -vec3_t vpn; -vec3_t vright; -vec3_t r_origin; +vec3_t vup; +vec3_t vpn; +vec3_t vright; +vec3_t r_origin; float r_fovx, r_fovy; //johnfitz -- rendering fov may be different becuase of r_waterwarp and r_stereo // // screen size info // -refdef_t r_refdef; +refdef_t r_refdef; -mleaf_t *r_viewleaf, *r_oldviewleaf; +mleaf_t *r_viewleaf, *r_oldviewleaf; -int32_t d_lightstylevalue[256]; // 8.8 fraction of base light value +int32_t d_lightstylevalue[256]; // 8.8 fraction of base light value -cvar_t r_norefresh = {"r_norefresh","0",CVAR_NONE}; -cvar_t r_drawentities = {"r_drawentities","1",CVAR_NONE}; -cvar_t r_drawviewmodel = {"r_drawviewmodel","1",CVAR_NONE}; -cvar_t r_speeds = {"r_speeds","0",CVAR_NONE}; -cvar_t r_pos = {"r_pos","0",CVAR_NONE}; -cvar_t r_fullbright = {"r_fullbright","0",CVAR_NONE}; -cvar_t r_lightmap = {"r_lightmap","0",CVAR_NONE}; -cvar_t r_shadows = {"r_shadows","0",CVAR_ARCHIVE}; -cvar_t r_wateralpha = {"r_wateralpha","1",CVAR_ARCHIVE}; -cvar_t r_dynamic = {"r_dynamic","1",CVAR_ARCHIVE}; -cvar_t r_novis = {"r_novis","0",CVAR_ARCHIVE}; +cvar_t r_norefresh = {"r_norefresh", "0", CVAR_NONE}; +cvar_t r_drawentities = {"r_drawentities", "1", CVAR_NONE}; +cvar_t r_drawviewmodel = {"r_drawviewmodel", "1", CVAR_NONE}; +cvar_t r_speeds = {"r_speeds", "0", CVAR_NONE}; +cvar_t r_pos = {"r_pos", "0", CVAR_NONE}; +cvar_t r_fullbright = {"r_fullbright", "0", CVAR_NONE}; +cvar_t r_lightmap = {"r_lightmap", "0", CVAR_NONE}; +cvar_t r_shadows = {"r_shadows", "0", CVAR_ARCHIVE}; +cvar_t r_wateralpha = {"r_wateralpha", "1", CVAR_ARCHIVE}; +cvar_t r_dynamic = {"r_dynamic", "1", CVAR_ARCHIVE}; +cvar_t r_novis = {"r_novis", "0", CVAR_ARCHIVE}; -cvar_t gl_finish = {"gl_finish","0",CVAR_NONE}; -cvar_t gl_clear = {"gl_clear","1",CVAR_NONE}; -cvar_t gl_cull = {"gl_cull","1",CVAR_NONE}; -cvar_t gl_smoothmodels = {"gl_smoothmodels","1",CVAR_NONE}; -cvar_t gl_affinemodels = {"gl_affinemodels","0",CVAR_NONE}; -cvar_t gl_polyblend = {"gl_polyblend","1",CVAR_NONE}; -cvar_t gl_flashblend = {"gl_flashblend","0",CVAR_ARCHIVE}; -cvar_t gl_playermip = {"gl_playermip","0",CVAR_NONE}; -cvar_t gl_nocolors = {"gl_nocolors","0",CVAR_NONE}; +cvar_t gl_finish = {"gl_finish", "0", CVAR_NONE}; +cvar_t gl_clear = {"gl_clear", "1", CVAR_NONE}; +cvar_t gl_cull = {"gl_cull", "1", CVAR_NONE}; +cvar_t gl_smoothmodels = {"gl_smoothmodels", "1", CVAR_NONE}; +cvar_t gl_affinemodels = {"gl_affinemodels", "0", CVAR_NONE}; +cvar_t gl_polyblend = {"gl_polyblend", "1", CVAR_NONE}; +cvar_t gl_flashblend = {"gl_flashblend", "0", CVAR_ARCHIVE}; +cvar_t gl_playermip = {"gl_playermip", "0", CVAR_NONE}; +cvar_t gl_nocolors = {"gl_nocolors", "0", CVAR_NONE}; //johnfitz -- new cvars -cvar_t r_stereo = {"r_stereo","0",CVAR_NONE}; -cvar_t r_stereodepth = {"r_stereodepth","128",CVAR_NONE}; -cvar_t r_clearcolor = {"r_clearcolor","2",CVAR_ARCHIVE}; -cvar_t r_drawflat = {"r_drawflat","0",CVAR_NONE}; -cvar_t r_flatlightstyles = {"r_flatlightstyles", "0", CVAR_NONE}; -cvar_t gl_fullbrights = {"gl_fullbrights", "1", CVAR_ARCHIVE}; -cvar_t gl_farclip = {"gl_farclip", "16384", CVAR_ARCHIVE}; -cvar_t gl_overbright = {"gl_overbright", "1", CVAR_ARCHIVE}; -cvar_t gl_overbright_models = {"gl_overbright_models", "1", CVAR_ARCHIVE}; -cvar_t r_oldskyleaf = {"r_oldskyleaf", "0", CVAR_NONE}; -cvar_t r_drawworld = {"r_drawworld", "1", CVAR_NONE}; -cvar_t r_showtris = {"r_showtris", "0", CVAR_NONE}; -cvar_t r_showbboxes = {"r_showbboxes", "0", CVAR_NONE}; -cvar_t r_lerpmodels = {"r_lerpmodels", "1", CVAR_NONE}; -cvar_t r_lerpmove = {"r_lerpmove", "1", CVAR_NONE}; -cvar_t r_nolerp_list = {"r_nolerp_list", "progs/flame.mdl,progs/flame2.mdl,progs/braztall.mdl,progs/brazshrt.mdl,progs/longtrch.mdl,progs/flame_pyre.mdl,progs/v_saw.mdl,progs/v_xfist.mdl,progs/h2stuff/newfire.mdl", CVAR_NONE}; -cvar_t r_noshadow_list = {"r_noshadow_list", "progs/flame2.mdl,progs/flame.mdl,progs/bolt1.mdl,progs/bolt2.mdl,progs/bolt3.mdl,progs/laser.mdl", CVAR_NONE}; +cvar_t r_stereo = {"r_stereo", "0", CVAR_NONE}; +cvar_t r_stereodepth = {"r_stereodepth", "128", CVAR_NONE}; +cvar_t r_clearcolor = {"r_clearcolor", "2", CVAR_ARCHIVE}; +cvar_t r_drawflat = {"r_drawflat", "0", CVAR_NONE}; +cvar_t r_flatlightstyles = {"r_flatlightstyles", "0", CVAR_NONE}; +cvar_t gl_fullbrights = {"gl_fullbrights", "1", CVAR_ARCHIVE}; +cvar_t gl_farclip = {"gl_farclip", "16384", CVAR_ARCHIVE}; +cvar_t gl_overbright = {"gl_overbright", "1", CVAR_ARCHIVE}; +cvar_t gl_overbright_models = {"gl_overbright_models", "1", CVAR_ARCHIVE}; +cvar_t r_oldskyleaf = {"r_oldskyleaf", "0", CVAR_NONE}; +cvar_t r_drawworld = {"r_drawworld", "1", CVAR_NONE}; +cvar_t r_showtris = {"r_showtris", "0", CVAR_NONE}; +cvar_t r_showbboxes = {"r_showbboxes", "0", CVAR_NONE}; +cvar_t r_lerpmodels = {"r_lerpmodels", "1", CVAR_NONE}; +cvar_t r_lerpmove = {"r_lerpmove", "1", CVAR_NONE}; +cvar_t r_nolerp_list = {"r_nolerp_list", "progs/flame.mdl,progs/flame2.mdl,progs/braztall.mdl,progs/brazshrt.mdl,progs/longtrch.mdl,progs/flame_pyre.mdl,progs/v_saw.mdl,progs/v_xfist.mdl,progs/h2stuff/newfire.mdl", CVAR_NONE}; +cvar_t r_noshadow_list = {"r_noshadow_list", "progs/flame2.mdl,progs/flame.mdl,progs/bolt1.mdl,progs/bolt2.mdl,progs/bolt3.mdl,progs/laser.mdl", CVAR_NONE}; -extern cvar_t r_vfog; +extern cvar_t r_vfog; //johnfitz -cvar_t gl_zfix = {"gl_zfix", "0", CVAR_NONE}; // QuakeSpasm z-fighting fix +cvar_t gl_zfix = {"gl_zfix", "0", CVAR_NONE}; // QuakeSpasm z-fighting fix -cvar_t r_lavaalpha = {"r_lavaalpha","0",CVAR_NONE}; -cvar_t r_telealpha = {"r_telealpha","0",CVAR_NONE}; -cvar_t r_slimealpha = {"r_slimealpha","0",CVAR_NONE}; +cvar_t r_lavaalpha = {"r_lavaalpha", "0", CVAR_NONE}; +cvar_t r_telealpha = {"r_telealpha", "0", CVAR_NONE}; +cvar_t r_slimealpha = {"r_slimealpha", "0", CVAR_NONE}; -float map_wateralpha, map_lavaalpha, map_telealpha, map_slimealpha; +float map_wateralpha, map_lavaalpha, map_telealpha, map_slimealpha; bool r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz -cvar_t r_scale = {"r_scale", "1", CVAR_ARCHIVE}; +cvar_t r_scale = {"r_scale", "1", CVAR_ARCHIVE}; //============================================================================== // @@ -134,9 +134,9 @@ static GLuint textureLoc; GLSLGamma_DeleteTexture ============= */ -void GLSLGamma_DeleteTexture (void) +void GLSLGamma_DeleteTexture(void) { - glDeleteTextures (1, &r_gamma_texture); + glDeleteTextures(1, &r_gamma_texture); r_gamma_texture = 0; r_gamma_program = 0; // deleted in R_DeleteShaders } @@ -146,38 +146,38 @@ void GLSLGamma_DeleteTexture (void) GLSLGamma_CreateShaders ============= */ -static void GLSLGamma_CreateShaders (void) +static void GLSLGamma_CreateShaders(void) { const GLchar *vertSource = \ - "#version 110\n" - "\n" - "void main(void) {\n" - " gl_Position = vec4(gl_Vertex.xy, 0.0, 1.0);\n" - " gl_TexCoord[0] = gl_MultiTexCoord0;\n" - "}\n"; + "#version 110\n" + "\n" + "void main(void) {\n" + " gl_Position = vec4(gl_Vertex.xy, 0.0, 1.0);\n" + " gl_TexCoord[0] = gl_MultiTexCoord0;\n" + "}\n"; const GLchar *fragSource = \ - "#version 110\n" - "\n" - "uniform sampler2D GammaTexture;\n" - "uniform float GammaValue;\n" - "uniform float ContrastValue;\n" - "\n" - "void main(void) {\n" - " vec4 frag = texture2D(GammaTexture, gl_TexCoord[0].xy);\n" - " frag.rgb = frag.rgb * ContrastValue;\n" - " gl_FragColor = vec4(pow(frag.rgb, vec3(GammaValue)), 1.0);\n" - "}\n"; + "#version 110\n" + "\n" + "uniform sampler2D GammaTexture;\n" + "uniform float GammaValue;\n" + "uniform float ContrastValue;\n" + "\n" + "void main(void) {\n" + " vec4 frag = texture2D(GammaTexture, gl_TexCoord[0].xy);\n" + " frag.rgb = frag.rgb * ContrastValue;\n" + " gl_FragColor = vec4(pow(frag.rgb, vec3(GammaValue)), 1.0);\n" + "}\n"; - if (!gl_glsl_gamma_able) + if(!gl_glsl_gamma_able) return; - r_gamma_program = GL_CreateProgram (vertSource, fragSource, 0, NULL); + r_gamma_program = GL_CreateProgram(vertSource, fragSource, 0, NULL); // get uniform locations - gammaLoc = GL_GetUniformLocation (&r_gamma_program, "GammaValue"); - contrastLoc = GL_GetUniformLocation (&r_gamma_program, "ContrastValue"); - textureLoc = GL_GetUniformLocation (&r_gamma_program, "GammaTexture"); + gammaLoc = GL_GetUniformLocation(&r_gamma_program, "GammaValue"); + contrastLoc = GL_GetUniformLocation(&r_gamma_program, "ContrastValue"); + textureLoc = GL_GetUniformLocation(&r_gamma_program, "GammaTexture"); } /* @@ -185,41 +185,41 @@ static void GLSLGamma_CreateShaders (void) GLSLGamma_GammaCorrect ============= */ -void GLSLGamma_GammaCorrect (void) +void GLSLGamma_GammaCorrect(void) { float smax, tmax; - if (!gl_glsl_gamma_able) + if(!gl_glsl_gamma_able) return; - if (vid_gamma.value == 1 && vid_contrast.value == 1) + if(vid_gamma.value == 1 && vid_contrast.value == 1) return; // create render-to-texture texture if needed - if (!r_gamma_texture) + if(!r_gamma_texture) { - glGenTextures (1, &r_gamma_texture); - glBindTexture (GL_TEXTURE_2D, r_gamma_texture); + glGenTextures(1, &r_gamma_texture); + glBindTexture(GL_TEXTURE_2D, r_gamma_texture); r_gamma_texture_width = glwidth; r_gamma_texture_height = glheight; - if (!gl_texture_NPOT) + if(!gl_texture_NPOT) { r_gamma_texture_width = TexMgr_Pad(r_gamma_texture_width); r_gamma_texture_height = TexMgr_Pad(r_gamma_texture_height); } - glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, r_gamma_texture_width, r_gamma_texture_height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, r_gamma_texture_width, r_gamma_texture_height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } // create shader if needed - if (!r_gamma_program) + if(!r_gamma_program) { - GLSLGamma_CreateShaders (); - if (!r_gamma_program) + GLSLGamma_CreateShaders(); + if(!r_gamma_program) { Sys_Error("GLSLGamma_CreateShaders failed"); } @@ -227,38 +227,38 @@ void GLSLGamma_GammaCorrect (void) // copy the framebuffer to the texture GL_DisableMultitexture(); - glBindTexture (GL_TEXTURE_2D, r_gamma_texture); - glCopyTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, glx, gly, glwidth, glheight); + glBindTexture(GL_TEXTURE_2D, r_gamma_texture); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, glx, gly, glwidth, glheight); // draw the texture back to the framebuffer with a fragment shader - GL_UseProgramFunc (r_gamma_program); - GL_Uniform1fFunc (gammaLoc, vid_gamma.value); - GL_Uniform1fFunc (contrastLoc, q_min(2.0, q_max(1.0, vid_contrast.value))); - GL_Uniform1iFunc (textureLoc, 0); // use texture unit 0 + GL_UseProgramFunc(r_gamma_program); + GL_Uniform1fFunc(gammaLoc, vid_gamma.value); + GL_Uniform1fFunc(contrastLoc, q_min(2.0, q_max(1.0, vid_contrast.value))); + GL_Uniform1iFunc(textureLoc, 0); // use texture unit 0 - glDisable (GL_ALPHA_TEST); - glDisable (GL_DEPTH_TEST); + glDisable(GL_ALPHA_TEST); + glDisable(GL_DEPTH_TEST); - glViewport (glx, gly, glwidth, glheight); + glViewport(glx, gly, glwidth, glheight); - smax = glwidth/(float)r_gamma_texture_width; - tmax = glheight/(float)r_gamma_texture_height; + smax = glwidth / (float)r_gamma_texture_width; + tmax = glheight / (float)r_gamma_texture_height; - glBegin (GL_QUADS); - glTexCoord2f (0, 0); - glVertex2f (-1, -1); - glTexCoord2f (smax, 0); - glVertex2f (1, -1); - glTexCoord2f (smax, tmax); - glVertex2f (1, 1); - glTexCoord2f (0, tmax); - glVertex2f (-1, 1); - glEnd (); + glBegin(GL_QUADS); + glTexCoord2f(0, 0); + glVertex2f(-1, -1); + glTexCoord2f(smax, 0); + glVertex2f(1, -1); + glTexCoord2f(smax, tmax); + glVertex2f(1, 1); + glTexCoord2f(0, tmax); + glVertex2f(-1, 1); + glEnd(); - GL_UseProgramFunc (0); + GL_UseProgramFunc(0); // clear cached binding - GL_ClearBindings (); + GL_ClearBindings(); } /* @@ -268,46 +268,46 @@ R_CullBox -- johnfitz -- replaced with new function from lordhavoc Returns true if the box is completely outside the frustum ================= */ -bool R_CullBox (vec3_t emins, vec3_t emaxs) +bool R_CullBox(vec3_t emins, vec3_t emaxs) { int32_t i; mplane_t *p; - for (i = 0;i < 4;i++) + for(i = 0; i < 4; i++) { p = frustum + i; switch(p->signbits) { default: case 0: - if (p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2] < p->dist) + if(p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2] < p->dist) return true; break; case 1: - if (p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2] < p->dist) + if(p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2] < p->dist) return true; break; case 2: - if (p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2] < p->dist) + if(p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2] < p->dist) return true; break; case 3: - if (p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2] < p->dist) + if(p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2] < p->dist) return true; break; case 4: - if (p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2] < p->dist) + if(p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2] < p->dist) return true; break; case 5: - if (p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2] < p->dist) + if(p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2] < p->dist) return true; break; case 6: - if (p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2] < p->dist) + if(p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2] < p->dist) return true; break; case 7: - if (p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2] < p->dist) + if(p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2] < p->dist) return true; break; } @@ -319,27 +319,27 @@ bool R_CullBox (vec3_t emins, vec3_t emaxs) R_CullModelForEntity -- johnfitz -- uses correct bounds based on rotation =============== */ -bool R_CullModelForEntity (entity_t *e) +bool R_CullModelForEntity(entity_t *e) { vec3_t mins, maxs; - if (e->angles[0] || e->angles[2]) //pitch or roll + if(e->angles[0] || e->angles[2]) //pitch or roll { - VectorAdd (e->origin, e->model->rmins, mins); - VectorAdd (e->origin, e->model->rmaxs, maxs); + VectorAdd(e->origin, e->model->rmins, mins); + VectorAdd(e->origin, e->model->rmaxs, maxs); } - else if (e->angles[1]) //yaw + else if(e->angles[1]) //yaw { - VectorAdd (e->origin, e->model->ymins, mins); - VectorAdd (e->origin, e->model->ymaxs, maxs); + VectorAdd(e->origin, e->model->ymins, mins); + VectorAdd(e->origin, e->model->ymaxs, maxs); } else //no rotation { - VectorAdd (e->origin, e->model->mins, mins); - VectorAdd (e->origin, e->model->maxs, maxs); + VectorAdd(e->origin, e->model->mins, mins); + VectorAdd(e->origin, e->model->maxs, maxs); } - return R_CullBox (mins, maxs); + return R_CullBox(mins, maxs); } /* @@ -347,12 +347,12 @@ bool R_CullModelForEntity (entity_t *e) R_RotateForEntity -- johnfitz -- modified to take origin and angles instead of pointer to entity =============== */ -void R_RotateForEntity (vec3_t origin, vec3_t angles) +void R_RotateForEntity(vec3_t origin, vec3_t angles) { - glTranslatef (origin[0], origin[1], origin[2]); - glRotatef (angles[1], 0, 0, 1); - glRotatef (-angles[0], 0, 1, 0); - glRotatef (angles[2], 1, 0, 0); + glTranslatef(origin[0], origin[1], origin[2]); + glRotatef(angles[1], 0, 0, 1); + glRotatef(-angles[0], 0, 1, 0); + glRotatef(angles[2], 1, 0, 0); } /* @@ -362,24 +362,24 @@ GL_PolygonOffset -- johnfitz negative offset moves polygon closer to camera ============= */ -void GL_PolygonOffset (int32_t offset) +void GL_PolygonOffset(int32_t offset) { - if (offset > 0) + if(offset > 0) { - glEnable (GL_POLYGON_OFFSET_FILL); - glEnable (GL_POLYGON_OFFSET_LINE); + glEnable(GL_POLYGON_OFFSET_FILL); + glEnable(GL_POLYGON_OFFSET_LINE); glPolygonOffset(1, offset); } - else if (offset < 0) + else if(offset < 0) { - glEnable (GL_POLYGON_OFFSET_FILL); - glEnable (GL_POLYGON_OFFSET_LINE); + glEnable(GL_POLYGON_OFFSET_FILL); + glEnable(GL_POLYGON_OFFSET_LINE); glPolygonOffset(-1, offset); } else { - glDisable (GL_POLYGON_OFFSET_FILL); - glDisable (GL_POLYGON_OFFSET_LINE); + glDisable(GL_POLYGON_OFFSET_FILL); + glDisable(GL_POLYGON_OFFSET_LINE); } } @@ -389,17 +389,17 @@ void GL_PolygonOffset (int32_t offset) // //============================================================================== -int32_t SignbitsForPlane (mplane_t *out) +int32_t SignbitsForPlane(mplane_t *out) { - int32_t bits, j; + int32_t bits, j; // for fast box on planeside test bits = 0; - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { - if (out->normal[j] < 0) - bits |= 1<normal[j] < 0) + bits |= 1 << j; } return bits; } @@ -415,16 +415,16 @@ to turn away from side, use a negative angle =============== */ #define DEG2RAD( a ) ( (a) * M_PI_DIV_180 ) -void TurnVector (vec3_t out, const vec3_t forward, const vec3_t side, float angle) +void TurnVector(vec3_t out, const vec3_t forward, const vec3_t side, float angle) { float scale_forward, scale_side; - scale_forward = cos( DEG2RAD( angle ) ); - scale_side = sin( DEG2RAD( angle ) ); + scale_forward = cos(DEG2RAD(angle)); + scale_side = sin(DEG2RAD(angle)); - out[0] = scale_forward*forward[0] + scale_side*side[0]; - out[1] = scale_forward*forward[1] + scale_side*side[1]; - out[2] = scale_forward*forward[2] + scale_side*side[2]; + out[0] = scale_forward * forward[0] + scale_side * side[0]; + out[1] = scale_forward * forward[1] + scale_side * side[1]; + out[2] = scale_forward * forward[2] + scale_side * side[2]; } /* @@ -432,23 +432,23 @@ void TurnVector (vec3_t out, const vec3_t forward, const vec3_t side, float angl R_SetFrustum -- johnfitz -- rewritten =============== */ -void R_SetFrustum (float fovx, float fovy) +void R_SetFrustum(float fovx, float fovy) { - int32_t i; + int32_t i; - if (r_stereo.value) + if(r_stereo.value) fovx += 10; //silly hack so that polygons don't drop out becuase of stereo skew - TurnVector(frustum[0].normal, vpn, vright, fovx/2 - 90); //left plane - TurnVector(frustum[1].normal, vpn, vright, 90 - fovx/2); //right plane - TurnVector(frustum[2].normal, vpn, vup, 90 - fovy/2); //bottom plane - TurnVector(frustum[3].normal, vpn, vup, fovy/2 - 90); //top plane + TurnVector(frustum[0].normal, vpn, vright, fovx / 2 - 90); //left plane + TurnVector(frustum[1].normal, vpn, vright, 90 - fovx / 2); //right plane + TurnVector(frustum[2].normal, vpn, vup, 90 - fovy / 2); //bottom plane + TurnVector(frustum[3].normal, vpn, vup, fovy / 2 - 90); //top plane - for (i=0 ; i<4 ; i++) + for(i = 0 ; i < 4 ; i++) { frustum[i].type = PLANE_ANYZ; - frustum[i].dist = DotProduct (r_origin, frustum[i].normal); //FIXME: shouldn't this always be zero? - frustum[i].signbits = SignbitsForPlane (&frustum[i]); + frustum[i].dist = DotProduct(r_origin, frustum[i].normal); //FIXME: shouldn't this always be zero? + frustum[i].signbits = SignbitsForPlane(&frustum[i]); } } @@ -462,8 +462,8 @@ float frustum_skew = 0.0; //used by r_stereo void GL_SetFrustum(float fovx, float fovy) { float xmax, ymax; - xmax = NEARCLIP * tan( fovx * M_PI / 360.0 ); - ymax = NEARCLIP * tan( fovy * M_PI / 360.0 ); + xmax = NEARCLIP * tan(fovx * M_PI / 360.0); + ymax = NEARCLIP * tan(fovy * M_PI / 360.0); glFrustum(-xmax + frustum_skew, xmax + frustum_skew, -ymax, ymax, NEARCLIP, gl_farclip.value); } @@ -472,38 +472,38 @@ void GL_SetFrustum(float fovx, float fovy) R_SetupGL ============= */ -void R_SetupGL (void) +void R_SetupGL(void) { int32_t scale; //johnfitz -- rewrote this section glMatrixMode(GL_PROJECTION); - glLoadIdentity (); + glLoadIdentity(); scale = CLAMP(1, (int32_t)r_scale.value, 4); // ericw -- see R_ScaleView - glViewport (glx + r_refdef.vrect.x, - gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height, - r_refdef.vrect.width / scale, - r_refdef.vrect.height / scale); + glViewport(glx + r_refdef.vrect.x, + gly + glheight - r_refdef.vrect.y - r_refdef.vrect.height, + r_refdef.vrect.width / scale, + r_refdef.vrect.height / scale); //johnfitz - GL_SetFrustum (r_fovx, r_fovy); //johnfitz -- use r_fov* vars + GL_SetFrustum(r_fovx, r_fovy); //johnfitz -- use r_fov* vars // glCullFace(GL_BACK); //johnfitz -- glquake used CCW with backwards culling -- let's do it right glMatrixMode(GL_MODELVIEW); - glLoadIdentity (); + glLoadIdentity(); - glRotatef (-90, 1, 0, 0); // put Z going up - glRotatef (90, 0, 0, 1); // put Z going up - glRotatef (-r_refdef.viewangles[2], 1, 0, 0); - glRotatef (-r_refdef.viewangles[0], 0, 1, 0); - glRotatef (-r_refdef.viewangles[1], 0, 0, 1); - glTranslatef (-r_refdef.vieworg[0], -r_refdef.vieworg[1], -r_refdef.vieworg[2]); + glRotatef(-90, 1, 0, 0); // put Z going up + glRotatef(90, 0, 0, 1); // put Z going up + glRotatef(-r_refdef.viewangles[2], 1, 0, 0); + glRotatef(-r_refdef.viewangles[0], 0, 1, 0); + glRotatef(-r_refdef.viewangles[1], 0, 0, 1); + glTranslatef(-r_refdef.vieworg[0], -r_refdef.vieworg[1], -r_refdef.vieworg[2]); // // set drawing parms // - if (gl_cull.value) + if(gl_cull.value) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); @@ -518,17 +518,17 @@ void R_SetupGL (void) R_Clear -- johnfitz -- rewritten and gutted ============= */ -void R_Clear (void) +void R_Clear(void) { uint32_t clearbits; clearbits = GL_DEPTH_BUFFER_BIT; // from mh -- if we get a stencil buffer, we should clear it, even though we don't use it - if (gl_stencilbits) + if(gl_stencilbits) clearbits |= GL_STENCIL_BUFFER_BIT; - if (gl_clear.value) + if(gl_clear.value) clearbits |= GL_COLOR_BUFFER_BIT; - glClear (clearbits); + glClear(clearbits); } /* @@ -536,12 +536,12 @@ void R_Clear (void) R_SetupScene -- johnfitz -- this is the stuff that needs to be done once per eye in stereo mode =============== */ -void R_SetupScene (void) +void R_SetupScene(void) { - R_PushDlights (); - R_AnimateLight (); + R_PushDlights(); + R_AnimateLight(); r_framecount++; - R_SetupGL (); + R_SetupGL(); } /* @@ -549,30 +549,30 @@ void R_SetupScene (void) R_SetupView -- johnfitz -- this is the stuff that needs to be done once per frame, even in stereo mode =============== */ -void R_SetupView (void) +void R_SetupView(void) { - Fog_SetupFrame (); //johnfitz + Fog_SetupFrame(); //johnfitz // build the transformation matrix for the given view angles - VectorCopy (r_refdef.vieworg, r_origin); - AngleVectors (r_refdef.viewangles, vpn, vright, vup); + VectorCopy(r_refdef.vieworg, r_origin); + AngleVectors(r_refdef.viewangles, vpn, vright, vup); // current viewleaf r_oldviewleaf = r_viewleaf; - r_viewleaf = Mod_PointInLeaf (r_origin, cl.worldmodel); + r_viewleaf = Mod_PointInLeaf(r_origin, cl.worldmodel); - V_SetContentsColor (r_viewleaf->contents); - V_CalcBlend (); + V_SetContentsColor(r_viewleaf->contents); + V_CalcBlend(); r_cache_thrash = false; //johnfitz -- calculate r_fovx and r_fovy here r_fovx = r_refdef.fov_x; r_fovy = r_refdef.fov_y; - if (r_waterwarp.value) + if(r_waterwarp.value) { - int32_t contents = Mod_PointInLeaf (r_origin, cl.worldmodel)->contents; - if (contents == CONTENTS_WATER || contents == CONTENTS_SLIME || contents == CONTENTS_LAVA) + int32_t contents = Mod_PointInLeaf(r_origin, cl.worldmodel)->contents; + if(contents == CONTENTS_WATER || contents == CONTENTS_SLIME || contents == CONTENTS_LAVA) { //variance is a percentage of width, where width = 2 * tan(fov / 2) otherwise the effect is too dramatic at high FOV and too subtle at low FOV. what a mess! r_fovx = atan(tan(DEG2RAD(r_refdef.fov_x) / 2) * (0.97 + sin(cl.time * 1.5) * 0.03)) * 2 / M_PI_DIV_180; @@ -581,26 +581,26 @@ void R_SetupView (void) } //johnfitz - R_SetFrustum (r_fovx, r_fovy); //johnfitz -- use r_fov* vars + R_SetFrustum(r_fovx, r_fovy); //johnfitz -- use r_fov* vars - R_MarkSurfaces (); //johnfitz -- create texture chains from PVS + R_MarkSurfaces(); //johnfitz -- create texture chains from PVS - R_CullSurfaces (); //johnfitz -- do after R_SetFrustum and R_MarkSurfaces + R_CullSurfaces(); //johnfitz -- do after R_SetFrustum and R_MarkSurfaces - R_UpdateWarpTextures (); //johnfitz -- do this before R_Clear + R_UpdateWarpTextures(); //johnfitz -- do this before R_Clear - R_Clear (); + R_Clear(); //johnfitz -- cheat-protect some draw modes r_drawflat_cheatsafe = r_fullbright_cheatsafe = r_lightmap_cheatsafe = false; r_drawworld_cheatsafe = true; - if (cl.maxclients == 1) + if(cl.maxclients == 1) { - if (!r_drawworld.value) r_drawworld_cheatsafe = false; + if(!r_drawworld.value) r_drawworld_cheatsafe = false; - if (r_drawflat.value) r_drawflat_cheatsafe = true; - else if (r_fullbright.value || !cl.worldmodel->lightdata) r_fullbright_cheatsafe = true; - else if (r_lightmap.value) r_lightmap_cheatsafe = true; + if(r_drawflat.value) r_drawflat_cheatsafe = true; + else if(r_fullbright.value || !cl.worldmodel->lightdata) r_fullbright_cheatsafe = true; + else if(r_lightmap.value) r_lightmap_cheatsafe = true; } //johnfitz } @@ -616,40 +616,40 @@ void R_SetupView (void) R_DrawEntitiesOnList ============= */ -void R_DrawEntitiesOnList (bool alphapass) //johnfitz -- added parameter +void R_DrawEntitiesOnList(bool alphapass) //johnfitz -- added parameter { - int32_t i; + int32_t i; - if (!r_drawentities.value) + if(!r_drawentities.value) return; //johnfitz -- sprites are not a special case - for (i=0 ; ialpha) < 1 && !alphapass) || - (ENTALPHA_DECODE(currententity->alpha) == 1 && alphapass)) + if((ENTALPHA_DECODE(currententity->alpha) < 1 && !alphapass) || + (ENTALPHA_DECODE(currententity->alpha) == 1 && alphapass)) continue; //johnfitz -- chasecam - if (currententity == &cl_entities[cl.viewentity]) + if(currententity == &cl_entities[cl.viewentity]) currententity->angles[0] *= 0.3; //johnfitz - switch (currententity->model->type) + switch(currententity->model->type) { - case mod_alias: - R_DrawAliasModel (currententity); - break; - case mod_brush: - R_DrawBrushModel (currententity); - break; - case mod_sprite: - R_DrawSpriteModel (currententity); - break; + case mod_alias: + R_DrawAliasModel(currententity); + break; + case mod_brush: + R_DrawBrushModel(currententity); + break; + case mod_sprite: + R_DrawSpriteModel(currententity); + break; } } } @@ -659,27 +659,27 @@ void R_DrawEntitiesOnList (bool alphapass) //johnfitz -- added parameter R_DrawViewModel -- johnfitz -- gutted ============= */ -void R_DrawViewModel (void) +void R_DrawViewModel(void) { - if (!r_drawviewmodel.value || !r_drawentities.value || chase_active.value) + if(!r_drawviewmodel.value || !r_drawentities.value || chase_active.value) return; - if (cl.items & IT_INVISIBILITY || cl.stats[STAT_HEALTH] <= 0) + if(cl.items & IT_INVISIBILITY || cl.stats[STAT_HEALTH] <= 0) return; currententity = &cl.viewent; - if (!currententity->model) + if(!currententity->model) return; //johnfitz -- this fixes a crash - if (currententity->model->type != mod_alias) + if(currententity->model->type != mod_alias) return; //johnfitz // hack the depth range to prevent view model from poking into walls - glDepthRange (0, 0.3); - R_DrawAliasModel (currententity); - glDepthRange (0, 1); + glDepthRange(0, 0.3); + R_DrawAliasModel(currententity); + glDepthRange(0, 1); } /* @@ -687,18 +687,18 @@ void R_DrawViewModel (void) R_EmitWirePoint -- johnfitz -- draws a wireframe cross shape for point entities ================ */ -void R_EmitWirePoint (vec3_t origin) +void R_EmitWirePoint(vec3_t origin) { - int32_t size=8; + int32_t size = 8; - glBegin (GL_LINES); - glVertex3f (origin[0]-size, origin[1], origin[2]); - glVertex3f (origin[0]+size, origin[1], origin[2]); - glVertex3f (origin[0], origin[1]-size, origin[2]); - glVertex3f (origin[0], origin[1]+size, origin[2]); - glVertex3f (origin[0], origin[1], origin[2]-size); - glVertex3f (origin[0], origin[1], origin[2]+size); - glEnd (); + glBegin(GL_LINES); + glVertex3f(origin[0] - size, origin[1], origin[2]); + glVertex3f(origin[0] + size, origin[1], origin[2]); + glVertex3f(origin[0], origin[1] - size, origin[2]); + glVertex3f(origin[0], origin[1] + size, origin[2]); + glVertex3f(origin[0], origin[1], origin[2] - size); + glVertex3f(origin[0], origin[1], origin[2] + size); + glEnd(); } /* @@ -706,20 +706,20 @@ void R_EmitWirePoint (vec3_t origin) R_EmitWireBox -- johnfitz -- draws one axis aligned bounding box ================ */ -void R_EmitWireBox (vec3_t mins, vec3_t maxs) +void R_EmitWireBox(vec3_t mins, vec3_t maxs) { - glBegin (GL_QUAD_STRIP); - glVertex3f (mins[0], mins[1], mins[2]); - glVertex3f (mins[0], mins[1], maxs[2]); - glVertex3f (maxs[0], mins[1], mins[2]); - glVertex3f (maxs[0], mins[1], maxs[2]); - glVertex3f (maxs[0], maxs[1], mins[2]); - glVertex3f (maxs[0], maxs[1], maxs[2]); - glVertex3f (mins[0], maxs[1], mins[2]); - glVertex3f (mins[0], maxs[1], maxs[2]); - glVertex3f (mins[0], mins[1], mins[2]); - glVertex3f (mins[0], mins[1], maxs[2]); - glEnd (); + glBegin(GL_QUAD_STRIP); + glVertex3f(mins[0], mins[1], mins[2]); + glVertex3f(mins[0], mins[1], maxs[2]); + glVertex3f(maxs[0], mins[1], mins[2]); + glVertex3f(maxs[0], mins[1], maxs[2]); + glVertex3f(maxs[0], maxs[1], mins[2]); + glVertex3f(maxs[0], maxs[1], maxs[2]); + glVertex3f(mins[0], maxs[1], mins[2]); + glVertex3f(mins[0], maxs[1], maxs[2]); + glVertex3f(mins[0], mins[1], mins[2]); + glVertex3f(mins[0], mins[1], maxs[2]); + glEnd(); } /* @@ -729,54 +729,54 @@ R_ShowBoundingBoxes -- johnfitz draw bounding boxes -- the server-side boxes, not the renderer cullboxes ================ */ -void R_ShowBoundingBoxes (void) +void R_ShowBoundingBoxes(void) { - extern edict_t *sv_player; - vec3_t mins,maxs; - edict_t *ed; - int32_t i; + extern edict_t *sv_player; + vec3_t mins, maxs; + edict_t *ed; + int32_t i; - if (!r_showbboxes.value || cl.maxclients > 1 || !r_drawentities.value || !sv.active) + if(!r_showbboxes.value || cl.maxclients > 1 || !r_drawentities.value || !sv.active) return; - glDisable (GL_DEPTH_TEST); - glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); - GL_PolygonOffset (OFFSET_SHOWTRIS); - glDisable (GL_TEXTURE_2D); - glDisable (GL_CULL_FACE); - glColor3f (1,1,1); + glDisable(GL_DEPTH_TEST); + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + GL_PolygonOffset(OFFSET_SHOWTRIS); + glDisable(GL_TEXTURE_2D); + glDisable(GL_CULL_FACE); + glColor3f(1, 1, 1); - for (i=0, ed=NEXT_EDICT(sv.edicts) ; iv.mins[0] == ed->v.maxs[0] && ed->v.mins[1] == ed->v.maxs[1] && ed->v.mins[2] == ed->v.maxs[2]) + if(ed->v.mins[0] == ed->v.maxs[0] && ed->v.mins[1] == ed->v.maxs[1] && ed->v.mins[2] == ed->v.maxs[2]) { //point entity - R_EmitWirePoint (ed->v.origin); + R_EmitWirePoint(ed->v.origin); } else { //box entity - VectorAdd (ed->v.mins, ed->v.origin, mins); - VectorAdd (ed->v.maxs, ed->v.origin, maxs); - R_EmitWireBox (mins, maxs); + VectorAdd(ed->v.mins, ed->v.origin, mins); + VectorAdd(ed->v.maxs, ed->v.origin, maxs); + R_EmitWireBox(mins, maxs); } } - glColor3f (1,1,1); - glEnable (GL_TEXTURE_2D); - glEnable (GL_CULL_FACE); - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - GL_PolygonOffset (OFFSET_NONE); - glEnable (GL_DEPTH_TEST); + glColor3f(1, 1, 1); + glEnable(GL_TEXTURE_2D); + glEnable(GL_CULL_FACE); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + GL_PolygonOffset(OFFSET_NONE); + glEnable(GL_DEPTH_TEST); - Sbar_Changed (); //so we don't get dots collecting on the statusbar + Sbar_Changed(); //so we don't get dots collecting on the statusbar } /* @@ -784,47 +784,47 @@ void R_ShowBoundingBoxes (void) R_ShowTris -- johnfitz ================ */ -void R_ShowTris (void) +void R_ShowTris(void) { extern cvar_t r_particles; int32_t i; - if (r_showtris.value < 1 || r_showtris.value > 2 || cl.maxclients > 1) + if(r_showtris.value < 1 || r_showtris.value > 2 || cl.maxclients > 1) return; - if (r_showtris.value == 1) - glDisable (GL_DEPTH_TEST); - glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); - GL_PolygonOffset (OFFSET_SHOWTRIS); - glDisable (GL_TEXTURE_2D); - glColor3f (1,1,1); + if(r_showtris.value == 1) + glDisable(GL_DEPTH_TEST); + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + GL_PolygonOffset(OFFSET_SHOWTRIS); + glDisable(GL_TEXTURE_2D); + glColor3f(1, 1, 1); // glEnable (GL_BLEND); // glBlendFunc (GL_ONE, GL_ONE); - if (r_drawworld.value) + if(r_drawworld.value) { - R_DrawWorld_ShowTris (); + R_DrawWorld_ShowTris(); } - if (r_drawentities.value) + if(r_drawentities.value) { - for (i=0 ; iangles[0] *= 0.3; - switch (currententity->model->type) + switch(currententity->model->type) { case mod_brush: - R_DrawBrushModel_ShowTris (currententity); + R_DrawBrushModel_ShowTris(currententity); break; case mod_alias: - R_DrawAliasModel_ShowTris (currententity); + R_DrawAliasModel_ShowTris(currententity); break; case mod_sprite: - R_DrawSpriteModel (currententity); + R_DrawSpriteModel(currententity); break; default: break; @@ -833,34 +833,34 @@ void R_ShowTris (void) // viewmodel currententity = &cl.viewent; - if (r_drawviewmodel.value - && !chase_active.value - && cl.stats[STAT_HEALTH] > 0 - && !(cl.items & IT_INVISIBILITY) - && currententity->model - && currententity->model->type == mod_alias) + if(r_drawviewmodel.value + && !chase_active.value + && cl.stats[STAT_HEALTH] > 0 + && !(cl.items & IT_INVISIBILITY) + && currententity->model + && currententity->model->type == mod_alias) { - glDepthRange (0, 0.3); - R_DrawAliasModel_ShowTris (currententity); - glDepthRange (0, 1); + glDepthRange(0, 0.3); + R_DrawAliasModel_ShowTris(currententity); + glDepthRange(0, 1); } } - if (r_particles.value) + if(r_particles.value) { - R_DrawParticles_ShowTris (); + R_DrawParticles_ShowTris(); } // glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glDisable (GL_BLEND); - glColor3f (1,1,1); - glEnable (GL_TEXTURE_2D); - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - GL_PolygonOffset (OFFSET_NONE); - if (r_showtris.value == 1) - glEnable (GL_DEPTH_TEST); + glColor3f(1, 1, 1); + glEnable(GL_TEXTURE_2D); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + GL_PolygonOffset(OFFSET_NONE); + if(r_showtris.value == 1) + glEnable(GL_DEPTH_TEST); - Sbar_Changed (); //so we don't get dots collecting on the statusbar + Sbar_Changed(); //so we don't get dots collecting on the statusbar } /* @@ -868,15 +868,15 @@ void R_ShowTris (void) R_DrawShadows ================ */ -void R_DrawShadows (void) +void R_DrawShadows(void) { int32_t i; - if (!r_shadows.value || !r_drawentities.value || r_drawflat_cheatsafe || r_lightmap_cheatsafe) + if(!r_shadows.value || !r_drawentities.value || r_drawflat_cheatsafe || r_lightmap_cheatsafe) return; // Use stencil buffer to prevent self-intersecting shadows, from Baker (MarkV) - if (gl_stencilbits) + if(gl_stencilbits) { glClear(GL_STENCIL_BUFFER_BIT); glStencilFunc(GL_EQUAL, 0, ~0); @@ -884,20 +884,20 @@ void R_DrawShadows (void) glEnable(GL_STENCIL_TEST); } - for (i=0 ; imodel->type != mod_alias) + if(currententity->model->type != mod_alias) continue; - if (currententity == &cl.viewent) + if(currententity == &cl.viewent) return; - GL_DrawAliasShadow (currententity); + GL_DrawAliasShadow(currententity); } - if (gl_stencilbits) + if(gl_stencilbits) { glDisable(GL_STENCIL_TEST); } @@ -908,37 +908,37 @@ void R_DrawShadows (void) R_RenderScene ================ */ -void R_RenderScene (void) +void R_RenderScene(void) { - R_SetupScene (); //johnfitz -- this does everything that should be done once per call to RenderScene + R_SetupScene(); //johnfitz -- this does everything that should be done once per call to RenderScene - Fog_EnableGFog (); //johnfitz + Fog_EnableGFog(); //johnfitz - Sky_DrawSky (); //johnfitz + Sky_DrawSky(); //johnfitz - R_DrawWorld (); + R_DrawWorld(); - S_ExtraUpdate (); // don't let sound get messed up if going slow + S_ExtraUpdate(); // don't let sound get messed up if going slow - R_DrawShadows (); //johnfitz -- render entity shadows + R_DrawShadows(); //johnfitz -- render entity shadows - R_DrawEntitiesOnList (false); //johnfitz -- false means this is the pass for nonalpha entities + R_DrawEntitiesOnList(false); //johnfitz -- false means this is the pass for nonalpha entities - R_DrawWorld_Water (); //johnfitz -- drawn here since they might have transparency + R_DrawWorld_Water(); //johnfitz -- drawn here since they might have transparency - R_DrawEntitiesOnList (true); //johnfitz -- true means this is the pass for alpha entities + R_DrawEntitiesOnList(true); //johnfitz -- true means this is the pass for alpha entities - R_RenderDlights (); //triangle fan dlights -- johnfitz -- moved after water + R_RenderDlights(); //triangle fan dlights -- johnfitz -- moved after water - R_DrawParticles (); + R_DrawParticles(); - Fog_DisableGFog (); //johnfitz + Fog_DisableGFog(); //johnfitz - R_DrawViewModel (); //johnfitz -- moved here from R_RenderView + R_DrawViewModel(); //johnfitz -- moved here from R_RenderView - R_ShowTris (); //johnfitz + R_ShowTris(); //johnfitz - R_ShowBoundingBoxes (); //johnfitz + R_ShowBoundingBoxes(); //johnfitz } static GLuint r_scaleview_texture; @@ -949,9 +949,9 @@ static int32_t r_scaleview_texture_width, r_scaleview_texture_height; R_ScaleView_DeleteTexture ============= */ -void R_ScaleView_DeleteTexture (void) +void R_ScaleView_DeleteTexture(void) { - glDeleteTextures (1, &r_scaleview_texture); + glDeleteTextures(1, &r_scaleview_texture); r_scaleview_texture = 0; } @@ -965,7 +965,7 @@ r_refdef.vrect. This is for emulating a low-resolution pixellated look, or possibly as a perforance boost on slow graphics cards. ================ */ -void R_ScaleView (void) +void R_ScaleView(void) { float smax, tmax; int32_t scale; @@ -978,74 +978,74 @@ void R_ScaleView (void) srcw = r_refdef.vrect.width / scale; srch = r_refdef.vrect.height / scale; - if (scale == 1) + if(scale == 1) return; // make sure texture unit 0 is selected - GL_DisableMultitexture (); + GL_DisableMultitexture(); // create (if needed) and bind the render-to-texture texture - if (!r_scaleview_texture) + if(!r_scaleview_texture) { - glGenTextures (1, &r_scaleview_texture); + glGenTextures(1, &r_scaleview_texture); r_scaleview_texture_width = 0; r_scaleview_texture_height = 0; } - glBindTexture (GL_TEXTURE_2D, r_scaleview_texture); + glBindTexture(GL_TEXTURE_2D, r_scaleview_texture); // resize render-to-texture texture if needed - if (r_scaleview_texture_width < srcw - || r_scaleview_texture_height < srch) + if(r_scaleview_texture_width < srcw + || r_scaleview_texture_height < srch) { r_scaleview_texture_width = srcw; r_scaleview_texture_height = srch; - if (!gl_texture_NPOT) + if(!gl_texture_NPOT) { r_scaleview_texture_width = TexMgr_Pad(r_scaleview_texture_width); r_scaleview_texture_height = TexMgr_Pad(r_scaleview_texture_height); } - glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, r_scaleview_texture_width, r_scaleview_texture_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, r_scaleview_texture_width, r_scaleview_texture_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } // copy the framebuffer to the texture - glBindTexture (GL_TEXTURE_2D, r_scaleview_texture); - glCopyTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, srcx, srcy, srcw, srch); + glBindTexture(GL_TEXTURE_2D, r_scaleview_texture); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, srcx, srcy, srcw, srch); // draw the texture back to the framebuffer - glDisable (GL_ALPHA_TEST); - glDisable (GL_DEPTH_TEST); - glDisable (GL_CULL_FACE); - glDisable (GL_BLEND); + glDisable(GL_ALPHA_TEST); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); - glViewport (srcx, srcy, r_refdef.vrect.width, r_refdef.vrect.height); + glViewport(srcx, srcy, r_refdef.vrect.width, r_refdef.vrect.height); glMatrixMode(GL_PROJECTION); - glLoadIdentity (); + glLoadIdentity(); glMatrixMode(GL_MODELVIEW); - glLoadIdentity (); + glLoadIdentity(); // correction factor if we lack NPOT textures, normally these are 1.0f - smax = srcw/(float)r_scaleview_texture_width; - tmax = srch/(float)r_scaleview_texture_height; + smax = srcw / (float)r_scaleview_texture_width; + tmax = srch / (float)r_scaleview_texture_height; - glBegin (GL_QUADS); - glTexCoord2f (0, 0); - glVertex2f (-1, -1); - glTexCoord2f (smax, 0); - glVertex2f (1, -1); - glTexCoord2f (smax, tmax); - glVertex2f (1, 1); - glTexCoord2f (0, tmax); - glVertex2f (-1, 1); - glEnd (); + glBegin(GL_QUADS); + glTexCoord2f(0, 0); + glVertex2f(-1, -1); + glTexCoord2f(smax, 0); + glVertex2f(1, -1); + glTexCoord2f(smax, tmax); + glVertex2f(1, 1); + glTexCoord2f(0, tmax); + glVertex2f(-1, 1); + glEnd(); // clear cached binding - GL_ClearBindings (); + GL_ClearBindings(); } /* @@ -1053,96 +1053,96 @@ void R_ScaleView (void) R_RenderView ================ */ -void R_RenderView (void) +void R_RenderView(void) { - double time1, time2; + double time1, time2; - if (r_norefresh.value) + if(r_norefresh.value) return; - if (!cl.worldmodel) - Sys_Error ("R_RenderView: NULL worldmodel"); + if(!cl.worldmodel) + Sys_Error("R_RenderView: NULL worldmodel"); time1 = 0; /* avoid compiler warning */ - if (r_speeds.value) + if(r_speeds.value) { - glFinish (); - time1 = Sys_DoubleTime (); + glFinish(); + time1 = Sys_DoubleTime(); //johnfitz -- rendering statistics rs_brushpolys = rs_aliaspolys = rs_skypolys = rs_particles = rs_fogpolys = rs_megatexels = - rs_dynamiclightmaps = rs_aliaspasses = rs_skypasses = rs_brushpasses = 0; + rs_dynamiclightmaps = rs_aliaspasses = rs_skypasses = rs_brushpasses = 0; } - else if (gl_finish.value) - glFinish (); + else if(gl_finish.value) + glFinish(); - R_SetupView (); //johnfitz -- this does everything that should be done once per frame + R_SetupView(); //johnfitz -- this does everything that should be done once per frame //johnfitz -- stereo rendering -- full of hacky goodness - if (r_stereo.value) + if(r_stereo.value) { float eyesep = CLAMP(-8.0f, r_stereo.value, 8.0f); float fdepth = CLAMP(32.0f, r_stereodepth.value, 1024.0f); - AngleVectors (r_refdef.viewangles, vpn, vright, vup); + AngleVectors(r_refdef.viewangles, vpn, vright, vup); //render left eye (red) glColorMask(1, 0, 0, 1); - VectorMA (r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); + VectorMA(r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); frustum_skew = 0.5 * eyesep * NEARCLIP / fdepth; - srand((int32_t) (cl.time * 1000)); //sync random stuff between eyes + srand((int32_t)(cl.time * 1000)); //sync random stuff between eyes - R_RenderScene (); + R_RenderScene(); //render right eye (cyan) - glClear (GL_DEPTH_BUFFER_BIT); + glClear(GL_DEPTH_BUFFER_BIT); glColorMask(0, 1, 1, 1); - VectorMA (r_refdef.vieworg, 1.0f * eyesep, vright, r_refdef.vieworg); + VectorMA(r_refdef.vieworg, 1.0f * eyesep, vright, r_refdef.vieworg); frustum_skew = -frustum_skew; - srand((int32_t) (cl.time * 1000)); //sync random stuff between eyes + srand((int32_t)(cl.time * 1000)); //sync random stuff between eyes - R_RenderScene (); + R_RenderScene(); //restore glColorMask(1, 1, 1, 1); - VectorMA (r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); + VectorMA(r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); frustum_skew = 0.0f; } else { - R_RenderScene (); + R_RenderScene(); } //johnfitz - R_ScaleView (); + R_ScaleView(); //johnfitz -- modified r_speeds output - time2 = Sys_DoubleTime (); - if (r_pos.value) - Con_Printf ("x %" PRIi32 " y %" PRIi32 " z %" PRIi32 " (pitch %" PRIi32 " yaw %" PRIi32 " roll %" PRIi32 ")\n", - (int32_t)cl_entities[cl.viewentity].origin[0], - (int32_t)cl_entities[cl.viewentity].origin[1], - (int32_t)cl_entities[cl.viewentity].origin[2], - (int32_t)cl.viewangles[PITCH], - (int32_t)cl.viewangles[YAW], - (int32_t)cl.viewangles[ROLL]); - else if (r_speeds.value == 2) - Con_Printf ("%3" PRIi32 " ms %4" PRIi32 "/%4" PRIi32 " wpoly %4" PRIi32 "/%4" PRIi32 " epoly %3" PRIi32 " lmap %4" PRIi32 "%4" PRIi32 "sky %1.1f mtex\n", - (int32_t)((time2-time1)*1000), - rs_brushpolys, - rs_brushpasses, - rs_aliaspolys, - rs_aliaspasses, - rs_dynamiclightmaps, - rs_skypolys, - rs_skypasses, - TexMgr_FrameUsage ()); - else if (r_speeds.value) - Con_Printf ("%3" PRIi32 " ms %4" PRIi32 " wpoly %4" PRIi32 " epoly %3" PRIi32 " lmap\n", - (int32_t)((time2-time1)*1000), - rs_brushpolys, - rs_aliaspolys, - rs_dynamiclightmaps); + time2 = Sys_DoubleTime(); + if(r_pos.value) + Con_Printf("x %" PRIi32 " y %" PRIi32 " z %" PRIi32 " (pitch %" PRIi32 " yaw %" PRIi32 " roll %" PRIi32 ")\n", + (int32_t)cl_entities[cl.viewentity].origin[0], + (int32_t)cl_entities[cl.viewentity].origin[1], + (int32_t)cl_entities[cl.viewentity].origin[2], + (int32_t)cl.viewangles[PITCH], + (int32_t)cl.viewangles[YAW], + (int32_t)cl.viewangles[ROLL]); + else if(r_speeds.value == 2) + Con_Printf("%3" PRIi32 " ms %4" PRIi32 "/%4" PRIi32 " wpoly %4" PRIi32 "/%4" PRIi32 " epoly %3" PRIi32 " lmap %4" PRIi32 "%4" PRIi32 "sky %1.1f mtex\n", + (int32_t)((time2 - time1) * 1000), + rs_brushpolys, + rs_brushpasses, + rs_aliaspolys, + rs_aliaspasses, + rs_dynamiclightmaps, + rs_skypolys, + rs_skypasses, + TexMgr_FrameUsage()); + else if(r_speeds.value) + Con_Printf("%3" PRIi32 " ms %4" PRIi32 " wpoly %4" PRIi32 " epoly %3" PRIi32 " lmap\n", + (int32_t)((time2 - time1) * 1000), + rs_brushpolys, + rs_aliaspolys, + rs_dynamiclightmaps); //johnfitz } diff --git a/source/gl_rmisc.c b/source/gl_rmisc.c index 0b693b6..b5f6844 100644 --- a/source/gl_rmisc.c +++ b/source/gl_rmisc.c @@ -56,10 +56,10 @@ extern gltexture_t *playertextures[MAX_SCOREBOARD]; //johnfitz GL_Overbright_f -- johnfitz ==================== */ -static void GL_Overbright_f (cvar_t *var) +static void GL_Overbright_f(cvar_t *var) { (void)var; - R_RebuildAllLightmaps (); + R_RebuildAllLightmaps(); } /* @@ -67,10 +67,10 @@ static void GL_Overbright_f (cvar_t *var) GL_Fullbrights_f -- johnfitz ==================== */ -static void GL_Fullbrights_f (cvar_t *var) +static void GL_Fullbrights_f(cvar_t *var) { (void)var; - TexMgr_ReloadNobrightImages (); + TexMgr_ReloadNobrightImages(); } /* @@ -78,15 +78,15 @@ static void GL_Fullbrights_f (cvar_t *var) R_SetClearColor_f -- johnfitz ==================== */ -static void R_SetClearColor_f (cvar_t *var) +static void R_SetClearColor_f(cvar_t *var) { - byte *rgb; - int32_t s; + byte *rgb; + int32_t s; (void)var; s = (int32_t)r_clearcolor.value & 0xFF; rgb = (byte*)(d_8to24table + s); - glClearColor (rgb[0]/255.0,rgb[1]/255.0,rgb[2]/255.0,0); + glClearColor(rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0, 0); } /* @@ -94,7 +94,7 @@ static void R_SetClearColor_f (cvar_t *var) R_Novis_f -- johnfitz ==================== */ -static void R_VisChanged (cvar_t *var) +static void R_VisChanged(cvar_t *var) { extern int32_t vis_changed; (void)var; @@ -106,12 +106,12 @@ static void R_VisChanged (cvar_t *var) R_Model_ExtraFlags_List_f -- johnfitz -- called when r_nolerp_list or r_noshadow_list cvar changes =============== */ -static void R_Model_ExtraFlags_List_f (cvar_t *var) +static void R_Model_ExtraFlags_List_f(cvar_t *var) { (void)var; int32_t i; - for (i=0; i < MAX_MODELS; i++) - Mod_SetExtraFlags (cl.model_precache[i]); + for(i = 0; i < MAX_MODELS; i++) + Mod_SetExtraFlags(cl.model_precache[i]); } /* @@ -119,7 +119,7 @@ static void R_Model_ExtraFlags_List_f (cvar_t *var) R_SetWateralpha_f -- ericw ==================== */ -static void R_SetWateralpha_f (cvar_t *var) +static void R_SetWateralpha_f(cvar_t *var) { map_wateralpha = var->value; } @@ -129,7 +129,7 @@ static void R_SetWateralpha_f (cvar_t *var) R_SetLavaalpha_f -- ericw ==================== */ -static void R_SetLavaalpha_f (cvar_t *var) +static void R_SetLavaalpha_f(cvar_t *var) { map_lavaalpha = var->value; } @@ -139,7 +139,7 @@ static void R_SetLavaalpha_f (cvar_t *var) R_SetTelealpha_f -- ericw ==================== */ -static void R_SetTelealpha_f (cvar_t *var) +static void R_SetTelealpha_f(cvar_t *var) { map_telealpha = var->value; } @@ -149,7 +149,7 @@ static void R_SetTelealpha_f (cvar_t *var) R_SetSlimealpha_f -- ericw ==================== */ -static void R_SetSlimealpha_f (cvar_t *var) +static void R_SetSlimealpha_f(cvar_t *var) { map_slimealpha = var->value; } @@ -159,13 +159,13 @@ static void R_SetSlimealpha_f (cvar_t *var) GL_WaterAlphaForSurfface -- ericw ==================== */ -float GL_WaterAlphaForSurface (msurface_t *fa) +float GL_WaterAlphaForSurface(msurface_t *fa) { - if (fa->flags & SURF_DRAWLAVA) + if(fa->flags & SURF_DRAWLAVA) return map_lavaalpha > 0 ? map_lavaalpha : map_wateralpha; - else if (fa->flags & SURF_DRAWTELE) + else if(fa->flags & SURF_DRAWTELE) return map_telealpha > 0 ? map_telealpha : map_wateralpha; - else if (fa->flags & SURF_DRAWSLIME) + else if(fa->flags & SURF_DRAWSLIME) return map_slimealpha > 0 ? map_slimealpha : map_wateralpha; else return map_wateralpha; @@ -177,80 +177,80 @@ float GL_WaterAlphaForSurface (msurface_t *fa) R_Init =============== */ -void R_Init (void) +void R_Init(void) { extern cvar_t gl_finish; - Cmd_AddCommand ("timerefresh", R_TimeRefresh_f); - Cmd_AddCommand ("pointfile", R_ReadPointFile_f); + Cmd_AddCommand("timerefresh", R_TimeRefresh_f); + Cmd_AddCommand("pointfile", R_ReadPointFile_f); - Cvar_RegisterVariable (&r_norefresh); - Cvar_RegisterVariable (&r_lightmap); - Cvar_RegisterVariable (&r_fullbright); - Cvar_RegisterVariable (&r_drawentities); - Cvar_RegisterVariable (&r_drawviewmodel); - Cvar_RegisterVariable (&r_shadows); - Cvar_RegisterVariable (&r_wateralpha); - Cvar_SetCallback (&r_wateralpha, R_SetWateralpha_f); - Cvar_RegisterVariable (&r_dynamic); - Cvar_RegisterVariable (&r_novis); - Cvar_SetCallback (&r_novis, R_VisChanged); - Cvar_RegisterVariable (&r_speeds); - Cvar_RegisterVariable (&r_pos); + Cvar_RegisterVariable(&r_norefresh); + Cvar_RegisterVariable(&r_lightmap); + Cvar_RegisterVariable(&r_fullbright); + Cvar_RegisterVariable(&r_drawentities); + Cvar_RegisterVariable(&r_drawviewmodel); + Cvar_RegisterVariable(&r_shadows); + Cvar_RegisterVariable(&r_wateralpha); + Cvar_SetCallback(&r_wateralpha, R_SetWateralpha_f); + Cvar_RegisterVariable(&r_dynamic); + Cvar_RegisterVariable(&r_novis); + Cvar_SetCallback(&r_novis, R_VisChanged); + Cvar_RegisterVariable(&r_speeds); + Cvar_RegisterVariable(&r_pos); - Cvar_RegisterVariable (&gl_finish); - Cvar_RegisterVariable (&gl_clear); - Cvar_RegisterVariable (&gl_cull); - Cvar_RegisterVariable (&gl_smoothmodels); - Cvar_RegisterVariable (&gl_affinemodels); - Cvar_RegisterVariable (&gl_polyblend); - Cvar_RegisterVariable (&gl_flashblend); - Cvar_RegisterVariable (&gl_playermip); - Cvar_RegisterVariable (&gl_nocolors); + Cvar_RegisterVariable(&gl_finish); + Cvar_RegisterVariable(&gl_clear); + Cvar_RegisterVariable(&gl_cull); + Cvar_RegisterVariable(&gl_smoothmodels); + Cvar_RegisterVariable(&gl_affinemodels); + Cvar_RegisterVariable(&gl_polyblend); + Cvar_RegisterVariable(&gl_flashblend); + Cvar_RegisterVariable(&gl_playermip); + Cvar_RegisterVariable(&gl_nocolors); //johnfitz -- new cvars - Cvar_RegisterVariable (&r_stereo); - Cvar_RegisterVariable (&r_stereodepth); - Cvar_RegisterVariable (&r_clearcolor); - Cvar_SetCallback (&r_clearcolor, R_SetClearColor_f); - Cvar_RegisterVariable (&r_waterquality); - Cvar_RegisterVariable (&r_oldwater); - Cvar_RegisterVariable (&r_waterwarp); - Cvar_RegisterVariable (&r_drawflat); - Cvar_RegisterVariable (&r_flatlightstyles); - Cvar_RegisterVariable (&r_oldskyleaf); - Cvar_SetCallback (&r_oldskyleaf, R_VisChanged); - Cvar_RegisterVariable (&r_drawworld); - Cvar_RegisterVariable (&r_showtris); - Cvar_RegisterVariable (&r_showbboxes); - Cvar_RegisterVariable (&gl_farclip); - Cvar_RegisterVariable (&gl_fullbrights); - Cvar_RegisterVariable (&gl_overbright); - Cvar_SetCallback (&gl_fullbrights, GL_Fullbrights_f); - Cvar_SetCallback (&gl_overbright, GL_Overbright_f); - Cvar_RegisterVariable (&gl_overbright_models); - Cvar_RegisterVariable (&r_lerpmodels); - Cvar_RegisterVariable (&r_lerpmove); - Cvar_RegisterVariable (&r_nolerp_list); - Cvar_SetCallback (&r_nolerp_list, R_Model_ExtraFlags_List_f); - Cvar_RegisterVariable (&r_noshadow_list); - Cvar_SetCallback (&r_noshadow_list, R_Model_ExtraFlags_List_f); + Cvar_RegisterVariable(&r_stereo); + Cvar_RegisterVariable(&r_stereodepth); + Cvar_RegisterVariable(&r_clearcolor); + Cvar_SetCallback(&r_clearcolor, R_SetClearColor_f); + Cvar_RegisterVariable(&r_waterquality); + Cvar_RegisterVariable(&r_oldwater); + Cvar_RegisterVariable(&r_waterwarp); + Cvar_RegisterVariable(&r_drawflat); + Cvar_RegisterVariable(&r_flatlightstyles); + Cvar_RegisterVariable(&r_oldskyleaf); + Cvar_SetCallback(&r_oldskyleaf, R_VisChanged); + Cvar_RegisterVariable(&r_drawworld); + Cvar_RegisterVariable(&r_showtris); + Cvar_RegisterVariable(&r_showbboxes); + Cvar_RegisterVariable(&gl_farclip); + Cvar_RegisterVariable(&gl_fullbrights); + Cvar_RegisterVariable(&gl_overbright); + Cvar_SetCallback(&gl_fullbrights, GL_Fullbrights_f); + Cvar_SetCallback(&gl_overbright, GL_Overbright_f); + Cvar_RegisterVariable(&gl_overbright_models); + Cvar_RegisterVariable(&r_lerpmodels); + Cvar_RegisterVariable(&r_lerpmove); + Cvar_RegisterVariable(&r_nolerp_list); + Cvar_SetCallback(&r_nolerp_list, R_Model_ExtraFlags_List_f); + Cvar_RegisterVariable(&r_noshadow_list); + Cvar_SetCallback(&r_noshadow_list, R_Model_ExtraFlags_List_f); //johnfitz - Cvar_RegisterVariable (&gl_zfix); // QuakeSpasm z-fighting fix - Cvar_RegisterVariable (&r_lavaalpha); - Cvar_RegisterVariable (&r_telealpha); - Cvar_RegisterVariable (&r_slimealpha); - Cvar_RegisterVariable (&r_scale); - Cvar_SetCallback (&r_lavaalpha, R_SetLavaalpha_f); - Cvar_SetCallback (&r_telealpha, R_SetTelealpha_f); - Cvar_SetCallback (&r_slimealpha, R_SetSlimealpha_f); + Cvar_RegisterVariable(&gl_zfix); // QuakeSpasm z-fighting fix + Cvar_RegisterVariable(&r_lavaalpha); + Cvar_RegisterVariable(&r_telealpha); + Cvar_RegisterVariable(&r_slimealpha); + Cvar_RegisterVariable(&r_scale); + Cvar_SetCallback(&r_lavaalpha, R_SetLavaalpha_f); + Cvar_SetCallback(&r_telealpha, R_SetTelealpha_f); + Cvar_SetCallback(&r_slimealpha, R_SetSlimealpha_f); - R_InitParticles (); - R_SetClearColor_f (&r_clearcolor); //johnfitz + R_InitParticles(); + R_SetClearColor_f(&r_clearcolor); //johnfitz - Sky_Init (); //johnfitz - Fog_Init (); //johnfitz + Sky_Init(); //johnfitz + Fog_Init(); //johnfitz } /* @@ -258,17 +258,17 @@ void R_Init (void) R_TranslatePlayerSkin -- johnfitz -- rewritten. also, only handles new colors, not new skins =============== */ -void R_TranslatePlayerSkin (int32_t playernum) +void R_TranslatePlayerSkin(int32_t playernum) { - int32_t top, bottom; + int32_t top, bottom; - top = (cl.scores[playernum].colors & 0xf0)>>4; - bottom = cl.scores[playernum].colors &15; + top = (cl.scores[playernum].colors & 0xf0) >> 4; + bottom = cl.scores[playernum].colors & 15; //FIXME: if gl_nocolors is on, then turned off, the textures may be out of sync with the scoreboard colors. - if (!gl_nocolors.value) - if (playertextures[playernum]) - TexMgr_ReloadImage (playertextures[playernum], top, bottom); + if(!gl_nocolors.value) + if(playertextures[playernum]) + TexMgr_ReloadImage(playertextures[playernum], top, bottom); } /* @@ -278,25 +278,25 @@ the skin or model actually changes, instead of just new colors added bug fix from bengt jardup =============== */ -void R_TranslateNewPlayerSkin (int32_t playernum) +void R_TranslateNewPlayerSkin(int32_t playernum) { - char name[64]; - byte *pixels; - aliashdr_t *paliashdr; - int32_t skinnum; + char name[64]; + byte *pixels; + aliashdr_t *paliashdr; + int32_t skinnum; //get correct texture pixels - currententity = &cl_entities[1+playernum]; + currententity = &cl_entities[1 + playernum]; - if (!currententity->model || currententity->model->type != mod_alias) + if(!currententity->model || currententity->model->type != mod_alias) return; - paliashdr = (aliashdr_t *)Mod_Extradata (currententity->model); + paliashdr = (aliashdr_t *)Mod_Extradata(currententity->model); skinnum = currententity->skinnum; //TODO: move these tests to the place where skinnum gets received from the server - if (skinnum < 0 || skinnum >= paliashdr->numskins) + if(skinnum < 0 || skinnum >= paliashdr->numskins) { Con_DPrintf("(%" PRIi32 "): Invalid player skin #%" PRIi32 "\n", playernum, skinnum); skinnum = 0; @@ -306,11 +306,11 @@ void R_TranslateNewPlayerSkin (int32_t playernum) //upload new image q_snprintf(name, sizeof(name), "player_%" PRIi32 "", playernum); - playertextures[playernum] = TexMgr_LoadImage (currententity->model, name, paliashdr->skinwidth, paliashdr->skinheight, - SRC_INDEXED, pixels, paliashdr->gltextures[skinnum][0]->source_file, paliashdr->gltextures[skinnum][0]->source_offset, TEXPREF_PAD | TEXPREF_OVERWRITE); + playertextures[playernum] = TexMgr_LoadImage(currententity->model, name, paliashdr->skinwidth, paliashdr->skinheight, + SRC_INDEXED, pixels, paliashdr->gltextures[skinnum][0]->source_file, paliashdr->gltextures[skinnum][0]->source_offset, TEXPREF_PAD | TEXPREF_OVERWRITE); //now recolor it - R_TranslatePlayerSkin (playernum); + R_TranslatePlayerSkin(playernum); } /* @@ -318,12 +318,12 @@ void R_TranslateNewPlayerSkin (int32_t playernum) R_NewGame -- johnfitz -- handle a game switch =============== */ -void R_NewGame (void) +void R_NewGame(void) { int32_t i; //clear playertexture pointers (the textures themselves were freed by texmgr_newgame) - for (i=0; ientities); - if (!data) + if(!data) return; // error - if (com_token[0] != '{') + if(com_token[0] != '{') return; // error - while (1) + while(1) { data = COM_Parse(data); - if (!data) + if(!data) return; // error - if (com_token[0] == '}') + if(com_token[0] == '}') break; // end of worldspawn - if (com_token[0] == '_') + if(com_token[0] == '_') strcpy(key, com_token + 1); else strcpy(key, com_token); - while (key[strlen(key)-1] == ' ') // remove trailing spaces - key[strlen(key)-1] = 0; + while(key[strlen(key) - 1] == ' ') // remove trailing spaces + key[strlen(key) - 1] = 0; data = COM_Parse(data); - if (!data) + if(!data) return; // error strcpy(value, com_token); - if (!strcmp("wateralpha", key)) + if(!strcmp("wateralpha", key)) map_wateralpha = atof(value); - if (!strcmp("lavaalpha", key)) + if(!strcmp("lavaalpha", key)) map_lavaalpha = atof(value); - if (!strcmp("telealpha", key)) + if(!strcmp("telealpha", key)) map_telealpha = atof(value); - if (!strcmp("slimealpha", key)) + if(!strcmp("slimealpha", key)) map_slimealpha = atof(value); } } @@ -387,31 +387,31 @@ static void R_ParseWorldspawn (void) R_NewMap =============== */ -void R_NewMap (void) +void R_NewMap(void) { - int32_t i; + int32_t i; - for (i=0 ; i<256 ; i++) - d_lightstylevalue[i] = 264; // normal light value + for(i = 0 ; i < 256 ; i++) + d_lightstylevalue[i] = 264; // normal light value // clear out efrags in case the level hasn't been reloaded // FIXME: is this one short? - for (i=0 ; inumleafs ; i++) + for(i = 0 ; i < cl.worldmodel->numleafs ; i++) cl.worldmodel->leafs[i].efrags = NULL; r_viewleaf = NULL; - R_ClearParticles (); + R_ClearParticles(); - GL_BuildLightmaps (); - GL_BuildBModelVertexBuffer (); + GL_BuildLightmaps(); + GL_BuildBModelVertexBuffer(); //ericw -- no longer load alias models into a VBO here, it's done in Mod_LoadAliasModel r_framecount = 0; //johnfitz -- paranoid? r_visframecount = 0; //johnfitz -- paranoid? - Sky_NewMap (); //johnfitz -- skybox in worldspawn - Fog_NewMap (); //johnfitz -- global fog in worldspawn - R_ParseWorldspawn (); //ericw -- wateralpha, lavaalpha, telealpha, slimealpha in worldspawn + Sky_NewMap(); //johnfitz -- skybox in worldspawn + Fog_NewMap(); //johnfitz -- global fog in worldspawn + R_ParseWorldspawn(); //ericw -- wateralpha, lavaalpha, telealpha, slimealpha in worldspawn load_subdivide_size = gl_subdivide_size.value; //johnfitz -- is this the right place to set this? } @@ -423,71 +423,71 @@ R_TimeRefresh_f For program optimization ==================== */ -void R_TimeRefresh_f (void) +void R_TimeRefresh_f(void) { - int32_t i; - float start, stop, time; + int32_t i; + float start, stop, time; - if (cls.state != ca_connected) + if(cls.state != ca_connected) { Con_Printf("Not connected to a server\n"); return; } - start = Sys_DoubleTime (); - for (i = 0; i < 128; i++) + start = Sys_DoubleTime(); + for(i = 0; i < 128; i++) { GL_BeginRendering(&glx, &gly, &glwidth, &glheight); - r_refdef.viewangles[1] = i/128.0*360.0; - R_RenderView (); - GL_EndRendering (); + r_refdef.viewangles[1] = i / 128.0 * 360.0; + R_RenderView(); + GL_EndRendering(); } - glFinish (); - stop = Sys_DoubleTime (); - time = stop-start; - Con_Printf ("%f seconds (%f fps)\n", time, 128/time); + glFinish(); + stop = Sys_DoubleTime(); + time = stop - start; + Con_Printf("%f seconds (%f fps)\n", time, 128 / time); } -void D_FlushCaches (void) +void D_FlushCaches(void) { } static GLuint gl_programs[16]; static int32_t gl_num_programs; -static bool GL_CheckShader (GLuint shader) +static bool GL_CheckShader(GLuint shader) { GLint status; - GL_GetShaderivFunc (shader, GL_COMPILE_STATUS, &status); + GL_GetShaderivFunc(shader, GL_COMPILE_STATUS, &status); - if (status != GL_TRUE) + if(status != GL_TRUE) { char infolog[1024]; memset(infolog, 0, sizeof(infolog)); - GL_GetShaderInfoLogFunc (shader, sizeof(infolog), NULL, infolog); + GL_GetShaderInfoLogFunc(shader, sizeof(infolog), NULL, infolog); - Con_Warning ("GLSL program failed to compile: %s", infolog); + Con_Warning("GLSL program failed to compile: %s", infolog); return false; } return true; } -static bool GL_CheckProgram (GLuint program) +static bool GL_CheckProgram(GLuint program) { GLint status; - GL_GetProgramivFunc (program, GL_LINK_STATUS, &status); + GL_GetProgramivFunc(program, GL_LINK_STATUS, &status); - if (status != GL_TRUE) + if(status != GL_TRUE) { char infolog[1024]; memset(infolog, 0, sizeof(infolog)); - GL_GetProgramInfoLogFunc (program, sizeof(infolog), NULL, infolog); + GL_GetProgramInfoLogFunc(program, sizeof(infolog), NULL, infolog); - Con_Warning ("GLSL program failed to link: %s", infolog); + Con_Warning("GLSL program failed to link: %s", infolog); return false; } @@ -499,15 +499,15 @@ static bool GL_CheckProgram (GLuint program) GL_GetUniformLocation ============= */ -GLint GL_GetUniformLocation (GLuint *programPtr, const char *name) +GLint GL_GetUniformLocation(GLuint *programPtr, const char *name) { GLint location; - if (!programPtr) + if(!programPtr) return -1; location = GL_GetUniformLocationFunc(*programPtr, name); - if (location == -1) + if(location == -1) { Con_Warning("GL_GetUniformLocationFunc %s failed\n", name); *programPtr = 0; @@ -522,55 +522,55 @@ GL_CreateProgram Compiles and returns GLSL program. ==================== */ -GLuint GL_CreateProgram (const GLchar *vertSource, const GLchar *fragSource, int32_t numbindings, const glsl_attrib_binding_t *bindings) +GLuint GL_CreateProgram(const GLchar *vertSource, const GLchar *fragSource, int32_t numbindings, const glsl_attrib_binding_t *bindings) { int32_t i; GLuint program, vertShader, fragShader; - if (!gl_glsl_able) + if(!gl_glsl_able) return 0; - vertShader = GL_CreateShaderFunc (GL_VERTEX_SHADER); - GL_ShaderSourceFunc (vertShader, 1, &vertSource, NULL); - GL_CompileShaderFunc (vertShader); - if (!GL_CheckShader (vertShader)) + vertShader = GL_CreateShaderFunc(GL_VERTEX_SHADER); + GL_ShaderSourceFunc(vertShader, 1, &vertSource, NULL); + GL_CompileShaderFunc(vertShader); + if(!GL_CheckShader(vertShader)) { - GL_DeleteShaderFunc (vertShader); + GL_DeleteShaderFunc(vertShader); return 0; } - fragShader = GL_CreateShaderFunc (GL_FRAGMENT_SHADER); - GL_ShaderSourceFunc (fragShader, 1, &fragSource, NULL); - GL_CompileShaderFunc (fragShader); - if (!GL_CheckShader (fragShader)) + fragShader = GL_CreateShaderFunc(GL_FRAGMENT_SHADER); + GL_ShaderSourceFunc(fragShader, 1, &fragSource, NULL); + GL_CompileShaderFunc(fragShader); + if(!GL_CheckShader(fragShader)) { - GL_DeleteShaderFunc (vertShader); - GL_DeleteShaderFunc (fragShader); + GL_DeleteShaderFunc(vertShader); + GL_DeleteShaderFunc(fragShader); return 0; } - program = GL_CreateProgramFunc (); - GL_AttachShaderFunc (program, vertShader); - GL_DeleteShaderFunc (vertShader); - GL_AttachShaderFunc (program, fragShader); - GL_DeleteShaderFunc (fragShader); + program = GL_CreateProgramFunc(); + GL_AttachShaderFunc(program, vertShader); + GL_DeleteShaderFunc(vertShader); + GL_AttachShaderFunc(program, fragShader); + GL_DeleteShaderFunc(fragShader); - for (i = 0; i < numbindings; i++) + for(i = 0; i < numbindings; i++) { - GL_BindAttribLocationFunc (program, bindings[i].attrib, bindings[i].name); + GL_BindAttribLocationFunc(program, bindings[i].attrib, bindings[i].name); } - GL_LinkProgramFunc (program); + GL_LinkProgramFunc(program); - if (!GL_CheckProgram (program)) + if(!GL_CheckProgram(program)) { - GL_DeleteProgramFunc (program); + GL_DeleteProgramFunc(program); return 0; } else { - if (gl_num_programs == (sizeof(gl_programs)/sizeof(GLuint))) - Host_Error ("gl_programs overflow"); + if(gl_num_programs == (sizeof(gl_programs) / sizeof(GLuint))) + Host_Error("gl_programs overflow"); gl_programs[gl_num_programs] = program; gl_num_programs++; @@ -586,16 +586,16 @@ R_DeleteShaders Deletes any GLSL programs that have been created. ==================== */ -void R_DeleteShaders (void) +void R_DeleteShaders(void) { int32_t i; - if (!gl_glsl_able) + if(!gl_glsl_able) return; - for (i = 0; i < gl_num_programs; i++) + for(i = 0; i < gl_num_programs; i++) { - GL_DeleteProgramFunc (gl_programs[i]); + GL_DeleteProgramFunc(gl_programs[i]); gl_programs[i] = 0; } gl_num_programs = 0; @@ -609,30 +609,30 @@ GL_BindBuffer glBindBuffer wrapper ==================== */ -void GL_BindBuffer (GLenum target, GLuint buffer) +void GL_BindBuffer(GLenum target, GLuint buffer) { GLuint *cache; - if (!gl_vbo_able) + if(!gl_vbo_able) return; - switch (target) + switch(target) { - case GL_ARRAY_BUFFER: - cache = ¤t_array_buffer; - break; - case GL_ELEMENT_ARRAY_BUFFER: - cache = ¤t_element_array_buffer; - break; - default: - Host_Error("GL_BindBuffer: unsupported target %" PRIi32 "", (int32_t)target); - return; + case GL_ARRAY_BUFFER: + cache = ¤t_array_buffer; + break; + case GL_ELEMENT_ARRAY_BUFFER: + cache = ¤t_element_array_buffer; + break; + default: + Host_Error("GL_BindBuffer: unsupported target %" PRIi32 "", (int32_t)target); + return; } - if (*cache != buffer) + if(*cache != buffer) { *cache = buffer; - GL_BindBufferFunc (target, *cache); + GL_BindBufferFunc(target, *cache); } } @@ -644,13 +644,13 @@ This must be called if you do anything that could make the cached bindings invalid (e.g. manually binding, destroying the context). ==================== */ -void GL_ClearBufferBindings () +void GL_ClearBufferBindings() { - if (!gl_vbo_able) + if(!gl_vbo_able) return; current_array_buffer = 0; current_element_array_buffer = 0; - GL_BindBufferFunc (GL_ARRAY_BUFFER, 0); - GL_BindBufferFunc (GL_ELEMENT_ARRAY_BUFFER, 0); + GL_BindBufferFunc(GL_ARRAY_BUFFER, 0); + GL_BindBufferFunc(GL_ELEMENT_ARRAY_BUFFER, 0); } diff --git a/source/gl_screen.c b/source/gl_screen.c index b1bb3cf..ffda047 100644 --- a/source/gl_screen.c +++ b/source/gl_screen.c @@ -65,60 +65,60 @@ the refresh is allways rendered, unless the console is full screen console is: - notify lines - half - full + notify lines + half + full */ -int32_t glx, gly, glwidth, glheight; +int32_t glx, gly, glwidth, glheight; -float scr_con_current; -float scr_conlines; // lines of console to display +float scr_con_current; +float scr_conlines; // lines of console to display //johnfitz -- new cvars -cvar_t scr_menuscale = {"scr_menuscale", "1", CVAR_ARCHIVE}; -cvar_t scr_sbarscale = {"scr_sbarscale", "1", CVAR_ARCHIVE}; -cvar_t scr_sbaralpha = {"scr_sbaralpha", "0.75", CVAR_ARCHIVE}; -cvar_t scr_conwidth = {"scr_conwidth", "0", CVAR_ARCHIVE}; -cvar_t scr_conscale = {"scr_conscale", "1", CVAR_ARCHIVE}; -cvar_t scr_crosshairscale = {"scr_crosshairscale", "1", CVAR_ARCHIVE}; -cvar_t scr_showfps = {"scr_showfps", "0", CVAR_NONE}; -cvar_t scr_clock = {"scr_clock", "0", CVAR_NONE}; +cvar_t scr_menuscale = {"scr_menuscale", "1", CVAR_ARCHIVE}; +cvar_t scr_sbarscale = {"scr_sbarscale", "1", CVAR_ARCHIVE}; +cvar_t scr_sbaralpha = {"scr_sbaralpha", "0.75", CVAR_ARCHIVE}; +cvar_t scr_conwidth = {"scr_conwidth", "0", CVAR_ARCHIVE}; +cvar_t scr_conscale = {"scr_conscale", "1", CVAR_ARCHIVE}; +cvar_t scr_crosshairscale = {"scr_crosshairscale", "1", CVAR_ARCHIVE}; +cvar_t scr_showfps = {"scr_showfps", "0", CVAR_NONE}; +cvar_t scr_clock = {"scr_clock", "0", CVAR_NONE}; //johnfitz -cvar_t scr_viewsize = {"viewsize","100", CVAR_ARCHIVE}; -cvar_t scr_fov = {"fov","90",CVAR_NONE}; // 10 - 170 -cvar_t scr_fov_adapt = {"fov_adapt","1",CVAR_ARCHIVE}; -cvar_t scr_conspeed = {"scr_conspeed","500",CVAR_ARCHIVE}; -cvar_t scr_centertime = {"scr_centertime","2",CVAR_NONE}; -cvar_t scr_showram = {"showram","1",CVAR_NONE}; -cvar_t scr_showturtle = {"showturtle","0",CVAR_NONE}; -cvar_t scr_showpause = {"showpause","1",CVAR_NONE}; -cvar_t scr_printspeed = {"scr_printspeed","8",CVAR_NONE}; -cvar_t gl_triplebuffer = {"gl_triplebuffer", "1", CVAR_ARCHIVE}; +cvar_t scr_viewsize = {"viewsize", "100", CVAR_ARCHIVE}; +cvar_t scr_fov = {"fov", "90", CVAR_NONE}; // 10 - 170 +cvar_t scr_fov_adapt = {"fov_adapt", "1", CVAR_ARCHIVE}; +cvar_t scr_conspeed = {"scr_conspeed", "500", CVAR_ARCHIVE}; +cvar_t scr_centertime = {"scr_centertime", "2", CVAR_NONE}; +cvar_t scr_showram = {"showram", "1", CVAR_NONE}; +cvar_t scr_showturtle = {"showturtle", "0", CVAR_NONE}; +cvar_t scr_showpause = {"showpause", "1", CVAR_NONE}; +cvar_t scr_printspeed = {"scr_printspeed", "8", CVAR_NONE}; +cvar_t gl_triplebuffer = {"gl_triplebuffer", "1", CVAR_ARCHIVE}; -extern cvar_t crosshair; +extern cvar_t crosshair; -bool scr_initialized; // ready to draw +bool scr_initialized; // ready to draw -qpic_t *scr_ram; -qpic_t *scr_net; -qpic_t *scr_turtle; +qpic_t *scr_ram; +qpic_t *scr_net; +qpic_t *scr_turtle; -int32_t clearconsole; -int32_t clearnotify; +int32_t clearconsole; +int32_t clearnotify; -vrect_t scr_vrect; +vrect_t scr_vrect; -bool scr_disabled_for_loading; -bool scr_drawloading; -float scr_disabled_time; +bool scr_disabled_for_loading; +bool scr_drawloading; +float scr_disabled_time; -int32_t scr_tileclear_updates = 0; //johnfitz +int32_t scr_tileclear_updates = 0; //johnfitz -void SCR_ScreenShot_f (void); +void SCR_ScreenShot_f(void); /* =============================================================================== @@ -128,12 +128,12 @@ CENTER PRINTING =============================================================================== */ -char scr_centerstring[1024]; -float scr_centertime_start; // for slow victory printing -float scr_centertime_off; -int32_t scr_center_lines; -int32_t scr_erase_lines; -int32_t scr_erase_center; +char scr_centerstring[1024]; +float scr_centertime_start; // for slow victory printing +float scr_centertime_off; +int32_t scr_center_lines; +int32_t scr_erase_lines; +int32_t scr_erase_center; /* ============== @@ -143,35 +143,35 @@ Called for important messages that should stay in the center of the screen for a few moments ============== */ -void SCR_CenterPrint (const char *str) //update centerprint data +void SCR_CenterPrint(const char *str) //update centerprint data { - strncpy (scr_centerstring, str, sizeof(scr_centerstring)-1); + strncpy(scr_centerstring, str, sizeof(scr_centerstring) - 1); scr_centertime_off = scr_centertime.value; scr_centertime_start = cl.time; // count the number of lines for centering scr_center_lines = 1; str = scr_centerstring; - while (*str) + while(*str) { - if (*str == '\n') + if(*str == '\n') scr_center_lines++; str++; } } -void SCR_DrawCenterString (void) //actually do the drawing +void SCR_DrawCenterString(void) //actually do the drawing { - char *start; - int32_t l; - int32_t j; - int32_t x, y; - int32_t remaining; + char *start; + int32_t l; + int32_t j; + int32_t x, y; + int32_t remaining; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz // the finale prints the characters one at a time - if (cl.intermission) + if(cl.intermission) remaining = scr_printspeed.value * (cl.time - scr_centertime_start); else remaining = 9999; @@ -179,53 +179,54 @@ void SCR_DrawCenterString (void) //actually do the drawing scr_erase_center = 0; start = scr_centerstring; - if (scr_center_lines <= 4) - y = 200*0.35; //johnfitz -- 320x200 coordinate system + if(scr_center_lines <= 4) + y = 200 * 0.35; //johnfitz -- 320x200 coordinate system else y = 48; - if (crosshair.value) + if(crosshair.value) y -= 8; do { - // scan the width of the line - for (l=0 ; l<40 ; l++) - if (start[l] == '\n' || !start[l]) + // scan the width of the line + for(l = 0 ; l < 40 ; l++) + if(start[l] == '\n' || !start[l]) break; - x = (320 - l*8)/2; //johnfitz -- 320x200 coordinate system - for (j=0 ; j scr_erase_lines) + if(scr_center_lines > scr_erase_lines) scr_erase_lines = scr_center_lines; scr_centertime_off -= host_frametime; - if (scr_centertime_off <= 0 && !cl.intermission) + if(scr_centertime_off <= 0 && !cl.intermission) return; - if (key_dest != key_game) + if(key_dest != key_game) return; - if (cl.paused) //johnfitz -- don't show centerprint during a pause + if(cl.paused) //johnfitz -- don't show centerprint during a pause return; - SCR_DrawCenterString (); + SCR_DrawCenterString(); } //============================================================================= @@ -237,16 +238,16 @@ Adapt a 4:3 horizontal FOV to the current screen size using the "Hor+" scaling: 2.0 * atan(width / height * 3.0 / 4.0 * tan(fov_x / 2.0)) ==================== */ -float AdaptFovx (float fov_x, float width, float height) +float AdaptFovx(float fov_x, float width, float height) { - float a, x; + float a, x; - if (fov_x < 1 || fov_x > 179) - Sys_Error ("Bad fov: %f", fov_x); + if(fov_x < 1 || fov_x > 179) + Sys_Error("Bad fov: %f", fov_x); - if (!scr_fov_adapt.value) + if(!scr_fov_adapt.value) return fov_x; - if ((x = height / width) == 0.75) + if((x = height / width) == 0.75) return fov_x; a = atan(0.75 / x * tan(fov_x / 360 * M_PI)); a = a * 360 / M_PI; @@ -258,12 +259,12 @@ float AdaptFovx (float fov_x, float width, float height) CalcFovy ==================== */ -float CalcFovy (float fov_x, float width, float height) +float CalcFovy(float fov_x, float width, float height) { - float a, x; + float a, x; - if (fov_x < 1 || fov_x > 179) - Sys_Error ("Bad fov: %f", fov_x); + if(fov_x < 1 || fov_x > 179) + Sys_Error("Bad fov: %f", fov_x); x = width / tan(fov_x / 360 * M_PI); a = atan(height / x); @@ -279,36 +280,36 @@ Must be called whenever vid changes Internal use only ================= */ -static void SCR_CalcRefdef (void) +static void SCR_CalcRefdef(void) { - float size, scale; //johnfitz -- scale + float size, scale; //johnfitz -- scale // force the status bar to redraw - Sbar_Changed (); + Sbar_Changed(); scr_tileclear_updates = 0; //johnfitz // bound viewsize - if (scr_viewsize.value < 30) - Cvar_SetQuick (&scr_viewsize, "30"); - if (scr_viewsize.value > 120) - Cvar_SetQuick (&scr_viewsize, "120"); + if(scr_viewsize.value < 30) + Cvar_SetQuick(&scr_viewsize, "30"); + if(scr_viewsize.value > 120) + Cvar_SetQuick(&scr_viewsize, "120"); // bound fov - if (scr_fov.value < 10) - Cvar_SetQuick (&scr_fov, "10"); - if (scr_fov.value > 170) - Cvar_SetQuick (&scr_fov, "170"); + if(scr_fov.value < 10) + Cvar_SetQuick(&scr_fov, "10"); + if(scr_fov.value > 170) + Cvar_SetQuick(&scr_fov, "170"); vid.recalc_refdef = 0; //johnfitz -- rewrote this section size = scr_viewsize.value; - scale = CLAMP (1.0, scr_sbarscale.value, (float)glwidth / 320.0); + scale = CLAMP(1.0, scr_sbarscale.value, (float)glwidth / 320.0); - if (size >= 120 || cl.intermission || scr_sbaralpha.value < 1) //johnfitz -- scr_sbaralpha.value + if(size >= 120 || cl.intermission || scr_sbaralpha.value < 1) //johnfitz -- scr_sbaralpha.value sb_lines = 0; - else if (size >= 110) + else if(size >= 110) sb_lines = 24 * scale; else sb_lines = 48 * scale; @@ -319,12 +320,12 @@ static void SCR_CalcRefdef (void) //johnfitz -- rewrote this section r_refdef.vrect.width = q_max(glwidth * size, 96); //no smaller than 96, for icons r_refdef.vrect.height = q_min(glheight * size, glheight - sb_lines); //make room for sbar - r_refdef.vrect.x = (glwidth - r_refdef.vrect.width)/2; - r_refdef.vrect.y = (glheight - sb_lines - r_refdef.vrect.height)/2; + r_refdef.vrect.x = (glwidth - r_refdef.vrect.width) / 2; + r_refdef.vrect.y = (glheight - sb_lines - r_refdef.vrect.height) / 2; //johnfitz r_refdef.fov_x = AdaptFovx(scr_fov.value, vid.width, vid.height); - r_refdef.fov_y = CalcFovy (r_refdef.fov_x, r_refdef.vrect.width, r_refdef.vrect.height); + r_refdef.fov_y = CalcFovy(r_refdef.fov_x, r_refdef.vrect.width, r_refdef.vrect.height); scr_vrect = r_refdef.vrect; } @@ -337,9 +338,9 @@ SCR_SizeUp_f Keybinding command ================= */ -void SCR_SizeUp_f (void) +void SCR_SizeUp_f(void) { - Cvar_SetValueQuick (&scr_viewsize, scr_viewsize.value+10); + Cvar_SetValueQuick(&scr_viewsize, scr_viewsize.value + 10); } @@ -350,12 +351,12 @@ SCR_SizeDown_f Keybinding command ================= */ -void SCR_SizeDown_f (void) +void SCR_SizeDown_f(void) { - Cvar_SetValueQuick (&scr_viewsize, scr_viewsize.value-10); + Cvar_SetValueQuick(&scr_viewsize, scr_viewsize.value - 10); } -static void SCR_Callback_refdef (cvar_t *var) +static void SCR_Callback_refdef(cvar_t *var) { (void)var; vid.recalc_refdef = 1; @@ -366,12 +367,12 @@ static void SCR_Callback_refdef (cvar_t *var) SCR_Conwidth_f -- johnfitz -- called when scr_conwidth or scr_conscale changes ================== */ -void SCR_Conwidth_f (cvar_t *var) +void SCR_Conwidth_f(cvar_t *var) { (void)var; vid.recalc_refdef = 1; - vid.conwidth = (scr_conwidth.value > 0) ? (int32_t)scr_conwidth.value : (scr_conscale.value > 0) ? (int32_t)(vid.width/scr_conscale.value) : vid.width; - vid.conwidth = CLAMP (320, vid.conwidth, vid.width); + vid.conwidth = (scr_conwidth.value > 0) ? (int32_t)scr_conwidth.value : (scr_conscale.value > 0) ? (int32_t)(vid.width / scr_conscale.value) : vid.width; + vid.conwidth = CLAMP(320, vid.conwidth, vid.width); vid.conwidth &= 0xFFFFFFF8; vid.conheight = vid.conwidth * vid.height / vid.width; } @@ -383,11 +384,11 @@ void SCR_Conwidth_f (cvar_t *var) SCR_LoadPics -- johnfitz ================== */ -void SCR_LoadPics (void) +void SCR_LoadPics(void) { - scr_ram = Draw_PicFromWad ("ram"); - scr_net = Draw_PicFromWad ("net"); - scr_turtle = Draw_PicFromWad ("turtle"); + scr_ram = Draw_PicFromWad("ram"); + scr_net = Draw_PicFromWad("net"); + scr_turtle = Draw_PicFromWad("turtle"); } /* @@ -395,40 +396,40 @@ void SCR_LoadPics (void) SCR_Init ================== */ -void SCR_Init (void) +void SCR_Init(void) { //johnfitz -- new cvars - Cvar_RegisterVariable (&scr_menuscale); - Cvar_RegisterVariable (&scr_sbarscale); - Cvar_SetCallback (&scr_sbaralpha, SCR_Callback_refdef); - Cvar_RegisterVariable (&scr_sbaralpha); - Cvar_SetCallback (&scr_conwidth, &SCR_Conwidth_f); - Cvar_SetCallback (&scr_conscale, &SCR_Conwidth_f); - Cvar_RegisterVariable (&scr_conwidth); - Cvar_RegisterVariable (&scr_conscale); - Cvar_RegisterVariable (&scr_crosshairscale); - Cvar_RegisterVariable (&scr_showfps); - Cvar_RegisterVariable (&scr_clock); + Cvar_RegisterVariable(&scr_menuscale); + Cvar_RegisterVariable(&scr_sbarscale); + Cvar_SetCallback(&scr_sbaralpha, SCR_Callback_refdef); + Cvar_RegisterVariable(&scr_sbaralpha); + Cvar_SetCallback(&scr_conwidth, &SCR_Conwidth_f); + Cvar_SetCallback(&scr_conscale, &SCR_Conwidth_f); + Cvar_RegisterVariable(&scr_conwidth); + Cvar_RegisterVariable(&scr_conscale); + Cvar_RegisterVariable(&scr_crosshairscale); + Cvar_RegisterVariable(&scr_showfps); + Cvar_RegisterVariable(&scr_clock); //johnfitz - Cvar_SetCallback (&scr_fov, SCR_Callback_refdef); - Cvar_SetCallback (&scr_fov_adapt, SCR_Callback_refdef); - Cvar_SetCallback (&scr_viewsize, SCR_Callback_refdef); - Cvar_RegisterVariable (&scr_fov); - Cvar_RegisterVariable (&scr_fov_adapt); - Cvar_RegisterVariable (&scr_viewsize); - Cvar_RegisterVariable (&scr_conspeed); - Cvar_RegisterVariable (&scr_showram); - Cvar_RegisterVariable (&scr_showturtle); - Cvar_RegisterVariable (&scr_showpause); - Cvar_RegisterVariable (&scr_centertime); - Cvar_RegisterVariable (&scr_printspeed); - Cvar_RegisterVariable (&gl_triplebuffer); + Cvar_SetCallback(&scr_fov, SCR_Callback_refdef); + Cvar_SetCallback(&scr_fov_adapt, SCR_Callback_refdef); + Cvar_SetCallback(&scr_viewsize, SCR_Callback_refdef); + Cvar_RegisterVariable(&scr_fov); + Cvar_RegisterVariable(&scr_fov_adapt); + Cvar_RegisterVariable(&scr_viewsize); + Cvar_RegisterVariable(&scr_conspeed); + Cvar_RegisterVariable(&scr_showram); + Cvar_RegisterVariable(&scr_showturtle); + Cvar_RegisterVariable(&scr_showpause); + Cvar_RegisterVariable(&scr_centertime); + Cvar_RegisterVariable(&scr_printspeed); + Cvar_RegisterVariable(&gl_triplebuffer); - Cmd_AddCommand ("screenshot",SCR_ScreenShot_f); - Cmd_AddCommand ("sizeup",SCR_SizeUp_f); - Cmd_AddCommand ("sizedown",SCR_SizeDown_f); + Cmd_AddCommand("screenshot", SCR_ScreenShot_f); + Cmd_AddCommand("sizeup", SCR_SizeUp_f); + Cmd_AddCommand("sizedown", SCR_SizeDown_f); - SCR_LoadPics (); //johnfitz + SCR_LoadPics(); //johnfitz scr_initialized = true; } @@ -440,41 +441,41 @@ void SCR_Init (void) SCR_DrawFPS -- johnfitz ============== */ -void SCR_DrawFPS (void) +void SCR_DrawFPS(void) { - static double oldtime = 0; - static double lastfps = 0; - static int32_t oldframecount = 0; - double elapsed_time; - int32_t frames; + static double oldtime = 0; + static double lastfps = 0; + static int32_t oldframecount = 0; + double elapsed_time; + int32_t frames; elapsed_time = realtime - oldtime; frames = r_framecount - oldframecount; - if (elapsed_time < 0 || frames < 0) + if(elapsed_time < 0 || frames < 0) { oldtime = realtime; oldframecount = r_framecount; return; } // update value every 3/4 second - if (elapsed_time > 0.75) + if(elapsed_time > 0.75) { lastfps = frames / elapsed_time; oldtime = realtime; oldframecount = r_framecount; } - if (scr_showfps.value) + if(scr_showfps.value) { - char st[16]; - int32_t x, y; - sprintf (st, "%4.0f fps", lastfps); - x = 320 - (strlen(st)<<3); + char st[16]; + int32_t x, y; + sprintf(st, "%4.0f fps", lastfps); + x = 320 - (strlen(st) << 3); y = 200 - 8; - if (scr_clock.value) y -= 8; //make room for clock - GL_SetCanvas (CANVAS_BOTTOMRIGHT); - Draw_String (x, y, st); + if(scr_clock.value) y -= 8; //make room for clock + GL_SetCanvas(CANVAS_BOTTOMRIGHT); + Draw_String(x, y, st); scr_tileclear_updates = 0; } } @@ -484,25 +485,25 @@ void SCR_DrawFPS (void) SCR_DrawClock -- johnfitz ============== */ -void SCR_DrawClock (void) +void SCR_DrawClock(void) { - char str[12]; + char str[12]; - if (scr_clock.value == 1) + if(scr_clock.value == 1) { int32_t minutes, seconds; minutes = cl.time / 60; - seconds = ((int32_t)cl.time)%60; + seconds = ((int32_t)cl.time) % 60; - sprintf (str,"%" PRIi32 ":%" PRIi32 "%" PRIi32 "", minutes, seconds/10, seconds%10); + sprintf(str, "%" PRIi32 ":%" PRIi32 "%" PRIi32 "", minutes, seconds / 10, seconds % 10); } else return; //draw it - GL_SetCanvas (CANVAS_BOTTOMRIGHT); - Draw_String (320 - (strlen(str)<<3), 200 - 8, str); + GL_SetCanvas(CANVAS_BOTTOMRIGHT); + Draw_String(320 - (strlen(str) << 3), 200 - 8, str); scr_tileclear_updates = 0; } @@ -512,45 +513,45 @@ void SCR_DrawClock (void) SCR_DrawDevStats ============== */ -void SCR_DrawDevStats (void) +void SCR_DrawDevStats(void) { - char str[40]; - int32_t y = 25-9; //9=number of lines to print - int32_t x = 0; //margin + char str[40]; + int32_t y = 25 - 9; //9=number of lines to print + int32_t x = 0; //margin - if (!devstats.value) + if(!devstats.value) return; - GL_SetCanvas (CANVAS_BOTTOMLEFT); + GL_SetCanvas(CANVAS_BOTTOMLEFT); - Draw_Fill (x, y*8, 19*8, 9*8, 0, 0.5); //dark rectangle + Draw_Fill(x, y * 8, 19 * 8, 9 * 8, 0, 0.5); //dark rectangle - sprintf (str, "devstats |Curr Peak"); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "devstats |Curr Peak"); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "---------+---------"); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "---------+---------"); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Edicts |%4" PRIi32 " %4" PRIi32 "", dev_stats.edicts, dev_peakstats.edicts); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Edicts |%4" PRIi32 " %4" PRIi32 "", dev_stats.edicts, dev_peakstats.edicts); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Packet |%4" PRIi32 " %4" PRIi32 "", dev_stats.packetsize, dev_peakstats.packetsize); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Packet |%4" PRIi32 " %4" PRIi32 "", dev_stats.packetsize, dev_peakstats.packetsize); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Visedicts|%4" PRIi32 " %4" PRIi32 "", dev_stats.visedicts, dev_peakstats.visedicts); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Visedicts|%4" PRIi32 " %4" PRIi32 "", dev_stats.visedicts, dev_peakstats.visedicts); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Efrags |%4" PRIi32 " %4" PRIi32 "", dev_stats.efrags, dev_peakstats.efrags); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Efrags |%4" PRIi32 " %4" PRIi32 "", dev_stats.efrags, dev_peakstats.efrags); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Dlights |%4" PRIi32 " %4" PRIi32 "", dev_stats.dlights, dev_peakstats.dlights); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Dlights |%4" PRIi32 " %4" PRIi32 "", dev_stats.dlights, dev_peakstats.dlights); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Beams |%4" PRIi32 " %4" PRIi32 "", dev_stats.beams, dev_peakstats.beams); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Beams |%4" PRIi32 " %4" PRIi32 "", dev_stats.beams, dev_peakstats.beams); + Draw_String(x, (y++) * 8 - x, str); - sprintf (str, "Tempents |%4" PRIi32 " %4" PRIi32 "", dev_stats.tempents, dev_peakstats.tempents); - Draw_String (x, (y++)*8-x, str); + sprintf(str, "Tempents |%4" PRIi32 " %4" PRIi32 "", dev_stats.tempents, dev_peakstats.tempents); + Draw_String(x, (y++) * 8 - x, str); } /* @@ -558,17 +559,17 @@ void SCR_DrawDevStats (void) SCR_DrawRam ============== */ -void SCR_DrawRam (void) +void SCR_DrawRam(void) { - if (!scr_showram.value) + if(!scr_showram.value) return; - if (!r_cache_thrash) + if(!r_cache_thrash) return; - GL_SetCanvas (CANVAS_DEFAULT); //johnfitz + GL_SetCanvas(CANVAS_DEFAULT); //johnfitz - Draw_Pic (scr_vrect.x+32, scr_vrect.y, scr_ram); + Draw_Pic(scr_vrect.x + 32, scr_vrect.y, scr_ram); } /* @@ -576,26 +577,26 @@ void SCR_DrawRam (void) SCR_DrawTurtle ============== */ -void SCR_DrawTurtle (void) +void SCR_DrawTurtle(void) { - static int32_t count; + static int32_t count; - if (!scr_showturtle.value) + if(!scr_showturtle.value) return; - if (host_frametime < 0.1) + if(host_frametime < 0.1) { count = 0; return; } count++; - if (count < 3) + if(count < 3) return; - GL_SetCanvas (CANVAS_DEFAULT); //johnfitz + GL_SetCanvas(CANVAS_DEFAULT); //johnfitz - Draw_Pic (scr_vrect.x, scr_vrect.y, scr_turtle); + Draw_Pic(scr_vrect.x, scr_vrect.y, scr_turtle); } /* @@ -603,16 +604,16 @@ void SCR_DrawTurtle (void) SCR_DrawNet ============== */ -void SCR_DrawNet (void) +void SCR_DrawNet(void) { - if (realtime - cl.last_received_message < 0.3) + if(realtime - cl.last_received_message < 0.3) return; - if (cls.demoplayback) + if(cls.demoplayback) return; - GL_SetCanvas (CANVAS_DEFAULT); //johnfitz + GL_SetCanvas(CANVAS_DEFAULT); //johnfitz - Draw_Pic (scr_vrect.x+64, scr_vrect.y, scr_net); + Draw_Pic(scr_vrect.x + 64, scr_vrect.y, scr_net); } /* @@ -620,20 +621,20 @@ void SCR_DrawNet (void) DrawPause ============== */ -void SCR_DrawPause (void) +void SCR_DrawPause(void) { - qpic_t *pic; + qpic_t *pic; - if (!cl.paused) + if(!cl.paused) return; - if (!scr_showpause.value) // turn off for screenshots + if(!scr_showpause.value) // turn off for screenshots return; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - pic = Draw_CachePic ("gfx/pause.lmp"); - Draw_Pic ( (320 - pic->width)/2, (240 - 48 - pic->height)/2, pic); //johnfitz -- stretched menus + pic = Draw_CachePic("gfx/pause.lmp"); + Draw_Pic((320 - pic->width) / 2, (240 - 48 - pic->height) / 2, pic); //johnfitz -- stretched menus scr_tileclear_updates = 0; //johnfitz } @@ -643,17 +644,17 @@ void SCR_DrawPause (void) SCR_DrawLoading ============== */ -void SCR_DrawLoading (void) +void SCR_DrawLoading(void) { - qpic_t *pic; + qpic_t *pic; - if (!scr_drawloading) + if(!scr_drawloading) return; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - pic = Draw_CachePic ("gfx/loading.lmp"); - Draw_Pic ( (320 - pic->width)/2, (240 - 48 - pic->height)/2, pic); //johnfitz -- stretched menus + pic = Draw_CachePic("gfx/loading.lmp"); + Draw_Pic((320 - pic->width) / 2, (240 - 48 - pic->height) / 2, pic); //johnfitz -- stretched menus scr_tileclear_updates = 0; //johnfitz } @@ -663,13 +664,13 @@ void SCR_DrawLoading (void) SCR_DrawCrosshair -- johnfitz ============== */ -void SCR_DrawCrosshair (void) +void SCR_DrawCrosshair(void) { - if (!crosshair.value) + if(!crosshair.value) return; - GL_SetCanvas (CANVAS_CROSSHAIR); - Draw_Character (-4, -4, '+'); //0,0 is center of viewport + GL_SetCanvas(CANVAS_CROSSHAIR); + Draw_Character(-4, -4, '+'); //0,0 is center of viewport } @@ -682,52 +683,52 @@ void SCR_DrawCrosshair (void) SCR_SetUpToDrawConsole ================== */ -void SCR_SetUpToDrawConsole (void) +void SCR_SetUpToDrawConsole(void) { //johnfitz -- let's hack away the problem of slow console when host_timescale is <0 extern cvar_t host_timescale; float timescale; //johnfitz - Con_CheckResize (); + Con_CheckResize(); - if (scr_drawloading) - return; // never a console with loading plaque + if(scr_drawloading) + return; // never a console with loading plaque // decide on the height of the console con_forcedup = !cl.worldmodel || cls.signon != SIGNONS; - if (con_forcedup) + if(con_forcedup) { scr_conlines = glheight; //full screen //johnfitz -- glheight instead of vid.height scr_con_current = scr_conlines; } - else if (key_dest == key_console) - scr_conlines = glheight/2; //half screen //johnfitz -- glheight instead of vid.height + else if(key_dest == key_console) + scr_conlines = glheight / 2; //half screen //johnfitz -- glheight instead of vid.height else scr_conlines = 0; //none visible timescale = (host_timescale.value > 0) ? host_timescale.value : 1; //johnfitz -- timescale - if (scr_conlines < scr_con_current) + if(scr_conlines < scr_con_current) { // ericw -- (glheight/600.0) factor makes conspeed resolution independent, using 800x600 as a baseline - scr_con_current -= scr_conspeed.value*(glheight/600.0)*host_frametime/timescale; //johnfitz -- timescale - if (scr_conlines > scr_con_current) + scr_con_current -= scr_conspeed.value * (glheight / 600.0) * host_frametime / timescale; //johnfitz -- timescale + if(scr_conlines > scr_con_current) scr_con_current = scr_conlines; } - else if (scr_conlines > scr_con_current) + else if(scr_conlines > scr_con_current) { // ericw -- (glheight/600.0) - scr_con_current += scr_conspeed.value*(glheight/600.0)*host_frametime/timescale; //johnfitz -- timescale - if (scr_conlines < scr_con_current) + scr_con_current += scr_conspeed.value * (glheight / 600.0) * host_frametime / timescale; //johnfitz -- timescale + if(scr_conlines < scr_con_current) scr_con_current = scr_conlines; } - if (clearconsole++ < vid.numpages) - Sbar_Changed (); + if(clearconsole++ < vid.numpages) + Sbar_Changed(); - if (!con_forcedup && scr_con_current) + if(!con_forcedup && scr_con_current) scr_tileclear_updates = 0; //johnfitz } @@ -736,17 +737,17 @@ void SCR_SetUpToDrawConsole (void) SCR_DrawConsole ================== */ -void SCR_DrawConsole (void) +void SCR_DrawConsole(void) { - if (scr_con_current) + if(scr_con_current) { - Con_DrawConsole (scr_con_current, true); + Con_DrawConsole(scr_con_current, true); clearconsole = 0; } else { - if (key_dest == key_game || key_dest == key_message) - Con_DrawNotify (); // only draw notify in game + if(key_dest == key_game || key_dest == key_message) + Con_DrawNotify(); // only draw notify in game } } @@ -759,11 +760,11 @@ SCREEN SHOTS ============================================================================== */ -static void SCR_ScreenShot_Usage (void) +static void SCR_ScreenShot_Usage(void) { - Con_Printf ("usage: screenshot \n"); - Con_Printf (" format must be \"png\" or \"tga\" or \"jpg\"\n"); - Con_Printf (" quality must be 1-100\n"); + Con_Printf("usage: screenshot \n"); + Con_Printf(" format must be \"png\" or \"tga\" or \"jpg\"\n"); + Con_Printf(" quality must be 1-100\n"); return; } @@ -772,82 +773,82 @@ static void SCR_ScreenShot_Usage (void) SCR_ScreenShot_f -- johnfitz -- rewritten to use Image_WriteTGA ================== */ -void SCR_ScreenShot_f (void) +void SCR_ScreenShot_f(void) { - byte *buffer; - char ext[4]; - char imagename[16]; //johnfitz -- was [80] - char checkname[MAX_OSPATH]; - int32_t i, quality; - bool ok; + byte *buffer; + char ext[4]; + char imagename[16]; //johnfitz -- was [80] + char checkname[MAX_OSPATH]; + int32_t i, quality; + bool ok; - Q_strncpy (ext, "png", sizeof(ext)); + Q_strncpy(ext, "png", sizeof(ext)); - if (Cmd_Argc () >= 2) + if(Cmd_Argc() >= 2) { - const char *requested_ext = Cmd_Argv (1); + const char *requested_ext = Cmd_Argv(1); - if (!q_strcasecmp ("png", requested_ext) - || !q_strcasecmp ("tga", requested_ext) - || !q_strcasecmp ("jpg", requested_ext)) - Q_strncpy (ext, requested_ext, sizeof(ext)); + if(!q_strcasecmp("png", requested_ext) + || !q_strcasecmp("tga", requested_ext) + || !q_strcasecmp("jpg", requested_ext)) + Q_strncpy(ext, requested_ext, sizeof(ext)); else { - SCR_ScreenShot_Usage (); + SCR_ScreenShot_Usage(); return; } } // read quality as the 3rd param (only used for JPG) quality = 90; - if (Cmd_Argc () >= 3) - quality = Q_atoi (Cmd_Argv(2)); - if (quality < 1 || quality > 100) + if(Cmd_Argc() >= 3) + quality = Q_atoi(Cmd_Argv(2)); + if(quality < 1 || quality > 100) { - SCR_ScreenShot_Usage (); + SCR_ScreenShot_Usage(); return; } // find a file name to save it to - for (i=0; i<10000; i++) + for(i = 0; i < 10000; i++) { - q_snprintf (imagename, sizeof(imagename), "quake%04" PRIi32 ".%s", i, ext); - q_snprintf (checkname, sizeof(checkname), "%s/%s", com_gamedir, imagename); - if (Sys_FileTime(checkname) == -1) - break; // file doesn't exist + q_snprintf(imagename, sizeof(imagename), "quake%04" PRIi32 ".%s", i, ext); + q_snprintf(checkname, sizeof(checkname), "%s/%s", com_gamedir, imagename); + if(Sys_FileTime(checkname) == -1) + break; // file doesn't exist } - if (i == 10000) + if(i == 10000) { - Con_Printf ("SCR_ScreenShot_f: Couldn't find an unused filename\n"); + Con_Printf("SCR_ScreenShot_f: Couldn't find an unused filename\n"); return; } //get data - if (!(buffer = (byte *) malloc(glwidth*glheight*3))) + if(!(buffer = (byte *) malloc(glwidth * glheight * 3))) { - Con_Printf ("SCR_ScreenShot_f: Couldn't allocate memory\n"); + Con_Printf("SCR_ScreenShot_f: Couldn't allocate memory\n"); return; } - glPixelStorei (GL_PACK_ALIGNMENT, 1);/* for widths that aren't a multiple of 4 */ - glReadPixels (glx, gly, glwidth, glheight, GL_RGB, GL_UNSIGNED_BYTE, buffer); + glPixelStorei(GL_PACK_ALIGNMENT, 1); /* for widths that aren't a multiple of 4 */ + glReadPixels(glx, gly, glwidth, glheight, GL_RGB, GL_UNSIGNED_BYTE, buffer); // now write the file - if (!q_strncasecmp (ext, "png", sizeof(ext))) - ok = Image_WritePNG (imagename, buffer, glwidth, glheight, 24, false); - else if (!q_strncasecmp (ext, "tga", sizeof(ext))) - ok = Image_WriteTGA (imagename, buffer, glwidth, glheight, 24, false); - else if (!q_strncasecmp (ext, "jpg", sizeof(ext))) - ok = Image_WriteJPG (imagename, buffer, glwidth, glheight, 24, quality, false); + if(!q_strncasecmp(ext, "png", sizeof(ext))) + ok = Image_WritePNG(imagename, buffer, glwidth, glheight, 24, false); + else if(!q_strncasecmp(ext, "tga", sizeof(ext))) + ok = Image_WriteTGA(imagename, buffer, glwidth, glheight, 24, false); + else if(!q_strncasecmp(ext, "jpg", sizeof(ext))) + ok = Image_WriteJPG(imagename, buffer, glwidth, glheight, 24, quality, false); else ok = false; - if (ok) - Con_Printf ("Wrote %s\n", imagename); + if(ok) + Con_Printf("Wrote %s\n", imagename); else - Con_Printf ("SCR_ScreenShot_f: Couldn't create %s\n", imagename); + Con_Printf("SCR_ScreenShot_f: Couldn't create %s\n", imagename); - free (buffer); + free(buffer); } @@ -860,23 +861,23 @@ SCR_BeginLoadingPlaque ================ */ -void SCR_BeginLoadingPlaque (void) +void SCR_BeginLoadingPlaque(void) { - S_StopAllSounds (true); + S_StopAllSounds(true); - if (cls.state != ca_connected) + if(cls.state != ca_connected) return; - if (cls.signon != SIGNONS) + if(cls.signon != SIGNONS) return; // redraw with no console and the loading plaque - Con_ClearNotify (); + Con_ClearNotify(); scr_centertime_off = 0; scr_con_current = 0; scr_drawloading = true; - Sbar_Changed (); - SCR_UpdateScreen (); + Sbar_Changed(); + SCR_UpdateScreen(); scr_drawloading = false; scr_disabled_for_loading = true; @@ -889,25 +890,25 @@ SCR_EndLoadingPlaque ================ */ -void SCR_EndLoadingPlaque (void) +void SCR_EndLoadingPlaque(void) { scr_disabled_for_loading = false; - Con_ClearNotify (); + Con_ClearNotify(); } //============================================================================= -const char *scr_notifystring; -bool scr_drawdialog; +const char *scr_notifystring; +bool scr_drawdialog; -void SCR_DrawNotifyString (void) +void SCR_DrawNotifyString(void) { - const char *start; - int32_t l; - int32_t j; - int32_t x, y; + const char *start; + int32_t l; + int32_t j; + int32_t x, y; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz start = scr_notifystring; @@ -915,23 +916,24 @@ void SCR_DrawNotifyString (void) do { - // scan the width of the line - for (l=0 ; l<40 ; l++) - if (start[l] == '\n' || !start[l]) + // scan the width of the line + for(l = 0 ; l < 40 ; l++) + if(start[l] == '\n' || !start[l]) break; - x = (320 - l*8)/2; //johnfitz -- stretched overlays - for (j=0 ; j time1) + if(time2 > time1) return false; //johnfitz @@ -997,43 +1000,43 @@ int32_t SCR_ModalMessage (const char *text, float timeout) //johnfitz -- timeout ================== SCR_TileClear johnfitz -- modified to use glwidth/glheight instead of vid.width/vid.height - also fixed the dimentions of right and top panels - also added scr_tileclear_updates + also fixed the dimentions of right and top panels + also added scr_tileclear_updates ================== */ -void SCR_TileClear (void) +void SCR_TileClear(void) { //ericw -- added check for glsl gamma. TODO: remove this ugly optimization? - if (scr_tileclear_updates >= vid.numpages && !gl_clear.value && !(gl_glsl_gamma_able && vid_gamma.value != 1)) + if(scr_tileclear_updates >= vid.numpages && !gl_clear.value && !(gl_glsl_gamma_able && vid_gamma.value != 1)) return; scr_tileclear_updates++; - if (r_refdef.vrect.x > 0) + if(r_refdef.vrect.x > 0) { // left - Draw_TileClear (0, - 0, - r_refdef.vrect.x, - glheight - sb_lines); + Draw_TileClear(0, + 0, + r_refdef.vrect.x, + glheight - sb_lines); // right - Draw_TileClear (r_refdef.vrect.x + r_refdef.vrect.width, - 0, - glwidth - r_refdef.vrect.x - r_refdef.vrect.width, - glheight - sb_lines); + Draw_TileClear(r_refdef.vrect.x + r_refdef.vrect.width, + 0, + glwidth - r_refdef.vrect.x - r_refdef.vrect.width, + glheight - sb_lines); } - if (r_refdef.vrect.y > 0) + if(r_refdef.vrect.y > 0) { // top - Draw_TileClear (r_refdef.vrect.x, - 0, - r_refdef.vrect.width, - r_refdef.vrect.y); + Draw_TileClear(r_refdef.vrect.x, + 0, + r_refdef.vrect.width, + r_refdef.vrect.y); // bottom - Draw_TileClear (r_refdef.vrect.x, - r_refdef.vrect.y + r_refdef.vrect.height, - r_refdef.vrect.width, - glheight - r_refdef.vrect.y - r_refdef.vrect.height - sb_lines); + Draw_TileClear(r_refdef.vrect.x, + r_refdef.vrect.y + r_refdef.vrect.height, + r_refdef.vrect.width, + glheight - r_refdef.vrect.y - r_refdef.vrect.height - sb_lines); } } @@ -1048,88 +1051,88 @@ WARNING: be very careful calling this from elsewhere, because the refresh needs almost the entire 256k of stack space! ================== */ -void SCR_UpdateScreen (void) +void SCR_UpdateScreen(void) { vid.numpages = (gl_triplebuffer.value) ? 3 : 2; - if (scr_disabled_for_loading) + if(scr_disabled_for_loading) { - if (realtime - scr_disabled_time > 60) + if(realtime - scr_disabled_time > 60) { scr_disabled_for_loading = false; - Con_Printf ("load failed.\n"); + Con_Printf("load failed.\n"); } else return; } - if (!scr_initialized || !con_initialized) - return; // not initialized yet + if(!scr_initialized || !con_initialized) + return; // not initialized yet - GL_BeginRendering (&glx, &gly, &glwidth, &glheight); + GL_BeginRendering(&glx, &gly, &glwidth, &glheight); // // determine size of refresh window // - if (vid.recalc_refdef) - SCR_CalcRefdef (); + if(vid.recalc_refdef) + SCR_CalcRefdef(); // // do 3D refresh drawing, and then update the screen // - SCR_SetUpToDrawConsole (); + SCR_SetUpToDrawConsole(); - V_RenderView (); + V_RenderView(); - GL_Set2D (); + GL_Set2D(); //FIXME: only call this when needed - SCR_TileClear (); + SCR_TileClear(); - if (scr_drawdialog) //new game confirm + if(scr_drawdialog) //new game confirm { - if (con_forcedup) - Draw_ConsoleBackground (); + if(con_forcedup) + Draw_ConsoleBackground(); else - Sbar_Draw (); - Draw_FadeScreen (); - SCR_DrawNotifyString (); + Sbar_Draw(); + Draw_FadeScreen(); + SCR_DrawNotifyString(); } - else if (scr_drawloading) //loading + else if(scr_drawloading) //loading { - SCR_DrawLoading (); - Sbar_Draw (); + SCR_DrawLoading(); + Sbar_Draw(); } - else if (cl.intermission == 1 && key_dest == key_game) //end of level + else if(cl.intermission == 1 && key_dest == key_game) //end of level { - Sbar_IntermissionOverlay (); + Sbar_IntermissionOverlay(); } - else if (cl.intermission == 2 && key_dest == key_game) //end of episode + else if(cl.intermission == 2 && key_dest == key_game) //end of episode { - Sbar_FinaleOverlay (); - SCR_CheckDrawCenterString (); + Sbar_FinaleOverlay(); + SCR_CheckDrawCenterString(); } else { - SCR_DrawCrosshair (); //johnfitz - SCR_DrawRam (); - SCR_DrawNet (); - SCR_DrawTurtle (); - SCR_DrawPause (); - SCR_CheckDrawCenterString (); - Sbar_Draw (); - SCR_DrawDevStats (); //johnfitz - SCR_DrawFPS (); //johnfitz - SCR_DrawClock (); //johnfitz - SCR_DrawConsole (); - M_Draw (); + SCR_DrawCrosshair(); //johnfitz + SCR_DrawRam(); + SCR_DrawNet(); + SCR_DrawTurtle(); + SCR_DrawPause(); + SCR_CheckDrawCenterString(); + Sbar_Draw(); + SCR_DrawDevStats(); //johnfitz + SCR_DrawFPS(); //johnfitz + SCR_DrawClock(); //johnfitz + SCR_DrawConsole(); + M_Draw(); } - V_UpdateBlend (); //johnfitz -- V_UpdatePalette cleaned up and renamed + V_UpdateBlend(); //johnfitz -- V_UpdatePalette cleaned up and renamed - GLSLGamma_GammaCorrect (); + GLSLGamma_GammaCorrect(); - GL_EndRendering (); + GL_EndRendering(); } diff --git a/source/gl_sky.c b/source/gl_sky.c index badaff8..384c34b 100644 --- a/source/gl_sky.c +++ b/source/gl_sky.c @@ -24,60 +24,61 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -#define MAX_CLIP_VERTS 64 +#define MAX_CLIP_VERTS 64 float Fog_GetDensity(void); float *Fog_GetColor(void); -extern qmodel_t *loadmodel; -extern int32_t rs_skypolys; //for r_speeds readout -extern int32_t rs_skypasses; //for r_speeds readout -float skyflatcolor[3]; -float skymins[2][6], skymaxs[2][6]; +extern qmodel_t *loadmodel; +extern int32_t rs_skypolys; //for r_speeds readout +extern int32_t rs_skypasses; //for r_speeds readout +float skyflatcolor[3]; +float skymins[2][6], skymaxs[2][6]; -char skybox_name[32] = ""; //name of current skybox, or "" if no skybox +char skybox_name[32] = ""; //name of current skybox, or "" if no skybox -gltexture_t *skybox_textures[6]; -gltexture_t *solidskytexture, *alphaskytexture; +gltexture_t *skybox_textures[6]; +gltexture_t *solidskytexture, *alphaskytexture; extern cvar_t gl_farclip; cvar_t r_fastsky = {"r_fastsky", "0", CVAR_NONE}; cvar_t r_sky_quality = {"r_sky_quality", "12", CVAR_NONE}; cvar_t r_skyalpha = {"r_skyalpha", "1", CVAR_NONE}; -cvar_t r_skyfog = {"r_skyfog","0.5",CVAR_NONE}; +cvar_t r_skyfog = {"r_skyfog", "0.5", CVAR_NONE}; -int32_t skytexorder[6] = {0,2,1,3,4,5}; //for skybox +int32_t skytexorder[6] = {0, 2, 1, 3, 4, 5}; //for skybox -vec3_t skyclip[6] = { - {1,1,0}, - {1,-1,0}, - {0,-1,1}, - {0,1,1}, - {1,0,1}, - {-1,0,1} -}; - -int32_t st_to_vec[6][3] = +vec3_t skyclip[6] = { - {3,-1,2}, - {-3,1,2}, - {1,3,2}, - {-1,-3,2}, - {-2,-1,3}, // straight up - {2,-1,-3} // straight down + {1, 1, 0}, + {1, -1, 0}, + {0, -1, 1}, + {0, 1, 1}, + {1, 0, 1}, + {-1, 0, 1} }; -int32_t vec_to_st[6][3] = +int32_t st_to_vec[6][3] = { - {-2,3,1}, - {2,3,-1}, - {1,3,2}, - {-1,3,-2}, - {-2,-1,3}, - {-2,1,-3} + {3, -1, 2}, + {-3, 1, 2}, + {1, 3, 2}, + {-1, -3, 2}, + {-2, -1, 3}, // straight up + {2, -1, -3} // straight down }; -float skyfog; // ericw +int32_t vec_to_st[6][3] = +{ + {-2, 3, 1}, + {2, 3, -1}, + {1, 3, 2}, + {-1, 3, -2}, + {-2, -1, 3}, + {-2, 1, -3} +}; + +float skyfog; // ericw //============================================================================== // @@ -92,44 +93,44 @@ Sky_LoadTexture A sky texture is 256*128, with the left side being a masked overlay ============== */ -void Sky_LoadTexture (texture_t *mt) +void Sky_LoadTexture(texture_t *mt) { - char texturename[64]; - int32_t i, j, p, r, g, b, count; - byte *src; - static byte front_data[128*128]; //FIXME: Hunk_Alloc - static byte back_data[128*128]; //FIXME: Hunk_Alloc - unsigned *rgba; + char texturename[64]; + int32_t i, j, p, r, g, b, count; + byte *src; + static byte front_data[128 * 128]; //FIXME: Hunk_Alloc + static byte back_data[128 * 128]; //FIXME: Hunk_Alloc + unsigned *rgba; src = (byte *)mt + mt->offsets[0]; // extract back layer and upload - for (i=0 ; i<128 ; i++) - for (j=0 ; j<128 ; j++) - back_data[(i*128) + j] = src[i*256 + j + 128]; + for(i = 0 ; i < 128 ; i++) + for(j = 0 ; j < 128 ; j++) + back_data[(i * 128) + j] = src[i * 256 + j + 128]; q_snprintf(texturename, sizeof(texturename), "%s:%s_back", loadmodel->name, mt->name); - solidskytexture = TexMgr_LoadImage (loadmodel, texturename, 128, 128, SRC_INDEXED, back_data, "", (src_offset_t)back_data, TEXPREF_NONE); + solidskytexture = TexMgr_LoadImage(loadmodel, texturename, 128, 128, SRC_INDEXED, back_data, "", (src_offset_t)back_data, TEXPREF_NONE); // extract front layer and upload - for (i=0 ; i<128 ; i++) - for (j=0 ; j<128 ; j++) + for(i = 0 ; i < 128 ; i++) + for(j = 0 ; j < 128 ; j++) { - front_data[(i*128) + j] = src[i*256 + j]; - if (front_data[(i*128) + j] == 0) - front_data[(i*128) + j] = 255; + front_data[(i * 128) + j] = src[i * 256 + j]; + if(front_data[(i * 128) + j] == 0) + front_data[(i * 128) + j] = 255; } q_snprintf(texturename, sizeof(texturename), "%s:%s_front", loadmodel->name, mt->name); - alphaskytexture = TexMgr_LoadImage (loadmodel, texturename, 128, 128, SRC_INDEXED, front_data, "", (src_offset_t)front_data, TEXPREF_ALPHA); + alphaskytexture = TexMgr_LoadImage(loadmodel, texturename, 128, 128, SRC_INDEXED, front_data, "", (src_offset_t)front_data, TEXPREF_ALPHA); // calculate r_fastsky color based on average of all opaque foreground colors r = g = b = count = 0; - for (i=0 ; i<128 ; i++) - for (j=0 ; j<128 ; j++) + for(i = 0 ; i < 128 ; i++) + for(j = 0 ; j < 128 ; j++) { - p = src[i*256 + j]; - if (p != 0) + p = src[i * 256 + j]; + if(p != 0) { rgba = &d_8to24table[p]; r += ((byte *)rgba)[0]; @@ -138,9 +139,9 @@ void Sky_LoadTexture (texture_t *mt) count++; } } - skyflatcolor[0] = (float)r/(count*255); - skyflatcolor[1] = (float)g/(count*255); - skyflatcolor[2] = (float)b/(count*255); + skyflatcolor[0] = (float)r / (count * 255); + skyflatcolor[1] = (float)g / (count * 255); + skyflatcolor[2] = (float)b / (count * 255); } /* @@ -148,57 +149,57 @@ void Sky_LoadTexture (texture_t *mt) Sky_LoadSkyBox ================== */ -const char *suf[6] = {"rt", "bk", "lf", "ft", "up", "dn"}; -void Sky_LoadSkyBox (const char *name) +const char *suf[6] = {"rt", "bk", "lf", "ft", "up", "dn"}; +void Sky_LoadSkyBox(const char *name) { - int32_t i, mark, width, height; - char filename[MAX_OSPATH]; - byte *data; + int32_t i, mark, width, height; + char filename[MAX_OSPATH]; + byte *data; bool nonefound = true; - if (strcmp(skybox_name, name) == 0) + if(strcmp(skybox_name, name) == 0) return; //no change //purge old textures - for (i=0; i<6; i++) + for(i = 0; i < 6; i++) { - if (skybox_textures[i] && skybox_textures[i] != notexture) - TexMgr_FreeTexture (skybox_textures[i]); + if(skybox_textures[i] && skybox_textures[i] != notexture) + TexMgr_FreeTexture(skybox_textures[i]); skybox_textures[i] = NULL; } //turn off skybox if sky is set to "" - if (name[0] == 0) + if(name[0] == 0) { skybox_name[0] = 0; return; } //load textures - for (i=0; i<6; i++) + for(i = 0; i < 6; i++) { - mark = Hunk_LowMark (); - q_snprintf (filename, sizeof(filename), "gfx/env/%s%s", name, suf[i]); - data = Image_LoadImage (filename, &width, &height); - if (data) + mark = Hunk_LowMark(); + q_snprintf(filename, sizeof(filename), "gfx/env/%s%s", name, suf[i]); + data = Image_LoadImage(filename, &width, &height); + if(data) { - skybox_textures[i] = TexMgr_LoadImage (cl.worldmodel, filename, width, height, SRC_RGBA, data, filename, 0, TEXPREF_NONE); + skybox_textures[i] = TexMgr_LoadImage(cl.worldmodel, filename, width, height, SRC_RGBA, data, filename, 0, TEXPREF_NONE); nonefound = false; } else { - Con_Printf ("Couldn't load %s\n", filename); + Con_Printf("Couldn't load %s\n", filename); skybox_textures[i] = notexture; } - Hunk_FreeToLowMark (mark); + Hunk_FreeToLowMark(mark); } - if (nonefound) // go back to scrolling sky if skybox is totally missing + if(nonefound) // go back to scrolling sky if skybox is totally missing { - for (i=0; i<6; i++) + for(i = 0; i < 6; i++) { - if (skybox_textures[i] && skybox_textures[i] != notexture) - TexMgr_FreeTexture (skybox_textures[i]); + if(skybox_textures[i] && skybox_textures[i] != notexture) + TexMgr_FreeTexture(skybox_textures[i]); skybox_textures[i] = NULL; } skybox_name[0] = 0; @@ -213,17 +214,17 @@ void Sky_LoadSkyBox (const char *name) Sky_NewMap ================= */ -void Sky_NewMap (void) +void Sky_NewMap(void) { - char key[128], value[4096]; - const char *data; - int32_t i; + char key[128], value[4096]; + const char *data; + int32_t i; // // initially no sky // skybox_name[0] = 0; - for (i=0; i<6; i++) + for(i = 0; i < 6; i++) skybox_textures[i] = NULL; skyfog = r_skyfog.value; @@ -231,43 +232,43 @@ void Sky_NewMap (void) // read worldspawn (this is so ugly, and shouldn't it be done on the server?) // data = cl.worldmodel->entities; - if (!data) + if(!data) return; //FIXME: how could this possibly ever happen? -- if there's no // worldspawn then the sever wouldn't send the loadmap message to the client data = COM_Parse(data); - if (!data) //should never happen + if(!data) //should never happen return; // error - if (com_token[0] != '{') //should never happen + if(com_token[0] != '{') //should never happen return; // error - while (1) + while(1) { data = COM_Parse(data); - if (!data) + if(!data) return; // error - if (com_token[0] == '}') + if(com_token[0] == '}') break; // end of worldspawn - if (com_token[0] == '_') + if(com_token[0] == '_') strcpy(key, com_token + 1); else strcpy(key, com_token); - while (key[strlen(key)-1] == ' ') // remove trailing spaces - key[strlen(key)-1] = 0; + while(key[strlen(key) - 1] == ' ') // remove trailing spaces + key[strlen(key) - 1] = 0; data = COM_Parse(data); - if (!data) + if(!data) return; // error strcpy(value, com_token); - if (!strcmp("sky", key)) + if(!strcmp("sky", key)) Sky_LoadSkyBox(value); - if (!strcmp("skyfog", key)) + if(!strcmp("skyfog", key)) skyfog = atof(value); #if 1 //also accept non-standard keys - else if (!strcmp("skyname", key)) //half-life + else if(!strcmp("skyname", key)) //half-life Sky_LoadSkyBox(value); - else if (!strcmp("qlsky", key)) //quake lives + else if(!strcmp("qlsky", key)) //quake lives Sky_LoadSkyBox(value); #endif } @@ -278,9 +279,9 @@ void Sky_NewMap (void) Sky_SkyCommand_f ================= */ -void Sky_SkyCommand_f (void) +void Sky_SkyCommand_f(void) { - switch (Cmd_Argc()) + switch(Cmd_Argc()) { case 1: Con_Printf("\"sky\" is \"%s\"\n", skybox_name); @@ -298,7 +299,7 @@ void Sky_SkyCommand_f (void) R_SetSkyfog_f -- ericw ==================== */ -static void R_SetSkyfog_f (cvar_t *var) +static void R_SetSkyfog_f(cvar_t *var) { // clear any skyfog setting from worldspawn skyfog = var->value; @@ -309,19 +310,19 @@ static void R_SetSkyfog_f (cvar_t *var) Sky_Init ============= */ -void Sky_Init (void) +void Sky_Init(void) { - int32_t i; + int32_t i; - Cvar_RegisterVariable (&r_fastsky); - Cvar_RegisterVariable (&r_sky_quality); - Cvar_RegisterVariable (&r_skyalpha); - Cvar_RegisterVariable (&r_skyfog); - Cvar_SetCallback (&r_skyfog, R_SetSkyfog_f); + Cvar_RegisterVariable(&r_fastsky); + Cvar_RegisterVariable(&r_sky_quality); + Cvar_RegisterVariable(&r_skyalpha); + Cvar_RegisterVariable(&r_skyfog); + Cvar_SetCallback(&r_skyfog, R_SetSkyfog_f); - Cmd_AddCommand ("sky",Sky_SkyCommand_f); + Cmd_AddCommand("sky", Sky_SkyCommand_f); - for (i=0; i<6; i++) + for(i = 0; i < 6; i++) skybox_textures[i] = NULL; } @@ -338,72 +339,72 @@ Sky_ProjectPoly update sky bounds ================= */ -void Sky_ProjectPoly (int32_t nump, vec3_t vecs) +void Sky_ProjectPoly(int32_t nump, vec3_t vecs) { - int32_t i,j; - vec3_t v, av; - float s, t, dv; - int32_t axis; - float *vp; + int32_t i, j; + vec3_t v, av; + float s, t, dv; + int32_t axis; + float *vp; // decide which face it maps to - VectorCopy (vec3_origin, v); - for (i=0, vp=vecs ; i av[1] && av[0] > av[2]) + if(av[0] > av[1] && av[0] > av[2]) { - if (v[0] < 0) + if(v[0] < 0) axis = 1; else axis = 0; } - else if (av[1] > av[2] && av[1] > av[0]) + else if(av[1] > av[2] && av[1] > av[0]) { - if (v[1] < 0) + if(v[1] < 0) axis = 3; else axis = 2; } else { - if (v[2] < 0) + if(v[2] < 0) axis = 5; else axis = 4; } // project new texture coords - for (i=0 ; i 0) + if(j > 0) dv = vecs[j - 1]; else dv = -vecs[-j - 1]; j = vec_to_st[axis][0]; - if (j < 0) - s = -vecs[-j -1] / dv; + if(j < 0) + s = -vecs[-j - 1] / dv; else - s = vecs[j-1] / dv; + s = vecs[j - 1] / dv; j = vec_to_st[axis][1]; - if (j < 0) - t = -vecs[-j -1] / dv; + if(j < 0) + t = -vecs[-j - 1] / dv; else - t = vecs[j-1] / dv; + t = vecs[j - 1] / dv; - if (s < skymins[0][axis]) + if(s < skymins[0][axis]) skymins[0][axis] = s; - if (t < skymins[1][axis]) + if(t < skymins[1][axis]) skymins[1][axis] = t; - if (s > skymaxs[0][axis]) + if(s > skymaxs[0][axis]) skymaxs[0][axis] = s; - if (t > skymaxs[1][axis]) + if(t > skymaxs[1][axis]) skymaxs[1][axis] = t; } } @@ -413,37 +414,37 @@ void Sky_ProjectPoly (int32_t nump, vec3_t vecs) Sky_ClipPoly ================= */ -void Sky_ClipPoly (int32_t nump, vec3_t vecs, int32_t stage) +void Sky_ClipPoly(int32_t nump, vec3_t vecs, int32_t stage) { - float *norm; - float *v; - bool front, back; - float d, e; - float dists[MAX_CLIP_VERTS]; - int32_t sides[MAX_CLIP_VERTS]; - vec3_t newv[2][MAX_CLIP_VERTS]; - int32_t newc[2]; - int32_t i, j; + float *norm; + float *v; + bool front, back; + float d, e; + float dists[MAX_CLIP_VERTS]; + int32_t sides[MAX_CLIP_VERTS]; + vec3_t newv[2][MAX_CLIP_VERTS]; + int32_t newc[2]; + int32_t i, j; - if (nump > MAX_CLIP_VERTS-2) - Sys_Error ("Sky_ClipPoly: MAX_CLIP_VERTS"); - if (stage == 6) // fully clipped + if(nump > MAX_CLIP_VERTS - 2) + Sys_Error("Sky_ClipPoly: MAX_CLIP_VERTS"); + if(stage == 6) // fully clipped { - Sky_ProjectPoly (nump, vecs); + Sky_ProjectPoly(nump, vecs); return; } front = back = false; norm = skyclip[stage]; - for (i=0, v = vecs ; i ON_EPSILON) + d = DotProduct(v, norm); + if(d > ON_EPSILON) { front = true; sides[i] = SIDE_FRONT; } - else if (d < ON_EPSILON) + else if(d < ON_EPSILON) { back = true; sides[i] = SIDE_BACK; @@ -453,45 +454,46 @@ void Sky_ClipPoly (int32_t nump, vec3_t vecs, int32_t stage) dists[i] = d; } - if (!front || !back) - { // not clipped - Sky_ClipPoly (nump, vecs, stage+1); + if(!front || !back) + { + // not clipped + Sky_ClipPoly(nump, vecs, stage + 1); return; } // clip it sides[i] = sides[0]; dists[i] = dists[0]; - VectorCopy (vecs, (vecs+(i*3)) ); + VectorCopy(vecs, (vecs + (i * 3))); newc[0] = newc[1] = 0; - for (i=0, v = vecs ; inumverts ; i++) - VectorSubtract (p->verts[i], r_origin, verts[i]); - Sky_ClipPoly (p->numverts, verts[0], 0); + for(i = 0 ; i < p->numverts ; i++) + VectorSubtract(p->verts[i], r_origin, verts[i]); + Sky_ClipPoly(p->numverts, verts[0], 0); } } @@ -532,25 +534,25 @@ void Sky_ProcessPoly (glpoly_t *p) Sky_ProcessTextureChains -- handles sky polys in world model ================ */ -void Sky_ProcessTextureChains (void) +void Sky_ProcessTextureChains(void) { - int32_t i; - msurface_t *s; - texture_t *t; + int32_t i; + msurface_t *s; + texture_t *t; - if (!r_drawworld_cheatsafe) + if(!r_drawworld_cheatsafe) return; - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < cl.worldmodel->numtextures ; i++) { t = cl.worldmodel->textures[i]; - if (!t || !t->texturechains[chain_world] || !(t->texturechains[chain_world]->flags & SURF_DRAWSKY)) + if(!t || !t->texturechains[chain_world] || !(t->texturechains[chain_world]->flags & SURF_DRAWSKY)) continue; - for (s = t->texturechains[chain_world]; s; s = s->texturechain) - if (!s->culled) - Sky_ProcessPoly (s->polys); + for(s = t->texturechains[chain_world]; s; s = s->texturechain) + if(!s->culled) + Sky_ProcessPoly(s->polys); } } @@ -559,78 +561,78 @@ void Sky_ProcessTextureChains (void) Sky_ProcessEntities -- handles sky polys on brush models ================ */ -void Sky_ProcessEntities (void) +void Sky_ProcessEntities(void) { - entity_t *e; - msurface_t *s; - glpoly_t *p; - int32_t i,j,k,mark; - float dot; - bool rotated; - vec3_t temp, forward, right, up; + entity_t *e; + msurface_t *s; + glpoly_t *p; + int32_t i, j, k, mark; + float dot; + bool rotated; + vec3_t temp, forward, right, up; - if (!r_drawentities.value) + if(!r_drawentities.value) return; - for (i=0 ; imodel->type != mod_brush) + if(e->model->type != mod_brush) continue; - if (R_CullModelForEntity(e)) + if(R_CullModelForEntity(e)) continue; - if (e->alpha == ENTALPHA_ZERO) + if(e->alpha == ENTALPHA_ZERO) continue; - VectorSubtract (r_refdef.vieworg, e->origin, modelorg); - if (e->angles[0] || e->angles[1] || e->angles[2]) + VectorSubtract(r_refdef.vieworg, e->origin, modelorg); + if(e->angles[0] || e->angles[1] || e->angles[2]) { rotated = true; - AngleVectors (e->angles, forward, right, up); - VectorCopy (modelorg, temp); - modelorg[0] = DotProduct (temp, forward); - modelorg[1] = -DotProduct (temp, right); - modelorg[2] = DotProduct (temp, up); + AngleVectors(e->angles, forward, right, up); + VectorCopy(modelorg, temp); + modelorg[0] = DotProduct(temp, forward); + modelorg[1] = -DotProduct(temp, right); + modelorg[2] = DotProduct(temp, up); } else rotated = false; s = &e->model->surfaces[e->model->firstmodelsurface]; - for (j=0 ; jmodel->nummodelsurfaces ; j++, s++) + for(j = 0 ; j < e->model->nummodelsurfaces ; j++, s++) { - if (s->flags & SURF_DRAWSKY) + if(s->flags & SURF_DRAWSKY) { - dot = DotProduct (modelorg, s->plane->normal) - s->plane->dist; - if (((s->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || - (!(s->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) + dot = DotProduct(modelorg, s->plane->normal) - s->plane->dist; + if(((s->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || + (!(s->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) { //copy the polygon and translate manually, since Sky_ProcessPoly needs it to be in world space mark = Hunk_LowMark(); - p = (glpoly_t *) Hunk_Alloc (sizeof(*s->polys)); //FIXME: don't allocate for each poly + p = (glpoly_t *) Hunk_Alloc(sizeof(*s->polys)); //FIXME: don't allocate for each poly p->numverts = s->polys->numverts; - for (k=0; knumverts; k++) + for(k = 0; k < p->numverts; k++) { - if (rotated) + if(rotated) { p->verts[k][0] = e->origin[0] + s->polys->verts[k][0] * forward[0] - - s->polys->verts[k][1] * right[0] - + s->polys->verts[k][2] * up[0]; + - s->polys->verts[k][1] * right[0] + + s->polys->verts[k][2] * up[0]; p->verts[k][1] = e->origin[1] + s->polys->verts[k][0] * forward[1] - - s->polys->verts[k][1] * right[1] - + s->polys->verts[k][2] * up[1]; + - s->polys->verts[k][1] * right[1] + + s->polys->verts[k][2] * up[1]; p->verts[k][2] = e->origin[2] + s->polys->verts[k][0] * forward[2] - - s->polys->verts[k][1] * right[2] - + s->polys->verts[k][2] * up[2]; + - s->polys->verts[k][1] * right[2] + + s->polys->verts[k][2] * up[2]; } else VectorAdd(s->polys->verts[k], e->origin, p->verts[k]); } - Sky_ProcessPoly (p); - Hunk_FreeToLowMark (mark); + Sky_ProcessPoly(p); + Hunk_FreeToLowMark(mark); } } } @@ -648,20 +650,20 @@ void Sky_ProcessEntities (void) Sky_EmitSkyBoxVertex ============== */ -void Sky_EmitSkyBoxVertex (float s, float t, int32_t axis) +void Sky_EmitSkyBoxVertex(float s, float t, int32_t axis) { - vec3_t v, b; - int32_t j, k; - float w, h; + vec3_t v, b; + int32_t j, k; + float w, h; b[0] = s * gl_farclip.value / sqrt(3.0); b[1] = t * gl_farclip.value / sqrt(3.0); b[2] = gl_farclip.value / sqrt(3.0); - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { k = st_to_vec[axis][j]; - if (k < 0) + if(k < 0) v[j] = -b[-k - 1]; else v[j] = b[k - 1]; @@ -669,18 +671,18 @@ void Sky_EmitSkyBoxVertex (float s, float t, int32_t axis) } // convert from range [-1,1] to [0,1] - s = (s+1)*0.5; - t = (t+1)*0.5; + s = (s + 1) * 0.5; + t = (t + 1) * 0.5; // avoid bilerp seam w = skybox_textures[skytexorder[axis]]->width; h = skybox_textures[skytexorder[axis]]->height; - s = s * (w-1)/w + 0.5/w; - t = t * (h-1)/h + 0.5/h; + s = s * (w - 1) / w + 0.5 / w; + t = t * (h - 1) / h + 0.5 / h; t = 1.0 - t; - glTexCoord2f (s, t); - glVertex3fv (v); + glTexCoord2f(s, t); + glVertex3fv(v); } /* @@ -690,16 +692,16 @@ Sky_DrawSkyBox FIXME: eliminate cracks by adding an extra vert on tjuncs ============== */ -void Sky_DrawSkyBox (void) +void Sky_DrawSkyBox(void) { - int32_t i; + int32_t i; - for (i=0 ; i<6 ; i++) + for(i = 0 ; i < 6 ; i++) { - if (skymins[0][i] >= skymaxs[0][i] || skymins[1][i] >= skymaxs[1][i]) + if(skymins[0][i] >= skymaxs[0][i] || skymins[1][i] >= skymaxs[1][i]) continue; - GL_Bind (skybox_textures[skytexorder[i]]); + GL_Bind(skybox_textures[skytexorder[i]]); #if 1 //FIXME: this is to avoid tjunctions until i can do it the right way skymins[0][i] = -1; @@ -707,35 +709,35 @@ void Sky_DrawSkyBox (void) skymaxs[0][i] = 1; skymaxs[1][i] = 1; #endif - glBegin (GL_QUADS); - Sky_EmitSkyBoxVertex (skymins[0][i], skymins[1][i], i); - Sky_EmitSkyBoxVertex (skymins[0][i], skymaxs[1][i], i); - Sky_EmitSkyBoxVertex (skymaxs[0][i], skymaxs[1][i], i); - Sky_EmitSkyBoxVertex (skymaxs[0][i], skymins[1][i], i); - glEnd (); + glBegin(GL_QUADS); + Sky_EmitSkyBoxVertex(skymins[0][i], skymins[1][i], i); + Sky_EmitSkyBoxVertex(skymins[0][i], skymaxs[1][i], i); + Sky_EmitSkyBoxVertex(skymaxs[0][i], skymaxs[1][i], i); + Sky_EmitSkyBoxVertex(skymaxs[0][i], skymins[1][i], i); + glEnd(); rs_skypolys++; rs_skypasses++; - if (Fog_GetDensity() > 0 && skyfog > 0) + if(Fog_GetDensity() > 0 && skyfog > 0) { float *c; c = Fog_GetColor(); - glEnable (GL_BLEND); - glDisable (GL_TEXTURE_2D); - glColor4f (c[0],c[1],c[2], CLAMP(0.0,skyfog,1.0)); + glEnable(GL_BLEND); + glDisable(GL_TEXTURE_2D); + glColor4f(c[0], c[1], c[2], CLAMP(0.0, skyfog, 1.0)); - glBegin (GL_QUADS); - Sky_EmitSkyBoxVertex (skymins[0][i], skymins[1][i], i); - Sky_EmitSkyBoxVertex (skymins[0][i], skymaxs[1][i], i); - Sky_EmitSkyBoxVertex (skymaxs[0][i], skymaxs[1][i], i); - Sky_EmitSkyBoxVertex (skymaxs[0][i], skymins[1][i], i); - glEnd (); + glBegin(GL_QUADS); + Sky_EmitSkyBoxVertex(skymins[0][i], skymins[1][i], i); + Sky_EmitSkyBoxVertex(skymins[0][i], skymaxs[1][i], i); + Sky_EmitSkyBoxVertex(skymaxs[0][i], skymaxs[1][i], i); + Sky_EmitSkyBoxVertex(skymaxs[0][i], skymins[1][i], i); + glEnd(); - glColor3f (1, 1, 1); - glEnable (GL_TEXTURE_2D); - glDisable (GL_BLEND); + glColor3f(1, 1, 1); + glEnable(GL_TEXTURE_2D); + glDisable(GL_BLEND); rs_skypasses++; } @@ -753,19 +755,19 @@ void Sky_DrawSkyBox (void) Sky_SetBoxVert ============== */ -void Sky_SetBoxVert (float s, float t, int32_t axis, vec3_t v) +void Sky_SetBoxVert(float s, float t, int32_t axis, vec3_t v) { - vec3_t b; - int32_t j, k; + vec3_t b; + int32_t j, k; b[0] = s * gl_farclip.value / sqrt(3.0); b[1] = t * gl_farclip.value / sqrt(3.0); b[2] = gl_farclip.value / sqrt(3.0); - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { k = st_to_vec[axis][j]; - if (k < 0) + if(k < 0) v[j] = -b[-k - 1]; else v[j] = b[k - 1]; @@ -778,23 +780,23 @@ void Sky_SetBoxVert (float s, float t, int32_t axis, vec3_t v) Sky_GetTexCoord ============= */ -void Sky_GetTexCoord (vec3_t v, float speed, float *s, float *t) +void Sky_GetTexCoord(vec3_t v, float speed, float *s, float *t) { - vec3_t dir; - float length, scroll; + vec3_t dir; + float length, scroll; - VectorSubtract (v, r_origin, dir); - dir[2] *= 3; // flatten the sphere + VectorSubtract(v, r_origin, dir); + dir[2] *= 3; // flatten the sphere - length = dir[0]*dir[0] + dir[1]*dir[1] + dir[2]*dir[2]; - length = sqrt (length); - length = 6*63/length; + length = dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]; + length = sqrt(length); + length = 6 * 63 / length; - scroll = cl.time*speed; + scroll = cl.time * speed; scroll -= (int32_t)scroll & ~127; - *s = (scroll + dir[0] * length) * (1.0/128); - *t = (scroll + dir[1] * length) * (1.0/128); + *s = (scroll + dir[0] * length) * (1.0 / 128); + *t = (scroll + dir[1] * length) * (1.0 / 128); } /* @@ -802,29 +804,29 @@ void Sky_GetTexCoord (vec3_t v, float speed, float *s, float *t) Sky_DrawFaceQuad =============== */ -void Sky_DrawFaceQuad (glpoly_t *p) +void Sky_DrawFaceQuad(glpoly_t *p) { - float s, t; - float *v; - int32_t i; + float s, t; + float *v; + int32_t i; - if (gl_mtexable && r_skyalpha.value >= 1.0) + if(gl_mtexable && r_skyalpha.value >= 1.0) { - GL_Bind (solidskytexture); + GL_Bind(solidskytexture); GL_EnableMultitexture(); - GL_Bind (alphaskytexture); + GL_Bind(alphaskytexture); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); - glBegin (GL_QUADS); - for (i=0, v=p->verts[0] ; i<4 ; i++, v+=VERTEXSIZE) + glBegin(GL_QUADS); + for(i = 0, v = p->verts[0] ; i < 4 ; i++, v += VERTEXSIZE) { - Sky_GetTexCoord (v, 8, &s, &t); - GL_MTexCoord2fFunc (GL_TEXTURE0_ARB, s, t); - Sky_GetTexCoord (v, 16, &s, &t); - GL_MTexCoord2fFunc (GL_TEXTURE1_ARB, s, t); - glVertex3fv (v); + Sky_GetTexCoord(v, 8, &s, &t); + GL_MTexCoord2fFunc(GL_TEXTURE0_ARB, s, t); + Sky_GetTexCoord(v, 16, &s, &t); + GL_MTexCoord2fFunc(GL_TEXTURE1_ARB, s, t); + glVertex3fv(v); } - glEnd (); + glEnd(); GL_DisableMultitexture(); @@ -833,58 +835,58 @@ void Sky_DrawFaceQuad (glpoly_t *p) } else { - GL_Bind (solidskytexture); + GL_Bind(solidskytexture); - if (r_skyalpha.value < 1.0) - glColor3f (1, 1, 1); + if(r_skyalpha.value < 1.0) + glColor3f(1, 1, 1); - glBegin (GL_QUADS); - for (i=0, v=p->verts[0] ; i<4 ; i++, v+=VERTEXSIZE) + glBegin(GL_QUADS); + for(i = 0, v = p->verts[0] ; i < 4 ; i++, v += VERTEXSIZE) { - Sky_GetTexCoord (v, 8, &s, &t); - glTexCoord2f (s, t); - glVertex3fv (v); + Sky_GetTexCoord(v, 8, &s, &t); + glTexCoord2f(s, t); + glVertex3fv(v); } - glEnd (); + glEnd(); - GL_Bind (alphaskytexture); - glEnable (GL_BLEND); + GL_Bind(alphaskytexture); + glEnable(GL_BLEND); - if (r_skyalpha.value < 1.0) - glColor4f (1, 1, 1, r_skyalpha.value); + if(r_skyalpha.value < 1.0) + glColor4f(1, 1, 1, r_skyalpha.value); - glBegin (GL_QUADS); - for (i=0, v=p->verts[0] ; i<4 ; i++, v+=VERTEXSIZE) + glBegin(GL_QUADS); + for(i = 0, v = p->verts[0] ; i < 4 ; i++, v += VERTEXSIZE) { - Sky_GetTexCoord (v, 16, &s, &t); - glTexCoord2f (s, t); - glVertex3fv (v); + Sky_GetTexCoord(v, 16, &s, &t); + glTexCoord2f(s, t); + glVertex3fv(v); } - glEnd (); + glEnd(); - glDisable (GL_BLEND); + glDisable(GL_BLEND); rs_skypolys++; rs_skypasses += 2; } - if (Fog_GetDensity() > 0 && skyfog > 0) + if(Fog_GetDensity() > 0 && skyfog > 0) { float *c; c = Fog_GetColor(); - glEnable (GL_BLEND); - glDisable (GL_TEXTURE_2D); - glColor4f (c[0],c[1],c[2], CLAMP(0.0,skyfog,1.0)); + glEnable(GL_BLEND); + glDisable(GL_TEXTURE_2D); + glColor4f(c[0], c[1], c[2], CLAMP(0.0, skyfog, 1.0)); - glBegin (GL_QUADS); - for (i=0, v=p->verts[0] ; i<4 ; i++, v+=VERTEXSIZE) - glVertex3fv (v); - glEnd (); + glBegin(GL_QUADS); + for(i = 0, v = p->verts[0] ; i < 4 ; i++, v += VERTEXSIZE) + glVertex3fv(v); + glEnd(); - glColor3f (1, 1, 1); - glEnable (GL_TEXTURE_2D); - glDisable (GL_BLEND); + glColor3f(1, 1, 1); + glEnable(GL_TEXTURE_2D); + glDisable(GL_BLEND); rs_skypasses++; } @@ -896,56 +898,56 @@ Sky_DrawFace ============== */ -void Sky_DrawFace (int32_t axis) +void Sky_DrawFace(int32_t axis) { - glpoly_t *p; - vec3_t verts[4]; - int32_t i, j, start; - float di,qi,dj,qj; - vec3_t vup, vright, temp, temp2; + glpoly_t *p; + vec3_t verts[4]; + int32_t i, j, start; + float di, qi, dj, qj; + vec3_t vup, vright, temp, temp2; Sky_SetBoxVert(-1.0, -1.0, axis, verts[0]); Sky_SetBoxVert(-1.0, 1.0, axis, verts[1]); Sky_SetBoxVert(1.0, 1.0, axis, verts[2]); Sky_SetBoxVert(1.0, -1.0, axis, verts[3]); - start = Hunk_LowMark (); + start = Hunk_LowMark(); p = (glpoly_t *) Hunk_Alloc(sizeof(glpoly_t)); - VectorSubtract(verts[2],verts[3],vup); - VectorSubtract(verts[2],verts[1],vright); + VectorSubtract(verts[2], verts[3], vup); + VectorSubtract(verts[2], verts[1], vright); di = q_max((int32_t)r_sky_quality.value, 1); qi = 1.0 / di; - dj = (axis < 4) ? di*2 : di; //subdivide vertically more than horizontally on skybox sides + dj = (axis < 4) ? di * 2 : di; //subdivide vertically more than horizontally on skybox sides qj = 1.0 / dj; - for (i=0; i skymaxs[0][axis]/2+0.5 || - j*qj < skymins[1][axis]/2+0.5 - qj || j*qj > skymaxs[1][axis]/2+0.5) + if(i * qi < skymins[0][axis] / 2 + 0.5 - qi || i * qi > skymaxs[0][axis] / 2 + 0.5 || + j * qj < skymins[1][axis] / 2 + 0.5 - qj || j * qj > skymaxs[1][axis] / 2 + 0.5) continue; //if (i&1 ^ j&1) continue; //checkerboard test - VectorScale (vright, qi*i, temp); - VectorScale (vup, qj*j, temp2); - VectorAdd(temp,temp2,temp); - VectorAdd(verts[0],temp,p->verts[0]); + VectorScale(vright, qi * i, temp); + VectorScale(vup, qj * j, temp2); + VectorAdd(temp, temp2, temp); + VectorAdd(verts[0], temp, p->verts[0]); - VectorScale (vup, qj, temp); - VectorAdd (p->verts[0],temp,p->verts[1]); + VectorScale(vup, qj, temp); + VectorAdd(p->verts[0], temp, p->verts[1]); - VectorScale (vright, qi, temp); - VectorAdd (p->verts[1],temp,p->verts[2]); + VectorScale(vright, qi, temp); + VectorAdd(p->verts[1], temp, p->verts[2]); - VectorAdd (p->verts[0],temp,p->verts[3]); + VectorAdd(p->verts[0], temp, p->verts[3]); - Sky_DrawFaceQuad (p); + Sky_DrawFaceQuad(p); } } - Hunk_FreeToLowMark (start); + Hunk_FreeToLowMark(start); } /* @@ -955,18 +957,18 @@ Sky_DrawSkyLayers draws the old-style scrolling cloud layers ============== */ -void Sky_DrawSkyLayers (void) +void Sky_DrawSkyLayers(void) { int32_t i; - if (r_skyalpha.value < 1.0) + if(r_skyalpha.value < 1.0) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - for (i=0 ; i<6 ; i++) - if (skymins[0][i] < skymaxs[0][i] && skymins[1][i] < skymaxs[1][i]) - Sky_DrawFace (i); + for(i = 0 ; i < 6 ; i++) + if(skymins[0][i] < skymaxs[0][i] && skymins[1][i] < skymaxs[1][i]) + Sky_DrawFace(i); - if (r_skyalpha.value < 1.0) + if(r_skyalpha.value < 1.0) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } @@ -977,18 +979,18 @@ Sky_DrawSky called once per frame before drawing anything else ============== */ -void Sky_DrawSky (void) +void Sky_DrawSky(void) { - int32_t i; + int32_t i; //in these special render modes, the sky faces are handled in the normal world/brush renderer - if (r_drawflat_cheatsafe || r_lightmap_cheatsafe ) + if(r_drawflat_cheatsafe || r_lightmap_cheatsafe) return; // // reset sky bounds // - for (i=0 ; i<6 ; i++) + for(i = 0 ; i < 6 ; i++) { skymins[0][i] = skymins[1][i] = 9999; skymaxs[0][i] = skymaxs[1][i] = -9999; @@ -997,27 +999,27 @@ void Sky_DrawSky (void) // // process world and bmodels: draw flat-shaded sky surfs, and update skybounds // - Fog_DisableGFog (); - glDisable (GL_TEXTURE_2D); - if (Fog_GetDensity() > 0) - glColor3fv (Fog_GetColor()); + Fog_DisableGFog(); + glDisable(GL_TEXTURE_2D); + if(Fog_GetDensity() > 0) + glColor3fv(Fog_GetColor()); else - glColor3fv (skyflatcolor); - Sky_ProcessTextureChains (); - Sky_ProcessEntities (); - glColor3f (1, 1, 1); - glEnable (GL_TEXTURE_2D); + glColor3fv(skyflatcolor); + Sky_ProcessTextureChains(); + Sky_ProcessEntities(); + glColor3f(1, 1, 1); + glEnable(GL_TEXTURE_2D); // // render slow sky: cloud layers or skybox // - if (!r_fastsky.value && !(Fog_GetDensity() > 0 && skyfog >= 1)) + if(!r_fastsky.value && !(Fog_GetDensity() > 0 && skyfog >= 1)) { glDepthFunc(GL_GEQUAL); glDepthMask(0); - if (skybox_name[0]) - Sky_DrawSkyBox (); + if(skybox_name[0]) + Sky_DrawSkyBox(); else Sky_DrawSkyLayers(); @@ -1025,5 +1027,5 @@ void Sky_DrawSky (void) glDepthFunc(GL_LEQUAL); } - Fog_EnableGFog (); + Fog_EnableGFog(); } diff --git a/source/gl_texmgr.c b/source/gl_texmgr.c index d17b232..fcf65a3 100644 --- a/source/gl_texmgr.c +++ b/source/gl_texmgr.c @@ -24,19 +24,19 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -const int32_t gl_solid_format = 3; -const int32_t gl_alpha_format = 4; +const int32_t gl_solid_format = 3; +const int32_t gl_alpha_format = 4; -static cvar_t gl_texturemode = {"gl_texturemode", "", CVAR_ARCHIVE}; -static cvar_t gl_texture_anisotropy = {"gl_texture_anisotropy", "1", CVAR_ARCHIVE}; -static cvar_t gl_max_size = {"gl_max_size", "0", CVAR_NONE}; -static cvar_t gl_picmip = {"gl_picmip", "0", CVAR_NONE}; -static GLint gl_hardware_maxsize; +static cvar_t gl_texturemode = {"gl_texturemode", "", CVAR_ARCHIVE}; +static cvar_t gl_texture_anisotropy = {"gl_texture_anisotropy", "1", CVAR_ARCHIVE}; +static cvar_t gl_max_size = {"gl_max_size", "0", CVAR_NONE}; +static cvar_t gl_picmip = {"gl_picmip", "0", CVAR_NONE}; +static GLint gl_hardware_maxsize; -#define MAX_GLTEXTURES 2048 +#define MAX_GLTEXTURES 2048 static int32_t numgltextures; -static gltexture_t *active_gltextures, *free_gltextures; -gltexture_t *notexture, *nulltexture; +static gltexture_t *active_gltextures, *free_gltextures; +gltexture_t *notexture, *nulltexture; uint32_t d_8to24table[256]; uint32_t d_8to24table_fbright[256]; @@ -50,24 +50,25 @@ uint32_t d_8to24table_pants[256]; /* ================================================================================ - COMMANDS + COMMANDS ================================================================================ */ typedef struct { - int32_t magfilter; - int32_t minfilter; + int32_t magfilter; + int32_t minfilter; const char *name; } glmode_t; -static glmode_t glmodes[] = { - {GL_NEAREST, GL_NEAREST, "GL_NEAREST"}, - {GL_NEAREST, GL_NEAREST_MIPMAP_NEAREST, "GL_NEAREST_MIPMAP_NEAREST"}, - {GL_NEAREST, GL_NEAREST_MIPMAP_LINEAR, "GL_NEAREST_MIPMAP_LINEAR"}, - {GL_LINEAR, GL_LINEAR, "GL_LINEAR"}, - {GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, "GL_LINEAR_MIPMAP_NEAREST"}, - {GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, "GL_LINEAR_MIPMAP_LINEAR"}, +static glmode_t glmodes[] = +{ + {GL_NEAREST, GL_NEAREST, "GL_NEAREST"}, + {GL_NEAREST, GL_NEAREST_MIPMAP_NEAREST, "GL_NEAREST_MIPMAP_NEAREST"}, + {GL_NEAREST, GL_NEAREST_MIPMAP_LINEAR, "GL_NEAREST_MIPMAP_LINEAR"}, + {GL_LINEAR, GL_LINEAR, "GL_LINEAR"}, + {GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, "GL_LINEAR_MIPMAP_NEAREST"}, + {GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, "GL_LINEAR_MIPMAP_LINEAR"}, }; #define NUM_GLMODES (int32_t)(sizeof(glmodes)/sizeof(glmodes[0])) static int32_t glmode_idx = NUM_GLMODES - 1; /* trilinear */ @@ -77,14 +78,14 @@ static int32_t glmode_idx = NUM_GLMODES - 1; /* trilinear */ TexMgr_DescribeTextureModes_f -- report available texturemodes =============== */ -static void TexMgr_DescribeTextureModes_f (void) +static void TexMgr_DescribeTextureModes_f(void) { int32_t i; - for (i = 0; i < NUM_GLMODES; i++) - Con_SafePrintf (" %2" PRIi32 ": %s\n", i + 1, glmodes[i].name); + for(i = 0; i < NUM_GLMODES; i++) + Con_SafePrintf(" %2" PRIi32 ": %s\n", i + 1, glmodes[i].name); - Con_Printf ("%" PRIi32 " modes\n", i); + Con_Printf("%" PRIi32 " modes\n", i); } /* @@ -92,21 +93,21 @@ static void TexMgr_DescribeTextureModes_f (void) TexMgr_SetFilterModes =============== */ -static void TexMgr_SetFilterModes (gltexture_t *glt) +static void TexMgr_SetFilterModes(gltexture_t *glt) { - GL_Bind (glt); + GL_Bind(glt); - if (glt->flags & TEXPREF_NEAREST) + if(glt->flags & TEXPREF_NEAREST) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } - else if (glt->flags & TEXPREF_LINEAR) + else if(glt->flags & TEXPREF_LINEAR) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } - else if (glt->flags & TEXPREF_MIPMAP) + else if(glt->flags & TEXPREF_MIPMAP) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glmodes[glmode_idx].magfilter); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glmodes[glmode_idx].minfilter); @@ -124,47 +125,47 @@ static void TexMgr_SetFilterModes (gltexture_t *glt) TexMgr_TextureMode_f -- called when gl_texturemode changes =============== */ -static void TexMgr_TextureMode_f (cvar_t *var) +static void TexMgr_TextureMode_f(cvar_t *var) { - gltexture_t *glt; + gltexture_t *glt; int32_t i; (void)var; - for (i = 0; i < NUM_GLMODES; i++) + for(i = 0; i < NUM_GLMODES; i++) { - if (!Q_strcmp (glmodes[i].name, gl_texturemode.string)) + if(!Q_strcmp(glmodes[i].name, gl_texturemode.string)) { - if (glmode_idx != i) + if(glmode_idx != i) { glmode_idx = i; - for (glt = active_gltextures; glt; glt = glt->next) - TexMgr_SetFilterModes (glt); - Sbar_Changed (); //sbar graphics need to be redrawn with new filter mode + for(glt = active_gltextures; glt; glt = glt->next) + TexMgr_SetFilterModes(glt); + Sbar_Changed(); //sbar graphics need to be redrawn with new filter mode //FIXME: warpimages need to be redrawn, too. } return; } } - for (i = 0; i < NUM_GLMODES; i++) + for(i = 0; i < NUM_GLMODES; i++) { - if (!q_strcasecmp (glmodes[i].name, gl_texturemode.string)) + if(!q_strcasecmp(glmodes[i].name, gl_texturemode.string)) { - Cvar_SetQuick (&gl_texturemode, glmodes[i].name); + Cvar_SetQuick(&gl_texturemode, glmodes[i].name); return; } } i = atoi(gl_texturemode.string); - if (i >= 1 && i <= NUM_GLMODES) + if(i >= 1 && i <= NUM_GLMODES) { - Cvar_SetQuick (&gl_texturemode, glmodes[i-1].name); + Cvar_SetQuick(&gl_texturemode, glmodes[i - 1].name); return; } - Con_Printf ("\"%s\" is not a valid texturemode\n", gl_texturemode.string); - Cvar_SetQuick (&gl_texturemode, glmodes[glmode_idx].name); + Con_Printf("\"%s\" is not a valid texturemode\n", gl_texturemode.string); + Cvar_SetQuick(&gl_texturemode, glmodes[glmode_idx].name); } /* @@ -172,29 +173,30 @@ static void TexMgr_TextureMode_f (cvar_t *var) TexMgr_Anisotropy_f -- called when gl_texture_anisotropy changes =============== */ -static void TexMgr_Anisotropy_f (cvar_t *var) +static void TexMgr_Anisotropy_f(cvar_t *var) { (void)var; - if (gl_texture_anisotropy.value < 1) + if(gl_texture_anisotropy.value < 1) { - Cvar_SetQuick (&gl_texture_anisotropy, "1"); + Cvar_SetQuick(&gl_texture_anisotropy, "1"); } - else if (gl_texture_anisotropy.value > gl_max_anisotropy) + else if(gl_texture_anisotropy.value > gl_max_anisotropy) { - Cvar_SetValueQuick (&gl_texture_anisotropy, gl_max_anisotropy); + Cvar_SetValueQuick(&gl_texture_anisotropy, gl_max_anisotropy); } else { - gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) + gltexture_t *glt; + for(glt = active_gltextures; glt; glt = glt->next) { - /* TexMgr_SetFilterModes (glt);*/ - if (glt->flags & TEXPREF_MIPMAP) { - GL_Bind (glt); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glmodes[glmode_idx].magfilter); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glmodes[glmode_idx].minfilter); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_anisotropy.value); - } + /* TexMgr_SetFilterModes (glt);*/ + if(glt->flags & TEXPREF_MIPMAP) + { + GL_Bind(glt); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glmodes[glmode_idx].magfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glmodes[glmode_idx].minfilter); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_texture_anisotropy.value); + } } } } @@ -204,23 +206,23 @@ static void TexMgr_Anisotropy_f (cvar_t *var) TexMgr_Imagelist_f -- report loaded textures =============== */ -static void TexMgr_Imagelist_f (void) +static void TexMgr_Imagelist_f(void) { float mb; float texels = 0; - gltexture_t *glt; + gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) + for(glt = active_gltextures; glt; glt = glt->next) { - Con_SafePrintf (" %4" PRIi32 " x%4" PRIi32 " %s\n", glt->width, glt->height, glt->name); - if (glt->flags & TEXPREF_MIPMAP) + Con_SafePrintf(" %4" PRIi32 " x%4" PRIi32 " %s\n", glt->width, glt->height, glt->name); + if(glt->flags & TEXPREF_MIPMAP) texels += glt->width * glt->height * 4.0f / 3.0f; else texels += (glt->width * glt->height); } mb = texels * (Cvar_VariableValue("vid_bpp") / 8.0f) / 0x100000; - Con_Printf ("%" PRIi32 " textures %" PRIi32 " pixels %1.1f megabytes\n", numgltextures, (int32_t)texels, mb); + Con_Printf("%" PRIi32 " textures %" PRIi32 " pixels %1.1f megabytes\n", numgltextures, (int32_t)texels, mb); } /* @@ -228,45 +230,45 @@ static void TexMgr_Imagelist_f (void) TexMgr_Imagedump_f -- dump all current textures to TGA files =============== */ -static void TexMgr_Imagedump_f (void) +static void TexMgr_Imagedump_f(void) { char tganame[MAX_OSPATH], tempname[MAX_OSPATH], dirname[MAX_OSPATH]; - gltexture_t *glt; + gltexture_t *glt; byte *buffer; char *c; //create directory q_snprintf(dirname, sizeof(dirname), "%s/imagedump", com_gamedir); - Sys_mkdir (dirname); + Sys_mkdir(dirname); //loop through textures - for (glt = active_gltextures; glt; glt = glt->next) + for(glt = active_gltextures; glt; glt = glt->next) { - q_strlcpy (tempname, glt->name, sizeof(tempname)); - while ( (c = strchr(tempname, ':')) ) *c = '_'; - while ( (c = strchr(tempname, '/')) ) *c = '_'; - while ( (c = strchr(tempname, '*')) ) *c = '_'; + q_strlcpy(tempname, glt->name, sizeof(tempname)); + while((c = strchr(tempname, ':'))) * c = '_'; + while((c = strchr(tempname, '/'))) * c = '_'; + while((c = strchr(tempname, '*'))) * c = '_'; q_snprintf(tganame, sizeof(tganame), "imagedump/%s.tga", tempname); - GL_Bind (glt); - glPixelStorei (GL_PACK_ALIGNMENT, 1);/* for widths that aren't a multiple of 4 */ + GL_Bind(glt); + glPixelStorei(GL_PACK_ALIGNMENT, 1); /* for widths that aren't a multiple of 4 */ - if (glt->flags & TEXPREF_ALPHA) + if(glt->flags & TEXPREF_ALPHA) { - buffer = (byte *) malloc(glt->width*glt->height*4); + buffer = (byte *) malloc(glt->width * glt->height * 4); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - Image_WriteTGA (tganame, buffer, glt->width, glt->height, 32, true); + Image_WriteTGA(tganame, buffer, glt->width, glt->height, 32, true); } else { - buffer = (byte *) malloc(glt->width*glt->height*3); + buffer = (byte *) malloc(glt->width * glt->height * 3); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer); - Image_WriteTGA (tganame, buffer, glt->width, glt->height, 24, true); + Image_WriteTGA(tganame, buffer, glt->width, glt->height, 24, true); } - free (buffer); + free(buffer); } - Con_Printf ("dumped %" PRIi32 " textures to %s\n", numgltextures, dirname); + Con_Printf("dumped %" PRIi32 " textures to %s\n", numgltextures, dirname); } /* @@ -274,17 +276,17 @@ static void TexMgr_Imagedump_f (void) TexMgr_FrameUsage -- report texture memory usage for this frame =============== */ -float TexMgr_FrameUsage (void) +float TexMgr_FrameUsage(void) { float mb; float texels = 0; - gltexture_t *glt; + gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) + for(glt = active_gltextures; glt; glt = glt->next) { - if (glt->visframe == r_framecount) + if(glt->visframe == r_framecount) { - if (glt->flags & TEXPREF_MIPMAP) + if(glt->flags & TEXPREF_MIPMAP) texels += glt->width * glt->height * 4.0f / 3.0f; else texels += (glt->width * glt->height); @@ -298,7 +300,7 @@ float TexMgr_FrameUsage (void) /* ================================================================================ - TEXTURE MANAGER + TEXTURE MANAGER ================================================================================ */ @@ -308,15 +310,15 @@ float TexMgr_FrameUsage (void) TexMgr_FindTexture ================ */ -gltexture_t *TexMgr_FindTexture (qmodel_t *owner, const char *name) +gltexture_t *TexMgr_FindTexture(qmodel_t *owner, const char *name) { - gltexture_t *glt; + gltexture_t *glt; - if (name) + if(name) { - for (glt = active_gltextures; glt; glt = glt->next) + for(glt = active_gltextures; glt; glt = glt->next) { - if (glt->owner == owner && !strcmp (glt->name, name)) + if(glt->owner == owner && !strcmp(glt->name, name)) return glt; } } @@ -329,11 +331,11 @@ gltexture_t *TexMgr_FindTexture (qmodel_t *owner, const char *name) TexMgr_NewTexture ================ */ -gltexture_t *TexMgr_NewTexture (void) +gltexture_t *TexMgr_NewTexture(void) { gltexture_t *glt; - if (numgltextures == MAX_GLTEXTURES) + if(numgltextures == MAX_GLTEXTURES) Sys_Error("numgltextures == MAX_GLTEXTURES\n"); glt = free_gltextures; @@ -346,7 +348,7 @@ gltexture_t *TexMgr_NewTexture (void) return glt; } -static void GL_DeleteTexture (gltexture_t *texture); +static void GL_DeleteTexture(gltexture_t *texture); //ericw -- workaround for preventing TexMgr_FreeTexture during TexMgr_ReloadImages static bool in_reload_images; @@ -356,20 +358,20 @@ static bool in_reload_images; TexMgr_FreeTexture ================ */ -void TexMgr_FreeTexture (gltexture_t *kill) +void TexMgr_FreeTexture(gltexture_t *kill) { gltexture_t *glt; - if (in_reload_images) + if(in_reload_images) return; - if (kill == NULL) + if(kill == NULL) { - Con_Printf ("TexMgr_FreeTexture: NULL texture\n"); + Con_Printf("TexMgr_FreeTexture: NULL texture\n"); return; } - if (active_gltextures == kill) + if(active_gltextures == kill) { active_gltextures = kill->next; kill->next = free_gltextures; @@ -380,9 +382,9 @@ void TexMgr_FreeTexture (gltexture_t *kill) return; } - for (glt = active_gltextures; glt; glt = glt->next) + for(glt = active_gltextures; glt; glt = glt->next) { - if (glt->next == kill) + if(glt->next == kill) { glt->next = kill->next; kill->next = free_gltextures; @@ -394,7 +396,7 @@ void TexMgr_FreeTexture (gltexture_t *kill) } } - Con_Printf ("TexMgr_FreeTexture: not found\n"); + Con_Printf("TexMgr_FreeTexture: not found\n"); } /* @@ -404,15 +406,15 @@ TexMgr_FreeTextures compares each bit in "flags" to the one in glt->flags only if that bit is active in "mask" ================ */ -void TexMgr_FreeTextures (uint32_t flags, uint32_t mask) +void TexMgr_FreeTextures(uint32_t flags, uint32_t mask) { gltexture_t *glt, *next; - for (glt = active_gltextures; glt; glt = next) + for(glt = active_gltextures; glt; glt = next) { next = glt->next; - if ((glt->flags & mask) == (flags & mask)) - TexMgr_FreeTexture (glt); + if((glt->flags & mask) == (flags & mask)) + TexMgr_FreeTexture(glt); } } @@ -421,15 +423,15 @@ void TexMgr_FreeTextures (uint32_t flags, uint32_t mask) TexMgr_FreeTexturesForOwner ================ */ -void TexMgr_FreeTexturesForOwner (qmodel_t *owner) +void TexMgr_FreeTexturesForOwner(qmodel_t *owner) { gltexture_t *glt, *next; - for (glt = active_gltextures; glt; glt = next) + for(glt = active_gltextures; glt; glt = next) { next = glt->next; - if (glt && glt->owner == owner) - TexMgr_FreeTexture (glt); + if(glt && glt->owner == owner) + TexMgr_FreeTexture(glt); } } @@ -438,20 +440,20 @@ void TexMgr_FreeTexturesForOwner (qmodel_t *owner) TexMgr_DeleteTextureObjects ================ */ -void TexMgr_DeleteTextureObjects (void) +void TexMgr_DeleteTextureObjects(void) { gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) + for(glt = active_gltextures; glt; glt = glt->next) { - GL_DeleteTexture (glt); + GL_DeleteTexture(glt); } } /* ================================================================================ - INIT + INIT ================================================================================ */ @@ -461,25 +463,25 @@ void TexMgr_DeleteTextureObjects (void) TexMgr_LoadPalette -- johnfitz -- was VID_SetPalette, moved here, renamed, rewritten ================= */ -void TexMgr_LoadPalette (void) +void TexMgr_LoadPalette(void) { byte *pal, *src, *dst; int32_t i, mark; FILE *f; - COM_FOpenFile ("gfx/palette.lmp", &f, NULL); - if (!f) - Sys_Error ("Couldn't load gfx/palette.lmp"); + COM_FOpenFile("gfx/palette.lmp", &f, NULL); + if(!f) + Sys_Error("Couldn't load gfx/palette.lmp"); - mark = Hunk_LowMark (); - pal = (byte *) Hunk_Alloc (768); - fread (pal, 1, 768, f); + mark = Hunk_LowMark(); + pal = (byte *) Hunk_Alloc(768); + fread(pal, 1, 768, f); fclose(f); //standard palette, 255 is transparent dst = (byte *)d_8to24table; src = pal; - for (i = 0; i < 256; i++) + for(i = 0; i < 256; i++) { *dst++ = *src++; *dst++ = *src++; @@ -489,16 +491,16 @@ void TexMgr_LoadPalette (void) ((byte *) &d_8to24table[255]) [3] = 0; //fullbright palette, 0-223 are black (for additive blending) - src = pal + 224*3; + src = pal + 224 * 3; dst = (byte *) &d_8to24table_fbright[224]; - for (i = 224; i < 256; i++) + for(i = 224; i < 256; i++) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = 255; } - for (i = 0; i < 224; i++) + for(i = 0; i < 224; i++) { dst = (byte *) &d_8to24table_fbright[i]; dst[3] = 255; @@ -508,14 +510,14 @@ void TexMgr_LoadPalette (void) //nobright palette, 224-255 are black (for additive blending) dst = (byte *)d_8to24table_nobright; src = pal; - for (i = 0; i < 256; i++) + for(i = 0; i < 256; i++) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = 255; } - for (i = 224; i < 256; i++) + for(i = 224; i < 256; i++) { dst = (byte *) &d_8to24table_nobright[i]; dst[3] = 255; @@ -523,18 +525,18 @@ void TexMgr_LoadPalette (void) } //fullbright palette, for fence textures - memcpy(d_8to24table_fbright_fence, d_8to24table_fbright, 256*4); + memcpy(d_8to24table_fbright_fence, d_8to24table_fbright, 256 * 4); d_8to24table_fbright_fence[255] = 0; // Alpha of zero. //nobright palette, for fence textures - memcpy(d_8to24table_nobright_fence, d_8to24table_nobright, 256*4); + memcpy(d_8to24table_nobright_fence, d_8to24table_nobright, 256 * 4); d_8to24table_nobright_fence[255] = 0; // Alpha of zero. //conchars palette, 0 and 255 are transparent - memcpy(d_8to24table_conchars, d_8to24table, 256*4); + memcpy(d_8to24table_conchars, d_8to24table, 256 * 4); ((byte *) &d_8to24table_conchars[0]) [3] = 0; - Hunk_FreeToLowMark (mark); + Hunk_FreeToLowMark(mark); } /* @@ -542,10 +544,10 @@ void TexMgr_LoadPalette (void) TexMgr_NewGame ================ */ -void TexMgr_NewGame (void) +void TexMgr_NewGame(void) { - TexMgr_FreeTextures (0, TEXPREF_PERSIST); //deletes all textures where TEXPREF_PERSIST is unset - TexMgr_LoadPalette (); + TexMgr_FreeTextures(0, TEXPREF_PERSIST); //deletes all textures where TEXPREF_PERSIST is unset + TexMgr_LoadPalette(); } /* @@ -555,21 +557,21 @@ TexMgr_RecalcWarpImageSize -- called during init, and after a vid_restart choose safe warpimage size and resize existing warpimage textures ============= */ -void TexMgr_RecalcWarpImageSize (void) +void TexMgr_RecalcWarpImageSize(void) { -// int32_t oldsize = gl_warpimagesize; - int32_t mark; +// int32_t oldsize = gl_warpimagesize; + int32_t mark; gltexture_t *glt; byte *dummy; // // find the new correct size // - gl_warpimagesize = TexMgr_SafeTextureSize (512); + gl_warpimagesize = TexMgr_SafeTextureSize(512); - while (gl_warpimagesize > vid.width) + while(gl_warpimagesize > vid.width) gl_warpimagesize >>= 1; - while (gl_warpimagesize > vid.height) + while(gl_warpimagesize > vid.height) gl_warpimagesize >>= 1; // ericw -- removed early exit if (gl_warpimagesize == oldsize). @@ -581,19 +583,19 @@ void TexMgr_RecalcWarpImageSize (void) // resize the textures in opengl // mark = Hunk_LowMark(); - dummy = (byte *) Hunk_Alloc (gl_warpimagesize*gl_warpimagesize*4); + dummy = (byte *) Hunk_Alloc(gl_warpimagesize * gl_warpimagesize * 4); - for (glt = active_gltextures; glt; glt = glt->next) + for(glt = active_gltextures; glt; glt = glt->next) { - if (glt->flags & TEXPREF_WARPIMAGE) + if(glt->flags & TEXPREF_WARPIMAGE) { - GL_Bind (glt); - glTexImage2D (GL_TEXTURE_2D, 0, gl_solid_format, gl_warpimagesize, gl_warpimagesize, 0, GL_RGBA, GL_UNSIGNED_BYTE, dummy); + GL_Bind(glt); + glTexImage2D(GL_TEXTURE_2D, 0, gl_solid_format, gl_warpimagesize, gl_warpimagesize, 0, GL_RGBA, GL_UNSIGNED_BYTE, dummy); glt->width = glt->height = gl_warpimagesize; } } - Hunk_FreeToLowMark (mark); + Hunk_FreeToLowMark(mark); } /* @@ -603,54 +605,54 @@ TexMgr_Init must be called before any texture loading ================ */ -void TexMgr_Init (void) +void TexMgr_Init(void) { int32_t i; - static byte notexture_data[16] = {159,91,83,255,0,0,0,255,0,0,0,255,159,91,83,255}; //black and pink checker - static byte nulltexture_data[16] = {127,191,255,255,0,0,0,255,0,0,0,255,127,191,255,255}; //black and blue checker + static byte notexture_data[16] = {159, 91, 83, 255, 0, 0, 0, 255, 0, 0, 0, 255, 159, 91, 83, 255}; //black and pink checker + static byte nulltexture_data[16] = {127, 191, 255, 255, 0, 0, 0, 255, 0, 0, 0, 255, 127, 191, 255, 255}; //black and blue checker extern texture_t *r_notexture_mip, *r_notexture_mip2; // init texture list - free_gltextures = (gltexture_t *) Hunk_AllocName (MAX_GLTEXTURES * sizeof(gltexture_t), "gltextures"); + free_gltextures = (gltexture_t *) Hunk_AllocName(MAX_GLTEXTURES * sizeof(gltexture_t), "gltextures"); active_gltextures = NULL; - for (i = 0; i < MAX_GLTEXTURES - 1; i++) - free_gltextures[i].next = &free_gltextures[i+1]; + for(i = 0; i < MAX_GLTEXTURES - 1; i++) + free_gltextures[i].next = &free_gltextures[i + 1]; free_gltextures[i].next = NULL; numgltextures = 0; // palette - TexMgr_LoadPalette (); + TexMgr_LoadPalette(); - Cvar_RegisterVariable (&gl_max_size); - Cvar_RegisterVariable (&gl_picmip); - Cvar_RegisterVariable (&gl_texture_anisotropy); - Cvar_SetCallback (&gl_texture_anisotropy, &TexMgr_Anisotropy_f); + Cvar_RegisterVariable(&gl_max_size); + Cvar_RegisterVariable(&gl_picmip); + Cvar_RegisterVariable(&gl_texture_anisotropy); + Cvar_SetCallback(&gl_texture_anisotropy, &TexMgr_Anisotropy_f); gl_texturemode.string = glmodes[glmode_idx].name; - Cvar_RegisterVariable (&gl_texturemode); - Cvar_SetCallback (&gl_texturemode, &TexMgr_TextureMode_f); - Cmd_AddCommand ("gl_describetexturemodes", &TexMgr_DescribeTextureModes_f); - Cmd_AddCommand ("imagelist", &TexMgr_Imagelist_f); - Cmd_AddCommand ("imagedump", &TexMgr_Imagedump_f); + Cvar_RegisterVariable(&gl_texturemode); + Cvar_SetCallback(&gl_texturemode, &TexMgr_TextureMode_f); + Cmd_AddCommand("gl_describetexturemodes", &TexMgr_DescribeTextureModes_f); + Cmd_AddCommand("imagelist", &TexMgr_Imagelist_f); + Cmd_AddCommand("imagedump", &TexMgr_Imagedump_f); // poll max size from hardware - glGetIntegerv (GL_MAX_TEXTURE_SIZE, &gl_hardware_maxsize); + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl_hardware_maxsize); // load notexture images - notexture = TexMgr_LoadImage (NULL, "notexture", 2, 2, SRC_RGBA, notexture_data, "", (src_offset_t)notexture_data, TEXPREF_NEAREST | TEXPREF_PERSIST | TEXPREF_NOPICMIP); - nulltexture = TexMgr_LoadImage (NULL, "nulltexture", 2, 2, SRC_RGBA, nulltexture_data, "", (src_offset_t)nulltexture_data, TEXPREF_NEAREST | TEXPREF_PERSIST | TEXPREF_NOPICMIP); + notexture = TexMgr_LoadImage(NULL, "notexture", 2, 2, SRC_RGBA, notexture_data, "", (src_offset_t)notexture_data, TEXPREF_NEAREST | TEXPREF_PERSIST | TEXPREF_NOPICMIP); + nulltexture = TexMgr_LoadImage(NULL, "nulltexture", 2, 2, SRC_RGBA, nulltexture_data, "", (src_offset_t)nulltexture_data, TEXPREF_NEAREST | TEXPREF_PERSIST | TEXPREF_NOPICMIP); //have to assign these here becuase Mod_Init is called before TexMgr_Init r_notexture_mip->gltexture = r_notexture_mip2->gltexture = notexture; //set safe size for warpimages gl_warpimagesize = 0; - TexMgr_RecalcWarpImageSize (); + TexMgr_RecalcWarpImageSize(); } /* ================================================================================ - IMAGE LOADING + IMAGE LOADING ================================================================================ */ @@ -660,10 +662,10 @@ void TexMgr_Init (void) TexMgr_Pad -- return smallest power of two greater than or equal to s ================ */ -int32_t TexMgr_Pad (int32_t s) +int32_t TexMgr_Pad(int32_t s) { int32_t i; - for (i = 1; i < s; i<<=1) + for(i = 1; i < s; i <<= 1) ; return i; } @@ -673,11 +675,11 @@ int32_t TexMgr_Pad (int32_t s) TexMgr_SafeTextureSize -- return a size with hardware and user prefs in mind =============== */ -int32_t TexMgr_SafeTextureSize (int32_t s) +int32_t TexMgr_SafeTextureSize(int32_t s) { - if (!gl_texture_NPOT) + if(!gl_texture_NPOT) s = TexMgr_Pad(s); - if ((int32_t)gl_max_size.value > 0) + if((int32_t)gl_max_size.value > 0) s = q_min(TexMgr_Pad((int32_t)gl_max_size.value), s); s = q_min(gl_hardware_maxsize, s); return s; @@ -688,9 +690,9 @@ int32_t TexMgr_SafeTextureSize (int32_t s) TexMgr_PadConditional -- only pad if a texture of that size would be padded. (used for tex coords) ================ */ -int32_t TexMgr_PadConditional (int32_t s) +int32_t TexMgr_PadConditional(int32_t s) { - if (s < TexMgr_SafeTextureSize(s)) + if(s < TexMgr_SafeTextureSize(s)) return TexMgr_Pad(s); else return s; @@ -701,20 +703,20 @@ int32_t TexMgr_PadConditional (int32_t s) TexMgr_MipMapW ================ */ -static unsigned *TexMgr_MipMapW (unsigned *data, int32_t width, int32_t height) +static unsigned *TexMgr_MipMapW(unsigned *data, int32_t width, int32_t height) { - int32_t i, size; - byte *out, *in; + int32_t i, size; + byte *out, *in; out = in = (byte *)data; - size = (width*height)>>1; + size = (width * height) >> 1; - for (i = 0; i < size; i++, out += 4, in += 8) + for(i = 0; i < size; i++, out += 4, in += 8) { - out[0] = (in[0] + in[4])>>1; - out[1] = (in[1] + in[5])>>1; - out[2] = (in[2] + in[6])>>1; - out[3] = (in[3] + in[7])>>1; + out[0] = (in[0] + in[4]) >> 1; + out[1] = (in[1] + in[5]) >> 1; + out[2] = (in[2] + in[6]) >> 1; + out[3] = (in[3] + in[7]) >> 1; } return data; @@ -725,23 +727,23 @@ static unsigned *TexMgr_MipMapW (unsigned *data, int32_t width, int32_t height) TexMgr_MipMapH ================ */ -static unsigned *TexMgr_MipMapH (unsigned *data, int32_t width, int32_t height) +static unsigned *TexMgr_MipMapH(unsigned *data, int32_t width, int32_t height) { - int32_t i, j; - byte *out, *in; + int32_t i, j; + byte *out, *in; out = in = (byte *)data; - height>>=1; - width<<=2; + height >>= 1; + width <<= 2; - for (i = 0; i < height; i++, in += width) + for(i = 0; i < height; i++, in += width) { - for (j = 0; j < width; j += 4, out += 4, in += 4) + for(j = 0; j < width; j += 4, out += 4, in += 4) { - out[0] = (in[0] + in[width+0])>>1; - out[1] = (in[1] + in[width+1])>>1; - out[2] = (in[2] + in[width+2])>>1; - out[3] = (in[3] + in[width+3])>>1; + out[0] = (in[0] + in[width + 0]) >> 1; + out[1] = (in[1] + in[width + 1]) >> 1; + out[2] = (in[2] + in[width + 2]) >> 1; + out[3] = (in[3] + in[width + 3]) >> 1; } } @@ -753,48 +755,48 @@ static unsigned *TexMgr_MipMapH (unsigned *data, int32_t width, int32_t height) TexMgr_ResampleTexture -- bilinear resample ================ */ -static unsigned *TexMgr_ResampleTexture (unsigned *in, int32_t inwidth, int32_t inheight, bool alpha) +static unsigned *TexMgr_ResampleTexture(unsigned *in, int32_t inwidth, int32_t inheight, bool alpha) { byte *nwpx, *nepx, *swpx, *sepx, *dest; unsigned xfrac, yfrac, x, y, modx, mody, imodx, imody, injump, outjump; unsigned *out; int32_t i, j, outwidth, outheight; - if (inwidth == TexMgr_Pad(inwidth) && inheight == TexMgr_Pad(inheight)) + if(inwidth == TexMgr_Pad(inwidth) && inheight == TexMgr_Pad(inheight)) return in; outwidth = TexMgr_Pad(inwidth); outheight = TexMgr_Pad(inheight); - out = (unsigned *) Hunk_Alloc(outwidth*outheight*4); + out = (unsigned *) Hunk_Alloc(outwidth * outheight * 4); - xfrac = ((inwidth-1) << 16) / (outwidth-1); - yfrac = ((inheight-1) << 16) / (outheight-1); + xfrac = ((inwidth - 1) << 16) / (outwidth - 1); + yfrac = ((inheight - 1) << 16) / (outheight - 1); y = outjump = 0; - for (i = 0; i < outheight; i++) + for(i = 0; i < outheight; i++) { - mody = (y>>8) & 0xFF; + mody = (y >> 8) & 0xFF; imody = 256 - mody; - injump = (y>>16) * inwidth; + injump = (y >> 16) * inwidth; x = 0; - for (j = 0; j < outwidth; j++) + for(j = 0; j < outwidth; j++) { - modx = (x>>8) & 0xFF; + modx = (x >> 8) & 0xFF; imodx = 256 - modx; - nwpx = (byte *)(in + (x>>16) + injump); + nwpx = (byte *)(in + (x >> 16) + injump); nepx = nwpx + 4; - swpx = nwpx + inwidth*4; + swpx = nwpx + inwidth * 4; sepx = swpx + 4; dest = (byte *)(out + outjump + j); - dest[0] = (nwpx[0]*imodx*imody + nepx[0]*modx*imody + swpx[0]*imodx*mody + sepx[0]*modx*mody)>>16; - dest[1] = (nwpx[1]*imodx*imody + nepx[1]*modx*imody + swpx[1]*imodx*mody + sepx[1]*modx*mody)>>16; - dest[2] = (nwpx[2]*imodx*imody + nepx[2]*modx*imody + swpx[2]*imodx*mody + sepx[2]*modx*mody)>>16; - if (alpha) - dest[3] = (nwpx[3]*imodx*imody + nepx[3]*modx*imody + swpx[3]*imodx*mody + sepx[3]*modx*mody)>>16; + dest[0] = (nwpx[0] * imodx * imody + nepx[0] * modx * imody + swpx[0] * imodx * mody + sepx[0] * modx * mody) >> 16; + dest[1] = (nwpx[1] * imodx * imody + nepx[1] * modx * imody + swpx[1] * imodx * mody + sepx[1] * modx * mody) >> 16; + dest[2] = (nwpx[2] * imodx * imody + nepx[2] * modx * imody + swpx[2] * imodx * mody + sepx[2] * modx * mody) >> 16; + if(alpha) + dest[3] = (nwpx[3] * imodx * imody + nepx[3] * modx * imody + swpx[3] * imodx * mody + sepx[3] * modx * mody) >> 16; else dest[3] = 255; @@ -815,43 +817,99 @@ eliminate pink edges on sprites, etc. operates in place on 32bit data =============== */ -static void TexMgr_AlphaEdgeFix (byte *data, int32_t width, int32_t height) +static void TexMgr_AlphaEdgeFix(byte *data, int32_t width, int32_t height) { - int32_t i, j, n = 0, b, c[3] = {0,0,0}, - lastrow, thisrow, nextrow, - lastpix, thispix, nextpix; - byte *dest = data; + int32_t i, j, n = 0, b, c[3] = {0, 0, 0}, + lastrow, thisrow, nextrow, + lastpix, thispix, nextpix; + byte *dest = data; - for (i = 0; i < height; i++) + for(i = 0; i < height; i++) { - lastrow = width * 4 * ((i == 0) ? height-1 : i-1); + lastrow = width * 4 * ((i == 0) ? height - 1 : i - 1); thisrow = width * 4 * i; - nextrow = width * 4 * ((i == height-1) ? 0 : i+1); + nextrow = width * 4 * ((i == height - 1) ? 0 : i + 1); - for (j = 0; j < width; j++, dest += 4) + for(j = 0; j < width; j++, dest += 4) { - if (dest[3]) //not transparent + if(dest[3]) //not transparent continue; - lastpix = 4 * ((j == 0) ? width-1 : j-1); + lastpix = 4 * ((j == 0) ? width - 1 : j - 1); thispix = 4 * j; - nextpix = 4 * ((j == width-1) ? 0 : j+1); + nextpix = 4 * ((j == width - 1) ? 0 : j + 1); - b = lastrow + lastpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = thisrow + lastpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = nextrow + lastpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = lastrow + thispix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = nextrow + thispix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = lastrow + nextpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = thisrow + nextpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} - b = nextrow + nextpix; if (data[b+3]) {c[0] += data[b]; c[1] += data[b+1]; c[2] += data[b+2]; n++;} + b = lastrow + lastpix; + if(data[b + 3]) + { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = thisrow + lastpix; + if(data[b + 3]) + { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = nextrow + lastpix; + if(data[b + 3]) + { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = lastrow + thispix; + if(data[b + 3]) + { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = nextrow + thispix; + if(data[b + 3]) + { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = lastrow + nextpix; + if(data[b + 3]) + { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = thisrow + nextpix; + if(data[b + 3]) + { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } + b = nextrow + nextpix; + if(data[b + 3]) + { + c[0] += data[b]; + c[1] += data[b + 1]; + c[2] += data[b + 2]; + n++; + } //average all non-transparent neighbors - if (n) + if(n) { - dest[0] = (byte)(c[0]/n); - dest[1] = (byte)(c[1]/n); - dest[2] = (byte)(c[2]/n); + dest[0] = (byte)(c[0] / n); + dest[1] = (byte)(c[1] / n); + dest[2] = (byte)(c[2] / n); n = c[0] = c[1] = c[2] = 0; } @@ -866,7 +924,7 @@ TexMgr_PadEdgeFixW -- special case of AlphaEdgeFix for textures that only need i operates in place on 32bit data, and expects unpadded height and width values =============== */ -static void TexMgr_PadEdgeFixW (byte *data, int32_t width, int32_t height) +static void TexMgr_PadEdgeFixW(byte *data, int32_t width, int32_t height) { byte *src, *dst; int32_t i, padw, padh; @@ -876,7 +934,7 @@ static void TexMgr_PadEdgeFixW (byte *data, int32_t width, int32_t height) //copy last full column to first empty column, leaving alpha byte at zero src = data + (width - 1) * 4; - for (i = 0; i < padh; i++) + for(i = 0; i < padh; i++) { src[4] = src[0]; src[5] = src[1]; @@ -887,7 +945,7 @@ static void TexMgr_PadEdgeFixW (byte *data, int32_t width, int32_t height) //copy first full column to last empty column, leaving alpha byte at zero src = data; dst = data + (padw - 1) * 4; - for (i = 0; i < padh; i++) + for(i = 0; i < padh; i++) { dst[0] = src[0]; dst[1] = src[1]; @@ -904,7 +962,7 @@ TexMgr_PadEdgeFixH -- special case of AlphaEdgeFix for textures that only need i operates in place on 32bit data, and expects unpadded height and width values =============== */ -static void TexMgr_PadEdgeFixH (byte *data, int32_t width, int32_t height) +static void TexMgr_PadEdgeFixH(byte *data, int32_t width, int32_t height) { byte *src, *dst; int32_t i, padw, padh; @@ -915,7 +973,7 @@ static void TexMgr_PadEdgeFixH (byte *data, int32_t width, int32_t height) //copy last full row to first empty row, leaving alpha byte at zero dst = data + height * padw * 4; src = dst - padw * 4; - for (i = 0; i < padw; i++) + for(i = 0; i < padw; i++) { dst[0] = src[0]; dst[1] = src[1]; @@ -927,7 +985,7 @@ static void TexMgr_PadEdgeFixH (byte *data, int32_t width, int32_t height) //copy first full row to last empty row, leaving alpha byte at zero dst = data + (padh - 1) * padw * 4; src = data; - for (i = 0; i < padw; i++) + for(i = 0; i < padw; i++) { dst[0] = src[0]; dst[1] = src[1]; @@ -942,14 +1000,14 @@ static void TexMgr_PadEdgeFixH (byte *data, int32_t width, int32_t height) TexMgr_8to32 ================ */ -static unsigned *TexMgr_8to32 (byte *in, int32_t pixels, uint32_t *usepal) +static unsigned *TexMgr_8to32(byte *in, int32_t pixels, uint32_t *usepal) { int32_t i; unsigned *out, *data; - out = data = (unsigned *) Hunk_Alloc(pixels*4); + out = data = (unsigned *) Hunk_Alloc(pixels * 4); - for (i = 0; i < pixels; i++) + for(i = 0; i < pixels; i++) *out++ = usepal[*in++]; return data; @@ -960,23 +1018,23 @@ static unsigned *TexMgr_8to32 (byte *in, int32_t pixels, uint32_t *usepal) TexMgr_PadImageW -- return image with width padded up to power-of-two dimentions ================ */ -static byte *TexMgr_PadImageW (byte *in, int32_t width, int32_t height, byte padbyte) +static byte *TexMgr_PadImageW(byte *in, int32_t width, int32_t height, byte padbyte) { int32_t i, j, outwidth; byte *out, *data; - if (width == TexMgr_Pad(width)) + if(width == TexMgr_Pad(width)) return in; outwidth = TexMgr_Pad(width); - out = data = (byte *) Hunk_Alloc(outwidth*height); + out = data = (byte *) Hunk_Alloc(outwidth * height); - for (i = 0; i < height; i++) + for(i = 0; i < height; i++) { - for (j = 0; j < width; j++) + for(j = 0; j < width; j++) *out++ = *in++; - for ( ; j < outwidth; j++) + for(; j < outwidth; j++) *out++ = padbyte; } @@ -988,12 +1046,12 @@ static byte *TexMgr_PadImageW (byte *in, int32_t width, int32_t height, byte pad TexMgr_PadImageH -- return image with height padded up to power-of-two dimentions ================ */ -static byte *TexMgr_PadImageH (byte *in, int32_t width, int32_t height, byte padbyte) +static byte *TexMgr_PadImageH(byte *in, int32_t width, int32_t height, byte padbyte) { int32_t i, srcpix, dstpix; byte *data, *out; - if (height == TexMgr_Pad(height)) + if(height == TexMgr_Pad(height)) return in; srcpix = width * height; @@ -1001,9 +1059,9 @@ static byte *TexMgr_PadImageH (byte *in, int32_t width, int32_t height, byte pad out = data = (byte *) Hunk_Alloc(dstpix); - for (i = 0; i < srcpix; i++) + for(i = 0; i < srcpix; i++) *out++ = *in++; - for ( ; i < dstpix; i++) + for(; i < dstpix; i++) *out++ = padbyte; return data; @@ -1014,66 +1072,66 @@ static byte *TexMgr_PadImageH (byte *in, int32_t width, int32_t height, byte pad TexMgr_LoadImage32 -- handles 32bit source data ================ */ -static void TexMgr_LoadImage32 (gltexture_t *glt, unsigned *data) +static void TexMgr_LoadImage32(gltexture_t *glt, unsigned *data) { - int32_t internalformat, miplevel, mipwidth, mipheight, picmip; + int32_t internalformat, miplevel, mipwidth, mipheight, picmip; - if (!gl_texture_NPOT) + if(!gl_texture_NPOT) { // resample up - data = TexMgr_ResampleTexture (data, glt->width, glt->height, glt->flags & TEXPREF_ALPHA); + data = TexMgr_ResampleTexture(data, glt->width, glt->height, glt->flags & TEXPREF_ALPHA); glt->width = TexMgr_Pad(glt->width); glt->height = TexMgr_Pad(glt->height); } // mipmap down picmip = (glt->flags & TEXPREF_NOPICMIP) ? 0 : q_max((int32_t)gl_picmip.value, 0); - mipwidth = TexMgr_SafeTextureSize (glt->width >> picmip); - mipheight = TexMgr_SafeTextureSize (glt->height >> picmip); - while ((int32_t) glt->width > mipwidth) + mipwidth = TexMgr_SafeTextureSize(glt->width >> picmip); + mipheight = TexMgr_SafeTextureSize(glt->height >> picmip); + while((int32_t) glt->width > mipwidth) { - TexMgr_MipMapW (data, glt->width, glt->height); + TexMgr_MipMapW(data, glt->width, glt->height); glt->width >>= 1; - if (glt->flags & TEXPREF_ALPHA) - TexMgr_AlphaEdgeFix ((byte *)data, glt->width, glt->height); + if(glt->flags & TEXPREF_ALPHA) + TexMgr_AlphaEdgeFix((byte *)data, glt->width, glt->height); } - while ((int32_t) glt->height > mipheight) + while((int32_t) glt->height > mipheight) { - TexMgr_MipMapH (data, glt->width, glt->height); + TexMgr_MipMapH(data, glt->width, glt->height); glt->height >>= 1; - if (glt->flags & TEXPREF_ALPHA) - TexMgr_AlphaEdgeFix ((byte *)data, glt->width, glt->height); + if(glt->flags & TEXPREF_ALPHA) + TexMgr_AlphaEdgeFix((byte *)data, glt->width, glt->height); } // upload - GL_Bind (glt); + GL_Bind(glt); internalformat = (glt->flags & TEXPREF_ALPHA) ? gl_alpha_format : gl_solid_format; - glTexImage2D (GL_TEXTURE_2D, 0, internalformat, glt->width, glt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + glTexImage2D(GL_TEXTURE_2D, 0, internalformat, glt->width, glt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); // upload mipmaps - if (glt->flags & TEXPREF_MIPMAP) + if(glt->flags & TEXPREF_MIPMAP) { mipwidth = glt->width; mipheight = glt->height; - for (miplevel=1; mipwidth > 1 || mipheight > 1; miplevel++) + for(miplevel = 1; mipwidth > 1 || mipheight > 1; miplevel++) { - if (mipwidth > 1) + if(mipwidth > 1) { - TexMgr_MipMapW (data, mipwidth, mipheight); + TexMgr_MipMapW(data, mipwidth, mipheight); mipwidth >>= 1; } - if (mipheight > 1) + if(mipheight > 1) { - TexMgr_MipMapH (data, mipwidth, mipheight); + TexMgr_MipMapH(data, mipwidth, mipheight); mipheight >>= 1; } - glTexImage2D (GL_TEXTURE_2D, miplevel, internalformat, mipwidth, mipheight, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + glTexImage2D(GL_TEXTURE_2D, miplevel, internalformat, mipwidth, mipheight, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); } } // set filter modes - TexMgr_SetFilterModes (glt); + TexMgr_SetFilterModes(glt); } /* @@ -1081,7 +1139,7 @@ static void TexMgr_LoadImage32 (gltexture_t *glt, unsigned *data) TexMgr_LoadImage8 -- handles 8bit source data, then passes it to LoadImage32 ================ */ -static void TexMgr_LoadImage8 (gltexture_t *glt, byte *data) +static void TexMgr_LoadImage8(gltexture_t *glt, byte *data) { extern cvar_t gl_fullbrights; bool padw = false, padh = false; @@ -1090,44 +1148,44 @@ static void TexMgr_LoadImage8 (gltexture_t *glt, byte *data) int32_t i; // HACK HACK HACK -- taken from tomazquake - if (strstr(glt->name, "shot1sid") && - glt->width == 32 && glt->height == 32 && - CRC_Block(data, 1024) == 65393) + if(strstr(glt->name, "shot1sid") && + glt->width == 32 && glt->height == 32 && + CRC_Block(data, 1024) == 65393) { // This texture in b_shell1.bsp has some of the first 32 pixels painted white. // They are invisible in software, but look really ugly in GL. So we just copy // 32 pixels from the bottom to make it look nice. - memcpy (data, data + 32*31, 32); + memcpy(data, data + 32 * 31, 32); } // detect false alpha cases - if (glt->flags & TEXPREF_ALPHA && !(glt->flags & TEXPREF_CONCHARS)) + if(glt->flags & TEXPREF_ALPHA && !(glt->flags & TEXPREF_CONCHARS)) { - for (i = 0; i < (int32_t) (glt->width * glt->height); i++) - if (data[i] == 255) //transparent index + for(i = 0; i < (int32_t)(glt->width * glt->height); i++) + if(data[i] == 255) //transparent index break; - if (i == (int32_t) (glt->width * glt->height)) + if(i == (int32_t)(glt->width * glt->height)) glt->flags -= TEXPREF_ALPHA; } // choose palette and padbyte - if (glt->flags & TEXPREF_FULLBRIGHT) + if(glt->flags & TEXPREF_FULLBRIGHT) { - if (glt->flags & TEXPREF_ALPHA) + if(glt->flags & TEXPREF_ALPHA) usepal = d_8to24table_fbright_fence; else usepal = d_8to24table_fbright; padbyte = 0; } - else if (glt->flags & TEXPREF_NOBRIGHT && gl_fullbrights.value) + else if(glt->flags & TEXPREF_NOBRIGHT && gl_fullbrights.value) { - if (glt->flags & TEXPREF_ALPHA) + if(glt->flags & TEXPREF_ALPHA) usepal = d_8to24table_nobright_fence; else usepal = d_8to24table_nobright; padbyte = 0; } - else if (glt->flags & TEXPREF_CONCHARS) + else if(glt->flags & TEXPREF_CONCHARS) { usepal = d_8to24table_conchars; padbyte = 0; @@ -1139,17 +1197,17 @@ static void TexMgr_LoadImage8 (gltexture_t *glt, byte *data) } // pad each dimention, but only if it's not going to be downsampled later - if (glt->flags & TEXPREF_PAD) + if(glt->flags & TEXPREF_PAD) { - if ((int32_t) glt->width < TexMgr_SafeTextureSize(glt->width)) + if((int32_t) glt->width < TexMgr_SafeTextureSize(glt->width)) { - data = TexMgr_PadImageW (data, glt->width, glt->height, padbyte); + data = TexMgr_PadImageW(data, glt->width, glt->height, padbyte); glt->width = TexMgr_Pad(glt->width); padw = true; } - if ((int32_t) glt->height < TexMgr_SafeTextureSize(glt->height)) + if((int32_t) glt->height < TexMgr_SafeTextureSize(glt->height)) { - data = TexMgr_PadImageH (data, glt->width, glt->height, padbyte); + data = TexMgr_PadImageH(data, glt->width, glt->height, padbyte); glt->height = TexMgr_Pad(glt->height); padh = true; } @@ -1159,18 +1217,18 @@ static void TexMgr_LoadImage8 (gltexture_t *glt, byte *data) data = (byte *)TexMgr_8to32(data, glt->width * glt->height, usepal); // fix edges - if (glt->flags & TEXPREF_ALPHA) - TexMgr_AlphaEdgeFix (data, glt->width, glt->height); + if(glt->flags & TEXPREF_ALPHA) + TexMgr_AlphaEdgeFix(data, glt->width, glt->height); else { - if (padw) - TexMgr_PadEdgeFixW (data, glt->source_width, glt->source_height); - if (padh) - TexMgr_PadEdgeFixH (data, glt->source_width, glt->source_height); + if(padw) + TexMgr_PadEdgeFixW(data, glt->source_width, glt->source_height); + if(padh) + TexMgr_PadEdgeFixH(data, glt->source_width, glt->source_height); } // upload it - TexMgr_LoadImage32 (glt, (unsigned *)data); + TexMgr_LoadImage32(glt, (unsigned *)data); } /* @@ -1178,14 +1236,14 @@ static void TexMgr_LoadImage8 (gltexture_t *glt, byte *data) TexMgr_LoadLightmap -- handles lightmap data ================ */ -static void TexMgr_LoadLightmap (gltexture_t *glt, byte *data) +static void TexMgr_LoadLightmap(gltexture_t *glt, byte *data) { // upload it - GL_Bind (glt); - glTexImage2D (GL_TEXTURE_2D, 0, lightmap_bytes, glt->width, glt->height, 0, gl_lightmap_format, GL_UNSIGNED_BYTE, data); + GL_Bind(glt); + glTexImage2D(GL_TEXTURE_2D, 0, lightmap_bytes, glt->width, glt->height, 0, gl_lightmap_format, GL_UNSIGNED_BYTE, data); // set filter modes - TexMgr_SetFilterModes (glt); + TexMgr_SetFilterModes(glt); } /* @@ -1193,18 +1251,18 @@ static void TexMgr_LoadLightmap (gltexture_t *glt, byte *data) TexMgr_LoadImage -- the one entry point for loading all textures ================ */ -gltexture_t *TexMgr_LoadImage (qmodel_t *owner, const char *name, int32_t width, int32_t height, enum srcformat format, - byte *data, const char *source_file, src_offset_t source_offset, unsigned flags) +gltexture_t *TexMgr_LoadImage(qmodel_t *owner, const char *name, int32_t width, int32_t height, enum srcformat format, + byte *data, const char *source_file, src_offset_t source_offset, unsigned flags) { uint16_t crc; gltexture_t *glt; int32_t mark; - if (isDedicated) + if(isDedicated) return NULL; // cache check - switch (format) + switch(format) { case SRC_INDEXED: crc = CRC_Block(data, width * height); @@ -1218,23 +1276,23 @@ gltexture_t *TexMgr_LoadImage (qmodel_t *owner, const char *name, int32_t width, default: /* not reachable but avoids compiler warnings */ crc = 0; } - if ((flags & TEXPREF_OVERWRITE) && (glt = TexMgr_FindTexture (owner, name))) + if((flags & TEXPREF_OVERWRITE) && (glt = TexMgr_FindTexture(owner, name))) { - if (glt->source_crc == crc) + if(glt->source_crc == crc) return glt; } else - glt = TexMgr_NewTexture (); + glt = TexMgr_NewTexture(); // copy data glt->owner = owner; - q_strlcpy (glt->name, name, sizeof(glt->name)); + q_strlcpy(glt->name, name, sizeof(glt->name)); glt->width = width; glt->height = height; glt->flags = flags; glt->shirt = -1; glt->pants = -1; - q_strlcpy (glt->source_file, source_file, sizeof(glt->source_file)); + q_strlcpy(glt->source_file, source_file, sizeof(glt->source_file)); glt->source_offset = source_offset; glt->source_format = format; glt->source_width = width; @@ -1244,16 +1302,16 @@ gltexture_t *TexMgr_LoadImage (qmodel_t *owner, const char *name, int32_t width, //upload it mark = Hunk_LowMark(); - switch (glt->source_format) + switch(glt->source_format) { case SRC_INDEXED: - TexMgr_LoadImage8 (glt, data); + TexMgr_LoadImage8(glt, data); break; case SRC_LIGHTMAP: - TexMgr_LoadLightmap (glt, data); + TexMgr_LoadLightmap(glt, data); break; case SRC_RGBA: - TexMgr_LoadImage32 (glt, (unsigned *)data); + TexMgr_LoadImage32(glt, (unsigned *)data); break; } @@ -1265,7 +1323,7 @@ gltexture_t *TexMgr_LoadImage (qmodel_t *owner, const char *name, int32_t width, /* ================================================================================ - COLORMAPPING AND TEXTURE RELOADING + COLORMAPPING AND TEXTURE RELOADING ================================================================================ */ @@ -1275,44 +1333,44 @@ gltexture_t *TexMgr_LoadImage (qmodel_t *owner, const char *name, int32_t width, TexMgr_ReloadImage -- reloads a texture, and colormaps it if needed ================ */ -void TexMgr_ReloadImage (gltexture_t *glt, int32_t shirt, int32_t pants) +void TexMgr_ReloadImage(gltexture_t *glt, int32_t shirt, int32_t pants) { - byte translation[256]; - byte *src, *dst, *data = NULL, *translated; - int32_t mark, size, i; + byte translation[256]; + byte *src, *dst, *data = NULL, *translated; + int32_t mark, size, i; // // get source data // - mark = Hunk_LowMark (); + mark = Hunk_LowMark(); - if (glt->source_file[0] && glt->source_offset) + if(glt->source_file[0] && glt->source_offset) { //lump inside file long size; FILE *f; COM_FOpenFile(glt->source_file, &f, NULL); - if (!f) + if(!f) goto invalid; - fseek (f, glt->source_offset, SEEK_CUR); - size = (long) (glt->source_width * glt->source_height); + fseek(f, glt->source_offset, SEEK_CUR); + size = (long)(glt->source_width * glt->source_height); /* should be SRC_INDEXED, but no harm being paranoid: */ - if (glt->source_format == SRC_RGBA) + if(glt->source_format == SRC_RGBA) size *= 4; - else if (glt->source_format == SRC_LIGHTMAP) + else if(glt->source_format == SRC_LIGHTMAP) size *= lightmap_bytes; - data = (byte *) Hunk_Alloc (size); - fread (data, 1, size, f); - fclose (f); + data = (byte *) Hunk_Alloc(size); + fread(data, 1, size, f); + fclose(f); } - else if (glt->source_file[0] && !glt->source_offset) - data = Image_LoadImage (glt->source_file, (int32_t *)&glt->source_width, (int32_t *)&glt->source_height); //simple file - else if (!glt->source_file[0] && glt->source_offset) + else if(glt->source_file[0] && !glt->source_offset) + data = Image_LoadImage(glt->source_file, (int32_t *)&glt->source_width, (int32_t *)&glt->source_height); //simple file + else if(!glt->source_file[0] && glt->source_offset) data = (byte *) glt->source_offset; //image in memory - if (!data) + if(!data) { invalid: - Con_Printf ("TexMgr_ReloadImage: invalid source for %s\n", glt->name); + Con_Printf("TexMgr_ReloadImage: invalid source for %s\n", glt->name); Hunk_FreeToLowMark(mark); return; } @@ -1324,52 +1382,52 @@ invalid: // // if shirt and pants are -1,-1, use existing shirt and pants colors // if existing shirt and pants colors are -1,-1, don't bother colormapping - if (shirt > -1 && pants > -1) + if(shirt > -1 && pants > -1) { - if (glt->source_format == SRC_INDEXED) + if(glt->source_format == SRC_INDEXED) { glt->shirt = shirt; glt->pants = pants; } else - Con_Printf ("TexMgr_ReloadImage: can't colormap a non SRC_INDEXED texture: %s\n", glt->name); + Con_Printf("TexMgr_ReloadImage: can't colormap a non SRC_INDEXED texture: %s\n", glt->name); } - if (glt->shirt > -1 && glt->pants > -1) + if(glt->shirt > -1 && glt->pants > -1) { //create new translation table - for (i = 0; i < 256; i++) + for(i = 0; i < 256; i++) translation[i] = i; shirt = glt->shirt * 16; - if (shirt < 128) + if(shirt < 128) { - for (i = 0; i < 16; i++) - translation[TOP_RANGE+i] = shirt + i; + for(i = 0; i < 16; i++) + translation[TOP_RANGE + i] = shirt + i; } else { - for (i = 0; i < 16; i++) - translation[TOP_RANGE+i] = shirt+15-i; + for(i = 0; i < 16; i++) + translation[TOP_RANGE + i] = shirt + 15 - i; } pants = glt->pants * 16; - if (pants < 128) + if(pants < 128) { - for (i = 0; i < 16; i++) - translation[BOTTOM_RANGE+i] = pants + i; + for(i = 0; i < 16; i++) + translation[BOTTOM_RANGE + i] = pants + i; } else { - for (i = 0; i < 16; i++) - translation[BOTTOM_RANGE+i] = pants+15-i; + for(i = 0; i < 16; i++) + translation[BOTTOM_RANGE + i] = pants + 15 - i; } //translate texture size = glt->width * glt->height; - dst = translated = (byte *) Hunk_Alloc (size); + dst = translated = (byte *) Hunk_Alloc(size); src = data; - for (i = 0; i < size; i++) + for(i = 0; i < size; i++) *dst++ = translation[*src++]; data = translated; @@ -1377,16 +1435,16 @@ invalid: // // upload it // - switch (glt->source_format) + switch(glt->source_format) { case SRC_INDEXED: - TexMgr_LoadImage8 (glt, data); + TexMgr_LoadImage8(glt, data); break; case SRC_LIGHTMAP: - TexMgr_LoadLightmap (glt, data); + TexMgr_LoadLightmap(glt, data); break; case SRC_RGBA: - TexMgr_LoadImage32 (glt, (unsigned *)data); + TexMgr_LoadImage32(glt, (unsigned *)data); break; } @@ -1398,7 +1456,7 @@ invalid: TexMgr_ReloadImages -- reloads all texture images. called only by vid_restart ================ */ -void TexMgr_ReloadImages (void) +void TexMgr_ReloadImages(void) { gltexture_t *glt; @@ -1412,10 +1470,10 @@ void TexMgr_ReloadImages (void) // switching to a boolean flag. in_reload_images = true; - for (glt = active_gltextures; glt; glt = glt->next) + for(glt = active_gltextures; glt; glt = glt->next) { glGenTextures(1, &glt->texnum); - TexMgr_ReloadImage (glt, -1, -1); + TexMgr_ReloadImage(glt, -1, -1); } in_reload_images = false; @@ -1426,35 +1484,35 @@ void TexMgr_ReloadImages (void) TexMgr_ReloadNobrightImages -- reloads all texture that were loaded with the nobright palette. called when gl_fullbrights changes ================ */ -void TexMgr_ReloadNobrightImages (void) +void TexMgr_ReloadNobrightImages(void) { gltexture_t *glt; - for (glt = active_gltextures; glt; glt = glt->next) - if (glt->flags & TEXPREF_NOBRIGHT) + for(glt = active_gltextures; glt; glt = glt->next) + if(glt->flags & TEXPREF_NOBRIGHT) TexMgr_ReloadImage(glt, -1, -1); } /* ================================================================================ - TEXTURE BINDING / TEXTURE UNIT SWITCHING + TEXTURE BINDING / TEXTURE UNIT SWITCHING ================================================================================ */ -static GLuint currenttexture[3] = {GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE}; // to avoid unnecessary texture sets -static GLenum currenttarget = GL_TEXTURE0_ARB; -bool mtexenabled = false; +static GLuint currenttexture[3] = {GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE, GL_UNUSED_TEXTURE}; // to avoid unnecessary texture sets +static GLenum currenttarget = GL_TEXTURE0_ARB; +bool mtexenabled = false; /* ================ GL_SelectTexture -- johnfitz -- rewritten ================ */ -void GL_SelectTexture (GLenum target) +void GL_SelectTexture(GLenum target) { - if (target == currenttarget) + if(target == currenttarget) return; GL_SelectTextureFunc(target); @@ -1468,7 +1526,7 @@ GL_DisableMultitexture -- selects texture unit 0 */ void GL_DisableMultitexture(void) { - if (mtexenabled) + if(mtexenabled) { glDisable(GL_TEXTURE_2D); GL_SelectTexture(GL_TEXTURE0_ARB); @@ -1483,7 +1541,7 @@ GL_EnableMultitexture -- selects texture unit 1 */ void GL_EnableMultitexture(void) { - if (gl_mtexable) + if(gl_mtexable) { GL_SelectTexture(GL_TEXTURE1_ARB); glEnable(GL_TEXTURE_2D); @@ -1496,15 +1554,15 @@ void GL_EnableMultitexture(void) GL_Bind -- johnfitz -- heavy revision ================ */ -void GL_Bind (gltexture_t *texture) +void GL_Bind(gltexture_t *texture) { - if (!texture) + if(!texture) texture = nulltexture; - if (texture->texnum != currenttexture[currenttarget - GL_TEXTURE0_ARB]) + if(texture->texnum != currenttexture[currenttarget - GL_TEXTURE0_ARB]) { currenttexture[currenttarget - GL_TEXTURE0_ARB] = texture->texnum; - glBindTexture (GL_TEXTURE_2D, texture->texnum); + glBindTexture(GL_TEXTURE_2D, texture->texnum); texture->visframe = r_framecount; } } @@ -1517,13 +1575,13 @@ Wrapper around glDeleteTextures that also clears the given texture number from our per-TMU cached texture binding table. ================ */ -static void GL_DeleteTexture (gltexture_t *texture) +static void GL_DeleteTexture(gltexture_t *texture) { - glDeleteTextures (1, &texture->texnum); + glDeleteTextures(1, &texture->texnum); - if (texture->texnum == currenttexture[0]) currenttexture[0] = GL_UNUSED_TEXTURE; - if (texture->texnum == currenttexture[1]) currenttexture[1] = GL_UNUSED_TEXTURE; - if (texture->texnum == currenttexture[2]) currenttexture[2] = GL_UNUSED_TEXTURE; + if(texture->texnum == currenttexture[0]) currenttexture[0] = GL_UNUSED_TEXTURE; + if(texture->texnum == currenttexture[1]) currenttexture[1] = GL_UNUSED_TEXTURE; + if(texture->texnum == currenttexture[2]) currenttexture[2] = GL_UNUSED_TEXTURE; texture->texnum = 0; } @@ -1540,7 +1598,7 @@ Call this after changing the binding outside of GL_Bind. void GL_ClearBindings(void) { int32_t i; - for (i = 0; i < 3; i++) + for(i = 0; i < 3; i++) { currenttexture[i] = GL_UNUSED_TEXTURE; } diff --git a/source/gl_texmgr.h b/source/gl_texmgr.h index e8433f9..df79c87 100644 --- a/source/gl_texmgr.h +++ b/source/gl_texmgr.h @@ -24,45 +24,46 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //gl_texmgr.h -- fitzquake's texture manager. manages opengl texture images -#define TEXPREF_NONE 0x0000 -#define TEXPREF_MIPMAP 0x0001 // generate mipmaps +#define TEXPREF_NONE 0x0000 +#define TEXPREF_MIPMAP 0x0001 // generate mipmaps // TEXPREF_NEAREST and TEXPREF_LINEAR aren't supposed to be ORed with TEX_MIPMAP -#define TEXPREF_LINEAR 0x0002 // force linear -#define TEXPREF_NEAREST 0x0004 // force nearest -#define TEXPREF_ALPHA 0x0008 // allow alpha -#define TEXPREF_PAD 0x0010 // allow padding -#define TEXPREF_PERSIST 0x0020 // never free -#define TEXPREF_OVERWRITE 0x0040 // overwrite existing same-name texture -#define TEXPREF_NOPICMIP 0x0080 // always load full-sized -#define TEXPREF_FULLBRIGHT 0x0100 // use fullbright mask palette -#define TEXPREF_NOBRIGHT 0x0200 // use nobright mask palette -#define TEXPREF_CONCHARS 0x0400 // use conchars palette -#define TEXPREF_WARPIMAGE 0x0800 // resize this texture when warpimagesize changes +#define TEXPREF_LINEAR 0x0002 // force linear +#define TEXPREF_NEAREST 0x0004 // force nearest +#define TEXPREF_ALPHA 0x0008 // allow alpha +#define TEXPREF_PAD 0x0010 // allow padding +#define TEXPREF_PERSIST 0x0020 // never free +#define TEXPREF_OVERWRITE 0x0040 // overwrite existing same-name texture +#define TEXPREF_NOPICMIP 0x0080 // always load full-sized +#define TEXPREF_FULLBRIGHT 0x0100 // use fullbright mask palette +#define TEXPREF_NOBRIGHT 0x0200 // use nobright mask palette +#define TEXPREF_CONCHARS 0x0400 // use conchars palette +#define TEXPREF_WARPIMAGE 0x0800 // resize this texture when warpimagesize changes enum srcformat {SRC_INDEXED, SRC_LIGHTMAP, SRC_RGBA}; typedef uintptr_t src_offset_t; -typedef struct gltexture_s { +typedef struct gltexture_s +{ //managed by texture manager - GLuint texnum; - struct gltexture_s *next; - qmodel_t *owner; + GLuint texnum; + struct gltexture_s *next; + qmodel_t *owner; //managed by image loading - char name[64]; - uint32_t width; //size of image as it exists in opengl - uint32_t height; //size of image as it exists in opengl - uint32_t flags; - char source_file[MAX_QPATH]; //relative filepath to data source, or "" if source is in memory - src_offset_t source_offset; //byte offset into file, or memory address - enum srcformat source_format; //format of pixel data (indexed, lightmap, or rgba) - uint32_t source_width; //size of image in source data - uint32_t source_height; //size of image in source data - uint16_t source_crc; //generated by source data before modifications - int8_t shirt; //0-13 shirt color, or -1 if never colormapped - int8_t pants; //0-13 pants color, or -1 if never colormapped + char name[64]; + uint32_t width; //size of image as it exists in opengl + uint32_t height; //size of image as it exists in opengl + uint32_t flags; + char source_file[MAX_QPATH]; //relative filepath to data source, or "" if source is in memory + src_offset_t source_offset; //byte offset into file, or memory address + enum srcformat source_format; //format of pixel data (indexed, lightmap, or rgba) + uint32_t source_width; //size of image in source data + uint32_t source_height; //size of image in source data + uint16_t source_crc; //generated by source data before modifications + int8_t shirt; //0-13 shirt color, or -1 if never colormapped + int8_t pants; //0-13 pants color, or -1 if never colormapped //used for rendering - int32_t visframe; //matches r_framecount if texture was bound this frame + int32_t visframe; //matches r_framecount if texture was bound this frame } gltexture_t; extern gltexture_t *notexture; @@ -77,34 +78,34 @@ extern uint32_t d_8to24table_pants[256]; // TEXTURE MANAGER -float TexMgr_FrameUsage (void); -gltexture_t *TexMgr_FindTexture (qmodel_t *owner, const char *name); -gltexture_t *TexMgr_NewTexture (void); -void TexMgr_FreeTexture (gltexture_t *kill); -void TexMgr_FreeTextures (uint32_t flags, uint32_t mask); -void TexMgr_FreeTexturesForOwner (qmodel_t *owner); -void TexMgr_NewGame (void); -void TexMgr_Init (void); -void TexMgr_DeleteTextureObjects (void); +float TexMgr_FrameUsage(void); +gltexture_t *TexMgr_FindTexture(qmodel_t *owner, const char *name); +gltexture_t *TexMgr_NewTexture(void); +void TexMgr_FreeTexture(gltexture_t *kill); +void TexMgr_FreeTextures(uint32_t flags, uint32_t mask); +void TexMgr_FreeTexturesForOwner(qmodel_t *owner); +void TexMgr_NewGame(void); +void TexMgr_Init(void); +void TexMgr_DeleteTextureObjects(void); // IMAGE LOADING -gltexture_t *TexMgr_LoadImage (qmodel_t *owner, const char *name, int32_t width, int32_t height, enum srcformat format, - byte *data, const char *source_file, src_offset_t source_offset, unsigned flags); -void TexMgr_ReloadImage (gltexture_t *glt, int32_t shirt, int32_t pants); -void TexMgr_ReloadImages (void); -void TexMgr_ReloadNobrightImages (void); +gltexture_t *TexMgr_LoadImage(qmodel_t *owner, const char *name, int32_t width, int32_t height, enum srcformat format, + byte *data, const char *source_file, src_offset_t source_offset, unsigned flags); +void TexMgr_ReloadImage(gltexture_t *glt, int32_t shirt, int32_t pants); +void TexMgr_ReloadImages(void); +void TexMgr_ReloadNobrightImages(void); int32_t TexMgr_Pad(int32_t s); -int32_t TexMgr_SafeTextureSize (int32_t s); -int32_t TexMgr_PadConditional (int32_t s); +int32_t TexMgr_SafeTextureSize(int32_t s); +int32_t TexMgr_PadConditional(int32_t s); // TEXTURE BINDING & TEXTURE UNIT SWITCHING -void GL_SelectTexture (GLenum target); -void GL_DisableMultitexture (void); //selects texture unit 0 -void GL_EnableMultitexture (void); //selects texture unit 1 -void GL_Bind (gltexture_t *texture); -void GL_ClearBindings (void); +void GL_SelectTexture(GLenum target); +void GL_DisableMultitexture(void); //selects texture unit 0 +void GL_EnableMultitexture(void); //selects texture unit 1 +void GL_Bind(gltexture_t *texture); +void GL_ClearBindings(void); -#endif /* _GL_TEXMAN_H */ +#endif /* _GL_TEXMAN_H */ diff --git a/source/gl_vidsdl.c b/source/gl_vidsdl.c index b27c899..e30ab17 100644 --- a/source/gl_vidsdl.c +++ b/source/gl_vidsdl.c @@ -33,23 +33,24 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include #endif -#define MAX_MODE_LIST 600 //johnfitz -- was 30 -#define MAX_BPPS_LIST 5 -#define MAX_RATES_LIST 20 -#define WARP_WIDTH 320 -#define WARP_HEIGHT 200 -#define MAXWIDTH 10000 -#define MAXHEIGHT 10000 +#define MAX_MODE_LIST 600 //johnfitz -- was 30 +#define MAX_BPPS_LIST 5 +#define MAX_RATES_LIST 20 +#define WARP_WIDTH 320 +#define WARP_HEIGHT 200 +#define MAXWIDTH 10000 +#define MAXHEIGHT 10000 -#define DEFAULT_SDL_FLAGS SDL_OPENGL +#define DEFAULT_SDL_FLAGS SDL_OPENGL -#define DEFAULT_REFRESHRATE 60 +#define DEFAULT_REFRESHRATE 60 -typedef struct { - int32_t width; - int32_t height; - int32_t refreshrate; - int32_t bpp; +typedef struct +{ + int32_t width; + int32_t height; + int32_t refreshrate; + int32_t bpp; } vmode_t; static const char *gl_vendor; @@ -60,29 +61,29 @@ static int32_t gl_version_minor; static const char *gl_extensions; static char * gl_extensions_nice; -static vmode_t modelist[MAX_MODE_LIST]; -static int32_t nummodes; +static vmode_t modelist[MAX_MODE_LIST]; +static int32_t nummodes; -static bool vid_initialized = false; +static bool vid_initialized = false; -static SDL_Window *draw_context; -static SDL_GLContext gl_context; +static SDL_Window *draw_context; +static SDL_GLContext gl_context; -static bool vid_locked = false; //johnfitz -static bool vid_changed = false; +static bool vid_locked = false; //johnfitz +static bool vid_changed = false; -static void VID_Menu_Init (void); //johnfitz -static void VID_Menu_f (void); //johnfitz -static void VID_MenuDraw (void); -static void VID_MenuKey (int32_t key); +static void VID_Menu_Init(void); //johnfitz +static void VID_Menu_f(void); //johnfitz +static void VID_MenuDraw(void); +static void VID_MenuKey(int32_t key); -static void ClearAllStates (void); -static void GL_Init (void); -static void GL_SetupState (void); //johnfitz +static void ClearAllStates(void); +static void GL_Init(void); +static void GL_SetupState(void); //johnfitz -viddef_t vid; // global video state -modestate_t modestate = MS_UNINIT; -bool scr_skipupdate; +viddef_t vid; // global video state +modestate_t modestate = MS_UNINIT; +bool scr_skipupdate; bool gl_mtexable = false; bool gl_texture_env_combine = false; //johnfitz @@ -134,19 +135,19 @@ QS_PFNGLUNIFORM4FPROC GL_Uniform4fFunc = NULL; //ericw //==================================== //johnfitz -- new cvars -static cvar_t vid_fullscreen = {"vid_fullscreen", "0", CVAR_ARCHIVE}; // QuakeSpasm, was "1" -static cvar_t vid_width = {"vid_width", "800", CVAR_ARCHIVE}; // QuakeSpasm, was 640 -static cvar_t vid_height = {"vid_height", "600", CVAR_ARCHIVE}; // QuakeSpasm, was 480 -static cvar_t vid_bpp = {"vid_bpp", "16", CVAR_ARCHIVE}; -static cvar_t vid_refreshrate = {"vid_refreshrate", "60", CVAR_ARCHIVE}; -static cvar_t vid_vsync = {"vid_vsync", "0", CVAR_ARCHIVE}; -static cvar_t vid_fsaa = {"vid_fsaa", "0", CVAR_ARCHIVE}; // QuakeSpasm -static cvar_t vid_desktopfullscreen = {"vid_desktopfullscreen", "0", CVAR_ARCHIVE}; // QuakeSpasm -static cvar_t vid_borderless = {"vid_borderless", "0", CVAR_ARCHIVE}; // QuakeSpasm +static cvar_t vid_fullscreen = {"vid_fullscreen", "0", CVAR_ARCHIVE}; // QuakeSpasm, was "1" +static cvar_t vid_width = {"vid_width", "800", CVAR_ARCHIVE}; // QuakeSpasm, was 640 +static cvar_t vid_height = {"vid_height", "600", CVAR_ARCHIVE}; // QuakeSpasm, was 480 +static cvar_t vid_bpp = {"vid_bpp", "16", CVAR_ARCHIVE}; +static cvar_t vid_refreshrate = {"vid_refreshrate", "60", CVAR_ARCHIVE}; +static cvar_t vid_vsync = {"vid_vsync", "0", CVAR_ARCHIVE}; +static cvar_t vid_fsaa = {"vid_fsaa", "0", CVAR_ARCHIVE}; // QuakeSpasm +static cvar_t vid_desktopfullscreen = {"vid_desktopfullscreen", "0", CVAR_ARCHIVE}; // QuakeSpasm +static cvar_t vid_borderless = {"vid_borderless", "0", CVAR_ARCHIVE}; // QuakeSpasm //johnfitz -cvar_t vid_gamma = {"gamma", "1", CVAR_ARCHIVE}; //johnfitz -- moved here from view.c -cvar_t vid_contrast = {"contrast", "1", CVAR_ARCHIVE}; //QuakeSpasm, MarkV +cvar_t vid_gamma = {"gamma", "1", CVAR_ARCHIVE}; //johnfitz -- moved here from view.c +cvar_t vid_contrast = {"contrast", "1", CVAR_ARCHIVE}; //QuakeSpasm, MarkV //========================================================================== // @@ -154,7 +155,7 @@ cvar_t vid_contrast = {"contrast", "1", CVAR_ARCHIVE}; //QuakeSpasm, MarkV // //========================================================================== -#define USE_GAMMA_RAMPS 0 +#define USE_GAMMA_RAMPS 0 #if USE_GAMMA_RAMPS static uint16_t vid_gamma_red[256]; @@ -166,7 +167,7 @@ static uint16_t vid_sysgamma_green[256]; static uint16_t vid_sysgamma_blue[256]; #endif -static bool gammaworks = false; // whether hw-gamma works +static bool gammaworks = false; // whether hw-gamma works static int32_t fsaa; /* @@ -174,26 +175,26 @@ static int32_t fsaa; VID_Gamma_SetGamma -- apply gamma correction ================ */ -static void VID_Gamma_SetGamma (void) +static void VID_Gamma_SetGamma(void) { - if (gl_glsl_gamma_able) + if(gl_glsl_gamma_able) return; - if (draw_context && gammaworks) + if(draw_context && gammaworks) { - float value; + float value; - if (vid_gamma.value > (1.0f / GAMMA_MAX)) + if(vid_gamma.value > (1.0f / GAMMA_MAX)) value = 1.0f / vid_gamma.value; else value = GAMMA_MAX; # if USE_GAMMA_RAMPS - if (SDL_SetWindowGammaRamp(draw_context, vid_gamma_red, vid_gamma_green, vid_gamma_blue) != 0) - Con_Printf ("VID_Gamma_SetGamma: failed on SDL_SetWindowGammaRamp\n"); + if(SDL_SetWindowGammaRamp(draw_context, vid_gamma_red, vid_gamma_green, vid_gamma_blue) != 0) + Con_Printf("VID_Gamma_SetGamma: failed on SDL_SetWindowGammaRamp\n"); # else - if (SDL_SetWindowBrightness(draw_context, value) != 0) - Con_Printf ("VID_Gamma_SetGamma: failed on SDL_SetWindowBrightness\n"); + if(SDL_SetWindowBrightness(draw_context, value) != 0) + Con_Printf("VID_Gamma_SetGamma: failed on SDL_SetWindowBrightness\n"); # endif } } @@ -203,19 +204,19 @@ static void VID_Gamma_SetGamma (void) VID_Gamma_Restore -- restore system gamma ================ */ -static void VID_Gamma_Restore (void) +static void VID_Gamma_Restore(void) { - if (gl_glsl_gamma_able) + if(gl_glsl_gamma_able) return; - if (draw_context && gammaworks) + if(draw_context && gammaworks) { # if USE_GAMMA_RAMPS - if (SDL_SetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) != 0) - Con_Printf ("VID_Gamma_Restore: failed on SDL_SetWindowGammaRamp\n"); + if(SDL_SetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) != 0) + Con_Printf("VID_Gamma_Restore: failed on SDL_SetWindowGammaRamp\n"); # else - if (SDL_SetWindowBrightness(draw_context, 1) != 0) - Con_Printf ("VID_Gamma_Restore: failed on SDL_SetWindowBrightness\n"); + if(SDL_SetWindowBrightness(draw_context, 1) != 0) + Con_Printf("VID_Gamma_Restore: failed on SDL_SetWindowBrightness\n"); # endif } } @@ -225,9 +226,9 @@ static void VID_Gamma_Restore (void) VID_Gamma_Shutdown -- called on exit ================ */ -static void VID_Gamma_Shutdown (void) +static void VID_Gamma_Shutdown(void) { - VID_Gamma_Restore (); + VID_Gamma_Restore(); } /* @@ -235,24 +236,24 @@ static void VID_Gamma_Shutdown (void) VID_Gamma_f -- callback when the cvar changes ================ */ -static void VID_Gamma_f (cvar_t *var) +static void VID_Gamma_f(cvar_t *var) { (void)var; - if (gl_glsl_gamma_able) + if(gl_glsl_gamma_able) return; #if USE_GAMMA_RAMPS int32_t i; - for (i = 0; i < 256; i++) + for(i = 0; i < 256; i++) { vid_gamma_red[i] = - CLAMP(0, (int32_t) ((255 * pow((i + 0.5)/255.5, vid_gamma.value) + 0.5) * vid_contrast.value), 255) << 8; + CLAMP(0, (int32_t)((255 * pow((i + 0.5) / 255.5, vid_gamma.value) + 0.5) * vid_contrast.value), 255) << 8; vid_gamma_green[i] = vid_gamma_red[i]; vid_gamma_blue[i] = vid_gamma_red[i]; } #endif - VID_Gamma_SetGamma (); + VID_Gamma_SetGamma(); } /* @@ -260,25 +261,25 @@ static void VID_Gamma_f (cvar_t *var) VID_Gamma_Init -- call on init ================ */ -static void VID_Gamma_Init (void) +static void VID_Gamma_Init(void) { - Cvar_RegisterVariable (&vid_gamma); - Cvar_RegisterVariable (&vid_contrast); - Cvar_SetCallback (&vid_gamma, VID_Gamma_f); - Cvar_SetCallback (&vid_contrast, VID_Gamma_f); + Cvar_RegisterVariable(&vid_gamma); + Cvar_RegisterVariable(&vid_contrast); + Cvar_SetCallback(&vid_gamma, VID_Gamma_f); + Cvar_SetCallback(&vid_contrast, VID_Gamma_f); - if (gl_glsl_gamma_able) + if(gl_glsl_gamma_able) return; # if USE_GAMMA_RAMPS - gammaworks = (SDL_GetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); - if (gammaworks) - gammaworks = (SDL_SetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); + gammaworks = (SDL_GetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); + if(gammaworks) + gammaworks = (SDL_SetWindowGammaRamp(draw_context, vid_sysgamma_red, vid_sysgamma_green, vid_sysgamma_blue) == 0); # else - gammaworks = (SDL_SetWindowBrightness(draw_context, 1) == 0); + gammaworks = (SDL_SetWindowBrightness(draw_context, 1) == 0); # endif - if (!gammaworks) + if(!gammaworks) Con_SafePrintf("gamma adjustment not available\n"); } @@ -287,7 +288,7 @@ static void VID_Gamma_Init (void) VID_GetCurrentWidth ====================== */ -static int32_t VID_GetCurrentWidth (void) +static int32_t VID_GetCurrentWidth(void) { int32_t w; SDL_GetWindowSize(draw_context, &w, NULL); @@ -299,7 +300,7 @@ static int32_t VID_GetCurrentWidth (void) VID_GetCurrentHeight ======================= */ -static int32_t VID_GetCurrentHeight (void) +static int32_t VID_GetCurrentHeight(void) { int32_t h; SDL_GetWindowSize(draw_context, NULL, &h); @@ -311,14 +312,14 @@ static int32_t VID_GetCurrentHeight (void) VID_GetCurrentRefreshRate ==================== */ -static int32_t VID_GetCurrentRefreshRate (void) +static int32_t VID_GetCurrentRefreshRate(void) { SDL_DisplayMode mode; int32_t current_display; current_display = SDL_GetWindowDisplayIndex(draw_context); - if (0 != SDL_GetCurrentDisplayMode(current_display, &mode)) + if(0 != SDL_GetCurrentDisplayMode(current_display, &mode)) return DEFAULT_REFRESHRATE; return mode.refresh_rate; @@ -330,7 +331,7 @@ static int32_t VID_GetCurrentRefreshRate (void) VID_GetCurrentBPP ==================== */ -static int32_t VID_GetCurrentBPP (void) +static int32_t VID_GetCurrentBPP(void) { const Uint32 pixelFormat = SDL_GetWindowPixelFormat(draw_context); return SDL_BITSPERPIXEL(pixelFormat); @@ -343,7 +344,7 @@ VID_GetFullscreen returns true if we are in regular fullscreen or "desktop fullscren" ==================== */ -static bool VID_GetFullscreen (void) +static bool VID_GetFullscreen(void) { return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN) != 0; } @@ -355,7 +356,7 @@ VID_GetDesktopFullscreen returns true if we are specifically in "desktop fullscreen" mode ==================== */ -static bool VID_GetDesktopFullscreen (void) +static bool VID_GetDesktopFullscreen(void) { return (SDL_GetWindowFlags(draw_context) & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP; } @@ -365,7 +366,7 @@ static bool VID_GetDesktopFullscreen (void) VID_GetVSync ==================== */ -static bool VID_GetVSync (void) +static bool VID_GetVSync(void) { return SDL_GL_GetSwapInterval() == 1; } @@ -377,7 +378,7 @@ VID_GetWindow used by pl_win.c ==================== */ -void *VID_GetWindow (void) +void *VID_GetWindow(void) { return draw_context; } @@ -387,7 +388,7 @@ void *VID_GetWindow (void) VID_HasMouseOrInputFocus ==================== */ -bool VID_HasMouseOrInputFocus (void) +bool VID_HasMouseOrInputFocus(void) { return (SDL_GetWindowFlags(draw_context) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS)) != 0; } @@ -397,7 +398,7 @@ bool VID_HasMouseOrInputFocus (void) VID_IsMinimized ==================== */ -bool VID_IsMinimized (void) +bool VID_IsMinimized(void) { return !(SDL_GetWindowFlags(draw_context) & SDL_WINDOW_SHOWN); } @@ -420,14 +421,14 @@ static SDL_DisplayMode *VID_SDL2_GetDisplayMode(int32_t width, int32_t height, i const int32_t sdlmodes = SDL_GetNumDisplayModes(0); int32_t i; - for (i = 0; i < sdlmodes; i++) + for(i = 0; i < sdlmodes; i++) { - if (SDL_GetDisplayMode(0, i, &mode) != 0) + if(SDL_GetDisplayMode(0, i, &mode) != 0) continue; - if (mode.w == width && mode.h == height - && SDL_BITSPERPIXEL(mode.format) == bpp - && mode.refresh_rate == refreshrate) + if(mode.w == width && mode.h == height + && SDL_BITSPERPIXEL(mode.format) == bpp + && mode.refresh_rate == refreshrate) { return &mode; } @@ -440,22 +441,22 @@ static SDL_DisplayMode *VID_SDL2_GetDisplayMode(int32_t width, int32_t height, i VID_ValidMode ================ */ -static bool VID_ValidMode (int32_t width, int32_t height, int32_t refreshrate, int32_t bpp, bool fullscreen) +static bool VID_ValidMode(int32_t width, int32_t height, int32_t refreshrate, int32_t bpp, bool fullscreen) { // ignore width / height / bpp if vid_desktopfullscreen is enabled - if (fullscreen && vid_desktopfullscreen.value) + if(fullscreen && vid_desktopfullscreen.value) return true; - if (width < 320) + if(width < 320) return false; - if (height < 200) + if(height < 200) return false; - if (fullscreen && VID_SDL2_GetDisplayMode(width, height, refreshrate, bpp) == NULL) + if(fullscreen && VID_SDL2_GetDisplayMode(width, height, refreshrate, bpp) == NULL) bpp = 0; - switch (bpp) + switch(bpp) { case 16: case 24: @@ -473,23 +474,23 @@ static bool VID_ValidMode (int32_t width, int32_t height, int32_t refreshrate, i VID_SetMode ================ */ -static bool VID_SetMode (int32_t width, int32_t height, int32_t refreshrate, int32_t bpp, bool fullscreen) +static bool VID_SetMode(int32_t width, int32_t height, int32_t refreshrate, int32_t bpp, bool fullscreen) { - int32_t temp; - Uint32 flags; - char caption[50]; - int32_t depthbits, stencilbits; - int32_t fsaa_obtained; - int32_t previous_display; + int32_t temp; + Uint32 flags; + char caption[50]; + int32_t depthbits, stencilbits; + int32_t fsaa_obtained; + int32_t previous_display; // so Con_Printfs don't mess us up by forcing vid and snd updates temp = scr_disabled_for_loading; scr_disabled_for_loading = true; - BGM_Pause (); + BGM_Pause(); /* z-buffer depth */ - if (bpp == 16) + if(bpp == 16) { depthbits = 16; stencilbits = 0; @@ -509,29 +510,32 @@ static bool VID_SetMode (int32_t width, int32_t height, int32_t refreshrate, int q_snprintf(caption, sizeof(caption), "QuakeSpasm " QUAKESPASM_VERSION); /* Create the window if needed, hidden */ - if (!draw_context) + if(!draw_context) { flags = SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN; - if (vid_borderless.value) + if(vid_borderless.value) flags |= SDL_WINDOW_BORDERLESS; - draw_context = SDL_CreateWindow (caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); - if (!draw_context) { // scale back fsaa + draw_context = SDL_CreateWindow(caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); + if(!draw_context) // scale back fsaa + { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); - draw_context = SDL_CreateWindow (caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); + draw_context = SDL_CreateWindow(caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); } - if (!draw_context) { // scale back SDL_GL_DEPTH_SIZE + if(!draw_context) // scale back SDL_GL_DEPTH_SIZE + { SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); - draw_context = SDL_CreateWindow (caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); + draw_context = SDL_CreateWindow(caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); } - if (!draw_context) { // scale back SDL_GL_STENCIL_SIZE + if(!draw_context) // scale back SDL_GL_STENCIL_SIZE + { SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0); - draw_context = SDL_CreateWindow (caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); + draw_context = SDL_CreateWindow(caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); } - if (!draw_context) - Sys_Error ("Couldn't create window"); + if(!draw_context) + Sys_Error("Couldn't create window"); previous_display = -1; } @@ -541,42 +545,44 @@ static bool VID_SetMode (int32_t width, int32_t height, int32_t refreshrate, int } /* Ensure the window is not fullscreen */ - if (VID_GetFullscreen ()) + if(VID_GetFullscreen()) { - if (SDL_SetWindowFullscreen (draw_context, 0) != 0) + if(SDL_SetWindowFullscreen(draw_context, 0) != 0) Sys_Error("Couldn't set fullscreen state mode"); } /* Set window size and display mode */ - SDL_SetWindowSize (draw_context, width, height); - if (previous_display >= 0) - SDL_SetWindowPosition (draw_context, SDL_WINDOWPOS_CENTERED_DISPLAY(previous_display), SDL_WINDOWPOS_CENTERED_DISPLAY(previous_display)); + SDL_SetWindowSize(draw_context, width, height); + if(previous_display >= 0) + SDL_SetWindowPosition(draw_context, SDL_WINDOWPOS_CENTERED_DISPLAY(previous_display), SDL_WINDOWPOS_CENTERED_DISPLAY(previous_display)); else SDL_SetWindowPosition(draw_context, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); - SDL_SetWindowDisplayMode (draw_context, VID_SDL2_GetDisplayMode(width, height, refreshrate, bpp)); - SDL_SetWindowBordered (draw_context, vid_borderless.value ? SDL_FALSE : SDL_TRUE); + SDL_SetWindowDisplayMode(draw_context, VID_SDL2_GetDisplayMode(width, height, refreshrate, bpp)); + SDL_SetWindowBordered(draw_context, vid_borderless.value ? SDL_FALSE : SDL_TRUE); /* Make window fullscreen if needed, and show the window */ - if (fullscreen) { + if(fullscreen) + { Uint32 flags = vid_desktopfullscreen.value ? - SDL_WINDOW_FULLSCREEN_DESKTOP : - SDL_WINDOW_FULLSCREEN; - if (SDL_SetWindowFullscreen (draw_context, flags) != 0) - Sys_Error ("Couldn't set fullscreen state mode"); + SDL_WINDOW_FULLSCREEN_DESKTOP : + SDL_WINDOW_FULLSCREEN; + if(SDL_SetWindowFullscreen(draw_context, flags) != 0) + Sys_Error("Couldn't set fullscreen state mode"); } - SDL_ShowWindow (draw_context); + SDL_ShowWindow(draw_context); /* Create GL context if needed */ - if (!gl_context) { + if(!gl_context) + { gl_context = SDL_GL_CreateContext(draw_context); - if (!gl_context) + if(!gl_context) Sys_Error("Couldn't create GL context"); } gl_swap_control = true; - if (SDL_GL_SetSwapInterval ((vid_vsync.value) ? 1 : 0) == -1) + if(SDL_GL_SetSwapInterval((vid_vsync.value) ? 1 : 0) == -1) gl_swap_control = false; vid.width = VID_GetCurrentWidth(); @@ -586,32 +592,32 @@ static bool VID_SetMode (int32_t width, int32_t height, int32_t refreshrate, int vid.numpages = 2; // read the obtained z-buffer depth - if (SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depthbits) == -1) + if(SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depthbits) == -1) depthbits = 0; // read obtained fsaa samples - if (SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &fsaa_obtained) == -1) + if(SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &fsaa_obtained) == -1) fsaa_obtained = 0; // read stencil bits - if (SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &gl_stencilbits) == -1) + if(SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &gl_stencilbits) == -1) gl_stencilbits = 0; modestate = VID_GetFullscreen() ? MS_FULLSCREEN : MS_WINDOWED; - BGM_Resume (); + BGM_Resume(); scr_disabled_for_loading = temp; // fix the leftover Alt from any Alt-Tab or the like that switched us away - ClearAllStates (); + ClearAllStates(); - Con_SafePrintf ("Video mode %" PRIi32 "x%" PRIi32 "x%" PRIi32 " %" PRIi32 "Hz (%" PRIi32 "-bit z-buffer, %" PRIi32 "x FSAA) initialized\n", - VID_GetCurrentWidth(), - VID_GetCurrentHeight(), - VID_GetCurrentBPP(), - VID_GetCurrentRefreshRate(), - depthbits, - fsaa_obtained); + Con_SafePrintf("Video mode %" PRIi32 "x%" PRIi32 "x%" PRIi32 " %" PRIi32 "Hz (%" PRIi32 "-bit z-buffer, %" PRIi32 "x FSAA) initialized\n", + VID_GetCurrentWidth(), + VID_GetCurrentHeight(), + VID_GetCurrentBPP(), + VID_GetCurrentRefreshRate(), + depthbits, + fsaa_obtained); vid.recalc_refdef = 1; @@ -626,7 +632,7 @@ static bool VID_SetMode (int32_t width, int32_t height, int32_t refreshrate, int VID_Changed_f -- kristian -- notify us that a value has changed that requires a vid_restart =================== */ -static void VID_Changed_f (cvar_t *var) +static void VID_Changed_f(cvar_t *var) { (void)var; vid_changed = true; @@ -637,12 +643,12 @@ static void VID_Changed_f (cvar_t *var) VID_Restart -- johnfitz -- change video modes on the fly =================== */ -static void VID_Restart (void) +static void VID_Restart(void) { int32_t width, height, refreshrate, bpp; bool fullscreen; - if (vid_locked || !vid_changed) + if(vid_locked || !vid_changed) return; width = (int32_t)vid_width.value; @@ -654,10 +660,10 @@ static void VID_Restart (void) // // validate new mode // - if (!VID_ValidMode (width, height, refreshrate, bpp, fullscreen)) + if(!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) { - Con_Printf ("%" PRIi32 "x%" PRIi32 "x%" PRIi32 " %" PRIi32 "Hz %s is not a valid mode\n", - width, height, bpp, refreshrate, fullscreen? "fullscreen" : "windowed"); + Con_Printf("%" PRIi32 "x%" PRIi32 "x%" PRIi32 " %" PRIi32 "Hz %s is not a valid mode\n", + width, height, bpp, refreshrate, fullscreen ? "fullscreen" : "windowed"); return; } @@ -668,31 +674,31 @@ static void VID_Restart (void) // one of the new objects could be given the same ID as an invalid handle // which is later deleted. - TexMgr_DeleteTextureObjects (); - GLSLGamma_DeleteTexture (); - R_ScaleView_DeleteTexture (); - R_DeleteShaders (); - GL_DeleteBModelVertexBuffer (); - GLMesh_DeleteVertexBuffers (); + TexMgr_DeleteTextureObjects(); + GLSLGamma_DeleteTexture(); + R_ScaleView_DeleteTexture(); + R_DeleteShaders(); + GL_DeleteBModelVertexBuffer(); + GLMesh_DeleteVertexBuffers(); // // set new mode // - VID_SetMode (width, height, refreshrate, bpp, fullscreen); + VID_SetMode(width, height, refreshrate, bpp, fullscreen); - GL_Init (); - TexMgr_ReloadImages (); - GL_BuildBModelVertexBuffer (); - GLMesh_LoadVertexBuffers (); - GL_SetupState (); - Fog_SetupState (); + GL_Init(); + TexMgr_ReloadImages(); + GL_BuildBModelVertexBuffer(); + GLMesh_LoadVertexBuffers(); + GL_SetupState(); + Fog_SetupState(); //warpimages needs to be recalculated - TexMgr_RecalcWarpImageSize (); + TexMgr_RecalcWarpImageSize(); //conwidth and conheight need to be recalculated - vid.conwidth = (scr_conwidth.value > 0) ? (int32_t)scr_conwidth.value : (scr_conscale.value > 0) ? (int32_t)(vid.width/scr_conscale.value) : vid.width; - vid.conwidth = CLAMP (320, vid.conwidth, vid.width); + vid.conwidth = (scr_conwidth.value > 0) ? (int32_t)scr_conwidth.value : (scr_conscale.value > 0) ? (int32_t)(vid.width / scr_conscale.value) : vid.width; + vid.conwidth = CLAMP(320, vid.conwidth, vid.width); vid.conwidth &= 0xFFFFFFF8; vid.conheight = vid.conwidth * vid.height / vid.width; // @@ -702,11 +708,11 @@ static void VID_Restart (void) // // update mouse grab // - if (key_dest == key_console || key_dest == key_menu) + if(key_dest == key_console || key_dest == key_menu) { - if (modestate == MS_WINDOWED) + if(modestate == MS_WINDOWED) IN_Deactivate(true); - else if (modestate == MS_FULLSCREEN) + else if(modestate == MS_FULLSCREEN) IN_Activate(); } } @@ -716,11 +722,11 @@ static void VID_Restart (void) VID_Test -- johnfitz -- like vid_restart, but asks for confirmation after switching modes ================ */ -static void VID_Test (void) +static void VID_Test(void) { int32_t old_width, old_height, old_refreshrate, old_bpp, old_fullscreen; - if (vid_locked || !vid_changed) + if(vid_locked || !vid_changed) return; // // now try the switch @@ -731,18 +737,18 @@ static void VID_Test (void) old_bpp = VID_GetCurrentBPP(); old_fullscreen = VID_GetFullscreen() ? true : false; - VID_Restart (); + VID_Restart(); //pop up confirmation dialoge - if (!SCR_ModalMessage("Would you like to keep this\nvideo mode? (y/n)\n", 5.0f)) + if(!SCR_ModalMessage("Would you like to keep this\nvideo mode? (y/n)\n", 5.0f)) { //revert cvars and mode - Cvar_SetValueQuick (&vid_width, old_width); - Cvar_SetValueQuick (&vid_height, old_height); - Cvar_SetValueQuick (&vid_refreshrate, old_refreshrate); - Cvar_SetValueQuick (&vid_bpp, old_bpp); - Cvar_SetQuick (&vid_fullscreen, old_fullscreen ? "1" : "0"); - VID_Restart (); + Cvar_SetValueQuick(&vid_width, old_width); + Cvar_SetValueQuick(&vid_height, old_height); + Cvar_SetValueQuick(&vid_refreshrate, old_refreshrate); + Cvar_SetValueQuick(&vid_bpp, old_bpp); + Cvar_SetQuick(&vid_fullscreen, old_fullscreen ? "1" : "0"); + VID_Restart(); } } @@ -751,7 +757,7 @@ static void VID_Test (void) VID_Unlock -- johnfitz ================ */ -static void VID_Unlock (void) +static void VID_Unlock(void) { vid_locked = false; VID_SyncCvars(); @@ -768,7 +774,7 @@ Used when changing gamedirs so the current settings override what was saved in the config.cfg. ================ */ -void VID_Lock (void) +void VID_Lock(void) { vid_locked = true; } @@ -784,31 +790,31 @@ void VID_Lock (void) GL_MakeNiceExtensionsList -- johnfitz =============== */ -static char *GL_MakeNiceExtensionsList (const char *in) +static char *GL_MakeNiceExtensionsList(const char *in) { char *copy, *token, *out; int32_t i, count; - if (!in) return Z_Strdup("(none)"); + if(!in) return Z_Strdup("(none)"); //each space will be replaced by 4 chars, so count the spaces before we malloc - for (i = 0, count = 1; i < (int32_t) strlen(in); i++) + for(i = 0, count = 1; i < (int32_t) strlen(in); i++) { - if (in[i] == ' ') + if(in[i] == ' ') count++; } - out = (char *) Z_Malloc (strlen(in) + count*3 + 1); //usually about 1-2k + out = (char *) Z_Malloc(strlen(in) + count * 3 + 1); //usually about 1-2k out[0] = 0; copy = (char *) Z_Strdup(in); - for (token = strtok(copy, " "); token; token = strtok(NULL, " ")) + for(token = strtok(copy, " "); token; token = strtok(NULL, " ")) { strcat(out, "\n "); strcat(out, token); } - Z_Free (copy); + Z_Free(copy); return out; } @@ -817,12 +823,12 @@ static char *GL_MakeNiceExtensionsList (const char *in) GL_Info_f -- johnfitz =============== */ -static void GL_Info_f (void) +static void GL_Info_f(void) { - Con_SafePrintf ("GL_VENDOR: %s\n", gl_vendor); - Con_SafePrintf ("GL_RENDERER: %s\n", gl_renderer); - Con_SafePrintf ("GL_VERSION: %s\n", gl_version); - Con_Printf ("GL_EXTENSIONS: %s\n", gl_extensions_nice); + Con_SafePrintf("GL_VENDOR: %s\n", gl_vendor); + Con_SafePrintf("GL_RENDERER: %s\n", gl_renderer); + Con_SafePrintf("GL_VERSION: %s\n", gl_version); + Con_Printf("GL_EXTENSIONS: %s\n", gl_extensions_nice); } /* @@ -830,40 +836,41 @@ static void GL_Info_f (void) GL_CheckExtensions =============== */ -static bool GL_ParseExtensionList (const char *list, const char *name) +static bool GL_ParseExtensionList(const char *list, const char *name) { - const char *start; - const char *where, *terminator; + const char *start; + const char *where, *terminator; - if (!list || !name || !*name) + if(!list || !name || !*name) return false; - if (strchr(name, ' ') != NULL) - return false; // extension names must not have spaces + if(strchr(name, ' ') != NULL) + return false; // extension names must not have spaces start = list; - while (1) { - where = strstr (start, name); - if (!where) + while(1) + { + where = strstr(start, name); + if(!where) break; - terminator = where + strlen (name); - if (where == start || where[-1] == ' ') - if (*terminator == ' ' || *terminator == '\0') + terminator = where + strlen(name); + if(where == start || where[-1] == ' ') + if(*terminator == ' ' || *terminator == '\0') return true; start = terminator; } return false; } -static void GL_CheckExtensions (void) +static void GL_CheckExtensions(void) { int32_t swap_control; // ARB_vertex_buffer_object // - if (COM_CheckParm("-novbo")) - Con_Warning ("Vertex buffer objects disabled at command line\n"); - else if (gl_version_major < 1 || (gl_version_major == 1 && gl_version_minor < 5)) - Con_Warning ("OpenGL version < 1.5, skipping ARB_vertex_buffer_object check\n"); + if(COM_CheckParm("-novbo")) + Con_Warning("Vertex buffer objects disabled at command line\n"); + else if(gl_version_major < 1 || (gl_version_major == 1 && gl_version_minor < 5)) + Con_Warning("OpenGL version < 1.5, skipping ARB_vertex_buffer_object check\n"); else { GL_BindBufferFunc = (PFNGLBINDBUFFERARBPROC) SDL_GL_GetProcAddress("glBindBufferARB"); @@ -871,27 +878,27 @@ static void GL_CheckExtensions (void) GL_BufferSubDataFunc = (PFNGLBUFFERSUBDATAARBPROC) SDL_GL_GetProcAddress("glBufferSubDataARB"); GL_DeleteBuffersFunc = (PFNGLDELETEBUFFERSARBPROC) SDL_GL_GetProcAddress("glDeleteBuffersARB"); GL_GenBuffersFunc = (PFNGLGENBUFFERSARBPROC) SDL_GL_GetProcAddress("glGenBuffersARB"); - if (GL_BindBufferFunc && GL_BufferDataFunc && GL_BufferSubDataFunc && GL_DeleteBuffersFunc && GL_GenBuffersFunc) + if(GL_BindBufferFunc && GL_BufferDataFunc && GL_BufferSubDataFunc && GL_DeleteBuffersFunc && GL_GenBuffersFunc) { Con_Printf("FOUND: ARB_vertex_buffer_object\n"); gl_vbo_able = true; } else { - Con_Warning ("ARB_vertex_buffer_object not available\n"); + Con_Warning("ARB_vertex_buffer_object not available\n"); } } // multitexture // - if (COM_CheckParm("-nomtex")) - Con_Warning ("Mutitexture disabled at command line\n"); - else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_multitexture")) + if(COM_CheckParm("-nomtex")) + Con_Warning("Mutitexture disabled at command line\n"); + else if(GL_ParseExtensionList(gl_extensions, "GL_ARB_multitexture")) { GL_MTexCoord2fFunc = (PFNGLMULTITEXCOORD2FARBPROC) SDL_GL_GetProcAddress("glMultiTexCoord2fARB"); GL_SelectTextureFunc = (PFNGLACTIVETEXTUREARBPROC) SDL_GL_GetProcAddress("glActiveTextureARB"); GL_ClientActiveTextureFunc = (PFNGLCLIENTACTIVETEXTUREARBPROC) SDL_GL_GetProcAddress("glClientActiveTextureARB"); - if (GL_MTexCoord2fFunc && GL_SelectTextureFunc && GL_ClientActiveTextureFunc) + if(GL_MTexCoord2fFunc && GL_SelectTextureFunc && GL_ClientActiveTextureFunc) { Con_Printf("FOUND: ARB_multitexture\n"); gl_mtexable = true; @@ -901,67 +908,67 @@ static void GL_CheckExtensions (void) } else { - Con_Warning ("Couldn't link to multitexture functions\n"); + Con_Warning("Couldn't link to multitexture functions\n"); } } else { - Con_Warning ("multitexture not supported (extension not found)\n"); + Con_Warning("multitexture not supported (extension not found)\n"); } // texture_env_combine // - if (COM_CheckParm("-nocombine")) - Con_Warning ("texture_env_combine disabled at command line\n"); - else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_combine")) + if(COM_CheckParm("-nocombine")) + Con_Warning("texture_env_combine disabled at command line\n"); + else if(GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_combine")) { Con_Printf("FOUND: ARB_texture_env_combine\n"); gl_texture_env_combine = true; } - else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_env_combine")) + else if(GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_env_combine")) { Con_Printf("FOUND: EXT_texture_env_combine\n"); gl_texture_env_combine = true; } else { - Con_Warning ("texture_env_combine not supported\n"); + Con_Warning("texture_env_combine not supported\n"); } // texture_env_add // - if (COM_CheckParm("-noadd")) - Con_Warning ("texture_env_add disabled at command line\n"); - else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_add")) + if(COM_CheckParm("-noadd")) + Con_Warning("texture_env_add disabled at command line\n"); + else if(GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_env_add")) { Con_Printf("FOUND: ARB_texture_env_add\n"); gl_texture_env_add = true; } - else if (GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_env_add")) + else if(GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_env_add")) { Con_Printf("FOUND: EXT_texture_env_add\n"); gl_texture_env_add = true; } else { - Con_Warning ("texture_env_add not supported\n"); + Con_Warning("texture_env_add not supported\n"); } // swap control // - if (!gl_swap_control) + if(!gl_swap_control) { - Con_Warning ("vertical sync not supported (SDL_GL_SetSwapInterval failed)\n"); + Con_Warning("vertical sync not supported (SDL_GL_SetSwapInterval failed)\n"); } - else if ((swap_control = SDL_GL_GetSwapInterval()) == -1) + else if((swap_control = SDL_GL_GetSwapInterval()) == -1) { gl_swap_control = false; - Con_Warning ("vertical sync not supported (SDL_GL_GetSwapInterval failed)\n"); + Con_Warning("vertical sync not supported (SDL_GL_GetSwapInterval failed)\n"); } - else if ((vid_vsync.value && swap_control != 1) || (!vid_vsync.value && swap_control != 0)) + else if((vid_vsync.value && swap_control != 1) || (!vid_vsync.value && swap_control != 0)) { gl_swap_control = false; - Con_Warning ("vertical sync not supported (swap_control doesn't match vid_vsync)\n"); + Con_Warning("vertical sync not supported (swap_control doesn't match vid_vsync)\n"); } else { @@ -970,65 +977,65 @@ static void GL_CheckExtensions (void) // anisotropic filtering // - if (GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_filter_anisotropic")) + if(GL_ParseExtensionList(gl_extensions, "GL_EXT_texture_filter_anisotropic")) { - float test1,test2; + float test1, test2; GLuint tex; // test to make sure we really have control over it // 1.0 and 2.0 should always be legal values glGenTextures(1, &tex); - glBindTexture (GL_TEXTURE_2D, tex); + glBindTexture(GL_TEXTURE_2D, tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); - glGetTexParameterfv (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &test1); + glGetTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &test1); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 2.0f); - glGetTexParameterfv (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &test2); + glGetTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, &test2); glDeleteTextures(1, &tex); - if (test1 == 1 && test2 == 2) + if(test1 == 1 && test2 == 2) { Con_Printf("FOUND: EXT_texture_filter_anisotropic\n"); gl_anisotropy_able = true; } else { - Con_Warning ("anisotropic filtering locked by driver. Current driver setting is %f\n", test1); + Con_Warning("anisotropic filtering locked by driver. Current driver setting is %f\n", test1); } //get max value either way, so the menu and stuff know it - glGetFloatv (GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_max_anisotropy); - if (gl_max_anisotropy < 2) + glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_max_anisotropy); + if(gl_max_anisotropy < 2) { gl_anisotropy_able = false; gl_max_anisotropy = 1; - Con_Warning ("anisotropic filtering broken: disabled\n"); + Con_Warning("anisotropic filtering broken: disabled\n"); } } else { gl_max_anisotropy = 1; - Con_Warning ("texture_filter_anisotropic not supported\n"); + Con_Warning("texture_filter_anisotropic not supported\n"); } // texture_non_power_of_two // - if (COM_CheckParm("-notexturenpot")) - Con_Warning ("texture_non_power_of_two disabled at command line\n"); - else if (GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_non_power_of_two")) + if(COM_CheckParm("-notexturenpot")) + Con_Warning("texture_non_power_of_two disabled at command line\n"); + else if(GL_ParseExtensionList(gl_extensions, "GL_ARB_texture_non_power_of_two")) { Con_Printf("FOUND: ARB_texture_non_power_of_two\n"); gl_texture_NPOT = true; } else { - Con_Warning ("texture_non_power_of_two not supported\n"); + Con_Warning("texture_non_power_of_two not supported\n"); } // GLSL // - if (COM_CheckParm("-noglsl")) - Con_Warning ("GLSL disabled at command line\n"); - else if (gl_version_major >= 2) + if(COM_CheckParm("-noglsl")) + Con_Warning("GLSL disabled at command line\n"); + else if(gl_version_major >= 2) { GL_CreateShaderFunc = (QS_PFNGLCREATESHADERPROC) SDL_GL_GetProcAddress("glCreateShader"); GL_DeleteShaderFunc = (QS_PFNGLDELETESHADERPROC) SDL_GL_GetProcAddress("glDeleteShader"); @@ -1054,67 +1061,67 @@ static void GL_CheckExtensions (void) GL_Uniform3fFunc = (QS_PFNGLUNIFORM3FPROC) SDL_GL_GetProcAddress("glUniform3f"); GL_Uniform4fFunc = (QS_PFNGLUNIFORM4FPROC) SDL_GL_GetProcAddress("glUniform4f"); - if (GL_CreateShaderFunc && - GL_DeleteShaderFunc && - GL_DeleteProgramFunc && - GL_ShaderSourceFunc && - GL_CompileShaderFunc && - GL_GetShaderivFunc && - GL_GetShaderInfoLogFunc && - GL_GetProgramivFunc && - GL_GetProgramInfoLogFunc && - GL_CreateProgramFunc && - GL_AttachShaderFunc && - GL_LinkProgramFunc && - GL_BindAttribLocationFunc && - GL_UseProgramFunc && - GL_GetAttribLocationFunc && - GL_VertexAttribPointerFunc && - GL_EnableVertexAttribArrayFunc && - GL_DisableVertexAttribArrayFunc && - GL_GetUniformLocationFunc && - GL_Uniform1iFunc && - GL_Uniform1fFunc && - GL_Uniform3fFunc && - GL_Uniform4fFunc) + if(GL_CreateShaderFunc && + GL_DeleteShaderFunc && + GL_DeleteProgramFunc && + GL_ShaderSourceFunc && + GL_CompileShaderFunc && + GL_GetShaderivFunc && + GL_GetShaderInfoLogFunc && + GL_GetProgramivFunc && + GL_GetProgramInfoLogFunc && + GL_CreateProgramFunc && + GL_AttachShaderFunc && + GL_LinkProgramFunc && + GL_BindAttribLocationFunc && + GL_UseProgramFunc && + GL_GetAttribLocationFunc && + GL_VertexAttribPointerFunc && + GL_EnableVertexAttribArrayFunc && + GL_DisableVertexAttribArrayFunc && + GL_GetUniformLocationFunc && + GL_Uniform1iFunc && + GL_Uniform1fFunc && + GL_Uniform3fFunc && + GL_Uniform4fFunc) { Con_Printf("FOUND: GLSL\n"); gl_glsl_able = true; } else { - Con_Warning ("GLSL not available\n"); + Con_Warning("GLSL not available\n"); } } else { - Con_Warning ("OpenGL version < 2, GLSL not available\n"); + Con_Warning("OpenGL version < 2, GLSL not available\n"); } // GLSL gamma // - if (COM_CheckParm("-noglslgamma")) - Con_Warning ("GLSL gamma disabled at command line\n"); - else if (gl_glsl_able) + if(COM_CheckParm("-noglslgamma")) + Con_Warning("GLSL gamma disabled at command line\n"); + else if(gl_glsl_able) { gl_glsl_gamma_able = true; } else { - Con_Warning ("GLSL gamma not available, using hardware gamma\n"); + Con_Warning("GLSL gamma not available, using hardware gamma\n"); } - // GLSL alias model rendering - // - if (COM_CheckParm("-noglslalias")) - Con_Warning ("GLSL alias model rendering disabled at command line\n"); - else if (gl_glsl_able && gl_vbo_able && gl_max_texture_units >= 3) + // GLSL alias model rendering + // + if(COM_CheckParm("-noglslalias")) + Con_Warning("GLSL alias model rendering disabled at command line\n"); + else if(gl_glsl_able && gl_vbo_able && gl_max_texture_units >= 3) { gl_glsl_alias_able = true; } else { - Con_Warning ("GLSL alias model rendering not available, using Fitz renderer\n"); + Con_Warning("GLSL alias model rendering not available, using Fitz renderer\n"); } } @@ -1125,25 +1132,25 @@ GL_SetupState -- johnfitz does all the stuff from GL_Init that needs to be done every time a new GL render context is created =============== */ -static void GL_SetupState (void) +static void GL_SetupState(void) { - glClearColor (0.15,0.15,0.15,0); //johnfitz -- originally 1,0,0,0 + glClearColor(0.15, 0.15, 0.15, 0); //johnfitz -- originally 1,0,0,0 glCullFace(GL_BACK); //johnfitz -- glquake used CCW with backwards culling -- let's do it right glFrontFace(GL_CW); //johnfitz -- glquake used CCW with backwards culling -- let's do it right glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.666); - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - glShadeModel (GL_FLAT); - glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //johnfitz - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + glShadeModel(GL_FLAT); + glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //johnfitz + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glDepthRange (0, 1); //johnfitz -- moved here becuase gl_ztrick is gone. - glDepthFunc (GL_LEQUAL); //johnfitz -- moved here becuase gl_ztrick is gone. + glDepthRange(0, 1); //johnfitz -- moved here becuase gl_ztrick is gone. + glDepthFunc(GL_LEQUAL); //johnfitz -- moved here becuase gl_ztrick is gone. } /* @@ -1151,50 +1158,50 @@ static void GL_SetupState (void) GL_Init =============== */ -static void GL_Init (void) +static void GL_Init(void) { - gl_vendor = (const char *) glGetString (GL_VENDOR); - gl_renderer = (const char *) glGetString (GL_RENDERER); - gl_version = (const char *) glGetString (GL_VERSION); - gl_extensions = (const char *) glGetString (GL_EXTENSIONS); + gl_vendor = (const char *) glGetString(GL_VENDOR); + gl_renderer = (const char *) glGetString(GL_RENDERER); + gl_version = (const char *) glGetString(GL_VERSION); + gl_extensions = (const char *) glGetString(GL_EXTENSIONS); - Con_SafePrintf ("GL_VENDOR: %s\n", gl_vendor); - Con_SafePrintf ("GL_RENDERER: %s\n", gl_renderer); - Con_SafePrintf ("GL_VERSION: %s\n", gl_version); + Con_SafePrintf("GL_VENDOR: %s\n", gl_vendor); + Con_SafePrintf("GL_RENDERER: %s\n", gl_renderer); + Con_SafePrintf("GL_VERSION: %s\n", gl_version); - if (gl_version == NULL || sscanf(gl_version, "%" PRIi32 ".%" PRIi32 "", &gl_version_major, &gl_version_minor) < 2) + if(gl_version == NULL || sscanf(gl_version, "%" PRIi32 ".%" PRIi32 "", &gl_version_major, &gl_version_minor) < 2) { gl_version_major = 0; gl_version_minor = 0; } - if (gl_extensions_nice != NULL) - Z_Free (gl_extensions_nice); - gl_extensions_nice = GL_MakeNiceExtensionsList (gl_extensions); + if(gl_extensions_nice != NULL) + Z_Free(gl_extensions_nice); + gl_extensions_nice = GL_MakeNiceExtensionsList(gl_extensions); - GL_CheckExtensions (); //johnfitz + GL_CheckExtensions(); //johnfitz #ifdef __APPLE__ // ericw -- enable multi-threaded OpenGL, gives a decent FPS boost. // https://developer.apple.com/library/mac/technotes/tn2085/ - if (host_parms->numcpus > 1 && - kCGLNoError != CGLEnable(CGLGetCurrentContext(), kCGLCEMPEngine)) + if(host_parms->numcpus > 1 && + kCGLNoError != CGLEnable(CGLGetCurrentContext(), kCGLCEMPEngine)) { - Con_Warning ("Couldn't enable multi-threaded OpenGL"); + Con_Warning("Couldn't enable multi-threaded OpenGL"); } #endif //johnfitz -- intel video workarounds from Baker - if (!strcmp(gl_vendor, "Intel")) + if(!strcmp(gl_vendor, "Intel")) { - Con_Printf ("Intel Display Adapter detected, enabling gl_clear\n"); - Cbuf_AddText ("gl_clear 1"); + Con_Printf("Intel Display Adapter detected, enabling gl_clear\n"); + Cbuf_AddText("gl_clear 1"); } //johnfitz - GLAlias_CreateShaders (); - GLWorld_CreateShaders (); - GL_ClearBufferBindings (); + GLAlias_CreateShaders(); + GLWorld_CreateShaders(); + GL_ClearBufferBindings(); } /* @@ -1202,7 +1209,7 @@ static void GL_Init (void) GL_BeginRendering -- sets values of glx, gly, glwidth, glheight ================= */ -void GL_BeginRendering (int32_t *x, int32_t *y, int32_t *width, int32_t *height) +void GL_BeginRendering(int32_t *x, int32_t *y, int32_t *width, int32_t *height) { *x = *y = 0; *width = vid.width; @@ -1214,20 +1221,20 @@ void GL_BeginRendering (int32_t *x, int32_t *y, int32_t *width, int32_t *height) GL_EndRendering ================= */ -void GL_EndRendering (void) +void GL_EndRendering(void) { - if (!scr_skipupdate) + if(!scr_skipupdate) { SDL_GL_SwapWindow(draw_context); } } -void VID_Shutdown (void) +void VID_Shutdown(void) { - if (vid_initialized) + if(vid_initialized) { - VID_Gamma_Shutdown (); //johnfitz + VID_Gamma_Shutdown(); //johnfitz SDL_QuitSubSystem(SDL_INIT_VIDEO); draw_context = NULL; @@ -1249,10 +1256,10 @@ MAIN WINDOW ClearAllStates ================ */ -static void ClearAllStates (void) +static void ClearAllStates(void) { - Key_ClearStates (); - IN_ClearStates (); + Key_ClearStates(); + IN_ClearStates(); } @@ -1267,15 +1274,15 @@ static void ClearAllStates (void) VID_DescribeCurrentMode_f ================= */ -static void VID_DescribeCurrentMode_f (void) +static void VID_DescribeCurrentMode_f(void) { - if (draw_context) + if(draw_context) Con_Printf("%" PRIi32 "x%" PRIi32 "x%" PRIi32 " %" PRIi32 "Hz %s\n", - VID_GetCurrentWidth(), - VID_GetCurrentHeight(), - VID_GetCurrentBPP(), - VID_GetCurrentRefreshRate(), - VID_GetFullscreen() ? "fullscreen" : "windowed"); + VID_GetCurrentWidth(), + VID_GetCurrentHeight(), + VID_GetCurrentBPP(), + VID_GetCurrentRefreshRate(), + VID_GetFullscreen() ? "fullscreen" : "windowed"); } /* @@ -1283,27 +1290,27 @@ static void VID_DescribeCurrentMode_f (void) VID_DescribeModes_f -- johnfitz -- changed formatting, and added refresh rates after each mode. ================= */ -static void VID_DescribeModes_f (void) +static void VID_DescribeModes_f(void) { - int32_t i; - int32_t lastwidth, lastheight, lastbpp, count; + int32_t i; + int32_t lastwidth, lastheight, lastbpp, count; lastwidth = lastheight = lastbpp = count = 0; - for (i = 0; i < nummodes; i++) + for(i = 0; i < nummodes; i++) { - if (lastwidth != modelist[i].width || lastheight != modelist[i].height || lastbpp != modelist[i].bpp) + if(lastwidth != modelist[i].width || lastheight != modelist[i].height || lastbpp != modelist[i].bpp) { - if (count > 0) - Con_SafePrintf ("\n"); - Con_SafePrintf (" %4" PRIi32 " x %4" PRIi32 " x %" PRIi32 " : %" PRIi32 "", modelist[i].width, modelist[i].height, modelist[i].bpp, modelist[i].refreshrate); + if(count > 0) + Con_SafePrintf("\n"); + Con_SafePrintf(" %4" PRIi32 " x %4" PRIi32 " x %" PRIi32 " : %" PRIi32 "", modelist[i].width, modelist[i].height, modelist[i].bpp, modelist[i].refreshrate); lastwidth = modelist[i].width; lastheight = modelist[i].height; lastbpp = modelist[i].bpp; count++; } } - Con_Printf ("\n%" PRIi32 " modes\n", count); + Con_Printf("\n%" PRIi32 " modes\n", count); } /* @@ -1311,10 +1318,10 @@ static void VID_DescribeModes_f (void) VID_FSAA_f -- ericw -- warn that vid_fsaa requires engine restart =================== */ -static void VID_FSAA_f (cvar_t *var) +static void VID_FSAA_f(cvar_t *var) { // don't print the warning if vid_fsaa is set during startup - if (vid_initialized) + if(vid_initialized) Con_Printf("%s %" PRIi32 " requires engine restart to take effect\n", var->name, (int32_t)var->value); } @@ -1329,19 +1336,19 @@ static void VID_FSAA_f (cvar_t *var) VID_InitModelist ================= */ -static void VID_InitModelist (void) +static void VID_InitModelist(void) { const int32_t sdlmodes = SDL_GetNumDisplayModes(0); int32_t i; nummodes = 0; - for (i = 0; i < sdlmodes; i++) + for(i = 0; i < sdlmodes; i++) { SDL_DisplayMode mode; - if (nummodes >= MAX_MODE_LIST) + if(nummodes >= MAX_MODE_LIST) break; - if (SDL_GetDisplayMode(0, i, &mode) == 0) + if(SDL_GetDisplayMode(0, i, &mode) == 0) { modelist[nummodes].width = mode.w; modelist[nummodes].height = mode.h; @@ -1357,56 +1364,57 @@ static void VID_InitModelist (void) VID_Init =================== */ -void VID_Init (void) +void VID_Init(void) { static char vid_center[] = "SDL_VIDEO_CENTERED=center"; - int32_t p, width, height, refreshrate, bpp; - int32_t display_width, display_height, display_refreshrate, display_bpp; - bool fullscreen; - const char *read_vars[] = { "vid_fullscreen", - "vid_width", - "vid_height", - "vid_refreshrate", - "vid_bpp", - "vid_vsync", - "vid_fsaa", - "vid_desktopfullscreen", - "vid_borderless"}; -#define num_readvars ( sizeof(read_vars)/sizeof(read_vars[0]) ) + int32_t p, width, height, refreshrate, bpp; + int32_t display_width, display_height, display_refreshrate, display_bpp; + bool fullscreen; + const char *read_vars[] = { "vid_fullscreen", + "vid_width", + "vid_height", + "vid_refreshrate", + "vid_bpp", + "vid_vsync", + "vid_fsaa", + "vid_desktopfullscreen", + "vid_borderless" + }; +#define num_readvars ( sizeof(read_vars)/sizeof(read_vars[0]) ) - Cvar_RegisterVariable (&vid_fullscreen); //johnfitz - Cvar_RegisterVariable (&vid_width); //johnfitz - Cvar_RegisterVariable (&vid_height); //johnfitz - Cvar_RegisterVariable (&vid_refreshrate); //johnfitz - Cvar_RegisterVariable (&vid_bpp); //johnfitz - Cvar_RegisterVariable (&vid_vsync); //johnfitz - Cvar_RegisterVariable (&vid_fsaa); //QuakeSpasm - Cvar_RegisterVariable (&vid_desktopfullscreen); //QuakeSpasm - Cvar_RegisterVariable (&vid_borderless); //QuakeSpasm - Cvar_SetCallback (&vid_fullscreen, VID_Changed_f); - Cvar_SetCallback (&vid_width, VID_Changed_f); - Cvar_SetCallback (&vid_height, VID_Changed_f); - Cvar_SetCallback (&vid_refreshrate, VID_Changed_f); - Cvar_SetCallback (&vid_bpp, VID_Changed_f); - Cvar_SetCallback (&vid_vsync, VID_Changed_f); - Cvar_SetCallback (&vid_fsaa, VID_FSAA_f); - Cvar_SetCallback (&vid_desktopfullscreen, VID_Changed_f); - Cvar_SetCallback (&vid_borderless, VID_Changed_f); + Cvar_RegisterVariable(&vid_fullscreen); //johnfitz + Cvar_RegisterVariable(&vid_width); //johnfitz + Cvar_RegisterVariable(&vid_height); //johnfitz + Cvar_RegisterVariable(&vid_refreshrate); //johnfitz + Cvar_RegisterVariable(&vid_bpp); //johnfitz + Cvar_RegisterVariable(&vid_vsync); //johnfitz + Cvar_RegisterVariable(&vid_fsaa); //QuakeSpasm + Cvar_RegisterVariable(&vid_desktopfullscreen); //QuakeSpasm + Cvar_RegisterVariable(&vid_borderless); //QuakeSpasm + Cvar_SetCallback(&vid_fullscreen, VID_Changed_f); + Cvar_SetCallback(&vid_width, VID_Changed_f); + Cvar_SetCallback(&vid_height, VID_Changed_f); + Cvar_SetCallback(&vid_refreshrate, VID_Changed_f); + Cvar_SetCallback(&vid_bpp, VID_Changed_f); + Cvar_SetCallback(&vid_vsync, VID_Changed_f); + Cvar_SetCallback(&vid_fsaa, VID_FSAA_f); + Cvar_SetCallback(&vid_desktopfullscreen, VID_Changed_f); + Cvar_SetCallback(&vid_borderless, VID_Changed_f); - Cmd_AddCommand ("vid_unlock", VID_Unlock); //johnfitz - Cmd_AddCommand ("vid_restart", VID_Restart); //johnfitz - Cmd_AddCommand ("vid_test", VID_Test); //johnfitz - Cmd_AddCommand ("vid_describecurrentmode", VID_DescribeCurrentMode_f); - Cmd_AddCommand ("vid_describemodes", VID_DescribeModes_f); + Cmd_AddCommand("vid_unlock", VID_Unlock); //johnfitz + Cmd_AddCommand("vid_restart", VID_Restart); //johnfitz + Cmd_AddCommand("vid_test", VID_Test); //johnfitz + Cmd_AddCommand("vid_describecurrentmode", VID_DescribeCurrentMode_f); + Cmd_AddCommand("vid_describemodes", VID_DescribeModes_f); - putenv (vid_center); /* SDL_putenv is problematic in versions <= 1.2.9 */ + putenv(vid_center); /* SDL_putenv is problematic in versions <= 1.2.9 */ - if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) + if(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) Sys_Error("Couldn't init SDL video: %s", SDL_GetError()); { SDL_DisplayMode mode; - if (SDL_GetDesktopDisplayMode(0, &mode) != 0) + if(SDL_GetDesktopDisplayMode(0, &mode) != 0) Sys_Error("Could not get desktop display mode"); display_width = mode.w; @@ -1415,9 +1423,9 @@ void VID_Init (void) display_bpp = SDL_BITSPERPIXEL(mode.format); } - Cvar_SetValueQuick (&vid_bpp, (float)display_bpp); + Cvar_SetValueQuick(&vid_bpp, (float)display_bpp); - if (CFG_OpenConfig("config.cfg") == 0) + if(CFG_OpenConfig("config.cfg") == 0) { CFG_ReadCvars(read_vars, num_readvars); CFG_CloseConfig(); @@ -1433,7 +1441,7 @@ void VID_Init (void) fullscreen = (int32_t)vid_fullscreen.value; fsaa = (int32_t)vid_fsaa.value; - if (COM_CheckParm("-current")) + if(COM_CheckParm("-current")) { width = display_width; height = display_height; @@ -1444,42 +1452,42 @@ void VID_Init (void) else { p = COM_CheckParm("-width"); - if (p && p < com_argc-1) + if(p && p < com_argc - 1) { - width = Q_atoi(com_argv[p+1]); + width = Q_atoi(com_argv[p + 1]); if(!COM_CheckParm("-height")) height = width * 3 / 4; } p = COM_CheckParm("-height"); - if (p && p < com_argc-1) + if(p && p < com_argc - 1) { - height = Q_atoi(com_argv[p+1]); + height = Q_atoi(com_argv[p + 1]); if(!COM_CheckParm("-width")) width = height * 4 / 3; } p = COM_CheckParm("-refreshrate"); - if (p && p < com_argc-1) - refreshrate = Q_atoi(com_argv[p+1]); + if(p && p < com_argc - 1) + refreshrate = Q_atoi(com_argv[p + 1]); p = COM_CheckParm("-bpp"); - if (p && p < com_argc-1) - bpp = Q_atoi(com_argv[p+1]); + if(p && p < com_argc - 1) + bpp = Q_atoi(com_argv[p + 1]); - if (COM_CheckParm("-window") || COM_CheckParm("-w")) + if(COM_CheckParm("-window") || COM_CheckParm("-w")) fullscreen = false; - else if (COM_CheckParm("-fullscreen") || COM_CheckParm("-f")) + else if(COM_CheckParm("-fullscreen") || COM_CheckParm("-f")) fullscreen = true; } - p = COM_CheckParm ("-fsaa"); - if (p && p < com_argc-1) - fsaa = atoi(com_argv[p+1]); + p = COM_CheckParm("-fsaa"); + if(p && p < com_argc - 1) + fsaa = atoi(com_argv[p + 1]); - if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) + if(!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) { width = (int32_t)vid_width.value; height = (int32_t)vid_height.value; @@ -1488,7 +1496,7 @@ void VID_Init (void) fullscreen = (int32_t)vid_fullscreen.value; } - if (!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) + if(!VID_ValidMode(width, height, refreshrate, bpp, fullscreen)) { width = 640; height = 480; @@ -1502,16 +1510,16 @@ void VID_Init (void) vid.maxwarpwidth = WARP_WIDTH; vid.maxwarpheight = WARP_HEIGHT; vid.colormap = host_colormap; - vid.fullbright = 256 - LittleLong (*((int32_t *)vid.colormap + 2048)); + vid.fullbright = 256 - LittleLong(*((int32_t *)vid.colormap + 2048)); // set window icon PL_SetWindowIcon(); - VID_SetMode (width, height, refreshrate, bpp, fullscreen); + VID_SetMode(width, height, refreshrate, bpp, fullscreen); - GL_Init (); - GL_SetupState (); - Cmd_AddCommand ("gl_info", GL_Info_f); //johnfitz + GL_Init(); + GL_SetupState(); + Cmd_AddCommand("gl_info", GL_Info_f); //johnfitz //johnfitz -- removed code creating "glquake" subdirectory @@ -1528,7 +1536,7 @@ void VID_Init (void) } // new proc by S.A., called by alt-return key binding. -void VID_Toggle (void) +void VID_Toggle(void) { // disabling the fast path completely because SDL_SetWindowFullscreen was changing // the window size on SDL2/WinXP and we weren't set up to handle it. --ericw @@ -1540,11 +1548,11 @@ void VID_Toggle (void) bool toggleWorked; Uint32 flags = 0; - S_ClearBuffer (); + S_ClearBuffer(); - if (!vid_toggle_works) + if(!vid_toggle_works) goto vrestart; - else if (gl_vbo_able) + else if(gl_vbo_able) { // disabling the fast path because with SDL 1.2 it invalidates VBOs (using them // causes a crash, sugesting that the fullscreen toggle created a new GL context, @@ -1556,36 +1564,37 @@ void VID_Toggle (void) goto vrestart; } - if (!VID_GetFullscreen()) { + if(!VID_GetFullscreen()) + { flags = vid_desktopfullscreen.value ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN; } toggleWorked = SDL_SetWindowFullscreen(draw_context, flags) == 0; - if (toggleWorked) + if(toggleWorked) { - Sbar_Changed (); // Sbar seems to need refreshing + Sbar_Changed(); // Sbar seems to need refreshing modestate = VID_GetFullscreen() ? MS_FULLSCREEN : MS_WINDOWED; VID_SyncCvars(); // update mouse grab - if (key_dest == key_console || key_dest == key_menu) + if(key_dest == key_console || key_dest == key_menu) { - if (modestate == MS_WINDOWED) + if(modestate == MS_WINDOWED) IN_Deactivate(true); - else if (modestate == MS_FULLSCREEN) + else if(modestate == MS_FULLSCREEN) IN_Activate(); } } else { vid_toggle_works = false; - Con_DPrintf ("SDL_WM_ToggleFullScreen failed, attempting VID_Restart\n"); - vrestart: - Cvar_SetQuick (&vid_fullscreen, VID_GetFullscreen() ? "0" : "1"); - Cbuf_AddText ("vid_restart\n"); + Con_DPrintf("SDL_WM_ToggleFullScreen failed, attempting VID_Restart\n"); +vrestart: + Cvar_SetQuick(&vid_fullscreen, VID_GetFullscreen() ? "0" : "1"); + Cbuf_AddText("vid_restart\n"); } } @@ -1594,21 +1603,21 @@ void VID_Toggle (void) VID_SyncCvars -- johnfitz -- set vid cvars to match current video mode ================ */ -void VID_SyncCvars (void) +void VID_SyncCvars(void) { - if (draw_context) + if(draw_context) { - if (!VID_GetDesktopFullscreen()) + if(!VID_GetDesktopFullscreen()) { - Cvar_SetValueQuick (&vid_width, VID_GetCurrentWidth()); - Cvar_SetValueQuick (&vid_height, VID_GetCurrentHeight()); + Cvar_SetValueQuick(&vid_width, VID_GetCurrentWidth()); + Cvar_SetValueQuick(&vid_height, VID_GetCurrentHeight()); } - Cvar_SetValueQuick (&vid_refreshrate, VID_GetCurrentRefreshRate()); - Cvar_SetValueQuick (&vid_bpp, VID_GetCurrentBPP()); - Cvar_SetQuick (&vid_fullscreen, VID_GetFullscreen() ? "1" : "0"); + Cvar_SetValueQuick(&vid_refreshrate, VID_GetCurrentRefreshRate()); + Cvar_SetValueQuick(&vid_bpp, VID_GetCurrentBPP()); + Cvar_SetQuick(&vid_fullscreen, VID_GetFullscreen() ? "1" : "0"); // don't sync vid_desktopfullscreen, it's a user preference that // should persist even if we are in windowed mode. - Cvar_SetQuick (&vid_vsync, VID_GetVSync() ? "1" : "0"); + Cvar_SetQuick(&vid_vsync, VID_GetVSync() ? "1" : "0"); } vid_changed = false; @@ -1620,7 +1629,8 @@ void VID_SyncCvars (void) // //========================================================================== -enum { +enum +{ VID_OPT_MODE, VID_OPT_BPP, VID_OPT_REFRESHRATE, @@ -1631,10 +1641,11 @@ enum { VIDEO_OPTIONS_ITEMS }; -static int32_t video_options_cursor = 0; +static int32_t video_options_cursor = 0; -typedef struct { - int32_t width,height; +typedef struct +{ + int32_t width, height; } vid_menu_mode; //TODO: replace these fixed-length arrays with hunk_allocated buffers @@ -1645,30 +1656,30 @@ static int32_t vid_menu_bpps[MAX_BPPS_LIST]; static int32_t vid_menu_numbpps = 0; static int32_t vid_menu_rates[MAX_RATES_LIST]; -static int32_t vid_menu_numrates=0; +static int32_t vid_menu_numrates = 0; /* ================ VID_Menu_Init ================ */ -static void VID_Menu_Init (void) +static void VID_Menu_Init(void) { int32_t i, j, h, w; - for (i = 0; i < nummodes; i++) + for(i = 0; i < nummodes; i++) { w = modelist[i].width; h = modelist[i].height; - for (j = 0; j < vid_menu_nummodes; j++) + for(j = 0; j < vid_menu_nummodes; j++) { - if (vid_menu_modes[j].width == w && - vid_menu_modes[j].height == h) + if(vid_menu_modes[j].width == w && + vid_menu_modes[j].height == h) break; } - if (j == vid_menu_nummodes) + if(j == vid_menu_nummodes) { vid_menu_modes[j].width = w; vid_menu_modes[j].height = h; @@ -1684,31 +1695,31 @@ VID_Menu_RebuildBppList regenerates bpp list based on current vid_width and vid_height ================ */ -static void VID_Menu_RebuildBppList (void) +static void VID_Menu_RebuildBppList(void) { int32_t i, j, b; vid_menu_numbpps = 0; - for (i = 0; i < nummodes; i++) + for(i = 0; i < nummodes; i++) { - if (vid_menu_numbpps >= MAX_BPPS_LIST) + if(vid_menu_numbpps >= MAX_BPPS_LIST) break; //bpp list is limited to bpps available with current width/height - if (modelist[i].width != vid_width.value || - modelist[i].height != vid_height.value) + if(modelist[i].width != vid_width.value || + modelist[i].height != vid_height.value) continue; b = modelist[i].bpp; - for (j = 0; j < vid_menu_numbpps; j++) + for(j = 0; j < vid_menu_numbpps; j++) { - if (vid_menu_bpps[j] == b) + if(vid_menu_bpps[j] == b) break; } - if (j == vid_menu_numbpps) + if(j == vid_menu_numbpps) { vid_menu_bpps[j] = b; vid_menu_numbpps++; @@ -1716,19 +1727,19 @@ static void VID_Menu_RebuildBppList (void) } //if there are no valid fullscreen bpps for this width/height, just pick one - if (vid_menu_numbpps == 0) + if(vid_menu_numbpps == 0) { - Cvar_SetValueQuick (&vid_bpp, (float)modelist[0].bpp); + Cvar_SetValueQuick(&vid_bpp, (float)modelist[0].bpp); return; } //if vid_bpp is not in the new list, change vid_bpp - for (i = 0; i < vid_menu_numbpps; i++) - if (vid_menu_bpps[i] == (int32_t)(vid_bpp.value)) + for(i = 0; i < vid_menu_numbpps; i++) + if(vid_menu_bpps[i] == (int32_t)(vid_bpp.value)) break; - if (i == vid_menu_numbpps) - Cvar_SetValueQuick (&vid_bpp, (float)vid_menu_bpps[0]); + if(i == vid_menu_numbpps) + Cvar_SetValueQuick(&vid_bpp, (float)vid_menu_bpps[0]); } /* @@ -1738,29 +1749,29 @@ VID_Menu_RebuildRateList regenerates rate list based on current vid_width, vid_height and vid_bpp ================ */ -static void VID_Menu_RebuildRateList (void) +static void VID_Menu_RebuildRateList(void) { - int32_t i,j,r; + int32_t i, j, r; - vid_menu_numrates=0; + vid_menu_numrates = 0; - for (i=0;i= vid_menu_nummodes) + if(i >= vid_menu_nummodes) i = 0; - else if (i < 0) - i = vid_menu_nummodes-1; + else if(i < 0) + i = vid_menu_nummodes - 1; } - Cvar_SetValueQuick (&vid_width, (float)vid_menu_modes[i].width); - Cvar_SetValueQuick (&vid_height, (float)vid_menu_modes[i].height); - VID_Menu_RebuildBppList (); - VID_Menu_RebuildRateList (); + Cvar_SetValueQuick(&vid_width, (float)vid_menu_modes[i].width); + Cvar_SetValueQuick(&vid_height, (float)vid_menu_modes[i].height); + VID_Menu_RebuildBppList(); + VID_Menu_RebuildRateList(); } } @@ -1831,32 +1842,32 @@ VID_Menu_ChooseNextBpp chooses next bpp in order, then updates vid_bpp cvar ================ */ -static void VID_Menu_ChooseNextBpp (int32_t dir) +static void VID_Menu_ChooseNextBpp(int32_t dir) { int32_t i; - if (vid_menu_numbpps) + if(vid_menu_numbpps) { - for (i = 0; i < vid_menu_numbpps; i++) + for(i = 0; i < vid_menu_numbpps; i++) { - if (vid_menu_bpps[i] == vid_bpp.value) + if(vid_menu_bpps[i] == vid_bpp.value) break; } - if (i == vid_menu_numbpps) //can't find it in list + if(i == vid_menu_numbpps) //can't find it in list { i = 0; } else { i += dir; - if (i >= vid_menu_numbpps) + if(i >= vid_menu_numbpps) i = 0; - else if (i < 0) - i = vid_menu_numbpps-1; + else if(i < 0) + i = vid_menu_numbpps - 1; } - Cvar_SetValueQuick (&vid_bpp, (float)vid_menu_bpps[i]); + Cvar_SetValueQuick(&vid_bpp, (float)vid_menu_bpps[i]); } } @@ -1867,30 +1878,30 @@ VID_Menu_ChooseNextRate chooses next refresh rate in order, then updates vid_refreshrate cvar ================ */ -static void VID_Menu_ChooseNextRate (int32_t dir) +static void VID_Menu_ChooseNextRate(int32_t dir) { int32_t i; - for (i=0;i=vid_menu_numrates) + i += dir; + if(i >= vid_menu_numrates) i = 0; - else if (i<0) - i = vid_menu_numrates-1; + else if(i < 0) + i = vid_menu_numrates - 1; } - Cvar_SetValue ("vid_refreshrate",(float)vid_menu_rates[i]); + Cvar_SetValue("vid_refreshrate", (float)vid_menu_rates[i]); } /* @@ -1898,49 +1909,49 @@ static void VID_Menu_ChooseNextRate (int32_t dir) VID_MenuKey ================ */ -static void VID_MenuKey (int32_t key) +static void VID_MenuKey(int32_t key) { - switch (key) + switch(key) { case K_ESCAPE: case K_BBUTTON: - VID_SyncCvars (); //sync cvars before leaving menu. FIXME: there are other ways to leave menu - S_LocalSound ("misc/menu1.wav"); - M_Menu_Options_f (); + VID_SyncCvars(); //sync cvars before leaving menu. FIXME: there are other ways to leave menu + S_LocalSound("misc/menu1.wav"); + M_Menu_Options_f(); break; case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); video_options_cursor--; - if (video_options_cursor < 0) - video_options_cursor = VIDEO_OPTIONS_ITEMS-1; + if(video_options_cursor < 0) + video_options_cursor = VIDEO_OPTIONS_ITEMS - 1; break; case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); video_options_cursor++; - if (video_options_cursor >= VIDEO_OPTIONS_ITEMS) + if(video_options_cursor >= VIDEO_OPTIONS_ITEMS) video_options_cursor = 0; break; case K_LEFTARROW: - S_LocalSound ("misc/menu3.wav"); - switch (video_options_cursor) + S_LocalSound("misc/menu3.wav"); + switch(video_options_cursor) { case VID_OPT_MODE: - VID_Menu_ChooseNextMode (1); + VID_Menu_ChooseNextMode(1); break; case VID_OPT_BPP: - VID_Menu_ChooseNextBpp (1); + VID_Menu_ChooseNextBpp(1); break; case VID_OPT_REFRESHRATE: - VID_Menu_ChooseNextRate (1); + VID_Menu_ChooseNextRate(1); break; case VID_OPT_FULLSCREEN: - Cbuf_AddText ("toggle vid_fullscreen\n"); + Cbuf_AddText("toggle vid_fullscreen\n"); break; case VID_OPT_VSYNC: - Cbuf_AddText ("toggle vid_vsync\n"); // kristian + Cbuf_AddText("toggle vid_vsync\n"); // kristian break; default: break; @@ -1948,23 +1959,23 @@ static void VID_MenuKey (int32_t key) break; case K_RIGHTARROW: - S_LocalSound ("misc/menu3.wav"); - switch (video_options_cursor) + S_LocalSound("misc/menu3.wav"); + switch(video_options_cursor) { case VID_OPT_MODE: - VID_Menu_ChooseNextMode (-1); + VID_Menu_ChooseNextMode(-1); break; case VID_OPT_BPP: - VID_Menu_ChooseNextBpp (-1); + VID_Menu_ChooseNextBpp(-1); break; case VID_OPT_REFRESHRATE: - VID_Menu_ChooseNextRate (-1); + VID_Menu_ChooseNextRate(-1); break; case VID_OPT_FULLSCREEN: - Cbuf_AddText ("toggle vid_fullscreen\n"); + Cbuf_AddText("toggle vid_fullscreen\n"); break; case VID_OPT_VSYNC: - Cbuf_AddText ("toggle vid_vsync\n"); + Cbuf_AddText("toggle vid_vsync\n"); break; default: break; @@ -1975,28 +1986,28 @@ static void VID_MenuKey (int32_t key) case K_KP_ENTER: case K_ABUTTON: m_entersound = true; - switch (video_options_cursor) + switch(video_options_cursor) { case VID_OPT_MODE: - VID_Menu_ChooseNextMode (1); + VID_Menu_ChooseNextMode(1); break; case VID_OPT_BPP: - VID_Menu_ChooseNextBpp (1); + VID_Menu_ChooseNextBpp(1); break; case VID_OPT_REFRESHRATE: - VID_Menu_ChooseNextRate (1); + VID_Menu_ChooseNextRate(1); break; case VID_OPT_FULLSCREEN: - Cbuf_AddText ("toggle vid_fullscreen\n"); + Cbuf_AddText("toggle vid_fullscreen\n"); break; case VID_OPT_VSYNC: - Cbuf_AddText ("toggle vid_vsync\n"); + Cbuf_AddText("toggle vid_vsync\n"); break; case VID_OPT_TEST: - Cbuf_AddText ("vid_test\n"); + Cbuf_AddText("vid_test\n"); break; case VID_OPT_APPLY: - Cbuf_AddText ("vid_restart\n"); + Cbuf_AddText("vid_restart\n"); key_dest = key_game; m_state = m_none; IN_Activate(); @@ -2016,7 +2027,7 @@ static void VID_MenuKey (int32_t key) VID_MenuDraw ================ */ -static void VID_MenuDraw (void) +static void VID_MenuDraw(void) { int32_t i, y; qpic_t *p; @@ -2025,60 +2036,60 @@ static void VID_MenuDraw (void) y = 4; // plaque - p = Draw_CachePic ("gfx/qplaque.lmp"); - M_DrawTransPic (16, y, p); + p = Draw_CachePic("gfx/qplaque.lmp"); + M_DrawTransPic(16, y, p); //p = Draw_CachePic ("gfx/vidmodes.lmp"); - p = Draw_CachePic ("gfx/p_option.lmp"); - M_DrawPic ( (320-p->width)/2, y, p); + p = Draw_CachePic("gfx/p_option.lmp"); + M_DrawPic((320 - p->width) / 2, y, p); y += 28; // title title = "Video Options"; - M_PrintWhite ((320-8*strlen(title))/2, y, title); + M_PrintWhite((320 - 8 * strlen(title)) / 2, y, title); y += 16; // options - for (i = 0; i < VIDEO_OPTIONS_ITEMS; i++) + for(i = 0; i < VIDEO_OPTIONS_ITEMS; i++) { - switch (i) + switch(i) { case VID_OPT_MODE: - M_Print (16, y, " Video mode"); - M_Print (184, y, va("%" PRIi32 "x%" PRIi32 "", (int32_t)vid_width.value, (int32_t)vid_height.value)); + M_Print(16, y, " Video mode"); + M_Print(184, y, va("%" PRIi32 "x%" PRIi32 "", (int32_t)vid_width.value, (int32_t)vid_height.value)); break; case VID_OPT_BPP: - M_Print (16, y, " Color depth"); - M_Print (184, y, va("%" PRIi32 "", (int32_t)vid_bpp.value)); + M_Print(16, y, " Color depth"); + M_Print(184, y, va("%" PRIi32 "", (int32_t)vid_bpp.value)); break; case VID_OPT_REFRESHRATE: - M_Print (16, y, " Refresh rate"); - M_Print (184, y, va("%" PRIi32 "", (int32_t)vid_refreshrate.value)); + M_Print(16, y, " Refresh rate"); + M_Print(184, y, va("%" PRIi32 "", (int32_t)vid_refreshrate.value)); break; case VID_OPT_FULLSCREEN: - M_Print (16, y, " Fullscreen"); - M_DrawCheckbox (184, y, (int32_t)vid_fullscreen.value); + M_Print(16, y, " Fullscreen"); + M_DrawCheckbox(184, y, (int32_t)vid_fullscreen.value); break; case VID_OPT_VSYNC: - M_Print (16, y, " Vertical sync"); - if (gl_swap_control) - M_DrawCheckbox (184, y, (int32_t)vid_vsync.value); + M_Print(16, y, " Vertical sync"); + if(gl_swap_control) + M_DrawCheckbox(184, y, (int32_t)vid_vsync.value); else - M_Print (184, y, "N/A"); + M_Print(184, y, "N/A"); break; case VID_OPT_TEST: y += 8; //separate the test and apply items - M_Print (16, y, " Test changes"); + M_Print(16, y, " Test changes"); break; case VID_OPT_APPLY: - M_Print (16, y, " Apply changes"); + M_Print(16, y, " Apply changes"); break; } - if (video_options_cursor == i) - M_DrawCharacter (168, y, 12+((int32_t)(realtime*4)&1)); + if(video_options_cursor == i) + M_DrawCharacter(168, y, 12 + ((int32_t)(realtime * 4) & 1)); y += 8; } @@ -2089,7 +2100,7 @@ static void VID_MenuDraw (void) VID_Menu_f ================ */ -static void VID_Menu_f (void) +static void VID_Menu_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -2097,10 +2108,10 @@ static void VID_Menu_f (void) m_entersound = true; //set all the cvars to match the current mode when entering the menu - VID_SyncCvars (); + VID_SyncCvars(); //set up bpp and rate lists based on current cvars - VID_Menu_RebuildBppList (); - VID_Menu_RebuildRateList (); + VID_Menu_RebuildBppList(); + VID_Menu_RebuildRateList(); } diff --git a/source/gl_warp.c b/source/gl_warp.c index 3c8bde6..db7341c 100644 --- a/source/gl_warp.c +++ b/source/gl_warp.c @@ -31,7 +31,7 @@ cvar_t r_waterwarp = {"r_waterwarp", "1", CVAR_NONE}; int32_t gl_warpimagesize; float load_subdivide_size; //johnfitz -- remember what subdivide_size value was when this map was loaded -float turbsin[] = +float turbsin[] = { #include "gl_warp_sin.h" }; @@ -45,108 +45,108 @@ float turbsin[] = // //============================================================================== -extern qmodel_t *loadmodel; +extern qmodel_t *loadmodel; -msurface_t *warpface; +msurface_t *warpface; cvar_t gl_subdivide_size = {"gl_subdivide_size", "128", CVAR_ARCHIVE}; -void BoundPoly (int32_t numverts, float *verts, vec3_t mins, vec3_t maxs) +void BoundPoly(int32_t numverts, float *verts, vec3_t mins, vec3_t maxs) { - int32_t i, j; - float *v; + int32_t i, j; + float *v; mins[0] = mins[1] = mins[2] = 999999999; maxs[0] = maxs[1] = maxs[2] = -999999999; v = verts; - for (i=0 ; i maxs[j]) + if(*v > maxs[j]) maxs[j] = *v; } } -void SubdividePolygon (int32_t numverts, float *verts) +void SubdividePolygon(int32_t numverts, float *verts) { - int32_t i, j, k; - vec3_t mins, maxs; - float m; - float *v; - vec3_t front[64], back[64]; - int32_t f, b; - float dist[64]; - float frac; - glpoly_t *poly; - float s, t; + int32_t i, j, k; + vec3_t mins, maxs; + float m; + float *v; + vec3_t front[64], back[64]; + int32_t f, b; + float dist[64]; + float frac; + glpoly_t *poly; + float s, t; - if (numverts > 60) - Sys_Error ("numverts = %" PRIi32 "", numverts); + if(numverts > 60) + Sys_Error("numverts = %" PRIi32 "", numverts); - BoundPoly (numverts, verts, mins, maxs); + BoundPoly(numverts, verts, mins, maxs); - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { m = (mins[i] + maxs[i]) * 0.5; - m = gl_subdivide_size.value * floor (m/gl_subdivide_size.value + 0.5); - if (maxs[i] - m < 8) + m = gl_subdivide_size.value * floor(m / gl_subdivide_size.value + 0.5); + if(maxs[i] - m < 8) continue; - if (m - mins[i] < 8) + if(m - mins[i] < 8) continue; // cut it v = verts + i; - for (j=0 ; j= 0) + if(dist[j] >= 0) { - VectorCopy (v, front[f]); + VectorCopy(v, front[f]); f++; } - if (dist[j] <= 0) + if(dist[j] <= 0) { - VectorCopy (v, back[b]); + VectorCopy(v, back[b]); b++; } - if (dist[j] == 0 || dist[j+1] == 0) + if(dist[j] == 0 || dist[j + 1] == 0) continue; - if ( (dist[j] > 0) != (dist[j+1] > 0) ) + if((dist[j] > 0) != (dist[j + 1] > 0)) { // clip point - frac = dist[j] / (dist[j] - dist[j+1]); - for (k=0 ; k<3 ; k++) - front[f][k] = back[b][k] = v[k] + frac*(v[3+k] - v[k]); + frac = dist[j] / (dist[j] - dist[j + 1]); + for(k = 0 ; k < 3 ; k++) + front[f][k] = back[b][k] = v[k] + frac * (v[3 + k] - v[k]); f++; b++; } } - SubdividePolygon (f, front[0]); - SubdividePolygon (b, back[0]); + SubdividePolygon(f, front[0]); + SubdividePolygon(b, back[0]); return; } - poly = (glpoly_t *) Hunk_Alloc (sizeof(glpoly_t) + (numverts-4) * VERTEXSIZE*sizeof(float)); + poly = (glpoly_t *) Hunk_Alloc(sizeof(glpoly_t) + (numverts - 4) * VERTEXSIZE * sizeof(float)); poly->next = warpface->polys->next; warpface->polys->next = poly; poly->numverts = numverts; - for (i=0 ; iverts[i]); - s = DotProduct (verts, warpface->texinfo->vecs[0]); - t = DotProduct (verts, warpface->texinfo->vecs[1]); + VectorCopy(verts, poly->verts[i]); + s = DotProduct(verts, warpface->texinfo->vecs[0]); + t = DotProduct(verts, warpface->texinfo->vecs[1]); poly->verts[i][3] = s; poly->verts[i][4] = t; } @@ -157,19 +157,19 @@ void SubdividePolygon (int32_t numverts, float *verts) GL_SubdivideSurface ================ */ -void GL_SubdivideSurface (msurface_t *fa) +void GL_SubdivideSurface(msurface_t *fa) { - vec3_t verts[64]; - int32_t i; + vec3_t verts[64]; + int32_t i; warpface = fa; //the first poly in the chain is the undivided poly for newwater rendering. //grab the verts from that. - for (i=0; ipolys->numverts; i++) - VectorCopy (fa->polys->verts[i], verts[i]); + for(i = 0; i < fa->polys->numverts; i++) + VectorCopy(fa->polys->verts[i], verts[i]); - SubdividePolygon (fa->polys->numverts, verts[0]); + SubdividePolygon(fa->polys->numverts, verts[0]); } /* @@ -177,32 +177,32 @@ void GL_SubdivideSurface (msurface_t *fa) DrawWaterPoly -- johnfitz ================ */ -void DrawWaterPoly (glpoly_t *p) +void DrawWaterPoly(glpoly_t *p) { - float *v; - int32_t i; + float *v; + int32_t i; - if (load_subdivide_size > 48) + if(load_subdivide_size > 48) { - glBegin (GL_POLYGON); + glBegin(GL_POLYGON); v = p->verts[0]; - for (i=0 ; inumverts ; i++, v+= VERTEXSIZE) + for(i = 0 ; i < p->numverts ; i++, v += VERTEXSIZE) { - glTexCoord2f (WARPCALC2(v[3],v[4]), WARPCALC2(v[4],v[3])); - glVertex3fv (v); + glTexCoord2f(WARPCALC2(v[3], v[4]), WARPCALC2(v[4], v[3])); + glVertex3fv(v); } - glEnd (); + glEnd(); } else { - glBegin (GL_POLYGON); + glBegin(GL_POLYGON); v = p->verts[0]; - for (i=0 ; inumverts ; i++, v+= VERTEXSIZE) + for(i = 0 ; i < p->numverts ; i++, v += VERTEXSIZE) { - glTexCoord2f (WARPCALC(v[3],v[4]), WARPCALC(v[4],v[3])); - glVertex3fv (v); + glTexCoord2f(WARPCALC(v[3], v[4]), WARPCALC(v[4], v[3])); + glVertex3fv(v); } - glEnd (); + glEnd(); } } @@ -217,45 +217,45 @@ void DrawWaterPoly (glpoly_t *p) R_UpdateWarpTextures -- johnfitz -- each frame, update warping textures ============= */ -void R_UpdateWarpTextures (void) +void R_UpdateWarpTextures(void) { texture_t *tx; int32_t i; float x, y, x2, warptess; - if (r_oldwater.value || cl.paused || r_drawflat_cheatsafe || r_lightmap_cheatsafe) + if(r_oldwater.value || cl.paused || r_drawflat_cheatsafe || r_lightmap_cheatsafe) return; - warptess = 128.0/CLAMP (3.0, floor(r_waterquality.value), 64.0); + warptess = 128.0 / CLAMP(3.0, floor(r_waterquality.value), 64.0); - for (i=0; inumtextures; i++) + for(i = 0; i < cl.worldmodel->numtextures; i++) { - if (!(tx = cl.worldmodel->textures[i])) + if(!(tx = cl.worldmodel->textures[i])) continue; - if (!tx->update_warp) + if(!tx->update_warp) continue; //render warp - GL_SetCanvas (CANVAS_WARPIMAGE); - GL_Bind (tx->gltexture); - for (x=0.0; x<128.0; x=x2) + GL_SetCanvas(CANVAS_WARPIMAGE); + GL_Bind(tx->gltexture); + for(x = 0.0; x < 128.0; x = x2) { x2 = x + warptess; - glBegin (GL_TRIANGLE_STRIP); - for (y=0.0; y<128.01; y+=warptess) // .01 for rounding errors + glBegin(GL_TRIANGLE_STRIP); + for(y = 0.0; y < 128.01; y += warptess) // .01 for rounding errors { - glTexCoord2f (WARPCALC(x,y), WARPCALC(y,x)); - glVertex2f (x,y); - glTexCoord2f (WARPCALC(x2,y), WARPCALC(y,x2)); - glVertex2f (x2,y); + glTexCoord2f(WARPCALC(x, y), WARPCALC(y, x)); + glVertex2f(x, y); + glTexCoord2f(WARPCALC(x2, y), WARPCALC(y, x2)); + glVertex2f(x2, y); } glEnd(); } //copy to texture - GL_Bind (tx->warpimage); - glCopyTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, glx, gly+glheight-gl_warpimagesize, gl_warpimagesize, gl_warpimagesize); + GL_Bind(tx->warpimage); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, glx, gly + glheight - gl_warpimagesize, gl_warpimagesize, gl_warpimagesize); tx->update_warp = false; } @@ -264,8 +264,8 @@ void R_UpdateWarpTextures (void) GL_SetCanvas(CANVAS_DEFAULT); //if warp render went down into sbar territory, we need to be sure to refresh it next frame - if (gl_warpimagesize + sb_lines > glheight) - Sbar_Changed (); + if(gl_warpimagesize + sb_lines > glheight) + Sbar_Changed(); //if viewsize is less than 100, we need to redraw the frame around the viewport scr_tileclear_updates = 0; diff --git a/source/gl_warp_sin.h b/source/gl_warp_sin.h index 313ab4e..f90e427 100644 --- a/source/gl_warp_sin.h +++ b/source/gl_warp_sin.h @@ -17,68 +17,68 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ - 0, 0.19633, 0.392541, 0.588517, - 0.784137, 0.979285, 1.17384, 1.3677, - 1.56072, 1.75281, 1.94384, 2.1337, - 2.32228, 2.50945, 2.69512, 2.87916, - 3.06147, 3.24193, 3.42044, 3.59689, - 3.77117, 3.94319, 4.11282, 4.27998, - 4.44456, 4.60647, 4.76559, 4.92185, - 5.07515, 5.22538, 5.37247, 5.51632, - 5.65685, 5.79398, 5.92761, 6.05767, - 6.18408, 6.30677, 6.42566, 6.54068, - 6.65176, 6.75883, 6.86183, 6.9607, - 7.05537, 7.14579, 7.23191, 7.31368, - 7.39104, 7.46394, 7.53235, 7.59623, - 7.65552, 7.71021, 7.76025, 7.80562, - 7.84628, 7.88222, 7.91341, 7.93984, - 7.96148, 7.97832, 7.99036, 7.99759, - 8, 7.99759, 7.99036, 7.97832, - 7.96148, 7.93984, 7.91341, 7.88222, - 7.84628, 7.80562, 7.76025, 7.71021, - 7.65552, 7.59623, 7.53235, 7.46394, - 7.39104, 7.31368, 7.23191, 7.14579, - 7.05537, 6.9607, 6.86183, 6.75883, - 6.65176, 6.54068, 6.42566, 6.30677, - 6.18408, 6.05767, 5.92761, 5.79398, - 5.65685, 5.51632, 5.37247, 5.22538, - 5.07515, 4.92185, 4.76559, 4.60647, - 4.44456, 4.27998, 4.11282, 3.94319, - 3.77117, 3.59689, 3.42044, 3.24193, - 3.06147, 2.87916, 2.69512, 2.50945, - 2.32228, 2.1337, 1.94384, 1.75281, - 1.56072, 1.3677, 1.17384, 0.979285, - 0.784137, 0.588517, 0.392541, 0.19633, - 9.79717e-16, -0.19633, -0.392541, -0.588517, - -0.784137, -0.979285, -1.17384, -1.3677, - -1.56072, -1.75281, -1.94384, -2.1337, - -2.32228, -2.50945, -2.69512, -2.87916, - -3.06147, -3.24193, -3.42044, -3.59689, - -3.77117, -3.94319, -4.11282, -4.27998, - -4.44456, -4.60647, -4.76559, -4.92185, - -5.07515, -5.22538, -5.37247, -5.51632, - -5.65685, -5.79398, -5.92761, -6.05767, - -6.18408, -6.30677, -6.42566, -6.54068, - -6.65176, -6.75883, -6.86183, -6.9607, - -7.05537, -7.14579, -7.23191, -7.31368, - -7.39104, -7.46394, -7.53235, -7.59623, - -7.65552, -7.71021, -7.76025, -7.80562, - -7.84628, -7.88222, -7.91341, -7.93984, - -7.96148, -7.97832, -7.99036, -7.99759, - -8, -7.99759, -7.99036, -7.97832, - -7.96148, -7.93984, -7.91341, -7.88222, - -7.84628, -7.80562, -7.76025, -7.71021, - -7.65552, -7.59623, -7.53235, -7.46394, - -7.39104, -7.31368, -7.23191, -7.14579, - -7.05537, -6.9607, -6.86183, -6.75883, - -6.65176, -6.54068, -6.42566, -6.30677, - -6.18408, -6.05767, -5.92761, -5.79398, - -5.65685, -5.51632, -5.37247, -5.22538, - -5.07515, -4.92185, -4.76559, -4.60647, - -4.44456, -4.27998, -4.11282, -3.94319, - -3.77117, -3.59689, -3.42044, -3.24193, - -3.06147, -2.87916, -2.69512, -2.50945, - -2.32228, -2.1337, -1.94384, -1.75281, - -1.56072, -1.3677, -1.17384, -0.979285, - -0.784137, -0.588517, -0.392541, -0.19633, +0, 0.19633, 0.392541, 0.588517, +0.784137, 0.979285, 1.17384, 1.3677, +1.56072, 1.75281, 1.94384, 2.1337, +2.32228, 2.50945, 2.69512, 2.87916, +3.06147, 3.24193, 3.42044, 3.59689, +3.77117, 3.94319, 4.11282, 4.27998, +4.44456, 4.60647, 4.76559, 4.92185, +5.07515, 5.22538, 5.37247, 5.51632, +5.65685, 5.79398, 5.92761, 6.05767, +6.18408, 6.30677, 6.42566, 6.54068, +6.65176, 6.75883, 6.86183, 6.9607, +7.05537, 7.14579, 7.23191, 7.31368, +7.39104, 7.46394, 7.53235, 7.59623, +7.65552, 7.71021, 7.76025, 7.80562, +7.84628, 7.88222, 7.91341, 7.93984, +7.96148, 7.97832, 7.99036, 7.99759, +8, 7.99759, 7.99036, 7.97832, +7.96148, 7.93984, 7.91341, 7.88222, +7.84628, 7.80562, 7.76025, 7.71021, +7.65552, 7.59623, 7.53235, 7.46394, +7.39104, 7.31368, 7.23191, 7.14579, +7.05537, 6.9607, 6.86183, 6.75883, +6.65176, 6.54068, 6.42566, 6.30677, +6.18408, 6.05767, 5.92761, 5.79398, +5.65685, 5.51632, 5.37247, 5.22538, +5.07515, 4.92185, 4.76559, 4.60647, +4.44456, 4.27998, 4.11282, 3.94319, +3.77117, 3.59689, 3.42044, 3.24193, +3.06147, 2.87916, 2.69512, 2.50945, +2.32228, 2.1337, 1.94384, 1.75281, +1.56072, 1.3677, 1.17384, 0.979285, +0.784137, 0.588517, 0.392541, 0.19633, +9.79717e-16, -0.19633, -0.392541, -0.588517, +-0.784137, -0.979285, -1.17384, -1.3677, + -1.56072, -1.75281, -1.94384, -2.1337, + -2.32228, -2.50945, -2.69512, -2.87916, + -3.06147, -3.24193, -3.42044, -3.59689, + -3.77117, -3.94319, -4.11282, -4.27998, + -4.44456, -4.60647, -4.76559, -4.92185, + -5.07515, -5.22538, -5.37247, -5.51632, + -5.65685, -5.79398, -5.92761, -6.05767, + -6.18408, -6.30677, -6.42566, -6.54068, + -6.65176, -6.75883, -6.86183, -6.9607, + -7.05537, -7.14579, -7.23191, -7.31368, + -7.39104, -7.46394, -7.53235, -7.59623, + -7.65552, -7.71021, -7.76025, -7.80562, + -7.84628, -7.88222, -7.91341, -7.93984, + -7.96148, -7.97832, -7.99036, -7.99759, + -8, -7.99759, -7.99036, -7.97832, + -7.96148, -7.93984, -7.91341, -7.88222, + -7.84628, -7.80562, -7.76025, -7.71021, + -7.65552, -7.59623, -7.53235, -7.46394, + -7.39104, -7.31368, -7.23191, -7.14579, + -7.05537, -6.9607, -6.86183, -6.75883, + -6.65176, -6.54068, -6.42566, -6.30677, + -6.18408, -6.05767, -5.92761, -5.79398, + -5.65685, -5.51632, -5.37247, -5.22538, + -5.07515, -4.92185, -4.76559, -4.60647, + -4.44456, -4.27998, -4.11282, -3.94319, + -3.77117, -3.59689, -3.42044, -3.24193, + -3.06147, -2.87916, -2.69512, -2.50945, + -2.32228, -2.1337, -1.94384, -1.75281, + -1.56072, -1.3677, -1.17384, -0.979285, + -0.784137, -0.588517, -0.392541, -0.19633, diff --git a/source/glquake.h b/source/glquake.h index 0e9eec5..e8ce441 100644 --- a/source/glquake.h +++ b/source/glquake.h @@ -24,35 +24,36 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef __GLQUAKE_H #define __GLQUAKE_H -void GL_BeginRendering (int32_t *x, int32_t *y, int32_t *width, int32_t *height); -void GL_EndRendering (void); -void GL_Set2D (void); +void GL_BeginRendering(int32_t *x, int32_t *y, int32_t *width, int32_t *height); +void GL_EndRendering(void); +void GL_Set2D(void); -extern int32_t glx, gly, glwidth, glheight; +extern int32_t glx, gly, glwidth, glheight; -#define GL_UNUSED_TEXTURE (~(GLuint)0) +#define GL_UNUSED_TEXTURE (~(GLuint)0) // r_local.h -- private refresh defs -#define ALIAS_BASE_SIZE_RATIO (1.0 / 11.0) - // normalizing factor so player model works out to about - // 1 pixel per triangle -#define MAX_LBM_HEIGHT 480 +#define ALIAS_BASE_SIZE_RATIO (1.0 / 11.0) +// normalizing factor so player model works out to about +// 1 pixel per triangle +#define MAX_LBM_HEIGHT 480 -#define TILE_SIZE 128 // size of textures generated by R_GenTiledSurf +#define TILE_SIZE 128 // size of textures generated by R_GenTiledSurf -#define SKYSHIFT 7 -#define SKYSIZE (1 << SKYSHIFT) -#define SKYMASK (SKYSIZE - 1) +#define SKYSHIFT 7 +#define SKYSIZE (1 << SKYSHIFT) +#define SKYMASK (SKYSIZE - 1) -#define BACKFACE_EPSILON 0.01 +#define BACKFACE_EPSILON 0.01 -void R_TimeRefresh_f (void); -void R_ReadPointFile_f (void); -texture_t *R_TextureAnimation (texture_t *base, int32_t frame); +void R_TimeRefresh_f(void); +void R_ReadPointFile_f(void); +texture_t *R_TextureAnimation(texture_t *base, int32_t frame); -typedef enum { +typedef enum +{ pt_static, pt_grav, pt_slowgrav, pt_fire, pt_explode, pt_explode2, pt_blob, pt_blob2 } ptype_t; @@ -60,87 +61,87 @@ typedef enum { typedef struct particle_s { // driver-usable fields - vec3_t org; - float color; + vec3_t org; + float color; // drivers never touch the following fields - struct particle_s *next; - vec3_t vel; - float ramp; - float die; - ptype_t type; + struct particle_s *next; + vec3_t vel; + float ramp; + float die; + ptype_t type; } particle_t; //==================================================== -extern bool r_cache_thrash; // compatability -extern vec3_t modelorg, r_entorigin; -extern entity_t *currententity; -extern int32_t r_visframecount; // ??? what difs? -extern int32_t r_framecount; -extern mplane_t frustum[4]; +extern bool r_cache_thrash; // compatability +extern vec3_t modelorg, r_entorigin; +extern entity_t *currententity; +extern int32_t r_visframecount; // ??? what difs? +extern int32_t r_framecount; +extern mplane_t frustum[4]; // // view origin // -extern vec3_t vup; -extern vec3_t vpn; -extern vec3_t vright; -extern vec3_t r_origin; +extern vec3_t vup; +extern vec3_t vpn; +extern vec3_t vright; +extern vec3_t r_origin; // // screen size info // -extern refdef_t r_refdef; -extern mleaf_t *r_viewleaf, *r_oldviewleaf; -extern int32_t d_lightstylevalue[256]; // 8.8 fraction of base light value +extern refdef_t r_refdef; +extern mleaf_t *r_viewleaf, *r_oldviewleaf; +extern int32_t d_lightstylevalue[256]; // 8.8 fraction of base light value -extern cvar_t r_norefresh; -extern cvar_t r_drawentities; -extern cvar_t r_drawworld; -extern cvar_t r_drawviewmodel; -extern cvar_t r_speeds; -extern cvar_t r_pos; -extern cvar_t r_waterwarp; -extern cvar_t r_fullbright; -extern cvar_t r_lightmap; -extern cvar_t r_shadows; -extern cvar_t r_wateralpha; -extern cvar_t r_lavaalpha; -extern cvar_t r_telealpha; -extern cvar_t r_slimealpha; -extern cvar_t r_dynamic; -extern cvar_t r_novis; -extern cvar_t r_scale; +extern cvar_t r_norefresh; +extern cvar_t r_drawentities; +extern cvar_t r_drawworld; +extern cvar_t r_drawviewmodel; +extern cvar_t r_speeds; +extern cvar_t r_pos; +extern cvar_t r_waterwarp; +extern cvar_t r_fullbright; +extern cvar_t r_lightmap; +extern cvar_t r_shadows; +extern cvar_t r_wateralpha; +extern cvar_t r_lavaalpha; +extern cvar_t r_telealpha; +extern cvar_t r_slimealpha; +extern cvar_t r_dynamic; +extern cvar_t r_novis; +extern cvar_t r_scale; -extern cvar_t gl_clear; -extern cvar_t gl_cull; -extern cvar_t gl_smoothmodels; -extern cvar_t gl_affinemodels; -extern cvar_t gl_polyblend; -extern cvar_t gl_flashblend; -extern cvar_t gl_nocolors; +extern cvar_t gl_clear; +extern cvar_t gl_cull; +extern cvar_t gl_smoothmodels; +extern cvar_t gl_affinemodels; +extern cvar_t gl_polyblend; +extern cvar_t gl_flashblend; +extern cvar_t gl_nocolors; -extern cvar_t gl_playermip; +extern cvar_t gl_playermip; -extern cvar_t gl_subdivide_size; -extern float load_subdivide_size; //johnfitz -- remember what subdivide_size value was when this map was loaded +extern cvar_t gl_subdivide_size; +extern float load_subdivide_size; //johnfitz -- remember what subdivide_size value was when this map was loaded -extern int32_t gl_stencilbits; +extern int32_t gl_stencilbits; // Multitexture -extern bool mtexenabled; -extern bool gl_mtexable; +extern bool mtexenabled; +extern bool gl_mtexable; extern PFNGLMULTITEXCOORD2FARBPROC GL_MTexCoord2fFunc; extern PFNGLACTIVETEXTUREARBPROC GL_SelectTextureFunc; -extern PFNGLCLIENTACTIVETEXTUREARBPROC GL_ClientActiveTextureFunc; -extern GLint gl_max_texture_units; //ericw +extern PFNGLCLIENTACTIVETEXTUREARBPROC GL_ClientActiveTextureFunc; +extern GLint gl_max_texture_units; //ericw //johnfitz -- anisotropic filtering -#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -extern float gl_max_anisotropy; -extern bool gl_anisotropy_able; +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +extern float gl_max_anisotropy; +extern bool gl_anisotropy_able; //ericw -- VBO extern PFNGLBINDBUFFERARBPROC GL_BindBufferFunc; @@ -148,35 +149,35 @@ extern PFNGLBUFFERDATAARBPROC GL_BufferDataFunc; extern PFNGLBUFFERSUBDATAARBPROC GL_BufferSubDataFunc; extern PFNGLDELETEBUFFERSARBPROC GL_DeleteBuffersFunc; extern PFNGLGENBUFFERSARBPROC GL_GenBuffersFunc; -extern bool gl_vbo_able; +extern bool gl_vbo_able; //ericw //ericw -- GLSL // SDL 1.2 has a bug where it doesn't provide these typedefs on OS X! -typedef GLuint (APIENTRYP QS_PFNGLCREATESHADERPROC) (GLenum type); -typedef void (APIENTRYP QS_PFNGLDELETESHADERPROC) (GLuint shader); -typedef void (APIENTRYP QS_PFNGLDELETEPROGRAMPROC) (GLuint program); -typedef void (APIENTRYP QS_PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); -typedef void (APIENTRYP QS_PFNGLCOMPILESHADERPROC) (GLuint shader); -typedef void (APIENTRYP QS_PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); -typedef void (APIENTRYP QS_PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -typedef void (APIENTRYP QS_PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); -typedef void (APIENTRYP QS_PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -typedef GLuint (APIENTRYP QS_PFNGLCREATEPROGRAMPROC) (void); -typedef void (APIENTRYP QS_PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); -typedef void (APIENTRYP QS_PFNGLLINKPROGRAMPROC) (GLuint program); -typedef void (APIENTRYP QS_PFNGLBINDATTRIBLOCATIONFUNC) (GLuint program, GLuint index, const GLchar *name); -typedef void (APIENTRYP QS_PFNGLUSEPROGRAMPROC) (GLuint program); -typedef GLint (APIENTRYP QS_PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); -typedef void (APIENTRYP QS_PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); -typedef void (APIENTRYP QS_PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); -typedef void (APIENTRYP QS_PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); -typedef GLint (APIENTRYP QS_PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); -typedef void (APIENTRYP QS_PFNGLUNIFORM1IPROC) (GLint location, GLint v0); -typedef void (APIENTRYP QS_PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); -typedef void (APIENTRYP QS_PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -typedef void (APIENTRYP QS_PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef GLuint(APIENTRYP QS_PFNGLCREATESHADERPROC)(GLenum type); +typedef void (APIENTRYP QS_PFNGLDELETESHADERPROC)(GLuint shader); +typedef void (APIENTRYP QS_PFNGLDELETEPROGRAMPROC)(GLuint program); +typedef void (APIENTRYP QS_PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +typedef void (APIENTRYP QS_PFNGLCOMPILESHADERPROC)(GLuint shader); +typedef void (APIENTRYP QS_PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint *params); +typedef void (APIENTRYP QS_PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP QS_PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint *params); +typedef void (APIENTRYP QS_PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef GLuint(APIENTRYP QS_PFNGLCREATEPROGRAMPROC)(void); +typedef void (APIENTRYP QS_PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); +typedef void (APIENTRYP QS_PFNGLLINKPROGRAMPROC)(GLuint program); +typedef void (APIENTRYP QS_PFNGLBINDATTRIBLOCATIONFUNC)(GLuint program, GLuint index, const GLchar *name); +typedef void (APIENTRYP QS_PFNGLUSEPROGRAMPROC)(GLuint program); +typedef GLint(APIENTRYP QS_PFNGLGETATTRIBLOCATIONPROC)(GLuint program, const GLchar *name); +typedef void (APIENTRYP QS_PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +typedef void (APIENTRYP QS_PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); +typedef void (APIENTRYP QS_PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); +typedef GLint(APIENTRYP QS_PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar *name); +typedef void (APIENTRYP QS_PFNGLUNIFORM1IPROC)(GLint location, GLint v0); +typedef void (APIENTRYP QS_PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); +typedef void (APIENTRYP QS_PFNGLUNIFORM3FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP QS_PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); extern QS_PFNGLCREATESHADERPROC GL_CreateShaderFunc; extern QS_PFNGLDELETESHADERPROC GL_DeleteShaderFunc; @@ -201,13 +202,13 @@ extern QS_PFNGLUNIFORM1IPROC GL_Uniform1iFunc; extern QS_PFNGLUNIFORM1FPROC GL_Uniform1fFunc; extern QS_PFNGLUNIFORM3FPROC GL_Uniform3fFunc; extern QS_PFNGLUNIFORM4FPROC GL_Uniform4fFunc; -extern bool gl_glsl_able; -extern bool gl_glsl_gamma_able; -extern bool gl_glsl_alias_able; +extern bool gl_glsl_able; +extern bool gl_glsl_gamma_able; +extern bool gl_glsl_alias_able; // ericw -- //ericw -- NPOT texture support -extern bool gl_texture_NPOT; +extern bool gl_texture_NPOT; //johnfitz -- polygon offset #define OFFSET_BMODEL 1 @@ -215,21 +216,21 @@ extern bool gl_texture_NPOT; #define OFFSET_DECAL -1 #define OFFSET_FOG -2 #define OFFSET_SHOWTRIS -3 -void GL_PolygonOffset (int32_t); +void GL_PolygonOffset(int32_t); //johnfitz -- GL_EXT_texture_env_combine //the values for GL_ARB_ are identical -#define GL_COMBINE_EXT 0x8570 -#define GL_COMBINE_RGB_EXT 0x8571 -#define GL_COMBINE_ALPHA_EXT 0x8572 -#define GL_RGB_SCALE_EXT 0x8573 -#define GL_CONSTANT_EXT 0x8576 -#define GL_PRIMARY_COLOR_EXT 0x8577 -#define GL_PREVIOUS_EXT 0x8578 -#define GL_SOURCE0_RGB_EXT 0x8580 -#define GL_SOURCE1_RGB_EXT 0x8581 -#define GL_SOURCE0_ALPHA_EXT 0x8588 -#define GL_SOURCE1_ALPHA_EXT 0x8589 +#define GL_COMBINE_EXT 0x8570 +#define GL_COMBINE_RGB_EXT 0x8571 +#define GL_COMBINE_ALPHA_EXT 0x8572 +#define GL_RGB_SCALE_EXT 0x8573 +#define GL_CONSTANT_EXT 0x8576 +#define GL_PRIMARY_COLOR_EXT 0x8577 +#define GL_PREVIOUS_EXT 0x8578 +#define GL_SOURCE0_RGB_EXT 0x8580 +#define GL_SOURCE1_RGB_EXT 0x8581 +#define GL_SOURCE0_ALPHA_EXT 0x8588 +#define GL_SOURCE1_ALPHA_EXT 0x8589 extern bool gl_texture_env_combine; extern bool gl_texture_env_add; // for GL_EXT_texture_env_add @@ -240,23 +241,25 @@ extern float rs_megatexels; //johnfitz -- track developer statistics that vary every frame extern cvar_t devstats; -typedef struct { - int32_t packetsize; - int32_t edicts; - int32_t visedicts; - int32_t efrags; - int32_t tempents; - int32_t beams; - int32_t dlights; +typedef struct +{ + int32_t packetsize; + int32_t edicts; + int32_t visedicts; + int32_t efrags; + int32_t tempents; + int32_t beams; + int32_t dlights; } devstats_t; extern devstats_t dev_stats, dev_peakstats; //ohnfitz -- reduce overflow warning spam -typedef struct { - double packetsize; - double efrags; - double beams; - double varstring; +typedef struct +{ + double packetsize; + double efrags; + double beams; + double varstring; } overflowtimes_t; extern overflowtimes_t dev_overflows; //this stores the last time overflow messages were displayed, not the last time overflows occured #define CONSOLE_RESPAM_TIME 3 // seconds between repeated warning messages @@ -270,107 +273,108 @@ extern int32_t gl_warpimagesize; //johnfitz -- for water warp extern bool r_drawflat_cheatsafe, r_fullbright_cheatsafe, r_lightmap_cheatsafe, r_drawworld_cheatsafe; //johnfitz -typedef struct glsl_attrib_binding_s { +typedef struct glsl_attrib_binding_s +{ const char *name; GLuint attrib; } glsl_attrib_binding_t; -extern float map_wateralpha, map_lavaalpha, map_telealpha, map_slimealpha; //ericw +extern float map_wateralpha, map_lavaalpha, map_telealpha, map_slimealpha; //ericw //johnfitz -- fog functions called from outside gl_fog.c -void Fog_ParseServerMessage (void); -float *Fog_GetColor (void); -float Fog_GetDensity (void); -void Fog_EnableGFog (void); -void Fog_DisableGFog (void); -void Fog_StartAdditive (void); -void Fog_StopAdditive (void); -void Fog_SetupFrame (void); -void Fog_NewMap (void); -void Fog_Init (void); -void Fog_SetupState (void); +void Fog_ParseServerMessage(void); +float *Fog_GetColor(void); +float Fog_GetDensity(void); +void Fog_EnableGFog(void); +void Fog_DisableGFog(void); +void Fog_StartAdditive(void); +void Fog_StopAdditive(void); +void Fog_SetupFrame(void); +void Fog_NewMap(void); +void Fog_Init(void); +void Fog_SetupState(void); -void R_NewGame (void); +void R_NewGame(void); -void R_AnimateLight (void); -void R_MarkSurfaces (void); -void R_CullSurfaces (void); -bool R_CullBox (vec3_t emins, vec3_t emaxs); -void R_StoreEfrags (efrag_t **ppefrag); -bool R_CullModelForEntity (entity_t *e); -void R_RotateForEntity (vec3_t origin, vec3_t angles); -void R_MarkLights (dlight_t *light, int32_t num, mnode_t *node); +void R_AnimateLight(void); +void R_MarkSurfaces(void); +void R_CullSurfaces(void); +bool R_CullBox(vec3_t emins, vec3_t emaxs); +void R_StoreEfrags(efrag_t **ppefrag); +bool R_CullModelForEntity(entity_t *e); +void R_RotateForEntity(vec3_t origin, vec3_t angles); +void R_MarkLights(dlight_t *light, int32_t num, mnode_t *node); -void R_InitParticles (void); -void R_DrawParticles (void); -void CL_RunParticles (void); -void R_ClearParticles (void); +void R_InitParticles(void); +void R_DrawParticles(void); +void CL_RunParticles(void); +void R_ClearParticles(void); -void R_TranslatePlayerSkin (int32_t playernum); -void R_TranslateNewPlayerSkin (int32_t playernum); //johnfitz -- this handles cases when the actual texture changes -void R_UpdateWarpTextures (void); +void R_TranslatePlayerSkin(int32_t playernum); +void R_TranslateNewPlayerSkin(int32_t playernum); //johnfitz -- this handles cases when the actual texture changes +void R_UpdateWarpTextures(void); -void R_DrawWorld (void); -void R_DrawAliasModel (entity_t *e); -void R_DrawBrushModel (entity_t *e); -void R_DrawSpriteModel (entity_t *e); +void R_DrawWorld(void); +void R_DrawAliasModel(entity_t *e); +void R_DrawBrushModel(entity_t *e); +void R_DrawSpriteModel(entity_t *e); -void R_DrawTextureChains_Water (qmodel_t *model, entity_t *ent, texchain_t chain); +void R_DrawTextureChains_Water(qmodel_t *model, entity_t *ent, texchain_t chain); -void R_RenderDlights (void); -void GL_BuildLightmaps (void); -void GL_DeleteBModelVertexBuffer (void); -void GL_BuildBModelVertexBuffer (void); -void GLMesh_LoadVertexBuffers (void); -void GLMesh_DeleteVertexBuffers (void); -void R_RebuildAllLightmaps (void); +void R_RenderDlights(void); +void GL_BuildLightmaps(void); +void GL_DeleteBModelVertexBuffer(void); +void GL_BuildBModelVertexBuffer(void); +void GLMesh_LoadVertexBuffers(void); +void GLMesh_DeleteVertexBuffers(void); +void R_RebuildAllLightmaps(void); -int32_t R_LightPoint (vec3_t p); +int32_t R_LightPoint(vec3_t p); -void GL_SubdivideSurface (msurface_t *fa); -void R_BuildLightMap (msurface_t *surf, byte *dest, int32_t stride); -void R_RenderDynamicLightmaps (msurface_t *fa); -void R_UploadLightmaps (void); +void GL_SubdivideSurface(msurface_t *fa); +void R_BuildLightMap(msurface_t *surf, byte *dest, int32_t stride); +void R_RenderDynamicLightmaps(msurface_t *fa); +void R_UploadLightmaps(void); -void R_DrawWorld_ShowTris (void); -void R_DrawBrushModel_ShowTris (entity_t *e); -void R_DrawAliasModel_ShowTris (entity_t *e); -void R_DrawParticles_ShowTris (void); +void R_DrawWorld_ShowTris(void); +void R_DrawBrushModel_ShowTris(entity_t *e); +void R_DrawAliasModel_ShowTris(entity_t *e); +void R_DrawParticles_ShowTris(void); -GLint GL_GetUniformLocation (GLuint *programPtr, const char *name); -GLuint GL_CreateProgram (const GLchar *vertSource, const GLchar *fragSource, int32_t numbindings, const glsl_attrib_binding_t *bindings); -void R_DeleteShaders (void); +GLint GL_GetUniformLocation(GLuint *programPtr, const char *name); +GLuint GL_CreateProgram(const GLchar *vertSource, const GLchar *fragSource, int32_t numbindings, const glsl_attrib_binding_t *bindings); +void R_DeleteShaders(void); -void GLWorld_CreateShaders (void); -void GLAlias_CreateShaders (void); -void GL_DrawAliasShadow (entity_t *e); -void DrawGLTriangleFan (glpoly_t *p); -void DrawGLPoly (glpoly_t *p); -void DrawWaterPoly (glpoly_t *p); -void GL_MakeAliasModelDisplayLists (qmodel_t *m, aliashdr_t *hdr); +void GLWorld_CreateShaders(void); +void GLAlias_CreateShaders(void); +void GL_DrawAliasShadow(entity_t *e); +void DrawGLTriangleFan(glpoly_t *p); +void DrawGLPoly(glpoly_t *p); +void DrawWaterPoly(glpoly_t *p); +void GL_MakeAliasModelDisplayLists(qmodel_t *m, aliashdr_t *hdr); -void Sky_Init (void); -void Sky_DrawSky (void); -void Sky_NewMap (void); -void Sky_LoadTexture (texture_t *mt); -void Sky_LoadSkyBox (const char *name); +void Sky_Init(void); +void Sky_DrawSky(void); +void Sky_NewMap(void); +void Sky_LoadTexture(texture_t *mt); +void Sky_LoadSkyBox(const char *name); -void TexMgr_RecalcWarpImageSize (void); +void TexMgr_RecalcWarpImageSize(void); -void R_ClearTextureChains (qmodel_t *mod, texchain_t chain); -void R_ChainSurface (msurface_t *surf, texchain_t chain); -void R_DrawTextureChains (qmodel_t *model, entity_t *ent, texchain_t chain); -void R_DrawWorld_Water (void); +void R_ClearTextureChains(qmodel_t *mod, texchain_t chain); +void R_ChainSurface(msurface_t *surf, texchain_t chain); +void R_DrawTextureChains(qmodel_t *model, entity_t *ent, texchain_t chain); +void R_DrawWorld_Water(void); -void GL_BindBuffer (GLenum target, GLuint buffer); -void GL_ClearBufferBindings (); +void GL_BindBuffer(GLenum target, GLuint buffer); +void GL_ClearBufferBindings(); -void GLSLGamma_DeleteTexture (void); -void GLSLGamma_GammaCorrect (void); +void GLSLGamma_DeleteTexture(void); +void GLSLGamma_GammaCorrect(void); -void R_ScaleView_DeleteTexture (void); +void R_ScaleView_DeleteTexture(void); -float GL_WaterAlphaForSurface (msurface_t *fa); +float GL_WaterAlphaForSurface(msurface_t *fa); -#endif /* __GLQUAKE_H */ +#endif /* __GLQUAKE_H */ diff --git a/source/host.c b/source/host.c index 25e2867..f1438ae 100644 --- a/source/host.c +++ b/source/host.c @@ -39,47 +39,47 @@ Memory is cleared / released when a server or client begins, not when they end. quakeparms_t *host_parms; -bool host_initialized; // true if into command execution +bool host_initialized; // true if into command execution -double host_frametime; -double realtime; // without any filtering or bounding -double oldrealtime; // last frame run +double host_frametime; +double realtime; // without any filtering or bounding +double oldrealtime; // last frame run -int32_t host_framecount; +int32_t host_framecount; -int32_t host_hunklevel; +int32_t host_hunklevel; -client_t *host_client; // current client +client_t *host_client; // current client -jmp_buf host_abortserver; +jmp_buf host_abortserver; -byte *host_colormap; +byte *host_colormap; -cvar_t host_framerate = {"host_framerate","0",CVAR_NONE}; // set for slow motion -cvar_t host_speeds = {"host_speeds","0",CVAR_NONE}; // set for running times -cvar_t host_maxfps = {"host_maxfps", "72", CVAR_ARCHIVE}; //johnfitz -cvar_t host_timescale = {"host_timescale", "0", CVAR_NONE}; //johnfitz -cvar_t max_edicts = {"max_edicts", "8192", CVAR_NONE}; //johnfitz //ericw -- changed from 2048 to 8192, removed CVAR_ARCHIVE +cvar_t host_framerate = {"host_framerate", "0", CVAR_NONE}; // set for slow motion +cvar_t host_speeds = {"host_speeds", "0", CVAR_NONE}; // set for running times +cvar_t host_maxfps = {"host_maxfps", "72", CVAR_ARCHIVE}; //johnfitz +cvar_t host_timescale = {"host_timescale", "0", CVAR_NONE}; //johnfitz +cvar_t max_edicts = {"max_edicts", "8192", CVAR_NONE}; //johnfitz //ericw -- changed from 2048 to 8192, removed CVAR_ARCHIVE -cvar_t sys_ticrate = {"sys_ticrate","0.05",CVAR_NONE}; // dedicated server -cvar_t serverprofile = {"serverprofile","0",CVAR_NONE}; +cvar_t sys_ticrate = {"sys_ticrate", "0.05", CVAR_NONE}; // dedicated server +cvar_t serverprofile = {"serverprofile", "0", CVAR_NONE}; -cvar_t fraglimit = {"fraglimit","0",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t timelimit = {"timelimit","0",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t teamplay = {"teamplay","0",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t samelevel = {"samelevel","0",CVAR_NONE}; -cvar_t noexit = {"noexit","0",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t skill = {"skill","1",CVAR_NONE}; // 0 - 3 -cvar_t deathmatch = {"deathmatch","0",CVAR_NONE}; // 0, 1, or 2 -cvar_t coop = {"coop","0",CVAR_NONE}; // 0 or 1 +cvar_t fraglimit = {"fraglimit", "0", CVAR_NOTIFY | CVAR_SERVERINFO}; +cvar_t timelimit = {"timelimit", "0", CVAR_NOTIFY | CVAR_SERVERINFO}; +cvar_t teamplay = {"teamplay", "0", CVAR_NOTIFY | CVAR_SERVERINFO}; +cvar_t samelevel = {"samelevel", "0", CVAR_NONE}; +cvar_t noexit = {"noexit", "0", CVAR_NOTIFY | CVAR_SERVERINFO}; +cvar_t skill = {"skill", "1", CVAR_NONE}; // 0 - 3 +cvar_t deathmatch = {"deathmatch", "0", CVAR_NONE}; // 0, 1, or 2 +cvar_t coop = {"coop", "0", CVAR_NONE}; // 0 or 1 -cvar_t pausable = {"pausable","1",CVAR_NONE}; +cvar_t pausable = {"pausable", "1", CVAR_NONE}; -cvar_t developer = {"developer","0",CVAR_NONE}; +cvar_t developer = {"developer", "0", CVAR_NONE}; -cvar_t temp1 = {"temp1","0",CVAR_NONE}; +cvar_t temp1 = {"temp1", "0", CVAR_NONE}; -cvar_t devstats = {"devstats","0",CVAR_NONE}; //johnfitz -- track developer statistics that vary every frame +cvar_t devstats = {"devstats", "0", CVAR_NONE}; //johnfitz -- track developer statistics that vary every frame devstats_t dev_stats, dev_peakstats; overflowtimes_t dev_overflows; //this stores the last time overflow messages were displayed, not the last time overflows occured @@ -89,12 +89,12 @@ overflowtimes_t dev_overflows; //this stores the last time overflow messages wer Max_Edicts_f -- johnfitz ================ */ -static void Max_Edicts_f (cvar_t *var) +static void Max_Edicts_f(cvar_t *var) { (void)var; //TODO: clamp it here? - if (cls.state == ca_connected || sv.active) - Con_Printf ("Changes to max_edicts will not take effect until the next time a map is loaded.\n"); + if(cls.state == ca_connected || sv.active) + Con_Printf("Changes to max_edicts will not take effect until the next time a map is loaded.\n"); } /* @@ -102,10 +102,10 @@ static void Max_Edicts_f (cvar_t *var) Max_Fps_f -- ericw ================ */ -static void Max_Fps_f (cvar_t *var) +static void Max_Fps_f(cvar_t *var) { - if (var->value > 72) - Con_Warning ("host_maxfps above 72 breaks physics.\n"); + if(var->value > 72) + Con_Warning("host_maxfps above 72 breaks physics.\n"); } /* @@ -113,28 +113,28 @@ static void Max_Fps_f (cvar_t *var) Host_EndGame ================ */ -void Host_EndGame (const char *message, ...) +void Host_EndGame(const char *message, ...) { - va_list argptr; - char string[1024]; + va_list argptr; + char string[1024]; - va_start (argptr,message); - q_vsnprintf (string, sizeof(string), message, argptr); - va_end (argptr); - Con_DPrintf ("Host_EndGame: %s\n",string); + va_start(argptr, message); + q_vsnprintf(string, sizeof(string), message, argptr); + va_end(argptr); + Con_DPrintf("Host_EndGame: %s\n", string); - if (sv.active) - Host_ShutdownServer (false); + if(sv.active) + Host_ShutdownServer(false); - if (cls.state == ca_dedicated) - Sys_Error ("Host_EndGame: %s\n",string); // dedicated servers exit + if(cls.state == ca_dedicated) + Sys_Error("Host_EndGame: %s\n", string); // dedicated servers exit - if (cls.demonum != -1) - CL_NextDemo (); + if(cls.demonum != -1) + CL_NextDemo(); else - CL_Disconnect (); + CL_Disconnect(); - longjmp (host_abortserver, 1); + longjmp(host_abortserver, 1); } /* @@ -144,36 +144,36 @@ Host_Error This shuts down both the client and server ================ */ -void Host_Error (const char *error, ...) +void Host_Error(const char *error, ...) { - va_list argptr; - char string[1024]; - static bool inerror = false; + va_list argptr; + char string[1024]; + static bool inerror = false; - if (inerror) - Sys_Error ("Host_Error: recursively entered"); + if(inerror) + Sys_Error("Host_Error: recursively entered"); inerror = true; - SCR_EndLoadingPlaque (); // reenable screen updates + SCR_EndLoadingPlaque(); // reenable screen updates - va_start (argptr,error); - q_vsnprintf (string, sizeof(string), error, argptr); - va_end (argptr); - Con_Printf ("Host_Error: %s\n",string); + va_start(argptr, error); + q_vsnprintf(string, sizeof(string), error, argptr); + va_end(argptr); + Con_Printf("Host_Error: %s\n", string); - if (sv.active) - Host_ShutdownServer (false); + if(sv.active) + Host_ShutdownServer(false); - if (cls.state == ca_dedicated) - Sys_Error ("Host_Error: %s\n",string); // dedicated servers exit + if(cls.state == ca_dedicated) + Sys_Error("Host_Error: %s\n", string); // dedicated servers exit - CL_Disconnect (); + CL_Disconnect(); cls.demonum = -1; cl.intermission = 0; //johnfitz -- for errors during intermissions (changelevel with no map found, etc.) inerror = false; - longjmp (host_abortserver, 1); + longjmp(host_abortserver, 1); } /* @@ -181,19 +181,19 @@ void Host_Error (const char *error, ...) Host_FindMaxClients ================ */ -void Host_FindMaxClients (void) +void Host_FindMaxClients(void) { - int32_t i; + int32_t i; svs.maxclients = 1; - i = COM_CheckParm ("-dedicated"); - if (i) + i = COM_CheckParm("-dedicated"); + if(i) { cls.state = ca_dedicated; - if (i != (com_argc - 1)) + if(i != (com_argc - 1)) { - svs.maxclients = Q_atoi (com_argv[i+1]); + svs.maxclients = Q_atoi(com_argv[i + 1]); } else svs.maxclients = 8; @@ -201,44 +201,44 @@ void Host_FindMaxClients (void) else cls.state = ca_disconnected; - i = COM_CheckParm ("-listen"); - if (i) + i = COM_CheckParm("-listen"); + if(i) { - if (cls.state == ca_dedicated) - Sys_Error ("Only one of -dedicated or -listen can be specified"); - if (i != (com_argc - 1)) - svs.maxclients = Q_atoi (com_argv[i+1]); + if(cls.state == ca_dedicated) + Sys_Error("Only one of -dedicated or -listen can be specified"); + if(i != (com_argc - 1)) + svs.maxclients = Q_atoi(com_argv[i + 1]); else svs.maxclients = 8; } - if (svs.maxclients < 1) + if(svs.maxclients < 1) svs.maxclients = 8; - else if (svs.maxclients > MAX_SCOREBOARD) + else if(svs.maxclients > MAX_SCOREBOARD) svs.maxclients = MAX_SCOREBOARD; svs.maxclientslimit = svs.maxclients; - if (svs.maxclientslimit < 4) + if(svs.maxclientslimit < 4) svs.maxclientslimit = 4; - svs.clients = (struct client_s *) Hunk_AllocName (svs.maxclientslimit*sizeof(client_t), "clients"); + svs.clients = (struct client_s *) Hunk_AllocName(svs.maxclientslimit * sizeof(client_t), "clients"); - if (svs.maxclients > 1) - Cvar_SetQuick (&deathmatch, "1"); + if(svs.maxclients > 1) + Cvar_SetQuick(&deathmatch, "1"); else - Cvar_SetQuick (&deathmatch, "0"); + Cvar_SetQuick(&deathmatch, "0"); } -void Host_Version_f (void) +void Host_Version_f(void) { - Con_Printf ("Quake Version %s\n", VERSION); - Con_Printf ("QuakeSpasm Version " QUAKESPASM_VERSION "\n"); - Con_Printf ("Exe: " __TIME__ " " __DATE__ "\n"); + Con_Printf("Quake Version %s\n", VERSION); + Con_Printf("QuakeSpasm Version " QUAKESPASM_VERSION "\n"); + Con_Printf("Exe: " __TIME__ " " __DATE__ "\n"); } /* cvar callback functions : */ -void Host_Callback_Notify (cvar_t *var) +void Host_Callback_Notify(cvar_t *var) { - if (sv.active) - SV_BroadcastPrintf ("\"%s\" changed to \"%s\"\n", var->name, var->string); + if(sv.active) + SV_BroadcastPrintf("\"%s\" changed to \"%s\"\n", var->name, var->string); } /* @@ -246,45 +246,45 @@ void Host_Callback_Notify (cvar_t *var) Host_InitLocal ====================== */ -void Host_InitLocal (void) +void Host_InitLocal(void) { - Cmd_AddCommand ("version", Host_Version_f); + Cmd_AddCommand("version", Host_Version_f); - Host_InitCommands (); + Host_InitCommands(); - Cvar_RegisterVariable (&host_framerate); - Cvar_RegisterVariable (&host_speeds); - Cvar_RegisterVariable (&host_maxfps); //johnfitz - Cvar_SetCallback (&host_maxfps, Max_Fps_f); - Cvar_RegisterVariable (&host_timescale); //johnfitz + Cvar_RegisterVariable(&host_framerate); + Cvar_RegisterVariable(&host_speeds); + Cvar_RegisterVariable(&host_maxfps); //johnfitz + Cvar_SetCallback(&host_maxfps, Max_Fps_f); + Cvar_RegisterVariable(&host_timescale); //johnfitz - Cvar_RegisterVariable (&max_edicts); //johnfitz - Cvar_SetCallback (&max_edicts, Max_Edicts_f); - Cvar_RegisterVariable (&devstats); //johnfitz + Cvar_RegisterVariable(&max_edicts); //johnfitz + Cvar_SetCallback(&max_edicts, Max_Edicts_f); + Cvar_RegisterVariable(&devstats); //johnfitz - Cvar_RegisterVariable (&sys_ticrate); - Cvar_RegisterVariable (&sys_throttle); - Cvar_RegisterVariable (&serverprofile); + Cvar_RegisterVariable(&sys_ticrate); + Cvar_RegisterVariable(&sys_throttle); + Cvar_RegisterVariable(&serverprofile); - Cvar_RegisterVariable (&fraglimit); - Cvar_RegisterVariable (&timelimit); - Cvar_RegisterVariable (&teamplay); - Cvar_SetCallback (&fraglimit, Host_Callback_Notify); - Cvar_SetCallback (&timelimit, Host_Callback_Notify); - Cvar_SetCallback (&teamplay, Host_Callback_Notify); - Cvar_RegisterVariable (&samelevel); - Cvar_RegisterVariable (&noexit); - Cvar_SetCallback (&noexit, Host_Callback_Notify); - Cvar_RegisterVariable (&skill); - Cvar_RegisterVariable (&developer); - Cvar_RegisterVariable (&coop); - Cvar_RegisterVariable (&deathmatch); + Cvar_RegisterVariable(&fraglimit); + Cvar_RegisterVariable(&timelimit); + Cvar_RegisterVariable(&teamplay); + Cvar_SetCallback(&fraglimit, Host_Callback_Notify); + Cvar_SetCallback(&timelimit, Host_Callback_Notify); + Cvar_SetCallback(&teamplay, Host_Callback_Notify); + Cvar_RegisterVariable(&samelevel); + Cvar_RegisterVariable(&noexit); + Cvar_SetCallback(&noexit, Host_Callback_Notify); + Cvar_RegisterVariable(&skill); + Cvar_RegisterVariable(&developer); + Cvar_RegisterVariable(&coop); + Cvar_RegisterVariable(&deathmatch); - Cvar_RegisterVariable (&pausable); + Cvar_RegisterVariable(&pausable); - Cvar_RegisterVariable (&temp1); + Cvar_RegisterVariable(&temp1); - Host_FindMaxClients (); + Host_FindMaxClients(); } @@ -295,32 +295,32 @@ Host_WriteConfiguration Writes key bindings and archived cvars to config.cfg =============== */ -void Host_WriteConfiguration (void) +void Host_WriteConfiguration(void) { - FILE *f; + FILE *f; // dedicated servers initialize the host but don't parse and set the // config.cfg cvars - if (host_initialized && !isDedicated && !host_parms->errstate) + if(host_initialized && !isDedicated && !host_parms->errstate) { - f = fopen (va("%s/config.cfg", com_gamedir), "w"); - if (!f) + f = fopen(va("%s/config.cfg", com_gamedir), "w"); + if(!f) { - Con_Printf ("Couldn't write config.cfg.\n"); + Con_Printf("Couldn't write config.cfg.\n"); return; } //VID_SyncCvars (); //johnfitz -- write actual current mode to config file, in case cvars were messed with - Key_WriteBindings (f); - Cvar_WriteVariables (f); + Key_WriteBindings(f); + Cvar_WriteVariables(f); //johnfitz -- extra commands to preserve state - fprintf (f, "vid_restart\n"); - if (in_mlook.state & 1) fprintf (f, "+mlook\n"); + fprintf(f, "vid_restart\n"); + if(in_mlook.state & 1) fprintf(f, "+mlook\n"); //johnfitz - fclose (f); + fclose(f); } } @@ -333,17 +333,17 @@ Sends text across to be displayed FIXME: make this just a stuffed echo? ================= */ -void SV_ClientPrintf (const char *fmt, ...) +void SV_ClientPrintf(const char *fmt, ...) { - va_list argptr; - char string[1024]; + va_list argptr; + char string[1024]; - va_start (argptr,fmt); - q_vsnprintf (string, sizeof(string), fmt,argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); - MSG_WriteByte (&host_client->message, svc_print); - MSG_WriteString (&host_client->message, string); + MSG_WriteByte(&host_client->message, svc_print); + MSG_WriteString(&host_client->message, string); } /* @@ -353,22 +353,22 @@ SV_BroadcastPrintf Sends text to all active clients ================= */ -void SV_BroadcastPrintf (const char *fmt, ...) +void SV_BroadcastPrintf(const char *fmt, ...) { - va_list argptr; - char string[1024]; - int32_t i; + va_list argptr; + char string[1024]; + int32_t i; - va_start (argptr,fmt); - q_vsnprintf (string, sizeof(string), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); - for (i = 0; i < svs.maxclients; i++) + for(i = 0; i < svs.maxclients; i++) { - if (svs.clients[i].active && svs.clients[i].spawned) + if(svs.clients[i].active && svs.clients[i].spawned) { - MSG_WriteByte (&svs.clients[i].message, svc_print); - MSG_WriteString (&svs.clients[i].message, string); + MSG_WriteByte(&svs.clients[i].message, svc_print); + MSG_WriteString(&svs.clients[i].message, string); } } } @@ -380,17 +380,17 @@ Host_ClientCommands Send text over to the client to be executed ================= */ -void Host_ClientCommands (const char *fmt, ...) +void Host_ClientCommands(const char *fmt, ...) { - va_list argptr; - char string[1024]; + va_list argptr; + char string[1024]; - va_start (argptr,fmt); - q_vsnprintf (string, sizeof(string), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(string, sizeof(string), fmt, argptr); + va_end(argptr); - MSG_WriteByte (&host_client->message, svc_stufftext); - MSG_WriteString (&host_client->message, string); + MSG_WriteByte(&host_client->message, svc_stufftext); + MSG_WriteString(&host_client->message, string); } /* @@ -401,36 +401,36 @@ Called when the player is getting totally kicked off the host if (crash = true), don't bother sending signofs ===================== */ -void SV_DropClient (bool crash) +void SV_DropClient(bool crash) { - int32_t saveSelf; - int32_t i; + int32_t saveSelf; + int32_t i; client_t *client; - if (!crash) + if(!crash) { // send any final messages (don't check for errors) - if (NET_CanSendMessage (host_client->netconnection)) + if(NET_CanSendMessage(host_client->netconnection)) { - MSG_WriteByte (&host_client->message, svc_disconnect); - NET_SendMessage (host_client->netconnection, &host_client->message); + MSG_WriteByte(&host_client->message, svc_disconnect); + NET_SendMessage(host_client->netconnection, &host_client->message); } - if (host_client->edict && host_client->spawned) + if(host_client->edict && host_client->spawned) { - // call the prog function for removing a client - // this will set the body to a dead frame, among other things + // call the prog function for removing a client + // this will set the body to a dead frame, among other things saveSelf = pr_global_struct->self; pr_global_struct->self = EDICT_TO_PROG(host_client->edict); - PR_ExecuteProgram (pr_global_struct->ClientDisconnect); + PR_ExecuteProgram(pr_global_struct->ClientDisconnect); pr_global_struct->self = saveSelf; } - Sys_Printf ("Client %s removed\n",host_client->name); + Sys_Printf("Client %s removed\n", host_client->name); } // break the net connection - NET_Close (host_client->netconnection); + NET_Close(host_client->netconnection); host_client->netconnection = NULL; // free the client (the body stays around) @@ -440,19 +440,19 @@ void SV_DropClient (bool crash) net_activeconnections--; // send notification to all clients - for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) + for(i = 0, client = svs.clients; i < svs.maxclients; i++, client++) { - if (!client->active) + if(!client->active) continue; - MSG_WriteByte (&client->message, svc_updatename); - MSG_WriteByte (&client->message, host_client - svs.clients); - MSG_WriteString (&client->message, ""); - MSG_WriteByte (&client->message, svc_updatefrags); - MSG_WriteByte (&client->message, host_client - svs.clients); - MSG_WriteShort (&client->message, 0); - MSG_WriteByte (&client->message, svc_updatecolors); - MSG_WriteByte (&client->message, host_client - svs.clients); - MSG_WriteByte (&client->message, 0); + MSG_WriteByte(&client->message, svc_updatename); + MSG_WriteByte(&client->message, host_client - svs.clients); + MSG_WriteString(&client->message, ""); + MSG_WriteByte(&client->message, svc_updatefrags); + MSG_WriteByte(&client->message, host_client - svs.clients); + MSG_WriteShort(&client->message, 0); + MSG_WriteByte(&client->message, svc_updatecolors); + MSG_WriteByte(&client->message, host_client - svs.clients); + MSG_WriteByte(&client->message, 0); } } @@ -465,34 +465,34 @@ This only happens at the end of a game, not between levels */ void Host_ShutdownServer(bool crash) { - int32_t i; - int32_t count; - sizebuf_t buf; - byte message[4]; - double start; + int32_t i; + int32_t count; + sizebuf_t buf; + byte message[4]; + double start; - if (!sv.active) + if(!sv.active) return; sv.active = false; // stop all client sounds immediately - if (cls.state == ca_connected) - CL_Disconnect (); + if(cls.state == ca_connected) + CL_Disconnect(); // flush any pending messages - like the score!!! start = Sys_DoubleTime(); do { count = 0; - for (i=0, host_client = svs.clients ; iactive && host_client->message.cursize) + if(host_client->active && host_client->message.cursize) { - if (NET_CanSendMessage (host_client->netconnection)) + if(NET_CanSendMessage(host_client->netconnection)) { NET_SendMessage(host_client->netconnection, &host_client->message); - SZ_Clear (&host_client->message); + SZ_Clear(&host_client->message); } else { @@ -501,10 +501,10 @@ void Host_ShutdownServer(bool crash) } } } - if ((Sys_DoubleTime() - start) > 3.0) + if((Sys_DoubleTime() - start) > 3.0) break; } - while (count); + while(count); // make sure all the clients know we're disconnecting buf.data = message; @@ -512,18 +512,18 @@ void Host_ShutdownServer(bool crash) buf.cursize = 0; MSG_WriteByte(&buf, svc_disconnect); count = NET_SendToAll(&buf, 5.0); - if (count) + if(count) Con_Printf("Host_ShutdownServer: NET_SendToAll failed for %" PRIu32 " clients\n", count); - for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) - if (host_client->active) + for(i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) + if(host_client->active) SV_DropClient(crash); // // clear structures // // memset (&sv, 0, sizeof(sv)); // ServerSpawn already do this by Host_ClearMemory - memset (svs.clients, 0, svs.maxclientslimit*sizeof(client_t)); + memset(svs.clients, 0, svs.maxclientslimit * sizeof(client_t)); } @@ -535,17 +535,17 @@ This clears all the memory used by both the client and server, but does not reinitialize anything. ================ */ -void Host_ClearMemory (void) +void Host_ClearMemory(void) { - Con_DPrintf ("Clearing memory\n"); - D_FlushCaches (); - Mod_ClearAll (); -/* host_hunklevel MUST be set at this point */ - Hunk_FreeToLowMark (host_hunklevel); + Con_DPrintf("Clearing memory\n"); + D_FlushCaches(); + Mod_ClearAll(); + /* host_hunklevel MUST be set at this point */ + Hunk_FreeToLowMark(host_hunklevel); cls.signon = 0; free(sv.edicts); // ericw -- sv.edicts switched to use malloc() - memset (&sv, 0, sizeof(sv)); - memset (&cl, 0, sizeof(cl)); + memset(&sv, 0, sizeof(sv)); + memset(&cl, 0, sizeof(cl)); } @@ -562,15 +562,15 @@ Host_FilterTime Returns false if the time is too short to run a frame =================== */ -bool Host_FilterTime (float time) +bool Host_FilterTime(float time) { float maxfps; //johnfitz realtime += time; //johnfitz -- max fps cvar - maxfps = CLAMP (10.0, host_maxfps.value, 1000.0); - if (!cls.timedemo && realtime - oldrealtime < 1.0/maxfps) + maxfps = CLAMP(10.0, host_maxfps.value, 1000.0); + if(!cls.timedemo && realtime - oldrealtime < 1.0 / maxfps) return false; // framerate is too high //johnfitz @@ -578,13 +578,13 @@ bool Host_FilterTime (float time) oldrealtime = realtime; //johnfitz -- host_timescale is more intuitive than host_framerate - if (host_timescale.value > 0) + if(host_timescale.value > 0) host_frametime *= host_timescale.value; //johnfitz - else if (host_framerate.value > 0) + else if(host_framerate.value > 0) host_frametime = host_framerate.value; else // don't allow really long or short frames - host_frametime = CLAMP (0.001, host_frametime, 0.1); //johnfitz -- use CLAMP + host_frametime = CLAMP(0.001, host_frametime, 0.1); //johnfitz -- use CLAMP return true; } @@ -596,19 +596,19 @@ Host_GetConsoleCommands Add them exactly as if they had been typed at the console =================== */ -void Host_GetConsoleCommands (void) +void Host_GetConsoleCommands(void) { - const char *cmd; + const char *cmd; - if (!isDedicated) - return; // no stdin necessary in graphical mode + if(!isDedicated) + return; // no stdin necessary in graphical mode - while (1) + while(1) { - cmd = Sys_ConsoleInput (); - if (!cmd) + cmd = Sys_ConsoleInput(); + if(!cmd) break; - Cbuf_AddText (cmd); + Cbuf_AddText(cmd); } } @@ -617,46 +617,46 @@ void Host_GetConsoleCommands (void) Host_ServerFrame ================== */ -void Host_ServerFrame (void) +void Host_ServerFrame(void) { - int32_t i, active; //johnfitz - edict_t *ent; //johnfitz + int32_t i, active; //johnfitz + edict_t *ent; //johnfitz // run the world state pr_global_struct->frametime = host_frametime; // set the time and clear the general datagram - SV_ClearDatagram (); + SV_ClearDatagram(); // check for new clients - SV_CheckForNewClients (); + SV_CheckForNewClients(); // read client messages - SV_RunClients (); + SV_RunClients(); // move things around and think // always pause in single player if in console or menus - if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) ) - SV_Physics (); + if(!sv.paused && (svs.maxclients > 1 || key_dest == key_game)) + SV_Physics(); //johnfitz -- devstats - if (cls.signon == SIGNONS) + if(cls.signon == SIGNONS) { - for (i=0, active=0; ifree) + if(!ent->free) active++; } - if (active > 600 && dev_peakstats.edicts <= 600) - Con_DWarning ("%" PRIi32 " edicts exceeds standard limit of 600 (max = %" PRIi32 ").\n", active, sv.max_edicts); + if(active > 600 && dev_peakstats.edicts <= 600) + Con_DWarning("%" PRIi32 " edicts exceeds standard limit of 600 (max = %" PRIi32 ").\n", active, sv.max_edicts); dev_stats.edicts = active; dev_peakstats.edicts = q_max(active, dev_peakstats.edicts); } //johnfitz // send all messages to the clients - SV_SendClientMessages (); + SV_SendClientMessages(); } /* @@ -666,39 +666,39 @@ Host_Frame Runs all active servers ================== */ -void _Host_Frame (float time) +void _Host_Frame(float time) { - static double time1 = 0; - static double time2 = 0; - static double time3 = 0; - int32_t pass1, pass2, pass3; + static double time1 = 0; + static double time2 = 0; + static double time3 = 0; + int32_t pass1, pass2, pass3; - if (setjmp (host_abortserver) ) - return; // something bad happened, or the server disconnected + if(setjmp(host_abortserver)) + return; // something bad happened, or the server disconnected // keep the random time dependent - rand (); + rand(); // decide the simulation time - if (!Host_FilterTime (time)) - return; // don't run too fast, or packets will flood out + if(!Host_FilterTime(time)) + return; // don't run too fast, or packets will flood out // get new key events - Key_UpdateForDest (); - IN_UpdateInputMode (); - Sys_SendKeyEvents (); + Key_UpdateForDest(); + IN_UpdateInputMode(); + Sys_SendKeyEvents(); // allow mice or other external controllers to add commands - IN_Commands (); + IN_Commands(); // process console commands - Cbuf_Execute (); + Cbuf_Execute(); NET_Poll(); // if running the server locally, make intentions now - if (sv.active) - CL_SendCmd (); + if(sv.active) + CL_SendCmd(); //------------------- // @@ -707,10 +707,10 @@ void _Host_Frame (float time) //------------------- // check for commands typed to the host - Host_GetConsoleCommands (); + Host_GetConsoleCommands(); - if (sv.active) - Host_ServerFrame (); + if(sv.active) + Host_ServerFrame(); //------------------- // @@ -720,82 +720,82 @@ void _Host_Frame (float time) // if running the server remotely, send intentions now after // the incoming messages have been read - if (!sv.active) - CL_SendCmd (); + if(!sv.active) + CL_SendCmd(); // fetch results from server - if (cls.state == ca_connected) - CL_ReadFromServer (); + if(cls.state == ca_connected) + CL_ReadFromServer(); // update video - if (host_speeds.value) - time1 = Sys_DoubleTime (); + if(host_speeds.value) + time1 = Sys_DoubleTime(); - SCR_UpdateScreen (); + SCR_UpdateScreen(); - CL_RunParticles (); //johnfitz -- seperated from rendering + CL_RunParticles(); //johnfitz -- seperated from rendering - if (host_speeds.value) - time2 = Sys_DoubleTime (); + if(host_speeds.value) + time2 = Sys_DoubleTime(); // update audio - BGM_Update(); // adds music raw samples and/or advances midi driver - if (cls.signon == SIGNONS) + BGM_Update(); // adds music raw samples and/or advances midi driver + if(cls.signon == SIGNONS) { - S_Update (r_origin, vpn, vright, vup); - CL_DecayLights (); + S_Update(r_origin, vpn, vright, vup); + CL_DecayLights(); } else - S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin); + S_Update(vec3_origin, vec3_origin, vec3_origin, vec3_origin); - if (host_speeds.value) + if(host_speeds.value) { - pass1 = (time1 - time3)*1000; - time3 = Sys_DoubleTime (); - pass2 = (time2 - time1)*1000; - pass3 = (time3 - time2)*1000; - Con_Printf ("%3" PRIi32 " tot %3" PRIi32 " server %3" PRIi32 " gfx %3" PRIi32 " snd\n", - pass1+pass2+pass3, pass1, pass2, pass3); + pass1 = (time1 - time3) * 1000; + time3 = Sys_DoubleTime(); + pass2 = (time2 - time1) * 1000; + pass3 = (time3 - time2) * 1000; + Con_Printf("%3" PRIi32 " tot %3" PRIi32 " server %3" PRIi32 " gfx %3" PRIi32 " snd\n", + pass1 + pass2 + pass3, pass1, pass2, pass3); } host_framecount++; } -void Host_Frame (float time) +void Host_Frame(float time) { - double time1, time2; - static double timetotal; - static int32_t timecount; - int32_t i, c, m; + double time1, time2; + static double timetotal; + static int32_t timecount; + int32_t i, c, m; - if (!serverprofile.value) + if(!serverprofile.value) { - _Host_Frame (time); + _Host_Frame(time); return; } - time1 = Sys_DoubleTime (); - _Host_Frame (time); - time2 = Sys_DoubleTime (); + time1 = Sys_DoubleTime(); + _Host_Frame(time); + time2 = Sys_DoubleTime(); timetotal += time2 - time1; timecount++; - if (timecount < 1000) + if(timecount < 1000) return; - m = timetotal*1000/timecount; + m = timetotal * 1000 / timecount; timecount = 0; timetotal = 0; c = 0; - for (i = 0; i < svs.maxclients; i++) + for(i = 0; i < svs.maxclients; i++) { - if (svs.clients[i].active) + if(svs.clients[i].active) c++; } - Con_Printf ("serverprofile: %2" PRIi32 " clients %2" PRIi32 " msec\n", c, m); + Con_Printf("serverprofile: %2" PRIi32 " clients %2" PRIi32 " msec\n", c, m); } /* @@ -803,91 +803,91 @@ void Host_Frame (float time) Host_Init ==================== */ -void Host_Init (void) +void Host_Init(void) { int32_t minimum_memory; - if (standard_quake) + if(standard_quake) minimum_memory = MINIMUM_MEMORY; else minimum_memory = MINIMUM_MEMORY_LEVELPAK; - if (COM_CheckParm ("-minmemory")) + if(COM_CheckParm("-minmemory")) host_parms->memsize = minimum_memory; - if (host_parms->memsize < minimum_memory) - Sys_Error ("Only %4.1f MiB of memory available, can't execute game", host_parms->memsize / (float)0x100000); + if(host_parms->memsize < minimum_memory) + Sys_Error("Only %4.1f MiB of memory available, can't execute game", host_parms->memsize / (float)0x100000); com_argc = host_parms->argc; com_argv = host_parms->argv; - Memory_Init (host_parms->membase, host_parms->memsize); - Cbuf_Init (); - Cmd_Init (); - LOG_Init (host_parms); - Cvar_Init (); //johnfitz - COM_Init (); - COM_InitFilesystem (); - Host_InitLocal (); - W_LoadWadFile (); //johnfitz -- filename is now hard-coded for honesty - if (cls.state != ca_dedicated) + Memory_Init(host_parms->membase, host_parms->memsize); + Cbuf_Init(); + Cmd_Init(); + LOG_Init(host_parms); + Cvar_Init(); //johnfitz + COM_Init(); + COM_InitFilesystem(); + Host_InitLocal(); + W_LoadWadFile(); //johnfitz -- filename is now hard-coded for honesty + if(cls.state != ca_dedicated) { - Key_Init (); - Con_Init (); + Key_Init(); + Con_Init(); } - PR_Init (); - Mod_Init (); - NET_Init (); - SV_Init (); + PR_Init(); + Mod_Init(); + NET_Init(); + SV_Init(); - Con_Printf ("Exe: " __TIME__ " " __DATE__ "\n"); - Con_Printf ("%4.1f megabyte heap\n", host_parms->memsize/ (1024*1024.0)); + Con_Printf("Exe: " __TIME__ " " __DATE__ "\n"); + Con_Printf("%4.1f megabyte heap\n", host_parms->memsize / (1024 * 1024.0)); - if (cls.state != ca_dedicated) + if(cls.state != ca_dedicated) { - host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp", NULL); - if (!host_colormap) - Sys_Error ("Couldn't load gfx/colormap.lmp"); + host_colormap = (byte *)COM_LoadHunkFile("gfx/colormap.lmp", NULL); + if(!host_colormap) + Sys_Error("Couldn't load gfx/colormap.lmp"); - V_Init (); - Chase_Init (); - M_Init (); - ExtraMaps_Init (); //johnfitz - Modlist_Init (); //johnfitz - DemoList_Init (); //ericw - VID_Init (); - IN_Init (); - TexMgr_Init (); //johnfitz - Draw_Init (); - SCR_Init (); - R_Init (); - S_Init (); + V_Init(); + Chase_Init(); + M_Init(); + ExtraMaps_Init(); //johnfitz + Modlist_Init(); //johnfitz + DemoList_Init(); //ericw + VID_Init(); + IN_Init(); + TexMgr_Init(); //johnfitz + Draw_Init(); + SCR_Init(); + R_Init(); + S_Init(); BGM_Init(); - Sbar_Init (); - CL_Init (); + Sbar_Init(); + CL_Init(); } - Hunk_AllocName (0, "-HOST_HUNKLEVEL-"); - host_hunklevel = Hunk_LowMark (); + Hunk_AllocName(0, "-HOST_HUNKLEVEL-"); + host_hunklevel = Hunk_LowMark(); host_initialized = true; - Con_Printf ("\n========= Quake Initialized =========\n\n"); + Con_Printf("\n========= Quake Initialized =========\n\n"); - if (cls.state != ca_dedicated) + if(cls.state != ca_dedicated) { - Cbuf_InsertText ("exec quake.rc\n"); - // johnfitz -- in case the vid mode was locked during vid_init, we can unlock it now. + Cbuf_InsertText("exec quake.rc\n"); + // johnfitz -- in case the vid mode was locked during vid_init, we can unlock it now. // note: two leading newlines because the command buffer swallows one of them. - Cbuf_AddText ("\n\nvid_unlock\n"); + Cbuf_AddText("\n\nvid_unlock\n"); } - if (cls.state == ca_dedicated) + if(cls.state == ca_dedicated) { - Cbuf_AddText ("exec autoexec.cfg\n"); - Cbuf_AddText ("stuffcmds"); - Cbuf_Execute (); - if (!sv.active) - Cbuf_AddText ("map start\n"); + Cbuf_AddText("exec autoexec.cfg\n"); + Cbuf_AddText("stuffcmds"); + Cbuf_Execute(); + if(!sv.active) + Cbuf_AddText("map start\n"); } } @@ -904,9 +904,9 @@ void Host_Shutdown(void) { static bool isdown = false; - if (isdown) + if(isdown) { - printf ("recursive shutdown\n"); + printf("recursive shutdown\n"); return; } isdown = true; @@ -914,20 +914,20 @@ void Host_Shutdown(void) // keep Con_Printf from trying to update the screen scr_disabled_for_loading = true; - Host_WriteConfiguration (); + Host_WriteConfiguration(); - NET_Shutdown (); + NET_Shutdown(); - if (cls.state != ca_dedicated) + if(cls.state != ca_dedicated) { - if (con_initialized) - History_Shutdown (); + if(con_initialized) + History_Shutdown(); BGM_Shutdown(); - S_Shutdown (); - IN_Shutdown (); + S_Shutdown(); + IN_Shutdown(); VID_Shutdown(); } - LOG_Close (); + LOG_Close(); } diff --git a/source/host_cmd.c b/source/host_cmd.c index e3503ef..5a3f968 100644 --- a/source/host_cmd.c +++ b/source/host_cmd.c @@ -26,11 +26,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include #endif -extern cvar_t pausable; +extern cvar_t pausable; -int32_t current_skill; +int32_t current_skill; -void Mod_Print (void); +void Mod_Print(void); /* ================== @@ -38,17 +38,17 @@ Host_Quit_f ================== */ -void Host_Quit_f (void) +void Host_Quit_f(void) { - if (key_dest != key_console && cls.state != ca_dedicated) + if(key_dest != key_console && cls.state != ca_dedicated) { - M_Menu_Quit_f (); + M_Menu_Quit_f(); return; } - CL_Disconnect (); + CL_Disconnect(); Host_ShutdownServer(false); - Sys_Quit (); + Sys_Quit(); } //============================================================================== @@ -60,23 +60,23 @@ void Host_Quit_f (void) FileList_Add ================== */ -void FileList_Add (const char *name, filelist_item_t **list) +void FileList_Add(const char *name, filelist_item_t **list) { - filelist_item_t *item,*cursor,*prev; + filelist_item_t *item, *cursor, *prev; // ignore duplicate - for (item = *list; item; item = item->next) + for(item = *list; item; item = item->next) { - if (!Q_strcmp (name, item->name)) + if(!Q_strcmp(name, item->name)) return; } item = (filelist_item_t *) Z_Malloc(sizeof(filelist_item_t)); - q_strlcpy (item->name, name, sizeof(item->name)); + q_strlcpy(item->name, name, sizeof(item->name)); // insert each entry in alphabetical order - if (*list == NULL || - q_strcasecmp(item->name, (*list)->name) < 0) //insert at front + if(*list == NULL || + q_strcasecmp(item->name, (*list)->name) < 0) //insert at front { item->next = *list; *list = item; @@ -85,7 +85,7 @@ void FileList_Add (const char *name, filelist_item_t **list) { prev = *list; cursor = (*list)->next; - while (cursor && (q_strcasecmp(item->name, cursor->name) > 0)) + while(cursor && (q_strcasecmp(item->name, cursor->name) > 0)) { prev = cursor; cursor = cursor->next; @@ -95,11 +95,11 @@ void FileList_Add (const char *name, filelist_item_t **list) } } -static void FileList_Clear (filelist_item_t **list) +static void FileList_Clear(filelist_item_t **list) { filelist_item_t *blah; - while (*list) + while(*list) { blah = (*list)->next; Z_Free(*list); @@ -107,75 +107,78 @@ static void FileList_Clear (filelist_item_t **list) } } -filelist_item_t *extralevels; +filelist_item_t *extralevels; -void ExtraMaps_Add (const char *name) +void ExtraMaps_Add(const char *name) { FileList_Add(name, &extralevels); } -void ExtraMaps_Init (void) +void ExtraMaps_Init(void) { #ifdef _WIN32 - WIN32_FIND_DATA fdat; - HANDLE fhnd; + WIN32_FIND_DATA fdat; + HANDLE fhnd; #else - DIR *dir_p; - struct dirent *dir_t; + DIR *dir_p; + struct dirent *dir_t; #endif - char filestring[MAX_OSPATH]; - char mapname[32]; - char ignorepakdir[32]; - searchpath_t *search; - pack_t *pak; - int32_t i; + char filestring[MAX_OSPATH]; + char mapname[32]; + char ignorepakdir[32]; + searchpath_t *search; + pack_t *pak; + int32_t i; // we don't want to list the maps in id1 pakfiles, // because these are not "add-on" levels - q_snprintf (ignorepakdir, sizeof(ignorepakdir), "/%s/", GAMENAME); + q_snprintf(ignorepakdir, sizeof(ignorepakdir), "/%s/", GAMENAME); - for (search = com_searchpaths; search; search = search->next) + for(search = com_searchpaths; search; search = search->next) { - if (*search->filename) //directory + if(*search->filename) //directory { #ifdef _WIN32 - q_snprintf (filestring, sizeof(filestring), "%s/maps/*.bsp", search->filename); + q_snprintf(filestring, sizeof(filestring), "%s/maps/*.bsp", search->filename); fhnd = FindFirstFile(filestring, &fdat); - if (fhnd == INVALID_HANDLE_VALUE) + if(fhnd == INVALID_HANDLE_VALUE) continue; do { COM_StripExtension(fdat.cFileName, mapname, sizeof(mapname)); - ExtraMaps_Add (mapname); - } while (FindNextFile(fhnd, &fdat)); + ExtraMaps_Add(mapname); + } + while(FindNextFile(fhnd, &fdat)); FindClose(fhnd); #else - q_snprintf (filestring, sizeof(filestring), "%s/maps/", search->filename); + q_snprintf(filestring, sizeof(filestring), "%s/maps/", search->filename); dir_p = opendir(filestring); - if (dir_p == NULL) + if(dir_p == NULL) continue; - while ((dir_t = readdir(dir_p)) != NULL) + while((dir_t = readdir(dir_p)) != NULL) { - if (q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "bsp") != 0) + if(q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "bsp") != 0) continue; COM_StripExtension(dir_t->d_name, mapname, sizeof(mapname)); - ExtraMaps_Add (mapname); + ExtraMaps_Add(mapname); } closedir(dir_p); #endif } else //pakfile { - if (!strstr(search->pack->filename, ignorepakdir)) - { //don't list standard id maps - for (i = 0, pak = search->pack; i < pak->numfiles; i++) + if(!strstr(search->pack->filename, ignorepakdir)) + { + //don't list standard id maps + for(i = 0, pak = search->pack; i < pak->numfiles; i++) { - if (!strcmp(COM_FileGetExtension(pak->files[i].name), "bsp")) + if(!strcmp(COM_FileGetExtension(pak->files[i].name), "bsp")) { - if (pak->files[i].filelen > 32*1024) - { // don't list files under 32k (ammo boxes etc) + if(pak->files[i].filelen > 32 * 1024) + { + // don't list files under 32k (ammo boxes etc) COM_StripExtension(pak->files[i].name + 5, mapname, sizeof(mapname)); - ExtraMaps_Add (mapname); + ExtraMaps_Add(mapname); } } } @@ -184,15 +187,15 @@ void ExtraMaps_Init (void) } } -static void ExtraMaps_Clear (void) +static void ExtraMaps_Clear(void) { FileList_Clear(&extralevels); } -void ExtraMaps_NewGame (void) +void ExtraMaps_NewGame(void) { - ExtraMaps_Clear (); - ExtraMaps_Init (); + ExtraMaps_Clear(); + ExtraMaps_Init(); } /* @@ -200,79 +203,81 @@ void ExtraMaps_NewGame (void) Host_Maps_f ================== */ -void Host_Maps_f (void) +void Host_Maps_f(void) { int32_t i; - filelist_item_t *level; + filelist_item_t *level; - for (level = extralevels, i = 0; level; level = level->next, i++) - Con_SafePrintf (" %s\n", level->name); + for(level = extralevels, i = 0; level; level = level->next, i++) + Con_SafePrintf(" %s\n", level->name); - if (i) - Con_SafePrintf ("%" PRIi32 " map(s)\n", i); + if(i) + Con_SafePrintf("%" PRIi32 " map(s)\n", i); else - Con_SafePrintf ("no maps found\n"); + Con_SafePrintf("no maps found\n"); } //============================================================================== //johnfitz -- modlist management //============================================================================== -filelist_item_t *modlist; +filelist_item_t *modlist; -void Modlist_Add (const char *name) +void Modlist_Add(const char *name) { FileList_Add(name, &modlist); } #ifdef _WIN32 -void Modlist_Init (void) +void Modlist_Init(void) { - WIN32_FIND_DATA fdat; - HANDLE fhnd; - DWORD attribs; - char dir_string[MAX_OSPATH], mod_string[MAX_OSPATH]; + WIN32_FIND_DATA fdat; + HANDLE fhnd; + DWORD attribs; + char dir_string[MAX_OSPATH], mod_string[MAX_OSPATH]; - q_snprintf (dir_string, sizeof(dir_string), "%s/*", com_basedir); + q_snprintf(dir_string, sizeof(dir_string), "%s/*", com_basedir); fhnd = FindFirstFile(dir_string, &fdat); - if (fhnd == INVALID_HANDLE_VALUE) + if(fhnd == INVALID_HANDLE_VALUE) return; do { - if (!strcmp(fdat.cFileName, ".") || !strcmp(fdat.cFileName, "..")) + if(!strcmp(fdat.cFileName, ".") || !strcmp(fdat.cFileName, "..")) continue; - q_snprintf (mod_string, sizeof(mod_string), "%s/%s", com_basedir, fdat.cFileName); - attribs = GetFileAttributes (mod_string); - if (attribs != INVALID_FILE_ATTRIBUTES && (attribs & FILE_ATTRIBUTE_DIRECTORY)) { + q_snprintf(mod_string, sizeof(mod_string), "%s/%s", com_basedir, fdat.cFileName); + attribs = GetFileAttributes(mod_string); + if(attribs != INVALID_FILE_ATTRIBUTES && (attribs & FILE_ATTRIBUTE_DIRECTORY)) + { /* don't bother testing for pak files / progs.dat */ Modlist_Add(fdat.cFileName); } - } while (FindNextFile(fhnd, &fdat)); + } + while(FindNextFile(fhnd, &fdat)); FindClose(fhnd); } #else -void Modlist_Init (void) +void Modlist_Init(void) { - DIR *dir_p, *mod_dir_p; - struct dirent *dir_t; - char dir_string[MAX_OSPATH], mod_string[MAX_OSPATH]; + DIR *dir_p, *mod_dir_p; + struct dirent *dir_t; + char dir_string[MAX_OSPATH], mod_string[MAX_OSPATH]; - q_snprintf (dir_string, sizeof(dir_string), "%s/", com_basedir); + q_snprintf(dir_string, sizeof(dir_string), "%s/", com_basedir); dir_p = opendir(dir_string); - if (dir_p == NULL) + if(dir_p == NULL) return; - while ((dir_t = readdir(dir_p)) != NULL) + while((dir_t = readdir(dir_p)) != NULL) { - if (!strcmp(dir_t->d_name, ".") || !strcmp(dir_t->d_name, "..")) + if(!strcmp(dir_t->d_name, ".") || !strcmp(dir_t->d_name, "..")) continue; - if (!q_strcasecmp (COM_FileGetExtension (dir_t->d_name), "app")) // skip .app bundles on macOS + if(!q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "app")) // skip .app bundles on macOS continue; q_snprintf(mod_string, sizeof(mod_string), "%s%s/", dir_string, dir_t->d_name); mod_dir_p = opendir(mod_string); - if (mod_dir_p == NULL) + if(mod_dir_p == NULL) continue; /* don't bother testing for pak files / progs.dat */ Modlist_Add(dir_t->d_name); @@ -287,80 +292,82 @@ void Modlist_Init (void) //ericw -- demo list management //============================================================================== -filelist_item_t *demolist; +filelist_item_t *demolist; -static void DemoList_Clear (void) +static void DemoList_Clear(void) { - FileList_Clear (&demolist); + FileList_Clear(&demolist); } -void DemoList_Rebuild (void) +void DemoList_Rebuild(void) { - DemoList_Clear (); - DemoList_Init (); + DemoList_Clear(); + DemoList_Init(); } // TODO: Factor out to a general-purpose file searching function -void DemoList_Init (void) +void DemoList_Init(void) { #ifdef _WIN32 - WIN32_FIND_DATA fdat; - HANDLE fhnd; + WIN32_FIND_DATA fdat; + HANDLE fhnd; #else - DIR *dir_p; - struct dirent *dir_t; + DIR *dir_p; + struct dirent *dir_t; #endif - char filestring[MAX_OSPATH]; - char demname[32]; - char ignorepakdir[32]; - searchpath_t *search; - pack_t *pak; - int32_t i; + char filestring[MAX_OSPATH]; + char demname[32]; + char ignorepakdir[32]; + searchpath_t *search; + pack_t *pak; + int32_t i; // we don't want to list the demos in id1 pakfiles, // because these are not "add-on" demos - q_snprintf (ignorepakdir, sizeof(ignorepakdir), "/%s/", GAMENAME); + q_snprintf(ignorepakdir, sizeof(ignorepakdir), "/%s/", GAMENAME); - for (search = com_searchpaths; search; search = search->next) + for(search = com_searchpaths; search; search = search->next) { - if (*search->filename) //directory + if(*search->filename) //directory { #ifdef _WIN32 - q_snprintf (filestring, sizeof(filestring), "%s/*.dem", search->filename); + q_snprintf(filestring, sizeof(filestring), "%s/*.dem", search->filename); fhnd = FindFirstFile(filestring, &fdat); - if (fhnd == INVALID_HANDLE_VALUE) + if(fhnd == INVALID_HANDLE_VALUE) continue; do { COM_StripExtension(fdat.cFileName, demname, sizeof(demname)); - FileList_Add (demname, &demolist); - } while (FindNextFile(fhnd, &fdat)); + FileList_Add(demname, &demolist); + } + while(FindNextFile(fhnd, &fdat)); FindClose(fhnd); #else - q_snprintf (filestring, sizeof(filestring), "%s/", search->filename); + q_snprintf(filestring, sizeof(filestring), "%s/", search->filename); dir_p = opendir(filestring); - if (dir_p == NULL) + if(dir_p == NULL) continue; - while ((dir_t = readdir(dir_p)) != NULL) + while((dir_t = readdir(dir_p)) != NULL) { - if (q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "dem") != 0) + if(q_strcasecmp(COM_FileGetExtension(dir_t->d_name), "dem") != 0) continue; COM_StripExtension(dir_t->d_name, demname, sizeof(demname)); - FileList_Add (demname, &demolist); + FileList_Add(demname, &demolist); } closedir(dir_p); #endif } else //pakfile { - if (!strstr(search->pack->filename, ignorepakdir)) - { //don't list standard id demos - for (i = 0, pak = search->pack; i < pak->numfiles; i++) + if(!strstr(search->pack->filename, ignorepakdir)) + { + //don't list standard id demos + for(i = 0, pak = search->pack; i < pak->numfiles; i++) { - if (!strcmp(COM_FileGetExtension(pak->files[i].name), "dem")) + if(!strcmp(COM_FileGetExtension(pak->files[i].name), "dem")) { COM_StripExtension(pak->files[i].name, demname, sizeof(demname)); - FileList_Add (demname, &demolist); + FileList_Add(demname, &demolist); } } } @@ -376,18 +383,18 @@ Host_Mods_f -- johnfitz list all potential mod directories (contain either a pak file or a progs.dat) ================== */ -void Host_Mods_f (void) +void Host_Mods_f(void) { int32_t i; - filelist_item_t *mod; + filelist_item_t *mod; - for (mod = modlist, i=0; mod; mod = mod->next, i++) - Con_SafePrintf (" %s\n", mod->name); + for(mod = modlist, i = 0; mod; mod = mod->next, i++) + Con_SafePrintf(" %s\n", mod->name); - if (i) - Con_SafePrintf ("%" PRIi32 " mod(s)\n", i); + if(i) + Con_SafePrintf("%" PRIi32 " mod(s)\n", i); else - Con_SafePrintf ("no mods found\n"); + Con_SafePrintf("no mods found\n"); } //============================================================================== @@ -397,21 +404,21 @@ void Host_Mods_f (void) Host_Mapname_f -- johnfitz ============= */ -void Host_Mapname_f (void) +void Host_Mapname_f(void) { - if (sv.active) + if(sv.active) { - Con_Printf ("\"mapname\" is \"%s\"\n", sv.name); + Con_Printf("\"mapname\" is \"%s\"\n", sv.name); return; } - if (cls.state == ca_connected) + if(cls.state == ca_connected) { - Con_Printf ("\"mapname\" is \"%s\"\n", cl.mapname); + Con_Printf("\"mapname\" is \"%s\"\n", cl.mapname); return; } - Con_Printf ("no map loaded\n"); + Con_Printf("no map loaded\n"); } /* @@ -419,21 +426,21 @@ void Host_Mapname_f (void) Host_Status_f ================== */ -void Host_Status_f (void) +void Host_Status_f(void) { - void (*print_fn) (const char *fmt, ...) - FUNCP_PRINTF(1,2); - client_t *client; - int32_t seconds; - int32_t minutes; - int32_t hours = 0; - int32_t j; + void (*print_fn)(const char *fmt, ...) + FUNCP_PRINTF(1, 2); + client_t *client; + int32_t seconds; + int32_t minutes; + int32_t hours = 0; + int32_t j; - if (cmd_source == src_command) + if(cmd_source == src_command) { - if (!sv.active) + if(!sv.active) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } print_fn = Con_Printf; @@ -441,31 +448,31 @@ void Host_Status_f (void) else print_fn = SV_ClientPrintf; - print_fn ("host: %s\n", Cvar_VariableString ("hostname")); - print_fn ("version: " VERSION "\n"); - if (tcpipAvailable) - print_fn ("tcp/ip: %s\n", my_tcpip_address); - if (ipxAvailable) - print_fn ("ipx: %s\n", my_ipx_address); - print_fn ("map: %s\n", sv.name); - print_fn ("players: %" PRIi32 " active (%" PRIi32 " max)\n\n", net_activeconnections, svs.maxclients); - for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) + print_fn("host: %s\n", Cvar_VariableString("hostname")); + print_fn("version: " VERSION "\n"); + if(tcpipAvailable) + print_fn("tcp/ip: %s\n", my_tcpip_address); + if(ipxAvailable) + print_fn("ipx: %s\n", my_ipx_address); + print_fn("map: %s\n", sv.name); + print_fn("players: %" PRIi32 " active (%" PRIi32 " max)\n\n", net_activeconnections, svs.maxclients); + for(j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { - if (!client->active) + if(!client->active) continue; seconds = (int32_t)(net_time - NET_QSocketGetTime(client->netconnection)); minutes = seconds / 60; - if (minutes) + if(minutes) { seconds -= (minutes * 60); hours = minutes / 60; - if (hours) + if(hours) minutes -= (hours * 60); } else hours = 0; - print_fn ("#%-2" PRIu32 " %-16.16s %3" PRIi32 " %2" PRIi32 ":%02" PRIi32 ":%02" PRIi32 "n", j+1, client->name, (int32_t)client->edict->v.frags, hours, minutes, seconds); - print_fn (" %s\n", NET_QSocketGetAddressString(client->netconnection)); + print_fn("#%-2" PRIu32 " %-16.16s %3" PRIi32 " %2" PRIi32 ":%02" PRIi32 ":%02" PRIi32 "n", j + 1, client->name, (int32_t)client->edict->v.frags, hours, minutes, seconds); + print_fn(" %s\n", NET_QSocketGetAddressString(client->netconnection)); } } @@ -476,37 +483,37 @@ Host_God_f Sets client to godmode ================== */ -void Host_God_f (void) +void Host_God_f(void) { - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - if (pr_global_struct->deathmatch) + if(pr_global_struct->deathmatch) return; //johnfitz -- allow user to explicitly set god mode to on or off - switch (Cmd_Argc()) + switch(Cmd_Argc()) { case 1: sv_player->v.flags = (int32_t)sv_player->v.flags ^ FL_GODMODE; - if (!((int32_t)sv_player->v.flags & FL_GODMODE) ) - SV_ClientPrintf ("godmode OFF\n"); + if(!((int32_t)sv_player->v.flags & FL_GODMODE)) + SV_ClientPrintf("godmode OFF\n"); else - SV_ClientPrintf ("godmode ON\n"); + SV_ClientPrintf("godmode ON\n"); break; case 2: - if (Q_atof(Cmd_Argv(1))) + if(Q_atof(Cmd_Argv(1))) { sv_player->v.flags = (int32_t)sv_player->v.flags | FL_GODMODE; - SV_ClientPrintf ("godmode ON\n"); + SV_ClientPrintf("godmode ON\n"); } else { sv_player->v.flags = (int32_t)sv_player->v.flags & ~FL_GODMODE; - SV_ClientPrintf ("godmode OFF\n"); + SV_ClientPrintf("godmode OFF\n"); } break; default: @@ -521,37 +528,37 @@ void Host_God_f (void) Host_Notarget_f ================== */ -void Host_Notarget_f (void) +void Host_Notarget_f(void) { - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - if (pr_global_struct->deathmatch) + if(pr_global_struct->deathmatch) return; //johnfitz -- allow user to explicitly set notarget to on or off - switch (Cmd_Argc()) + switch(Cmd_Argc()) { case 1: sv_player->v.flags = (int32_t)sv_player->v.flags ^ FL_NOTARGET; - if (!((int32_t)sv_player->v.flags & FL_NOTARGET) ) - SV_ClientPrintf ("notarget OFF\n"); + if(!((int32_t)sv_player->v.flags & FL_NOTARGET)) + SV_ClientPrintf("notarget OFF\n"); else - SV_ClientPrintf ("notarget ON\n"); + SV_ClientPrintf("notarget ON\n"); break; case 2: - if (Q_atof(Cmd_Argv(1))) + if(Q_atof(Cmd_Argv(1))) { sv_player->v.flags = (int32_t)sv_player->v.flags | FL_NOTARGET; - SV_ClientPrintf ("notarget ON\n"); + SV_ClientPrintf("notarget ON\n"); } else { sv_player->v.flags = (int32_t)sv_player->v.flags & ~FL_NOTARGET; - SV_ClientPrintf ("notarget OFF\n"); + SV_ClientPrintf("notarget OFF\n"); } break; default: @@ -568,46 +575,46 @@ bool noclip_anglehack; Host_Noclip_f ================== */ -void Host_Noclip_f (void) +void Host_Noclip_f(void) { - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - if (pr_global_struct->deathmatch) + if(pr_global_struct->deathmatch) return; //johnfitz -- allow user to explicitly set noclip to on or off - switch (Cmd_Argc()) + switch(Cmd_Argc()) { case 1: - if (sv_player->v.movetype != MOVETYPE_NOCLIP) + if(sv_player->v.movetype != MOVETYPE_NOCLIP) { noclip_anglehack = true; sv_player->v.movetype = MOVETYPE_NOCLIP; - SV_ClientPrintf ("noclip ON\n"); + SV_ClientPrintf("noclip ON\n"); } else { noclip_anglehack = false; sv_player->v.movetype = MOVETYPE_WALK; - SV_ClientPrintf ("noclip OFF\n"); + SV_ClientPrintf("noclip OFF\n"); } break; case 2: - if (Q_atof(Cmd_Argv(1))) + if(Q_atof(Cmd_Argv(1))) { noclip_anglehack = true; sv_player->v.movetype = MOVETYPE_NOCLIP; - SV_ClientPrintf ("noclip ON\n"); + SV_ClientPrintf("noclip ON\n"); } else { noclip_anglehack = false; sv_player->v.movetype = MOVETYPE_WALK; - SV_ClientPrintf ("noclip OFF\n"); + SV_ClientPrintf("noclip OFF\n"); } break; default: @@ -626,36 +633,36 @@ adapted from fteqw, originally by Alex Shadowalker */ void Host_SetPos_f(void) { - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - if (pr_global_struct->deathmatch) + if(pr_global_struct->deathmatch) return; - if (Cmd_Argc() != 7 && Cmd_Argc() != 4) + if(Cmd_Argc() != 7 && Cmd_Argc() != 4) { SV_ClientPrintf("usage:\n"); SV_ClientPrintf(" setpos \n"); SV_ClientPrintf(" setpos \n"); SV_ClientPrintf("current values:\n"); SV_ClientPrintf(" %" PRIi32 " %" PRIi32 " %" PRIi32 " %" PRIi32 " %" PRIi32 " %" PRIi32 "\n", - (int32_t)sv_player->v.origin[0], - (int32_t)sv_player->v.origin[1], - (int32_t)sv_player->v.origin[2], - (int32_t)sv_player->v.v_angle[0], - (int32_t)sv_player->v.v_angle[1], - (int32_t)sv_player->v.v_angle[2]); + (int32_t)sv_player->v.origin[0], + (int32_t)sv_player->v.origin[1], + (int32_t)sv_player->v.origin[2], + (int32_t)sv_player->v.v_angle[0], + (int32_t)sv_player->v.v_angle[1], + (int32_t)sv_player->v.v_angle[2]); return; } - if (sv_player->v.movetype != MOVETYPE_NOCLIP) + if(sv_player->v.movetype != MOVETYPE_NOCLIP) { noclip_anglehack = true; sv_player->v.movetype = MOVETYPE_NOCLIP; - SV_ClientPrintf ("noclip ON\n"); + SV_ClientPrintf("noclip ON\n"); } //make sure they're not going to whizz away from it @@ -667,7 +674,7 @@ void Host_SetPos_f(void) sv_player->v.origin[1] = atof(Cmd_Argv(2)); sv_player->v.origin[2] = atof(Cmd_Argv(3)); - if (Cmd_Argc() == 7) + if(Cmd_Argc() == 7) { sv_player->v.angles[0] = atof(Cmd_Argv(4)); sv_player->v.angles[1] = atof(Cmd_Argv(5)); @@ -675,7 +682,7 @@ void Host_SetPos_f(void) sv_player->v.fixangle = 1; } - SV_LinkEdict (sv_player, false); + SV_LinkEdict(sv_player, false); } /* @@ -685,42 +692,42 @@ Host_Fly_f Sets client to flymode ================== */ -void Host_Fly_f (void) +void Host_Fly_f(void) { - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - if (pr_global_struct->deathmatch) + if(pr_global_struct->deathmatch) return; //johnfitz -- allow user to explicitly set noclip to on or off - switch (Cmd_Argc()) + switch(Cmd_Argc()) { case 1: - if (sv_player->v.movetype != MOVETYPE_FLY) + if(sv_player->v.movetype != MOVETYPE_FLY) { sv_player->v.movetype = MOVETYPE_FLY; - SV_ClientPrintf ("flymode ON\n"); + SV_ClientPrintf("flymode ON\n"); } else { sv_player->v.movetype = MOVETYPE_WALK; - SV_ClientPrintf ("flymode OFF\n"); + SV_ClientPrintf("flymode OFF\n"); } break; case 2: - if (Q_atof(Cmd_Argv(1))) + if(Q_atof(Cmd_Argv(1))) { sv_player->v.movetype = MOVETYPE_FLY; - SV_ClientPrintf ("flymode ON\n"); + SV_ClientPrintf("flymode ON\n"); } else { sv_player->v.movetype = MOVETYPE_WALK; - SV_ClientPrintf ("flymode OFF\n"); + SV_ClientPrintf("flymode OFF\n"); } break; default: @@ -737,28 +744,28 @@ Host_Ping_f ================== */ -void Host_Ping_f (void) +void Host_Ping_f(void) { - int32_t i, j; - float total; - client_t *client; + int32_t i, j; + float total; + client_t *client; - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - SV_ClientPrintf ("Client ping times:\n"); - for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) + SV_ClientPrintf("Client ping times:\n"); + for(i = 0, client = svs.clients; i < svs.maxclients; i++, client++) { - if (!client->active) + if(!client->active) continue; total = 0; - for (j = 0; j < NUM_PING_TIMES; j++) - total+=client->ping_times[j]; + for(j = 0; j < NUM_PING_TIMES; j++) + total += client->ping_times[j]; total /= NUM_PING_TIMES; - SV_ClientPrintf ("%4" PRIi32 " %s\n", (int32_t)(total*1000), client->name); + SV_ClientPrintf("%4" PRIi32 " %s\n", (int32_t)(total * 1000), client->name); } } @@ -780,64 +787,64 @@ map command from the console. Active clients are kicked off. ====================== */ -void Host_Map_f (void) +void Host_Map_f(void) { - int32_t i; - char name[MAX_QPATH], *p; + int32_t i; + char name[MAX_QPATH], *p; - if (Cmd_Argc() < 2) //no map name given + if(Cmd_Argc() < 2) //no map name given { - if (cls.state == ca_dedicated) + if(cls.state == ca_dedicated) { - if (sv.active) - Con_Printf ("Current map: %s\n", sv.name); + if(sv.active) + Con_Printf("Current map: %s\n", sv.name); else - Con_Printf ("Server not active\n"); + Con_Printf("Server not active\n"); } - else if (cls.state == ca_connected) + else if(cls.state == ca_connected) { - Con_Printf ("Current map: %s ( %s )\n", cl.levelname, cl.mapname); + Con_Printf("Current map: %s ( %s )\n", cl.levelname, cl.mapname); } else { - Con_Printf ("map : start a new server\n"); + Con_Printf("map : start a new server\n"); } return; } - if (cmd_source != src_command) + if(cmd_source != src_command) return; - cls.demonum = -1; // stop demo loop in case this fails + cls.demonum = -1; // stop demo loop in case this fails - CL_Disconnect (); + CL_Disconnect(); Host_ShutdownServer(false); - if (cls.state != ca_dedicated) + if(cls.state != ca_dedicated) IN_Activate(); - key_dest = key_game; // remove console or menu - SCR_BeginLoadingPlaque (); + key_dest = key_game; // remove console or menu + SCR_BeginLoadingPlaque(); - svs.serverflags = 0; // haven't completed an episode yet - q_strlcpy (name, Cmd_Argv(1), sizeof(name)); + svs.serverflags = 0; // haven't completed an episode yet + q_strlcpy(name, Cmd_Argv(1), sizeof(name)); // remove (any) trailing ".bsp" from mapname -- S.A. p = strstr(name, ".bsp"); - if (p && p[4] == '\0') + if(p && p[4] == '\0') *p = '\0'; - SV_SpawnServer (name); - if (!sv.active) + SV_SpawnServer(name); + if(!sv.active) return; - if (cls.state != ca_dedicated) + if(cls.state != ca_dedicated) { - memset (cls.spawnparms, 0, MAX_MAPSTRING); - for (i = 2; i < Cmd_Argc(); i++) + memset(cls.spawnparms, 0, MAX_MAPSTRING); + for(i = 2; i < Cmd_Argc(); i++) { - q_strlcat (cls.spawnparms, Cmd_Argv(i), MAX_MAPSTRING); - q_strlcat (cls.spawnparms, " ", MAX_MAPSTRING); + q_strlcat(cls.spawnparms, Cmd_Argv(i), MAX_MAPSTRING); + q_strlcat(cls.spawnparms, " ", MAX_MAPSTRING); } - Cmd_ExecuteString ("connect local", src_command); + Cmd_ExecuteString("connect local", src_command); } } @@ -848,31 +855,31 @@ Host_Randmap_f Loads a random map from the "maps" list. ====================== */ -void Host_Randmap_f (void) +void Host_Randmap_f(void) { - int32_t i, randlevel, numlevels; - filelist_item_t *level; + int32_t i, randlevel, numlevels; + filelist_item_t *level; - if (cmd_source != src_command) + if(cmd_source != src_command) return; - for (level = extralevels, numlevels = 0; level; level = level->next) + for(level = extralevels, numlevels = 0; level; level = level->next) numlevels++; - if (numlevels == 0) + if(numlevels == 0) { - Con_Printf ("no maps\n"); + Con_Printf("no maps\n"); return; } randlevel = (rand() % numlevels); - for (level = extralevels, i = 0; level; level = level->next, i++) + for(level = extralevels, i = 0; level; level = level->next, i++) { - if (i == randlevel) + if(i == randlevel) { - Con_Printf ("Starting map %s...\n", level->name); - Cbuf_AddText (va("map %s\n", level->name)); + Con_Printf("Starting map %s...\n", level->name); + Cbuf_AddText(va("map %s\n", level->name)); return; } } @@ -885,36 +892,36 @@ Host_Changelevel_f Goes to a new map, taking all clients along ================== */ -void Host_Changelevel_f (void) +void Host_Changelevel_f(void) { - char level[MAX_QPATH]; + char level[MAX_QPATH]; - if (Cmd_Argc() != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("changelevel : continue game on a new level\n"); + Con_Printf("changelevel : continue game on a new level\n"); return; } - if (!sv.active || cls.demoplayback) + if(!sv.active || cls.demoplayback) { - Con_Printf ("Only the server may changelevel\n"); + Con_Printf("Only the server may changelevel\n"); return; } //johnfitz -- check for client having map before anything else - q_snprintf (level, sizeof(level), "maps/%s.bsp", Cmd_Argv(1)); - if (!COM_FileExists(level, NULL)) - Host_Error ("cannot find map %s", level); + q_snprintf(level, sizeof(level), "maps/%s.bsp", Cmd_Argv(1)); + if(!COM_FileExists(level, NULL)) + Host_Error("cannot find map %s", level); //johnfitz - if (cls.state != ca_dedicated) - IN_Activate(); // -- S.A. - key_dest = key_game; // remove console or menu - SV_SaveSpawnparms (); - q_strlcpy (level, Cmd_Argv(1), sizeof(level)); - SV_SpawnServer (level); + if(cls.state != ca_dedicated) + IN_Activate(); // -- S.A. + key_dest = key_game; // remove console or menu + SV_SaveSpawnparms(); + q_strlcpy(level, Cmd_Argv(1), sizeof(level)); + SV_SpawnServer(level); // also issue an error if spawn failed -- O.S. - if (!sv.active) - Host_Error ("cannot run map %s", level); + if(!sv.active) + Host_Error("cannot run map %s", level); } /* @@ -924,19 +931,19 @@ Host_Restart_f Restarts the current server for a dead player ================== */ -void Host_Restart_f (void) +void Host_Restart_f(void) { - char mapname[MAX_QPATH]; + char mapname[MAX_QPATH]; - if (cls.demoplayback || !sv.active) + if(cls.demoplayback || !sv.active) return; - if (cmd_source != src_command) + if(cmd_source != src_command) return; - q_strlcpy (mapname, sv.name, sizeof(mapname)); // mapname gets cleared in spawnserver - SV_SpawnServer (mapname); - if (!sv.active) - Host_Error ("cannot restart map %s", mapname); + q_strlcpy(mapname, sv.name, sizeof(mapname)); // mapname gets cleared in spawnserver + SV_SpawnServer(mapname); + if(!sv.active) + Host_Error("cannot restart map %s", mapname); } /* @@ -947,13 +954,13 @@ This command causes the client to wait for the signon messages again. This is sent just before a server changes levels ================== */ -void Host_Reconnect_f (void) +void Host_Reconnect_f(void) { - if (cls.demoplayback) // cross-map demo playback fix from Baker + if(cls.demoplayback) // cross-map demo playback fix from Baker return; - SCR_BeginLoadingPlaque (); - cls.signon = 0; // need new connection messages + SCR_BeginLoadingPlaque(); + cls.signon = 0; // need new connection messages } /* @@ -963,19 +970,19 @@ Host_Connect_f User command to connect to server ===================== */ -void Host_Connect_f (void) +void Host_Connect_f(void) { - char name[MAX_QPATH]; + char name[MAX_QPATH]; - cls.demonum = -1; // stop demo loop in case this fails - if (cls.demoplayback) + cls.demonum = -1; // stop demo loop in case this fails + if(cls.demoplayback) { - CL_StopPlayback (); - CL_Disconnect (); + CL_StopPlayback(); + CL_Disconnect(); } - q_strlcpy (name, Cmd_Argv(1), sizeof(name)); - CL_EstablishConnection (name); - Host_Reconnect_f (); + q_strlcpy(name, Cmd_Argv(1), sizeof(name)); + CL_EstablishConnection(name); + Host_Reconnect_f(); } @@ -987,7 +994,7 @@ LOAD / SAVE GAME =============================================================================== */ -#define SAVEGAME_VERSION 5 +#define SAVEGAME_VERSION 5 /* =============== @@ -996,20 +1003,20 @@ Host_SavegameComment Writes a SAVEGAME_COMMENT_LENGTH character comment describing the current =============== */ -void Host_SavegameComment (char *text) +void Host_SavegameComment(char *text) { - int32_t i; - char kills[20]; + int32_t i; + char kills[20]; - for (i = 0; i < SAVEGAME_COMMENT_LENGTH; i++) + for(i = 0; i < SAVEGAME_COMMENT_LENGTH; i++) text[i] = ' '; - memcpy (text, cl.levelname, q_min(strlen(cl.levelname),22)); //johnfitz -- only copy 22 chars. - sprintf (kills,"kills:%3" PRIi32 "/%3" PRIi32 "", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]); - memcpy (text+22, kills, strlen(kills)); + memcpy(text, cl.levelname, q_min(strlen(cl.levelname), 22)); //johnfitz -- only copy 22 chars. + sprintf(kills, "kills:%3" PRIi32 "/%3" PRIi32 "", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]); + memcpy(text + 22, kills, strlen(kills)); // convert space to _ to make stdio happy - for (i = 0; i < SAVEGAME_COMMENT_LENGTH; i++) + for(i = 0; i < SAVEGAME_COMMENT_LENGTH; i++) { - if (text[i] == ' ') + if(text[i] == ' ') text[i] = '_'; } text[SAVEGAME_COMMENT_LENGTH] = '\0'; @@ -1021,94 +1028,94 @@ void Host_SavegameComment (char *text) Host_Savegame_f =============== */ -void Host_Savegame_f (void) +void Host_Savegame_f(void) { - char name[MAX_OSPATH]; - FILE *f; - int32_t i; - char comment[SAVEGAME_COMMENT_LENGTH+1]; + char name[MAX_OSPATH]; + FILE *f; + int32_t i; + char comment[SAVEGAME_COMMENT_LENGTH + 1]; - if (cmd_source != src_command) + if(cmd_source != src_command) return; - if (!sv.active) + if(!sv.active) { - Con_Printf ("Not playing a local game.\n"); + Con_Printf("Not playing a local game.\n"); return; } - if (cl.intermission) + if(cl.intermission) { - Con_Printf ("Can't save in intermission.\n"); + Con_Printf("Can't save in intermission.\n"); return; } - if (svs.maxclients != 1) + if(svs.maxclients != 1) { - Con_Printf ("Can't save multiplayer games.\n"); + Con_Printf("Can't save multiplayer games.\n"); return; } - if (Cmd_Argc() != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("save : save a game\n"); + Con_Printf("save : save a game\n"); return; } - if (strstr(Cmd_Argv(1), "..")) + if(strstr(Cmd_Argv(1), "..")) { - Con_Printf ("Relative pathnames are not allowed.\n"); + Con_Printf("Relative pathnames are not allowed.\n"); return; } - for (i=0 ; iv.health <= 0) ) + if(svs.clients[i].active && (svs.clients[i].edict->v.health <= 0)) { - Con_Printf ("Can't savegame with a dead player\n"); + Con_Printf("Can't savegame with a dead player\n"); return; } } - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); - COM_AddExtension (name, ".sav", sizeof(name)); + q_snprintf(name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); + COM_AddExtension(name, ".sav", sizeof(name)); - Con_Printf ("Saving game to %s...\n", name); - f = fopen (name, "w"); - if (!f) + Con_Printf("Saving game to %s...\n", name); + f = fopen(name, "w"); + if(!f) { - Con_Printf ("ERROR: couldn't open.\n"); + Con_Printf("ERROR: couldn't open.\n"); return; } - fprintf (f, "%" PRIi32 "\n", SAVEGAME_VERSION); - Host_SavegameComment (comment); - fprintf (f, "%s\n", comment); - for (i = 0; i < NUM_SPAWN_PARMS; i++) - fprintf (f, "%f\n", svs.clients->spawn_parms[i]); - fprintf (f, "%" PRIi32 "\n", current_skill); - fprintf (f, "%s\n", sv.name); - fprintf (f, "%f\n",sv.time); + fprintf(f, "%" PRIi32 "\n", SAVEGAME_VERSION); + Host_SavegameComment(comment); + fprintf(f, "%s\n", comment); + for(i = 0; i < NUM_SPAWN_PARMS; i++) + fprintf(f, "%f\n", svs.clients->spawn_parms[i]); + fprintf(f, "%" PRIi32 "\n", current_skill); + fprintf(f, "%s\n", sv.name); + fprintf(f, "%f\n", sv.time); // write the light styles - for (i = 0; i < MAX_LIGHTSTYLES; i++) + for(i = 0; i < MAX_LIGHTSTYLES; i++) { - if (sv.lightstyles[i]) - fprintf (f, "%s\n", sv.lightstyles[i]); + if(sv.lightstyles[i]) + fprintf(f, "%s\n", sv.lightstyles[i]); else - fprintf (f,"m\n"); + fprintf(f, "m\n"); } - ED_WriteGlobals (f); - for (i = 0; i < sv.num_edicts; i++) + ED_WriteGlobals(f); + for(i = 0; i < sv.num_edicts; i++) { - ED_Write (f, EDICT_NUM(i)); - fflush (f); + ED_Write(f, EDICT_NUM(i)); + fflush(f); } - fclose (f); - Con_Printf ("done.\n"); + fclose(f); + Con_Printf("done.\n"); } @@ -1117,131 +1124,135 @@ void Host_Savegame_f (void) Host_Loadgame_f =============== */ -void Host_Loadgame_f (void) +void Host_Loadgame_f(void) { - static char *start; + static char *start; - char name[MAX_OSPATH]; - char mapname[MAX_QPATH]; - float time, tfloat; - const char *data; - int32_t i; - edict_t *ent; - int32_t entnum; - int32_t version; - float spawn_parms[NUM_SPAWN_PARMS]; + char name[MAX_OSPATH]; + char mapname[MAX_QPATH]; + float time, tfloat; + const char *data; + int32_t i; + edict_t *ent; + int32_t entnum; + int32_t version; + float spawn_parms[NUM_SPAWN_PARMS]; - if (cmd_source != src_command) + if(cmd_source != src_command) return; - if (Cmd_Argc() != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("load : load a game\n"); + Con_Printf("load : load a game\n"); return; } - if (strstr(Cmd_Argv(1), "..")) + if(strstr(Cmd_Argv(1), "..")) { - Con_Printf ("Relative pathnames are not allowed.\n"); + Con_Printf("Relative pathnames are not allowed.\n"); return; } - cls.demonum = -1; // stop demo loop in case this fails + cls.demonum = -1; // stop demo loop in case this fails - q_snprintf (name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); - COM_AddExtension (name, ".sav", sizeof(name)); + q_snprintf(name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); + COM_AddExtension(name, ".sav", sizeof(name)); // we can't call SCR_BeginLoadingPlaque, because too much stack space has // been used. The menu calls it before stuffing loadgame command // SCR_BeginLoadingPlaque (); - Con_Printf ("Loading game from %s...\n", name); + Con_Printf("Loading game from %s...\n", name); // avoid leaking if the previous Host_Loadgame_f failed with a Host_Error - if (start != NULL) - free (start); + if(start != NULL) + free(start); start = (char *) COM_LoadMallocFile_TextMode_OSPath(name, NULL); - if (start == NULL) + if(start == NULL) { - Con_Printf ("ERROR: couldn't open.\n"); + Con_Printf("ERROR: couldn't open.\n"); return; } data = start; - data = COM_ParseIntNewline (data, &version); - if (version != SAVEGAME_VERSION) + data = COM_ParseIntNewline(data, &version); + if(version != SAVEGAME_VERSION) { - free (start); + free(start); start = NULL; - Con_Printf ("Savegame is version %" PRIi32 ", not %" PRIi32 "\n", version, SAVEGAME_VERSION); + Con_Printf("Savegame is version %" PRIi32 ", not %" PRIi32 "\n", version, SAVEGAME_VERSION); return; } - data = COM_ParseStringNewline (data); - for (i = 0; i < NUM_SPAWN_PARMS; i++) - data = COM_ParseFloatNewline (data, &spawn_parms[i]); + data = COM_ParseStringNewline(data); + for(i = 0; i < NUM_SPAWN_PARMS; i++) + data = COM_ParseFloatNewline(data, &spawn_parms[i]); // this silliness is so we can load 1.06 save files, which have float skill values data = COM_ParseFloatNewline(data, &tfloat); current_skill = (int32_t)(tfloat + 0.1); - Cvar_SetValue ("skill", (float)current_skill); + Cvar_SetValue("skill", (float)current_skill); - data = COM_ParseStringNewline (data); - q_strlcpy (mapname, com_token, sizeof(mapname)); - data = COM_ParseFloatNewline (data, &time); + data = COM_ParseStringNewline(data); + q_strlcpy(mapname, com_token, sizeof(mapname)); + data = COM_ParseFloatNewline(data, &time); - CL_Disconnect_f (); + CL_Disconnect_f(); - SV_SpawnServer (mapname); + SV_SpawnServer(mapname); - if (!sv.active) + if(!sv.active) { - free (start); + free(start); start = NULL; - Con_Printf ("Couldn't load map\n"); + Con_Printf("Couldn't load map\n"); return; } - sv.paused = true; // pause until all clients connect + sv.paused = true; // pause until all clients connect sv.loadgame = true; // load the light styles - for (i = 0; i < MAX_LIGHTSTYLES; i++) + for(i = 0; i < MAX_LIGHTSTYLES; i++) { - data = COM_ParseStringNewline (data); - sv.lightstyles[i] = (const char *)Hunk_Strdup (com_token, "lightstyles"); + data = COM_ParseStringNewline(data); + sv.lightstyles[i] = (const char *)Hunk_Strdup(com_token, "lightstyles"); } // load the edicts out of the savegame file - entnum = -1; // -1 is the globals - while (*data) + entnum = -1; // -1 is the globals + while(*data) { - data = COM_Parse (data); - if (!com_token[0]) - break; // end of file - if (strcmp(com_token,"{")) + data = COM_Parse(data); + if(!com_token[0]) + break; // end of file + if(strcmp(com_token, "{")) { - Sys_Error ("First token isn't a brace"); + Sys_Error("First token isn't a brace"); } - if (entnum == -1) - { // parse the global vars - data = ED_ParseGlobals (data); + if(entnum == -1) + { + // parse the global vars + data = ED_ParseGlobals(data); } else - { // parse an edict + { + // parse an edict ent = EDICT_NUM(entnum); - if (entnum < sv.num_edicts) { + if(entnum < sv.num_edicts) + { ent->free = false; - memset (&ent->v, 0, progs->entityfields * 4); + memset(&ent->v, 0, progs->entityfields * 4); } - else { - memset (ent, 0, pr_edict_size); + else + { + memset(ent, 0, pr_edict_size); } - data = ED_ParseEdict (data, ent); + data = ED_ParseEdict(data, ent); - // link it into the bsp tree - if (!ent->free) - SV_LinkEdict (ent, false); + // link it into the bsp tree + if(!ent->free) + SV_LinkEdict(ent, false); } entnum++; @@ -1250,16 +1261,16 @@ void Host_Loadgame_f (void) sv.num_edicts = entnum; sv.time = time; - free (start); + free(start); start = NULL; - for (i = 0; i < NUM_SPAWN_PARMS; i++) + for(i = 0; i < NUM_SPAWN_PARMS; i++) svs.clients->spawn_parms[i] = spawn_parms[i]; - if (cls.state != ca_dedicated) + if(cls.state != ca_dedicated) { - CL_EstablishConnection ("local"); - Host_Reconnect_f (); + CL_EstablishConnection("local"); + Host_Reconnect_f(); } } @@ -1270,68 +1281,68 @@ void Host_Loadgame_f (void) Host_Name_f ====================== */ -void Host_Name_f (void) +void Host_Name_f(void) { - char newName[32]; + char newName[32]; - if (Cmd_Argc () == 1) + if(Cmd_Argc() == 1) { - Con_Printf ("\"name\" is \"%s\"\n", cl_name.string); + Con_Printf("\"name\" is \"%s\"\n", cl_name.string); return; } - if (Cmd_Argc () == 2) + if(Cmd_Argc() == 2) q_strlcpy(newName, Cmd_Argv(1), sizeof(newName)); else q_strlcpy(newName, Cmd_Args(), sizeof(newName)); - newName[15] = 0; // client_t structure actually says name[32]. + newName[15] = 0; // client_t structure actually says name[32]. - if (cmd_source == src_command) + if(cmd_source == src_command) { - if (Q_strcmp(cl_name.string, newName) == 0) + if(Q_strcmp(cl_name.string, newName) == 0) return; - Cvar_Set ("_cl_name", newName); - if (cls.state == ca_connected) - Cmd_ForwardToServer (); + Cvar_Set("_cl_name", newName); + if(cls.state == ca_connected) + Cmd_ForwardToServer(); return; } - if (host_client->name[0] && strcmp(host_client->name, "unconnected") ) + if(host_client->name[0] && strcmp(host_client->name, "unconnected")) { - if (Q_strcmp(host_client->name, newName) != 0) - Con_Printf ("%s renamed to %s\n", host_client->name, newName); + if(Q_strcmp(host_client->name, newName) != 0) + Con_Printf("%s renamed to %s\n", host_client->name, newName); } - Q_strcpy (host_client->name, newName); + Q_strcpy(host_client->name, newName); host_client->edict->v.netname = PR_SetEngineString(host_client->name); // send notification to all clients - MSG_WriteByte (&sv.reliable_datagram, svc_updatename); - MSG_WriteByte (&sv.reliable_datagram, host_client - svs.clients); - MSG_WriteString (&sv.reliable_datagram, host_client->name); + MSG_WriteByte(&sv.reliable_datagram, svc_updatename); + MSG_WriteByte(&sv.reliable_datagram, host_client - svs.clients); + MSG_WriteString(&sv.reliable_datagram, host_client->name); } void Host_Say(bool teamonly) { - int32_t j; - client_t *client; - client_t *save; - const char *p; - char text[MAXCMDLINE], *p2; - bool quoted; - bool fromServer = false; + int32_t j; + client_t *client; + client_t *save; + const char *p; + char text[MAXCMDLINE], *p2; + bool quoted; + bool fromServer = false; - if (cmd_source == src_command) + if(cmd_source == src_command) { - if (cls.state != ca_dedicated) + if(cls.state != ca_dedicated) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } fromServer = true; teamonly = false; } - if (Cmd_Argc () < 2) + if(Cmd_Argc() < 2) return; save = host_client; @@ -1339,20 +1350,20 @@ void Host_Say(bool teamonly) p = Cmd_Args(); // remove quotes if present quoted = false; - if (*p == '\"') + if(*p == '\"') { p++; quoted = true; } // turn on color set 1 - if (!fromServer) - q_snprintf (text, sizeof(text), "\001%s: %s", save->name, p); + if(!fromServer) + q_snprintf(text, sizeof(text), "\001%s: %s", save->name, p); else - q_snprintf (text, sizeof(text), "\001<%s> %s", hostname.string, p); + q_snprintf(text, sizeof(text), "\001<%s> %s", hostname.string, p); // check length & truncate if necessary j = (int32_t) strlen(text); - if (j >= (int32_t) sizeof(text) - 1) + if(j >= (int32_t) sizeof(text) - 1) { text[sizeof(text) - 2] = '\n'; text[sizeof(text) - 1] = '\0'; @@ -1360,10 +1371,10 @@ void Host_Say(bool teamonly) else { p2 = text + j; - while ((const char *)p2 > (const char *)text && - (p2[-1] == '\r' || p2[-1] == '\n' || (p2[-1] == '\"' && quoted)) ) + while((const char *)p2 > (const char *)text && + (p2[-1] == '\r' || p2[-1] == '\n' || (p2[-1] == '\"' && quoted))) { - if (p2[-1] == '\"' && quoted) + if(p2[-1] == '\"' && quoted) quoted = false; p2[-1] = '\0'; p2--; @@ -1372,18 +1383,18 @@ void Host_Say(bool teamonly) p2[1] = '\0'; } - for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) + for(j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { - if (!client || !client->active || !client->spawned) + if(!client || !client->active || !client->spawned) continue; - if (teamplay.value && teamonly && client->edict->v.team != save->edict->v.team) + if(teamplay.value && teamonly && client->edict->v.team != save->edict->v.team) continue; host_client = client; SV_ClientPrintf("%s", text); } host_client = save; - if (cls.state == ca_dedicated) + if(cls.state == ca_dedicated) Sys_Printf("%s", &text[1]); } @@ -1402,35 +1413,35 @@ void Host_Say_Team_f(void) void Host_Tell_f(void) { - int32_t j; - client_t *client; - client_t *save; - const char *p; - char text[MAXCMDLINE], *p2; - bool quoted; + int32_t j; + client_t *client; + client_t *save; + const char *p; + char text[MAXCMDLINE], *p2; + bool quoted; - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - if (Cmd_Argc () < 3) + if(Cmd_Argc() < 3) return; p = Cmd_Args(); // remove quotes if present quoted = false; - if (*p == '\"') + if(*p == '\"') { p++; quoted = true; } - q_snprintf (text, sizeof(text), "%s: %s", host_client->name, p); + q_snprintf(text, sizeof(text), "%s: %s", host_client->name, p); // check length & truncate if necessary j = (int32_t) strlen(text); - if (j >= (int32_t) sizeof(text) - 1) + if(j >= (int32_t) sizeof(text) - 1) { text[sizeof(text) - 2] = '\n'; text[sizeof(text) - 1] = '\0'; @@ -1438,10 +1449,10 @@ void Host_Tell_f(void) else { p2 = text + j; - while ((const char *)p2 > (const char *)text && - (p2[-1] == '\r' || p2[-1] == '\n' || (p2[-1] == '\"' && quoted)) ) + while((const char *)p2 > (const char *)text && + (p2[-1] == '\r' || p2[-1] == '\n' || (p2[-1] == '\"' && quoted))) { - if (p2[-1] == '\"' && quoted) + if(p2[-1] == '\"' && quoted) quoted = false; p2[-1] = '\0'; p2--; @@ -1451,11 +1462,11 @@ void Host_Tell_f(void) } save = host_client; - for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) + for(j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { - if (!client->active || !client->spawned) + if(!client->active || !client->spawned) continue; - if (q_strcasecmp(client->name, Cmd_Argv(1))) + if(q_strcasecmp(client->name, Cmd_Argv(1))) continue; host_client = client; SV_ClientPrintf("%s", text); @@ -1472,17 +1483,17 @@ Host_Color_f */ void Host_Color_f(void) { - int32_t top, bottom; - int32_t playercolor; + int32_t top, bottom; + int32_t playercolor; - if (Cmd_Argc() == 1) + if(Cmd_Argc() == 1) { - Con_Printf ("\"color\" is \"%" PRIi32 " %" PRIi32 "\"\n", ((int32_t)cl_color.value) >> 4, ((int32_t)cl_color.value) & 0x0f); - Con_Printf ("color <0-13> [0-13]\n"); + Con_Printf("\"color\" is \"%" PRIi32 " %" PRIi32 "\"\n", ((int32_t)cl_color.value) >> 4, ((int32_t)cl_color.value) & 0x0f); + Con_Printf("color <0-13> [0-13]\n"); return; } - if (Cmd_Argc() == 2) + if(Cmd_Argc() == 2) top = bottom = atoi(Cmd_Argv(1)); else { @@ -1491,19 +1502,19 @@ void Host_Color_f(void) } top &= 15; - if (top > 13) + if(top > 13) top = 13; bottom &= 15; - if (bottom > 13) + if(bottom > 13) bottom = 13; - playercolor = top*16 + bottom; + playercolor = top * 16 + bottom; - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cvar_SetValue ("_cl_color", playercolor); - if (cls.state == ca_connected) - Cmd_ForwardToServer (); + Cvar_SetValue("_cl_color", playercolor); + if(cls.state == ca_connected) + Cmd_ForwardToServer(); return; } @@ -1511,9 +1522,9 @@ void Host_Color_f(void) host_client->edict->v.team = bottom + 1; // send notification to all clients - MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors); - MSG_WriteByte (&sv.reliable_datagram, host_client - svs.clients); - MSG_WriteByte (&sv.reliable_datagram, host_client->colors); + MSG_WriteByte(&sv.reliable_datagram, svc_updatecolors); + MSG_WriteByte(&sv.reliable_datagram, host_client - svs.clients); + MSG_WriteByte(&sv.reliable_datagram, host_client->colors); } /* @@ -1521,23 +1532,23 @@ void Host_Color_f(void) Host_Kill_f ================== */ -void Host_Kill_f (void) +void Host_Kill_f(void) { - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - if (sv_player->v.health <= 0) + if(sv_player->v.health <= 0) { - SV_ClientPrintf ("Can't suicide -- allready dead!\n"); + SV_ClientPrintf("Can't suicide -- allready dead!\n"); return; } pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(sv_player); - PR_ExecuteProgram (pr_global_struct->ClientKill); + PR_ExecuteProgram(pr_global_struct->ClientKill); } @@ -1546,39 +1557,39 @@ void Host_Kill_f (void) Host_Pause_f ================== */ -void Host_Pause_f (void) +void Host_Pause_f(void) { //ericw -- demo pause support (inspired by MarkV) - if (cls.demoplayback) + if(cls.demoplayback) { cls.demopaused = !cls.demopaused; cl.paused = cls.demopaused; return; } - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - if (!pausable.value) - SV_ClientPrintf ("Pause not allowed.\n"); + if(!pausable.value) + SV_ClientPrintf("Pause not allowed.\n"); else { sv.paused ^= 1; - if (sv.paused) + if(sv.paused) { - SV_BroadcastPrintf ("%s paused the game\n", PR_GetString(sv_player->v.netname)); + SV_BroadcastPrintf("%s paused the game\n", PR_GetString(sv_player->v.netname)); } else { - SV_BroadcastPrintf ("%s unpaused the game\n",PR_GetString(sv_player->v.netname)); + SV_BroadcastPrintf("%s unpaused the game\n", PR_GetString(sv_player->v.netname)); } - // send notification to all clients - MSG_WriteByte (&sv.reliable_datagram, svc_setpause); - MSG_WriteByte (&sv.reliable_datagram, sv.paused); + // send notification to all clients + MSG_WriteByte(&sv.reliable_datagram, svc_setpause); + MSG_WriteByte(&sv.reliable_datagram, sv.paused); } } @@ -1590,23 +1601,23 @@ void Host_Pause_f (void) Host_PreSpawn_f ================== */ -void Host_PreSpawn_f (void) +void Host_PreSpawn_f(void) { - if (cmd_source == src_command) + if(cmd_source == src_command) { - Con_Printf ("prespawn is not valid from the console\n"); + Con_Printf("prespawn is not valid from the console\n"); return; } - if (host_client->spawned) + if(host_client->spawned) { - Con_Printf ("prespawn not valid -- allready spawned\n"); + Con_Printf("prespawn not valid -- allready spawned\n"); return; } - SZ_Write (&host_client->message, sv.signon.data, sv.signon.cursize); - MSG_WriteByte (&host_client->message, svc_signonnum); - MSG_WriteByte (&host_client->message, 2); + SZ_Write(&host_client->message, sv.signon.data, sv.signon.cursize); + MSG_WriteByte(&host_client->message, svc_signonnum); + MSG_WriteByte(&host_client->message, 2); host_client->sendsignon = true; } @@ -1615,27 +1626,28 @@ void Host_PreSpawn_f (void) Host_Spawn_f ================== */ -void Host_Spawn_f (void) +void Host_Spawn_f(void) { - int32_t i; - client_t *client; - edict_t *ent; + int32_t i; + client_t *client; + edict_t *ent; - if (cmd_source == src_command) + if(cmd_source == src_command) { - Con_Printf ("spawn is not valid from the console\n"); + Con_Printf("spawn is not valid from the console\n"); return; } - if (host_client->spawned) + if(host_client->spawned) { - Con_Printf ("Spawn not valid -- allready spawned\n"); + Con_Printf("Spawn not valid -- allready spawned\n"); return; } // run the entrance script - if (sv.loadgame) - { // loaded games are fully inited allready + if(sv.loadgame) + { + // loaded games are fully inited allready // if this is the last client to be connected, unpause sv.paused = false; } @@ -1644,72 +1656,72 @@ void Host_Spawn_f (void) // set up the edict ent = host_client->edict; - memset (&ent->v, 0, progs->entityfields * 4); + memset(&ent->v, 0, progs->entityfields * 4); ent->v.colormap = NUM_FOR_EDICT(ent); ent->v.team = (host_client->colors & 15) + 1; ent->v.netname = PR_SetEngineString(host_client->name); // copy spawn parms out of the client_t - for (i=0 ; i< NUM_SPAWN_PARMS ; i++) + for(i = 0 ; i < NUM_SPAWN_PARMS ; i++) (&pr_global_struct->parm1)[i] = host_client->spawn_parms[i]; // call the spawn function pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(sv_player); - PR_ExecuteProgram (pr_global_struct->ClientConnect); + PR_ExecuteProgram(pr_global_struct->ClientConnect); - if ((Sys_DoubleTime() - NET_QSocketGetTime(host_client->netconnection)) <= sv.time) - Sys_Printf ("%s entered the game\n", host_client->name); + if((Sys_DoubleTime() - NET_QSocketGetTime(host_client->netconnection)) <= sv.time) + Sys_Printf("%s entered the game\n", host_client->name); - PR_ExecuteProgram (pr_global_struct->PutClientInServer); + PR_ExecuteProgram(pr_global_struct->PutClientInServer); } // send all current names, colors, and frag counts - SZ_Clear (&host_client->message); + SZ_Clear(&host_client->message); // send time of update - MSG_WriteByte (&host_client->message, svc_time); - MSG_WriteFloat (&host_client->message, sv.time); + MSG_WriteByte(&host_client->message, svc_time); + MSG_WriteFloat(&host_client->message, sv.time); - for (i = 0, client = svs.clients; i < svs.maxclients; i++, client++) + for(i = 0, client = svs.clients; i < svs.maxclients; i++, client++) { - MSG_WriteByte (&host_client->message, svc_updatename); - MSG_WriteByte (&host_client->message, i); - MSG_WriteString (&host_client->message, client->name); - MSG_WriteByte (&host_client->message, svc_updatefrags); - MSG_WriteByte (&host_client->message, i); - MSG_WriteShort (&host_client->message, client->old_frags); - MSG_WriteByte (&host_client->message, svc_updatecolors); - MSG_WriteByte (&host_client->message, i); - MSG_WriteByte (&host_client->message, client->colors); + MSG_WriteByte(&host_client->message, svc_updatename); + MSG_WriteByte(&host_client->message, i); + MSG_WriteString(&host_client->message, client->name); + MSG_WriteByte(&host_client->message, svc_updatefrags); + MSG_WriteByte(&host_client->message, i); + MSG_WriteShort(&host_client->message, client->old_frags); + MSG_WriteByte(&host_client->message, svc_updatecolors); + MSG_WriteByte(&host_client->message, i); + MSG_WriteByte(&host_client->message, client->colors); } // send all current light styles - for (i = 0; i < MAX_LIGHTSTYLES; i++) + for(i = 0; i < MAX_LIGHTSTYLES; i++) { - MSG_WriteByte (&host_client->message, svc_lightstyle); - MSG_WriteByte (&host_client->message, (char)i); - MSG_WriteString (&host_client->message, sv.lightstyles[i]); + MSG_WriteByte(&host_client->message, svc_lightstyle); + MSG_WriteByte(&host_client->message, (char)i); + MSG_WriteString(&host_client->message, sv.lightstyles[i]); } // // send some stats // - MSG_WriteByte (&host_client->message, svc_updatestat); - MSG_WriteByte (&host_client->message, STAT_TOTALSECRETS); - MSG_WriteLong (&host_client->message, pr_global_struct->total_secrets); + MSG_WriteByte(&host_client->message, svc_updatestat); + MSG_WriteByte(&host_client->message, STAT_TOTALSECRETS); + MSG_WriteLong(&host_client->message, pr_global_struct->total_secrets); - MSG_WriteByte (&host_client->message, svc_updatestat); - MSG_WriteByte (&host_client->message, STAT_TOTALMONSTERS); - MSG_WriteLong (&host_client->message, pr_global_struct->total_monsters); + MSG_WriteByte(&host_client->message, svc_updatestat); + MSG_WriteByte(&host_client->message, STAT_TOTALMONSTERS); + MSG_WriteLong(&host_client->message, pr_global_struct->total_monsters); - MSG_WriteByte (&host_client->message, svc_updatestat); - MSG_WriteByte (&host_client->message, STAT_SECRETS); - MSG_WriteLong (&host_client->message, pr_global_struct->found_secrets); + MSG_WriteByte(&host_client->message, svc_updatestat); + MSG_WriteByte(&host_client->message, STAT_SECRETS); + MSG_WriteLong(&host_client->message, pr_global_struct->found_secrets); - MSG_WriteByte (&host_client->message, svc_updatestat); - MSG_WriteByte (&host_client->message, STAT_MONSTERS); - MSG_WriteLong (&host_client->message, pr_global_struct->killed_monsters); + MSG_WriteByte(&host_client->message, svc_updatestat); + MSG_WriteByte(&host_client->message, STAT_MONSTERS); + MSG_WriteLong(&host_client->message, pr_global_struct->killed_monsters); // // send a fixangle @@ -1717,16 +1729,16 @@ void Host_Spawn_f (void) // in a state where it is expecting the client to correct the angle // and it won't happen if the game was just loaded, so you wind up // with a permanent head tilt - ent = EDICT_NUM( 1 + (host_client - svs.clients) ); - MSG_WriteByte (&host_client->message, svc_setangle); - for (i = 0; i < 2; i++) - MSG_WriteAngle (&host_client->message, ent->v.angles[i], sv.protocolflags ); - MSG_WriteAngle (&host_client->message, 0, sv.protocolflags ); + ent = EDICT_NUM(1 + (host_client - svs.clients)); + MSG_WriteByte(&host_client->message, svc_setangle); + for(i = 0; i < 2; i++) + MSG_WriteAngle(&host_client->message, ent->v.angles[i], sv.protocolflags); + MSG_WriteAngle(&host_client->message, 0, sv.protocolflags); - SV_WriteClientdataToMessage (sv_player, &host_client->message); + SV_WriteClientdataToMessage(sv_player, &host_client->message); - MSG_WriteByte (&host_client->message, svc_signonnum); - MSG_WriteByte (&host_client->message, 3); + MSG_WriteByte(&host_client->message, svc_signonnum); + MSG_WriteByte(&host_client->message, 3); host_client->sendsignon = true; } @@ -1735,11 +1747,11 @@ void Host_Spawn_f (void) Host_Begin_f ================== */ -void Host_Begin_f (void) +void Host_Begin_f(void) { - if (cmd_source == src_command) + if(cmd_source == src_command) { - Con_Printf ("begin is not valid from the console\n"); + Con_Printf("begin is not valid from the console\n"); return; } @@ -1756,52 +1768,52 @@ Host_Kick_f Kicks a user off of the server ================== */ -void Host_Kick_f (void) +void Host_Kick_f(void) { - const char *who; - const char *message = NULL; - client_t *save; - int32_t i; - bool byNumber = false; + const char *who; + const char *message = NULL; + client_t *save; + int32_t i; + bool byNumber = false; - if (cmd_source == src_command) + if(cmd_source == src_command) { - if (!sv.active) + if(!sv.active) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } } - else if (pr_global_struct->deathmatch) + else if(pr_global_struct->deathmatch) return; save = host_client; - if (Cmd_Argc() > 2 && Q_strcmp(Cmd_Argv(1), "#") == 0) + if(Cmd_Argc() > 2 && Q_strcmp(Cmd_Argv(1), "#") == 0) { i = Q_atof(Cmd_Argv(2)) - 1; - if (i < 0 || i >= svs.maxclients) + if(i < 0 || i >= svs.maxclients) return; - if (!svs.clients[i].active) + if(!svs.clients[i].active) return; host_client = &svs.clients[i]; byNumber = true; } else { - for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) + for(i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { - if (!host_client->active) + if(!host_client->active) continue; - if (q_strcasecmp(host_client->name, Cmd_Argv(1)) == 0) + if(q_strcasecmp(host_client->name, Cmd_Argv(1)) == 0) break; } } - if (i < svs.maxclients) + if(i < svs.maxclients) { - if (cmd_source == src_command) - if (cls.state == ca_dedicated) + if(cmd_source == src_command) + if(cls.state == ca_dedicated) who = "Console"; else who = cl_name.string; @@ -1809,27 +1821,27 @@ void Host_Kick_f (void) who = save->name; // can't kick yourself! - if (host_client == save) + if(host_client == save) return; - if (Cmd_Argc() > 2) + if(Cmd_Argc() > 2) { message = COM_Parse(Cmd_Args()); - if (byNumber) + if(byNumber) { - message++; // skip the # - while (*message == ' ') // skip white space + message++; // skip the # + while(*message == ' ') // skip white space message++; - message += strlen(Cmd_Argv(2)); // skip the number + message += strlen(Cmd_Argv(2)); // skip the number } - while (*message && *message == ' ') + while(*message && *message == ' ') message++; } - if (message) - SV_ClientPrintf ("Kicked by %s: %s\n", who, message); + if(message) + SV_ClientPrintf("Kicked by %s: %s\n", who, message); else - SV_ClientPrintf ("Kicked by %s\n", who); - SV_DropClient (false); + SV_ClientPrintf("Kicked by %s\n", who); + SV_DropClient(false); } host_client = save; @@ -1848,25 +1860,25 @@ DEBUGGING TOOLS Host_Give_f ================== */ -void Host_Give_f (void) +void Host_Give_f(void) { - const char *t; - int32_t v; - eval_t *val; + const char *t; + int32_t v; + eval_t *val; - if (cmd_source == src_command) + if(cmd_source == src_command) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } - if (pr_global_struct->deathmatch) + if(pr_global_struct->deathmatch) return; t = Cmd_Argv(1); - v = atoi (Cmd_Argv(2)); + v = atoi(Cmd_Argv(2)); - switch (t[0]) + switch(t[0]) { case '0': case '1': @@ -1879,96 +1891,96 @@ void Host_Give_f (void) case '8': case '9': // MED 01/04/97 added hipnotic give stuff - if (hipnotic) + if(hipnotic) { - if (t[0] == '6') - { - if (t[1] == 'a') - sv_player->v.items = (int32_t)sv_player->v.items | HIT_PROXIMITY_GUN; - else - sv_player->v.items = (int32_t)sv_player->v.items | IT_GRENADE_LAUNCHER; - } - else if (t[0] == '9') - sv_player->v.items = (int32_t)sv_player->v.items | HIT_LASER_CANNON; - else if (t[0] == '0') - sv_player->v.items = (int32_t)sv_player->v.items | HIT_MJOLNIR; - else if (t[0] >= '2') - sv_player->v.items = (int32_t)sv_player->v.items | (IT_SHOTGUN << (t[0] - '2')); + if(t[0] == '6') + { + if(t[1] == 'a') + sv_player->v.items = (int32_t)sv_player->v.items | HIT_PROXIMITY_GUN; + else + sv_player->v.items = (int32_t)sv_player->v.items | IT_GRENADE_LAUNCHER; + } + else if(t[0] == '9') + sv_player->v.items = (int32_t)sv_player->v.items | HIT_LASER_CANNON; + else if(t[0] == '0') + sv_player->v.items = (int32_t)sv_player->v.items | HIT_MJOLNIR; + else if(t[0] >= '2') + sv_player->v.items = (int32_t)sv_player->v.items | (IT_SHOTGUN << (t[0] - '2')); } else { - if (t[0] >= '2') - sv_player->v.items = (int32_t)sv_player->v.items | (IT_SHOTGUN << (t[0] - '2')); + if(t[0] >= '2') + sv_player->v.items = (int32_t)sv_player->v.items | (IT_SHOTGUN << (t[0] - '2')); } break; case 's': - if (rogue) + if(rogue) { - val = GetEdictFieldValue(sv_player, "ammo_shells1"); - if (val) - val->_float = v; + val = GetEdictFieldValue(sv_player, "ammo_shells1"); + if(val) + val->_float = v; } sv_player->v.ammo_shells = v; break; case 'n': - if (rogue) + if(rogue) { - val = GetEdictFieldValue(sv_player, "ammo_nails1"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon <= IT_LIGHTNING) - sv_player->v.ammo_nails = v; - } + val = GetEdictFieldValue(sv_player, "ammo_nails1"); + if(val) + { + val->_float = v; + if(sv_player->v.weapon <= IT_LIGHTNING) + sv_player->v.ammo_nails = v; + } } else { - sv_player->v.ammo_nails = v; + sv_player->v.ammo_nails = v; } break; case 'l': - if (rogue) + if(rogue) { - val = GetEdictFieldValue(sv_player, "ammo_lava_nails"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon > IT_LIGHTNING) - sv_player->v.ammo_nails = v; - } + val = GetEdictFieldValue(sv_player, "ammo_lava_nails"); + if(val) + { + val->_float = v; + if(sv_player->v.weapon > IT_LIGHTNING) + sv_player->v.ammo_nails = v; + } } break; case 'r': - if (rogue) + if(rogue) { - val = GetEdictFieldValue(sv_player, "ammo_rockets1"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon <= IT_LIGHTNING) - sv_player->v.ammo_rockets = v; - } + val = GetEdictFieldValue(sv_player, "ammo_rockets1"); + if(val) + { + val->_float = v; + if(sv_player->v.weapon <= IT_LIGHTNING) + sv_player->v.ammo_rockets = v; + } } else { - sv_player->v.ammo_rockets = v; + sv_player->v.ammo_rockets = v; } break; case 'm': - if (rogue) + if(rogue) { - val = GetEdictFieldValue(sv_player, "ammo_multi_rockets"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon > IT_LIGHTNING) - sv_player->v.ammo_rockets = v; - } + val = GetEdictFieldValue(sv_player, "ammo_multi_rockets"); + if(val) + { + val->_float = v; + if(sv_player->v.weapon > IT_LIGHTNING) + sv_player->v.ammo_rockets = v; + } } break; @@ -1977,67 +1989,67 @@ void Host_Give_f (void) break; case 'c': - if (rogue) + if(rogue) { - val = GetEdictFieldValue(sv_player, "ammo_cells1"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon <= IT_LIGHTNING) - sv_player->v.ammo_cells = v; - } + val = GetEdictFieldValue(sv_player, "ammo_cells1"); + if(val) + { + val->_float = v; + if(sv_player->v.weapon <= IT_LIGHTNING) + sv_player->v.ammo_cells = v; + } } else { - sv_player->v.ammo_cells = v; + sv_player->v.ammo_cells = v; } break; case 'p': - if (rogue) + if(rogue) { - val = GetEdictFieldValue(sv_player, "ammo_plasma"); - if (val) - { - val->_float = v; - if (sv_player->v.weapon > IT_LIGHTNING) - sv_player->v.ammo_cells = v; - } + val = GetEdictFieldValue(sv_player, "ammo_plasma"); + if(val) + { + val->_float = v; + if(sv_player->v.weapon > IT_LIGHTNING) + sv_player->v.ammo_cells = v; + } } break; //johnfitz -- give armour case 'a': - if (v > 150) + if(v > 150) { - sv_player->v.armortype = 0.8; - sv_player->v.armorvalue = v; - sv_player->v.items = sv_player->v.items - - ((int32_t)(sv_player->v.items) & (int32_t)(IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + - IT_ARMOR3; + sv_player->v.armortype = 0.8; + sv_player->v.armorvalue = v; + sv_player->v.items = sv_player->v.items - + ((int32_t)(sv_player->v.items) & (int32_t)(IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + + IT_ARMOR3; } - else if (v > 100) + else if(v > 100) { - sv_player->v.armortype = 0.6; - sv_player->v.armorvalue = v; - sv_player->v.items = sv_player->v.items - - ((int32_t)(sv_player->v.items) & (int32_t)(IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + - IT_ARMOR2; + sv_player->v.armortype = 0.6; + sv_player->v.armorvalue = v; + sv_player->v.items = sv_player->v.items - + ((int32_t)(sv_player->v.items) & (int32_t)(IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + + IT_ARMOR2; } - else if (v >= 0) + else if(v >= 0) { - sv_player->v.armortype = 0.3; - sv_player->v.armorvalue = v; - sv_player->v.items = sv_player->v.items - - ((int32_t)(sv_player->v.items) & (int32_t)(IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + - IT_ARMOR1; + sv_player->v.armortype = 0.3; + sv_player->v.armorvalue = v; + sv_player->v.items = sv_player->v.items - + ((int32_t)(sv_player->v.items) & (int32_t)(IT_ARMOR1 | IT_ARMOR2 | IT_ARMOR3)) + + IT_ARMOR1; } break; //johnfitz } //johnfitz -- update currentammo to match new ammo (so statusbar updates correctly) - switch ((int32_t)(sv_player->v.weapon)) + switch((int32_t)(sv_player->v.weapon)) { case IT_SHOTGUN: case IT_SUPER_SHOTGUN: @@ -2060,31 +2072,31 @@ void Host_Give_f (void) sv_player->v.currentammo = sv_player->v.ammo_cells; break; case RIT_LAVA_NAILGUN: //same as IT_AXE - if (rogue) + if(rogue) sv_player->v.currentammo = sv_player->v.ammo_nails; break; case RIT_PLASMA_GUN: //same as HIT_PROXIMITY_GUN - if (rogue) + if(rogue) sv_player->v.currentammo = sv_player->v.ammo_cells; - if (hipnotic) + if(hipnotic) sv_player->v.currentammo = sv_player->v.ammo_rockets; break; } //johnfitz } -edict_t *FindViewthing (void) +edict_t *FindViewthing(void) { - int32_t i; - edict_t *e; + int32_t i; + edict_t *e; - for (i=0 ; iv.classname), "viewthing") ) + if(!strcmp(PR_GetString(e->v.classname), "viewthing")) return e; } - Con_Printf ("No viewthing on map\n"); + Con_Printf("No viewthing on map\n"); return NULL; } @@ -2093,19 +2105,19 @@ edict_t *FindViewthing (void) Host_Viewmodel_f ================== */ -void Host_Viewmodel_f (void) +void Host_Viewmodel_f(void) { - edict_t *e; - qmodel_t *m; + edict_t *e; + qmodel_t *m; - e = FindViewthing (); - if (!e) + e = FindViewthing(); + if(!e) return; - m = Mod_ForName (Cmd_Argv(1), false); - if (!m) + m = Mod_ForName(Cmd_Argv(1), false); + if(!m) { - Con_Printf ("Can't load %s\n", Cmd_Argv(1)); + Con_Printf("Can't load %s\n", Cmd_Argv(1)); return; } @@ -2118,36 +2130,36 @@ void Host_Viewmodel_f (void) Host_Viewframe_f ================== */ -void Host_Viewframe_f (void) +void Host_Viewframe_f(void) { - edict_t *e; - int32_t f; - qmodel_t *m; + edict_t *e; + int32_t f; + qmodel_t *m; - e = FindViewthing (); - if (!e) + e = FindViewthing(); + if(!e) return; m = cl.model_precache[(int32_t)e->v.modelindex]; f = atoi(Cmd_Argv(1)); - if (f >= m->numframes) + if(f >= m->numframes) f = m->numframes - 1; e->v.frame = f; } -void PrintFrameName (qmodel_t *m, int32_t frame) +void PrintFrameName(qmodel_t *m, int32_t frame) { - aliashdr_t *hdr; - maliasframedesc_t *pframedesc; + aliashdr_t *hdr; + maliasframedesc_t *pframedesc; - hdr = (aliashdr_t *)Mod_Extradata (m); - if (!hdr) + hdr = (aliashdr_t *)Mod_Extradata(m); + if(!hdr) return; pframedesc = &hdr->frames[frame]; - Con_Printf ("frame %" PRIi32 ": %s\n", frame, pframedesc->name); + Con_Printf("frame %" PRIi32 ": %s\n", frame, pframedesc->name); } /* @@ -2155,21 +2167,21 @@ void PrintFrameName (qmodel_t *m, int32_t frame) Host_Viewnext_f ================== */ -void Host_Viewnext_f (void) +void Host_Viewnext_f(void) { - edict_t *e; - qmodel_t *m; + edict_t *e; + qmodel_t *m; - e = FindViewthing (); - if (!e) + e = FindViewthing(); + if(!e) return; m = cl.model_precache[(int32_t)e->v.modelindex]; e->v.frame = e->v.frame + 1; - if (e->v.frame >= m->numframes) + if(e->v.frame >= m->numframes) e->v.frame = m->numframes - 1; - PrintFrameName (m, e->v.frame); + PrintFrameName(m, e->v.frame); } /* @@ -2177,22 +2189,22 @@ void Host_Viewnext_f (void) Host_Viewprev_f ================== */ -void Host_Viewprev_f (void) +void Host_Viewprev_f(void) { - edict_t *e; - qmodel_t *m; + edict_t *e; + qmodel_t *m; - e = FindViewthing (); - if (!e) + e = FindViewthing(); + if(!e) return; m = cl.model_precache[(int32_t)e->v.modelindex]; e->v.frame = e->v.frame - 1; - if (e->v.frame < 0) + if(e->v.frame < 0) e->v.frame = 0; - PrintFrameName (m, e->v.frame); + PrintFrameName(m, e->v.frame); } /* @@ -2209,35 +2221,36 @@ DEMO LOOP CONTROL Host_Startdemos_f ================== */ -void Host_Startdemos_f (void) +void Host_Startdemos_f(void) { - int32_t i, c; + int32_t i, c; - if (cls.state == ca_dedicated) + if(cls.state == ca_dedicated) return; c = Cmd_Argc() - 1; - if (c > MAX_DEMOS) + if(c > MAX_DEMOS) { - Con_Printf ("Max %" PRIi32 " demos in demoloop\n", MAX_DEMOS); + Con_Printf("Max %" PRIi32 " demos in demoloop\n", MAX_DEMOS); c = MAX_DEMOS; } - Con_Printf ("%" PRIi32 " demo(s) in loop\n", c); + Con_Printf("%" PRIi32 " demo(s) in loop\n", c); - for (i = 1; i < c + 1; i++) - q_strlcpy (cls.demos[i-1], Cmd_Argv(i), sizeof(cls.demos[0])); + for(i = 1; i < c + 1; i++) + q_strlcpy(cls.demos[i - 1], Cmd_Argv(i), sizeof(cls.demos[0])); - if (!sv.active && cls.demonum != -1 && !cls.demoplayback) + if(!sv.active && cls.demonum != -1 && !cls.demoplayback) { cls.demonum = 0; - if (!fitzmode) - { /* QuakeSpasm customization: */ + if(!fitzmode) + { + /* QuakeSpasm customization: */ /* go straight to menu, no CL_NextDemo */ cls.demonum = -1; Cbuf_InsertText("menu_main\n"); return; } - CL_NextDemo (); + CL_NextDemo(); } else { @@ -2253,14 +2266,14 @@ Host_Demos_f Return to looping demos ================== */ -void Host_Demos_f (void) +void Host_Demos_f(void) { - if (cls.state == ca_dedicated) + if(cls.state == ca_dedicated) return; - if (cls.demonum == -1) + if(cls.demonum == -1) cls.demonum = 1; - CL_Disconnect_f (); - CL_NextDemo (); + CL_Disconnect_f(); + CL_NextDemo(); } /* @@ -2270,14 +2283,14 @@ Host_Stopdemo_f Return to looping demos ================== */ -void Host_Stopdemo_f (void) +void Host_Stopdemo_f(void) { - if (cls.state == ca_dedicated) + if(cls.state == ca_dedicated) return; - if (!cls.demoplayback) + if(!cls.demoplayback) return; - CL_StopPlayback (); - CL_Disconnect (); + CL_StopPlayback(); + CL_Disconnect(); } //============================================================================= @@ -2287,52 +2300,52 @@ void Host_Stopdemo_f (void) Host_InitCommands ================== */ -void Host_InitCommands (void) +void Host_InitCommands(void) { - Cmd_AddCommand ("maps", Host_Maps_f); //johnfitz - Cmd_AddCommand ("mods", Host_Mods_f); //johnfitz - Cmd_AddCommand ("games", Host_Mods_f); // as an alias to "mods" -- S.A. / QuakeSpasm - Cmd_AddCommand ("mapname", Host_Mapname_f); //johnfitz - Cmd_AddCommand ("randmap", Host_Randmap_f); //ericw + Cmd_AddCommand("maps", Host_Maps_f); //johnfitz + Cmd_AddCommand("mods", Host_Mods_f); //johnfitz + Cmd_AddCommand("games", Host_Mods_f); // as an alias to "mods" -- S.A. / QuakeSpasm + Cmd_AddCommand("mapname", Host_Mapname_f); //johnfitz + Cmd_AddCommand("randmap", Host_Randmap_f); //ericw - Cmd_AddCommand ("status", Host_Status_f); - Cmd_AddCommand ("quit", Host_Quit_f); - Cmd_AddCommand ("god", Host_God_f); - Cmd_AddCommand ("notarget", Host_Notarget_f); - Cmd_AddCommand ("fly", Host_Fly_f); - Cmd_AddCommand ("map", Host_Map_f); - Cmd_AddCommand ("restart", Host_Restart_f); - Cmd_AddCommand ("changelevel", Host_Changelevel_f); - Cmd_AddCommand ("connect", Host_Connect_f); - Cmd_AddCommand ("reconnect", Host_Reconnect_f); - Cmd_AddCommand ("name", Host_Name_f); - Cmd_AddCommand ("noclip", Host_Noclip_f); - Cmd_AddCommand ("setpos", Host_SetPos_f); //QuakeSpasm + Cmd_AddCommand("status", Host_Status_f); + Cmd_AddCommand("quit", Host_Quit_f); + Cmd_AddCommand("god", Host_God_f); + Cmd_AddCommand("notarget", Host_Notarget_f); + Cmd_AddCommand("fly", Host_Fly_f); + Cmd_AddCommand("map", Host_Map_f); + Cmd_AddCommand("restart", Host_Restart_f); + Cmd_AddCommand("changelevel", Host_Changelevel_f); + Cmd_AddCommand("connect", Host_Connect_f); + Cmd_AddCommand("reconnect", Host_Reconnect_f); + Cmd_AddCommand("name", Host_Name_f); + Cmd_AddCommand("noclip", Host_Noclip_f); + Cmd_AddCommand("setpos", Host_SetPos_f); //QuakeSpasm - Cmd_AddCommand ("say", Host_Say_f); - Cmd_AddCommand ("say_team", Host_Say_Team_f); - Cmd_AddCommand ("tell", Host_Tell_f); - Cmd_AddCommand ("color", Host_Color_f); - Cmd_AddCommand ("kill", Host_Kill_f); - Cmd_AddCommand ("pause", Host_Pause_f); - Cmd_AddCommand ("spawn", Host_Spawn_f); - Cmd_AddCommand ("begin", Host_Begin_f); - Cmd_AddCommand ("prespawn", Host_PreSpawn_f); - Cmd_AddCommand ("kick", Host_Kick_f); - Cmd_AddCommand ("ping", Host_Ping_f); - Cmd_AddCommand ("load", Host_Loadgame_f); - Cmd_AddCommand ("save", Host_Savegame_f); - Cmd_AddCommand ("give", Host_Give_f); + Cmd_AddCommand("say", Host_Say_f); + Cmd_AddCommand("say_team", Host_Say_Team_f); + Cmd_AddCommand("tell", Host_Tell_f); + Cmd_AddCommand("color", Host_Color_f); + Cmd_AddCommand("kill", Host_Kill_f); + Cmd_AddCommand("pause", Host_Pause_f); + Cmd_AddCommand("spawn", Host_Spawn_f); + Cmd_AddCommand("begin", Host_Begin_f); + Cmd_AddCommand("prespawn", Host_PreSpawn_f); + Cmd_AddCommand("kick", Host_Kick_f); + Cmd_AddCommand("ping", Host_Ping_f); + Cmd_AddCommand("load", Host_Loadgame_f); + Cmd_AddCommand("save", Host_Savegame_f); + Cmd_AddCommand("give", Host_Give_f); - Cmd_AddCommand ("startdemos", Host_Startdemos_f); - Cmd_AddCommand ("demos", Host_Demos_f); - Cmd_AddCommand ("stopdemo", Host_Stopdemo_f); + Cmd_AddCommand("startdemos", Host_Startdemos_f); + Cmd_AddCommand("demos", Host_Demos_f); + Cmd_AddCommand("stopdemo", Host_Stopdemo_f); - Cmd_AddCommand ("viewmodel", Host_Viewmodel_f); - Cmd_AddCommand ("viewframe", Host_Viewframe_f); - Cmd_AddCommand ("viewnext", Host_Viewnext_f); - Cmd_AddCommand ("viewprev", Host_Viewprev_f); + Cmd_AddCommand("viewmodel", Host_Viewmodel_f); + Cmd_AddCommand("viewframe", Host_Viewframe_f); + Cmd_AddCommand("viewnext", Host_Viewnext_f); + Cmd_AddCommand("viewprev", Host_Viewprev_f); - Cmd_AddCommand ("mcache", Mod_Print); + Cmd_AddCommand("mcache", Mod_Print); } diff --git a/source/image.c b/source/image.c index fe393a6..aa7deb0 100644 --- a/source/image.c +++ b/source/image.c @@ -36,7 +36,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. static char loadfilename[MAX_OSPATH]; //file scope so that error messages can use it -typedef struct stdio_buffer_s { +typedef struct stdio_buffer_s +{ FILE *f; uint8_t buffer[1024]; int32_t size; @@ -57,12 +58,12 @@ static void Buf_Free(stdio_buffer_t *buf) static inline int32_t Buf_GetC(stdio_buffer_t *buf) { - if (buf->pos >= buf->size) + if(buf->pos >= buf->size) { buf->size = fread(buf->buffer, 1, sizeof(buf->buffer), buf->f); buf->pos = 0; - if (buf->size == 0) + if(buf->size == 0) return EOF; } @@ -78,19 +79,19 @@ returns a pointer to hunk allocated RGBA data TODO: search order: tga png jpg pcx lmp ============ */ -byte *Image_LoadImage (const char *name, int32_t *width, int32_t *height) +byte *Image_LoadImage(const char *name, int32_t *width, int32_t *height) { - FILE *f; + FILE *f; - q_snprintf (loadfilename, sizeof(loadfilename), "%s.tga", name); - COM_FOpenFile (loadfilename, &f, NULL); - if (f) - return Image_LoadTGA (f, width, height); + q_snprintf(loadfilename, sizeof(loadfilename), "%s.tga", name); + COM_FOpenFile(loadfilename, &f, NULL); + if(f) + return Image_LoadTGA(f, width, height); - q_snprintf (loadfilename, sizeof(loadfilename), "%s.pcx", name); - COM_FOpenFile (loadfilename, &f, NULL); - if (f) - return Image_LoadPCX (f, width, height); + q_snprintf(loadfilename, sizeof(loadfilename), "%s.pcx", name); + COM_FOpenFile(loadfilename, &f, NULL); + if(f) + return Image_LoadPCX(f, width, height); return NULL; } @@ -101,38 +102,39 @@ byte *Image_LoadImage (const char *name, int32_t *width, int32_t *height) // //============================================================================== -typedef struct targaheader_s { - uint8_t id_length, colormap_type, image_type; - uint16_t colormap_index, colormap_length; - uint8_t colormap_size; - uint16_t x_origin, y_origin, width, height; - uint8_t pixel_size, attributes; +typedef struct targaheader_s +{ + uint8_t id_length, colormap_type, image_type; + uint16_t colormap_index, colormap_length; + uint8_t colormap_size; + uint16_t x_origin, y_origin, width, height; + uint8_t pixel_size, attributes; } targaheader_t; #define TARGAHEADERSIZE 18 //size on disk targaheader_t targa_header; -int32_t fgetLittleShort (FILE *f) +int32_t fgetLittleShort(FILE *f) { - byte b1, b2; + byte b1, b2; b1 = fgetc(f); b2 = fgetc(f); - return (int16_t)(b1 + b2*256); + return (int16_t)(b1 + b2 * 256); } -int32_t fgetLittleLong (FILE *f) +int32_t fgetLittleLong(FILE *f) { - byte b1, b2, b3, b4; + byte b1, b2, b3, b4; b1 = fgetc(f); b2 = fgetc(f); b3 = fgetc(f); b4 = fgetc(f); - return b1 + (b2<<8) + (b3<<16) + (b4<<24); + return b1 + (b2 << 8) + (b3 << 16) + (b4 << 24); } /* @@ -144,41 +146,41 @@ returns true if successful TODO: support BGRA and BGR formats (since opengl can return them, and we don't have to swap) ============ */ -bool Image_WriteTGA (const char *name, byte *data, int32_t width, int32_t height, int32_t bpp, bool upsidedown) +bool Image_WriteTGA(const char *name, byte *data, int32_t width, int32_t height, int32_t bpp, bool upsidedown) { - int32_t handle, i, size, temp, bytes; - char pathname[MAX_OSPATH]; - byte header[TARGAHEADERSIZE]; + int32_t handle, i, size, temp, bytes; + char pathname[MAX_OSPATH]; + byte header[TARGAHEADERSIZE]; - Sys_mkdir (com_gamedir); //if we've switched to a nonexistant gamedir, create it now so we don't crash - q_snprintf (pathname, sizeof(pathname), "%s/%s", com_gamedir, name); - handle = Sys_FileOpenWrite (pathname); - if (handle == -1) + Sys_mkdir(com_gamedir); //if we've switched to a nonexistant gamedir, create it now so we don't crash + q_snprintf(pathname, sizeof(pathname), "%s/%s", com_gamedir, name); + handle = Sys_FileOpenWrite(pathname); + if(handle == -1) return false; - Q_memset (header, 0, TARGAHEADERSIZE); + Q_memset(header, 0, TARGAHEADERSIZE); header[2] = 2; // uncompressed type - header[12] = width&255; - header[13] = width>>8; - header[14] = height&255; - header[15] = height>>8; + header[12] = width & 255; + header[13] = width >> 8; + header[14] = height & 255; + header[15] = height >> 8; header[16] = bpp; // pixel size - if (upsidedown) + if(upsidedown) header[17] = 0x20; //upside-down attribute // swap red and blue bytes - bytes = bpp/8; - size = width*height*bytes; - for (i=0; i=0; row--) + for(row = rows - 1; row >= 0; row--) { //johnfitz -- fix for upside-down targas realrow = upside_down ? row : rows - 1 - row; - pixbuf = targa_rgba + realrow*columns*4; + pixbuf = targa_rgba + realrow * columns * 4; //johnfitz - for(column=0; column=0; row--) + uint8_t red, green, blue, alphabyte, packetHeader, packetSize, j; + for(row = rows - 1; row >= 0; row--) { //johnfitz -- fix for upside-down targas realrow = upside_down ? row : rows - 1 - row; - pixbuf = targa_rgba + realrow*columns*4; + pixbuf = targa_rgba + realrow * columns * 4; //johnfitz - for(column=0; column0) + column = 0; + if(row > 0) row--; else goto breakOut; //johnfitz -- fix for upside-down targas realrow = upside_down ? row : rows - 1 - row; - pixbuf = targa_rgba + realrow*columns*4; + pixbuf = targa_rgba + realrow * columns * 4; //johnfitz } } } else // non run-length packet { - for(j=0;j0) + column = 0; + if(row > 0) row--; else goto breakOut; //johnfitz -- fix for upside-down targas realrow = upside_down ? row : rows - 1 - row; - pixbuf = targa_rgba + realrow*columns*4; + pixbuf = targa_rgba + realrow * columns * 4; //johnfitz } } } } - breakOut:; +breakOut: + ; } } @@ -384,18 +387,18 @@ byte *Image_LoadTGA (FILE *fin, int32_t *width, int32_t *height) typedef struct { - int8_t signature; - int8_t version; - int8_t encoding; - int8_t bits_per_pixel; - uint16_t xmin,ymin,xmax,ymax; - uint16_t hdpi,vdpi; - uint8_t colortable[48]; - int8_t reserved; - int8_t color_planes; - uint16_t bytes_per_line; - uint16_t palette_type; - uint8_t filler[58]; + int8_t signature; + int8_t version; + int8_t encoding; + int8_t bits_per_pixel; + uint16_t xmin, ymin, xmax, ymax; + uint16_t hdpi, vdpi; + uint8_t colortable[48]; + int8_t reserved; + int8_t color_planes; + uint16_t bytes_per_line; + uint16_t palette_type; + uint8_t filler[58]; } pcxheader_t; /* @@ -403,51 +406,51 @@ typedef struct Image_LoadPCX ============ */ -byte *Image_LoadPCX (FILE *f, int32_t *width, int32_t *height) +byte *Image_LoadPCX(FILE *f, int32_t *width, int32_t *height) { - pcxheader_t pcx; - int32_t x, y, w, h, readbyte, runlength, start; - byte *p, *data; - byte palette[768]; + pcxheader_t pcx; + int32_t x, y, w, h, readbyte, runlength, start; + byte *p, *data; + byte palette[768]; stdio_buffer_t *buf; - start = ftell (f); //save start of file (since we might be inside a pak file, SEEK_SET might not be the start of the pcx) + start = ftell(f); //save start of file (since we might be inside a pak file, SEEK_SET might not be the start of the pcx) fread(&pcx, sizeof(pcx), 1, f); - pcx.xmin = (uint16_t)LittleShort (pcx.xmin); - pcx.ymin = (uint16_t)LittleShort (pcx.ymin); - pcx.xmax = (uint16_t)LittleShort (pcx.xmax); - pcx.ymax = (uint16_t)LittleShort (pcx.ymax); - pcx.bytes_per_line = (uint16_t)LittleShort (pcx.bytes_per_line); + pcx.xmin = (uint16_t)LittleShort(pcx.xmin); + pcx.ymin = (uint16_t)LittleShort(pcx.ymin); + pcx.xmax = (uint16_t)LittleShort(pcx.xmax); + pcx.ymax = (uint16_t)LittleShort(pcx.ymax); + pcx.bytes_per_line = (uint16_t)LittleShort(pcx.bytes_per_line); - if (pcx.signature != 0x0A) - Sys_Error ("'%s' is not a valid PCX file", loadfilename); + if(pcx.signature != 0x0A) + Sys_Error("'%s' is not a valid PCX file", loadfilename); - if (pcx.version != 5) - Sys_Error ("'%s' is version %" PRIi32 ", should be 5", loadfilename, pcx.version); + if(pcx.version != 5) + Sys_Error("'%s' is version %" PRIi32 ", should be 5", loadfilename, pcx.version); - if (pcx.encoding != 1 || pcx.bits_per_pixel != 8 || pcx.color_planes != 1) - Sys_Error ("'%s' has wrong encoding or bit depth", loadfilename); + if(pcx.encoding != 1 || pcx.bits_per_pixel != 8 || pcx.color_planes != 1) + Sys_Error("'%s' has wrong encoding or bit depth", loadfilename); w = pcx.xmax - pcx.xmin + 1; h = pcx.ymax - pcx.ymin + 1; - data = (byte *) Hunk_Alloc((w*h+1)*4); //+1 to allow reading padding byte on last line + data = (byte *) Hunk_Alloc((w * h + 1) * 4); //+1 to allow reading padding byte on last line //load palette - fseek (f, start + com_filesize - 768, SEEK_SET); - fread (palette, 1, 768, f); + fseek(f, start + com_filesize - 768, SEEK_SET); + fread(palette, 1, 768, f); //back to start of image data - fseek (f, start + sizeof(pcx), SEEK_SET); + fseek(f, start + sizeof(pcx), SEEK_SET); buf = Buf_Alloc(f); - for (y=0; y -static bool textmode; +static bool textmode; static cvar_t in_debugkeys = {"in_debugkeys", "0", CVAR_NONE}; @@ -41,50 +41,50 @@ static cvar_t in_debugkeys = {"in_debugkeys", "0", CVAR_NONE}; #endif // SDL2 Game Controller cvars -cvar_t joy_deadzone = { "joy_deadzone", "0.175", CVAR_ARCHIVE }; -cvar_t joy_deadzone_trigger = { "joy_deadzone_trigger", "0.2", CVAR_ARCHIVE }; -cvar_t joy_sensitivity_yaw = { "joy_sensitivity_yaw", "300", CVAR_ARCHIVE }; -cvar_t joy_sensitivity_pitch = { "joy_sensitivity_pitch", "150", CVAR_ARCHIVE }; -cvar_t joy_invert = { "joy_invert", "0", CVAR_ARCHIVE }; -cvar_t joy_exponent = { "joy_exponent", "3", CVAR_ARCHIVE }; -cvar_t joy_exponent_move = { "joy_exponent_move", "3", CVAR_ARCHIVE }; -cvar_t joy_swapmovelook = { "joy_swapmovelook", "0", CVAR_ARCHIVE }; -cvar_t joy_enable = { "joy_enable", "1", CVAR_ARCHIVE }; +cvar_t joy_deadzone = { "joy_deadzone", "0.175", CVAR_ARCHIVE }; +cvar_t joy_deadzone_trigger = { "joy_deadzone_trigger", "0.2", CVAR_ARCHIVE }; +cvar_t joy_sensitivity_yaw = { "joy_sensitivity_yaw", "300", CVAR_ARCHIVE }; +cvar_t joy_sensitivity_pitch = { "joy_sensitivity_pitch", "150", CVAR_ARCHIVE }; +cvar_t joy_invert = { "joy_invert", "0", CVAR_ARCHIVE }; +cvar_t joy_exponent = { "joy_exponent", "3", CVAR_ARCHIVE }; +cvar_t joy_exponent_move = { "joy_exponent_move", "3", CVAR_ARCHIVE }; +cvar_t joy_swapmovelook = { "joy_swapmovelook", "0", CVAR_ARCHIVE }; +cvar_t joy_enable = { "joy_enable", "1", CVAR_ARCHIVE }; static SDL_JoystickID joy_active_instaceid = -1; static SDL_GameController *joy_active_controller = NULL; -static bool no_mouse = false; +static bool no_mouse = false; static int32_t buttonremap[] = { K_MOUSE1, - K_MOUSE3, /* right button */ - K_MOUSE2, /* middle button */ + K_MOUSE3, /* right button */ + K_MOUSE2, /* middle button */ K_MOUSE4, K_MOUSE5 }; /* total accumulated mouse movement since last frame */ -static int32_t total_dx, total_dy = 0; +static int32_t total_dx, total_dy = 0; -static int32_t SDLCALL IN_FilterMouseEvents (const SDL_Event *event) +static int32_t SDLCALL IN_FilterMouseEvents(const SDL_Event *event) { - switch (event->type) + switch(event->type) { case SDL_MOUSEMOTION: - // case SDL_MOUSEBUTTONDOWN: - // case SDL_MOUSEBUTTONUP: + // case SDL_MOUSEBUTTONDOWN: + // case SDL_MOUSEBUTTONUP: return 0; } return 1; } -static int32_t SDLCALL IN_SDL2_FilterMouseEvents (void *userdata, SDL_Event *event) +static int32_t SDLCALL IN_SDL2_FilterMouseEvents(void *userdata, SDL_Event *event) { (void)userdata; - return IN_FilterMouseEvents (event); + return IN_FilterMouseEvents(event); } static void IN_BeginIgnoringMouseEvents(void) @@ -93,7 +93,7 @@ static void IN_BeginIgnoringMouseEvents(void) void *currentUserdata = NULL; SDL_GetEventFilter(¤tFilter, ¤tUserdata); - if (currentFilter != IN_SDL2_FilterMouseEvents) + if(currentFilter != IN_SDL2_FilterMouseEvents) SDL_SetEventFilter(IN_SDL2_FilterMouseEvents, NULL); } @@ -101,7 +101,7 @@ static void IN_EndIgnoringMouseEvents(void) { SDL_EventFilter currentFilter; void *currentUserdata; - if (SDL_GetEventFilter(¤tFilter, ¤tUserdata) == SDL_TRUE) + if(SDL_GetEventFilter(¤tFilter, ¤tUserdata) == SDL_TRUE) SDL_SetEventFilter(NULL, NULL); } @@ -117,11 +117,11 @@ static io_connect_t IN_GetIOHandle(void) kern_return_t status; status = IOMasterPort(MACH_PORT_NULL, &masterport); - if (status != KERN_SUCCESS) + if(status != KERN_SUCCESS) return 0; iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem"); - if (!iohidsystem) + if(!iohidsystem) return 0; status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle); @@ -130,14 +130,14 @@ static io_connect_t IN_GetIOHandle(void) return iohandle; } -static void IN_DisableOSXMouseAccel (void) +static void IN_DisableOSXMouseAccel(void) { io_connect_t mouseDev = IN_GetIOHandle(); - if (mouseDev != 0) + if(mouseDev != 0) { - if (IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess) + if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess) { - if (IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess) + if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess) { Cvar_Set("in_disablemacosxmouseaccel", "0"); Con_Printf("WARNING: Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n"); @@ -157,12 +157,12 @@ static void IN_DisableOSXMouseAccel (void) } } -static void IN_ReenableOSXMouseAccel (void) +static void IN_ReenableOSXMouseAccel(void) { io_connect_t mouseDev = IN_GetIOHandle(); - if (mouseDev != 0) + if(mouseDev != 0) { - if (IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess) + if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess) Con_Printf("WARNING: Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n"); IOServiceClose(mouseDev); } @@ -175,18 +175,18 @@ static void IN_ReenableOSXMouseAccel (void) #endif /* MACOS_X_ACCELERATION_HACK */ -void IN_Activate (void) +void IN_Activate(void) { - if (no_mouse) + if(no_mouse) return; #ifdef MACOS_X_ACCELERATION_HACK /* Save the status of mouse acceleration */ - if (originalMouseSpeed == -1 && in_disablemacosxmouseaccel.value) + if(originalMouseSpeed == -1 && in_disablemacosxmouseaccel.value) IN_DisableOSXMouseAccel(); #endif - if (SDL_SetRelativeMouseMode(SDL_TRUE) != 0) + if(SDL_SetRelativeMouseMode(SDL_TRUE) != 0) { Con_Printf("WARNING: SDL_SetRelativeMouseMode(SDL_TRUE) failed.\n"); } @@ -197,17 +197,17 @@ void IN_Activate (void) total_dy = 0; } -void IN_Deactivate (bool free_cursor) +void IN_Deactivate(bool free_cursor) { - if (no_mouse) + if(no_mouse) return; #ifdef MACOS_X_ACCELERATION_HACK - if (originalMouseSpeed != -1) + if(originalMouseSpeed != -1) IN_ReenableOSXMouseAccel(); #endif - if (free_cursor) + if(free_cursor) { SDL_SetRelativeMouseMode(SDL_FALSE); } @@ -216,45 +216,45 @@ void IN_Deactivate (bool free_cursor) IN_BeginIgnoringMouseEvents(); } -void IN_StartupJoystick (void) +void IN_StartupJoystick(void) { int32_t i; int32_t nummappings; char controllerdb[MAX_OSPATH]; SDL_GameController *gamecontroller; - if (COM_CheckParm("-nojoy")) + if(COM_CheckParm("-nojoy")) return; - if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == -1 ) + if(SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == -1) { Con_Warning("could not initialize SDL Game Controller\n"); return; } // Load additional SDL2 controller definitions from gamecontrollerdb.txt - q_snprintf (controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", com_basedir); + q_snprintf(controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", com_basedir); nummappings = SDL_GameControllerAddMappingsFromFile(controllerdb); - if (nummappings > 0) + if(nummappings > 0) Con_Printf("%" PRIi32 " mappings loaded from gamecontrollerdb.txt\n", nummappings); // Also try host_parms->userdir - if (host_parms->userdir != host_parms->basedir) + if(host_parms->userdir != host_parms->basedir) { - q_snprintf (controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", host_parms->userdir); + q_snprintf(controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", host_parms->userdir); nummappings = SDL_GameControllerAddMappingsFromFile(controllerdb); - if (nummappings > 0) + if(nummappings > 0) Con_Printf("%" PRIi32 " mappings loaded from gamecontrollerdb.txt\n", nummappings); } - for (i = 0; i < SDL_NumJoysticks(); i++) + for(i = 0; i < SDL_NumJoysticks(); i++) { const char *joyname = SDL_JoystickNameForIndex(i); - if ( SDL_IsGameController(i) ) + if(SDL_IsGameController(i)) { const char *controllername = SDL_GameControllerNameForIndex(i); gamecontroller = SDL_GameControllerOpen(i); - if (gamecontroller) + if(gamecontroller) { Con_Printf("detected controller: %s\n", controllername != NULL ? controllername : "NULL"); @@ -269,25 +269,25 @@ void IN_StartupJoystick (void) } else { - Con_Warning("joystick missing controller mappings: %s\n", joyname != NULL ? joyname : "NULL" ); + Con_Warning("joystick missing controller mappings: %s\n", joyname != NULL ? joyname : "NULL"); } } } -void IN_ShutdownJoystick (void) +void IN_ShutdownJoystick(void) { SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER); } -void IN_Init (void) +void IN_Init(void) { textmode = Key_TextEntry(); - if (textmode) + if(textmode) SDL_StartTextInput(); else SDL_StopTextInput(); - if (safemode || COM_CheckParm("-nomouse")) + if(safemode || COM_CheckParm("-nomouse")) { no_mouse = true; /* discard all mouse events when input is deactivated */ @@ -312,7 +312,7 @@ void IN_Init (void) IN_StartupJoystick(); } -void IN_Shutdown (void) +void IN_Shutdown(void) { IN_Deactivate(true); IN_ShutdownJoystick(); @@ -382,7 +382,7 @@ static joyaxis_t IN_ApplyEasing(joyaxis_t axis, float exponent) vec_t eased_magnitude; vec_t magnitude = IN_AxisMagnitude(axis); - if (magnitude == 0) + if(magnitude == 0) return result; eased_magnitude = powf(magnitude, exponent); @@ -434,7 +434,8 @@ static joyaxis_t IN_ApplyDeadzone(joyaxis_t axis, float deadzone) joyaxis_t result = {0}; vec_t magnitude = IN_AxisMagnitude(axis); - if ( magnitude > deadzone ) { + if(magnitude > deadzone) + { const vec_t new_magnitude = q_min(1.0, (magnitude - deadzone) / (1.0 - deadzone)); const vec_t scale = new_magnitude / magnitude; result.x = axis.x * scale; @@ -451,23 +452,38 @@ IN_KeyForControllerButton */ static int32_t IN_KeyForControllerButton(SDL_GameControllerButton button) { - switch (button) + switch(button) { - case SDL_CONTROLLER_BUTTON_A: return K_ABUTTON; - case SDL_CONTROLLER_BUTTON_B: return K_BBUTTON; - case SDL_CONTROLLER_BUTTON_X: return K_XBUTTON; - case SDL_CONTROLLER_BUTTON_Y: return K_YBUTTON; - case SDL_CONTROLLER_BUTTON_BACK: return K_TAB; - case SDL_CONTROLLER_BUTTON_START: return K_ESCAPE; - case SDL_CONTROLLER_BUTTON_LEFTSTICK: return K_LTHUMB; - case SDL_CONTROLLER_BUTTON_RIGHTSTICK: return K_RTHUMB; - case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: return K_LSHOULDER; - case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: return K_RSHOULDER; - case SDL_CONTROLLER_BUTTON_DPAD_UP: return K_UPARROW; - case SDL_CONTROLLER_BUTTON_DPAD_DOWN: return K_DOWNARROW; - case SDL_CONTROLLER_BUTTON_DPAD_LEFT: return K_LEFTARROW; - case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: return K_RIGHTARROW; - default: return 0; + case SDL_CONTROLLER_BUTTON_A: + return K_ABUTTON; + case SDL_CONTROLLER_BUTTON_B: + return K_BBUTTON; + case SDL_CONTROLLER_BUTTON_X: + return K_XBUTTON; + case SDL_CONTROLLER_BUTTON_Y: + return K_YBUTTON; + case SDL_CONTROLLER_BUTTON_BACK: + return K_TAB; + case SDL_CONTROLLER_BUTTON_START: + return K_ESCAPE; + case SDL_CONTROLLER_BUTTON_LEFTSTICK: + return K_LTHUMB; + case SDL_CONTROLLER_BUTTON_RIGHTSTICK: + return K_RTHUMB; + case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: + return K_LSHOULDER; + case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: + return K_RSHOULDER; + case SDL_CONTROLLER_BUTTON_DPAD_UP: + return K_UPARROW; + case SDL_CONTROLLER_BUTTON_DPAD_DOWN: + return K_DOWNARROW; + case SDL_CONTROLLER_BUTTON_DPAD_LEFT: + return K_LEFTARROW; + case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: + return K_RIGHTARROW; + default: + return 0; } } @@ -486,11 +502,11 @@ static void IN_JoyKeyEvent(bool wasdown, bool isdown, int32_t key, double *timer // we can't use `realtime` for key repeats because it is not monotomic const double currenttime = Sys_DoubleTime(); - if (wasdown) + if(wasdown) { - if (isdown) + if(isdown) { - if (currenttime >= *timer) + if(currenttime >= *timer) { *timer = currenttime + 0.1; Key_Event(key, true); @@ -504,7 +520,7 @@ static void IN_JoyKeyEvent(bool wasdown, bool isdown, int32_t key, double *timer } else { - if (isdown) + if(isdown) { *timer = currenttime + 0.5; Key_Event(key, true); @@ -519,21 +535,21 @@ IN_Commands Emit key events for game controller buttons, including emulated buttons for analog sticks/triggers ================ */ -void IN_Commands (void) +void IN_Commands(void) { joyaxisstate_t newaxisstate; int32_t i; const float stickthreshold = 0.9; const float triggerthreshold = joy_deadzone_trigger.value; - if (!joy_enable.value) + if(!joy_enable.value) return; - if (!joy_active_controller) + if(!joy_active_controller) return; // emit key events for controller buttons - for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++) + for(i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++) { bool newstate = SDL_GameControllerGetButton(joy_active_controller, (SDL_GameControllerButton)i); bool oldstate = joy_buttonstate.buttondown[i]; @@ -544,21 +560,21 @@ void IN_Commands (void) IN_JoyKeyEvent(oldstate, newstate, IN_KeyForControllerButton((SDL_GameControllerButton)i), &joy_buttontimer[i]); } - for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++) + for(i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++) { newaxisstate.axisvalue[i] = SDL_GameControllerGetAxis(joy_active_controller, (SDL_GameControllerAxis)i) / 32768.0f; } // emit emulated arrow keys so the analog sticks can be used in the menu - if (key_dest != key_game) + if(key_dest != key_game) { IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] < -stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] < -stickthreshold, K_LEFTARROW, &joy_emulatedkeytimer[0]); IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] > stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX] > stickthreshold, K_RIGHTARROW, &joy_emulatedkeytimer[1]); IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] < -stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] < -stickthreshold, K_UPARROW, &joy_emulatedkeytimer[2]); IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] > stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTY] > stickthreshold, K_DOWNARROW, &joy_emulatedkeytimer[3]); - IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTX] < -stickthreshold,newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTX] < -stickthreshold, K_LEFTARROW, &joy_emulatedkeytimer[4]); + IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTX] < -stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTX] < -stickthreshold, K_LEFTARROW, &joy_emulatedkeytimer[4]); IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTX] > stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTX] > stickthreshold, K_RIGHTARROW, &joy_emulatedkeytimer[5]); - IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTY] < -stickthreshold,newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTY] < -stickthreshold, K_UPARROW, &joy_emulatedkeytimer[6]); + IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTY] < -stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTY] < -stickthreshold, K_UPARROW, &joy_emulatedkeytimer[6]); IN_JoyKeyEvent(joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTY] > stickthreshold, newaxisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTY] > stickthreshold, K_DOWNARROW, &joy_emulatedkeytimer[7]); } @@ -574,16 +590,16 @@ void IN_Commands (void) IN_JoyMove ================ */ -void IN_JoyMove (usercmd_t *cmd) +void IN_JoyMove(usercmd_t *cmd) { - float speed; + float speed; joyaxis_t moveRaw, moveDeadzone, moveEased; joyaxis_t lookRaw, lookDeadzone, lookEased; - if (!joy_enable.value) + if(!joy_enable.value) return; - if (!joy_active_controller) + if(!joy_active_controller) return; moveRaw.x = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_LEFTX]; @@ -591,7 +607,7 @@ void IN_JoyMove (usercmd_t *cmd) lookRaw.x = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTX]; lookRaw.y = joy_axisstate.axisvalue[SDL_CONTROLLER_AXIS_RIGHTY]; - if (joy_swapmovelook.value) + if(joy_swapmovelook.value) { joyaxis_t temp = moveRaw; moveRaw = lookRaw; @@ -604,7 +620,7 @@ void IN_JoyMove (usercmd_t *cmd) moveEased = IN_ApplyMoveEasing(moveDeadzone, joy_exponent_move.value); lookEased = IN_ApplyEasing(lookDeadzone, joy_exponent.value); - if ((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) + if((in_speed.state & 1) ^ (cl_alwaysrun.value != 0.0)) speed = cl_movespeedkey.value; else speed = 1; @@ -615,19 +631,19 @@ void IN_JoyMove (usercmd_t *cmd) cl.viewangles[YAW] -= lookEased.x * joy_sensitivity_yaw.value * host_frametime; cl.viewangles[PITCH] += lookEased.y * joy_sensitivity_pitch.value * (joy_invert.value ? -1.0 : 1.0) * host_frametime; - if (lookEased.x != 0 || lookEased.y != 0) + if(lookEased.x != 0 || lookEased.y != 0) V_StopPitchDrift(); /* johnfitz -- variable pitch clamping */ - if (cl.viewangles[PITCH] > cl_maxpitch.value) + if(cl.viewangles[PITCH] > cl_maxpitch.value) cl.viewangles[PITCH] = cl_maxpitch.value; - if (cl.viewangles[PITCH] < cl_minpitch.value) + if(cl.viewangles[PITCH] < cl_minpitch.value) cl.viewangles[PITCH] = cl_minpitch.value; } void IN_MouseMove(usercmd_t *cmd) { - int32_t dmx, dmy; + int32_t dmx, dmy; dmx = total_dx * sensitivity.value; dmy = total_dy * sensitivity.value; @@ -635,29 +651,29 @@ void IN_MouseMove(usercmd_t *cmd) total_dx = 0; total_dy = 0; - if ( (in_strafe.state & 1) || (lookstrafe.value && (in_mlook.state & 1) )) + if((in_strafe.state & 1) || (lookstrafe.value && (in_mlook.state & 1))) cmd->sidemove += m_side.value * dmx; else cl.viewangles[YAW] -= m_yaw.value * dmx; - if (in_mlook.state & 1) + if(in_mlook.state & 1) { - if (dmx || dmy) - V_StopPitchDrift (); + if(dmx || dmy) + V_StopPitchDrift(); } - if ( (in_mlook.state & 1) && !(in_strafe.state & 1)) + if((in_mlook.state & 1) && !(in_strafe.state & 1)) { cl.viewangles[PITCH] += m_pitch.value * dmy; /* johnfitz -- variable pitch clamping */ - if (cl.viewangles[PITCH] > cl_maxpitch.value) + if(cl.viewangles[PITCH] > cl_maxpitch.value) cl.viewangles[PITCH] = cl_maxpitch.value; - if (cl.viewangles[PITCH] < cl_minpitch.value) + if(cl.viewangles[PITCH] < cl_minpitch.value) cl.viewangles[PITCH] = cl_minpitch.value; } else { - if ((in_strafe.state & 1) && noclip_anglehack) + if((in_strafe.state & 1) && noclip_anglehack) cmd->upmove -= m_forward.value * dmy; else cmd->forwardmove -= m_forward.value * dmy; @@ -670,26 +686,26 @@ void IN_Move(usercmd_t *cmd) IN_MouseMove(cmd); } -void IN_ClearStates (void) +void IN_ClearStates(void) { } -void IN_UpdateInputMode (void) +void IN_UpdateInputMode(void) { bool want_textmode = Key_TextEntry(); - if (textmode != want_textmode) + if(textmode != want_textmode) { textmode = want_textmode; - if (textmode) + if(textmode) { SDL_StartTextInput(); - if (in_debugkeys.value) + if(in_debugkeys.value) Con_Printf("SDL_StartTextInput time: %g\n", Sys_DoubleTime()); } else { SDL_StopTextInput(); - if (in_debugkeys.value) + if(in_debugkeys.value) Con_Printf("SDL_StopTextInput time: %g\n", Sys_DoubleTime()); } } @@ -697,204 +713,308 @@ void IN_UpdateInputMode (void) static inline int32_t IN_SDL2_ScancodeToQuakeKey(SDL_Scancode scancode) { - switch (scancode) + switch(scancode) { - case SDL_SCANCODE_TAB: return K_TAB; - case SDL_SCANCODE_RETURN: return K_ENTER; - case SDL_SCANCODE_RETURN2: return K_ENTER; - case SDL_SCANCODE_ESCAPE: return K_ESCAPE; - case SDL_SCANCODE_SPACE: return K_SPACE; + case SDL_SCANCODE_TAB: + return K_TAB; + case SDL_SCANCODE_RETURN: + return K_ENTER; + case SDL_SCANCODE_RETURN2: + return K_ENTER; + case SDL_SCANCODE_ESCAPE: + return K_ESCAPE; + case SDL_SCANCODE_SPACE: + return K_SPACE; - case SDL_SCANCODE_A: return 'a'; - case SDL_SCANCODE_B: return 'b'; - case SDL_SCANCODE_C: return 'c'; - case SDL_SCANCODE_D: return 'd'; - case SDL_SCANCODE_E: return 'e'; - case SDL_SCANCODE_F: return 'f'; - case SDL_SCANCODE_G: return 'g'; - case SDL_SCANCODE_H: return 'h'; - case SDL_SCANCODE_I: return 'i'; - case SDL_SCANCODE_J: return 'j'; - case SDL_SCANCODE_K: return 'k'; - case SDL_SCANCODE_L: return 'l'; - case SDL_SCANCODE_M: return 'm'; - case SDL_SCANCODE_N: return 'n'; - case SDL_SCANCODE_O: return 'o'; - case SDL_SCANCODE_P: return 'p'; - case SDL_SCANCODE_Q: return 'q'; - case SDL_SCANCODE_R: return 'r'; - case SDL_SCANCODE_S: return 's'; - case SDL_SCANCODE_T: return 't'; - case SDL_SCANCODE_U: return 'u'; - case SDL_SCANCODE_V: return 'v'; - case SDL_SCANCODE_W: return 'w'; - case SDL_SCANCODE_X: return 'x'; - case SDL_SCANCODE_Y: return 'y'; - case SDL_SCANCODE_Z: return 'z'; + case SDL_SCANCODE_A: + return 'a'; + case SDL_SCANCODE_B: + return 'b'; + case SDL_SCANCODE_C: + return 'c'; + case SDL_SCANCODE_D: + return 'd'; + case SDL_SCANCODE_E: + return 'e'; + case SDL_SCANCODE_F: + return 'f'; + case SDL_SCANCODE_G: + return 'g'; + case SDL_SCANCODE_H: + return 'h'; + case SDL_SCANCODE_I: + return 'i'; + case SDL_SCANCODE_J: + return 'j'; + case SDL_SCANCODE_K: + return 'k'; + case SDL_SCANCODE_L: + return 'l'; + case SDL_SCANCODE_M: + return 'm'; + case SDL_SCANCODE_N: + return 'n'; + case SDL_SCANCODE_O: + return 'o'; + case SDL_SCANCODE_P: + return 'p'; + case SDL_SCANCODE_Q: + return 'q'; + case SDL_SCANCODE_R: + return 'r'; + case SDL_SCANCODE_S: + return 's'; + case SDL_SCANCODE_T: + return 't'; + case SDL_SCANCODE_U: + return 'u'; + case SDL_SCANCODE_V: + return 'v'; + case SDL_SCANCODE_W: + return 'w'; + case SDL_SCANCODE_X: + return 'x'; + case SDL_SCANCODE_Y: + return 'y'; + case SDL_SCANCODE_Z: + return 'z'; - case SDL_SCANCODE_1: return '1'; - case SDL_SCANCODE_2: return '2'; - case SDL_SCANCODE_3: return '3'; - case SDL_SCANCODE_4: return '4'; - case SDL_SCANCODE_5: return '5'; - case SDL_SCANCODE_6: return '6'; - case SDL_SCANCODE_7: return '7'; - case SDL_SCANCODE_8: return '8'; - case SDL_SCANCODE_9: return '9'; - case SDL_SCANCODE_0: return '0'; + case SDL_SCANCODE_1: + return '1'; + case SDL_SCANCODE_2: + return '2'; + case SDL_SCANCODE_3: + return '3'; + case SDL_SCANCODE_4: + return '4'; + case SDL_SCANCODE_5: + return '5'; + case SDL_SCANCODE_6: + return '6'; + case SDL_SCANCODE_7: + return '7'; + case SDL_SCANCODE_8: + return '8'; + case SDL_SCANCODE_9: + return '9'; + case SDL_SCANCODE_0: + return '0'; - case SDL_SCANCODE_MINUS: return '-'; - case SDL_SCANCODE_EQUALS: return '='; - case SDL_SCANCODE_LEFTBRACKET: return '['; - case SDL_SCANCODE_RIGHTBRACKET: return ']'; - case SDL_SCANCODE_BACKSLASH: return '\\'; - case SDL_SCANCODE_NONUSHASH: return '#'; - case SDL_SCANCODE_SEMICOLON: return ';'; - case SDL_SCANCODE_APOSTROPHE: return '\''; - case SDL_SCANCODE_GRAVE: return '`'; - case SDL_SCANCODE_COMMA: return ','; - case SDL_SCANCODE_PERIOD: return '.'; - case SDL_SCANCODE_SLASH: return '/'; - case SDL_SCANCODE_NONUSBACKSLASH: return '\\'; + case SDL_SCANCODE_MINUS: + return '-'; + case SDL_SCANCODE_EQUALS: + return '='; + case SDL_SCANCODE_LEFTBRACKET: + return '['; + case SDL_SCANCODE_RIGHTBRACKET: + return ']'; + case SDL_SCANCODE_BACKSLASH: + return '\\'; + case SDL_SCANCODE_NONUSHASH: + return '#'; + case SDL_SCANCODE_SEMICOLON: + return ';'; + case SDL_SCANCODE_APOSTROPHE: + return '\''; + case SDL_SCANCODE_GRAVE: + return '`'; + case SDL_SCANCODE_COMMA: + return ','; + case SDL_SCANCODE_PERIOD: + return '.'; + case SDL_SCANCODE_SLASH: + return '/'; + case SDL_SCANCODE_NONUSBACKSLASH: + return '\\'; - case SDL_SCANCODE_BACKSPACE: return K_BACKSPACE; - case SDL_SCANCODE_UP: return K_UPARROW; - case SDL_SCANCODE_DOWN: return K_DOWNARROW; - case SDL_SCANCODE_LEFT: return K_LEFTARROW; - case SDL_SCANCODE_RIGHT: return K_RIGHTARROW; + case SDL_SCANCODE_BACKSPACE: + return K_BACKSPACE; + case SDL_SCANCODE_UP: + return K_UPARROW; + case SDL_SCANCODE_DOWN: + return K_DOWNARROW; + case SDL_SCANCODE_LEFT: + return K_LEFTARROW; + case SDL_SCANCODE_RIGHT: + return K_RIGHTARROW; - case SDL_SCANCODE_LALT: return K_ALT; - case SDL_SCANCODE_RALT: return K_ALT; - case SDL_SCANCODE_LCTRL: return K_CTRL; - case SDL_SCANCODE_RCTRL: return K_CTRL; - case SDL_SCANCODE_LSHIFT: return K_SHIFT; - case SDL_SCANCODE_RSHIFT: return K_SHIFT; + case SDL_SCANCODE_LALT: + return K_ALT; + case SDL_SCANCODE_RALT: + return K_ALT; + case SDL_SCANCODE_LCTRL: + return K_CTRL; + case SDL_SCANCODE_RCTRL: + return K_CTRL; + case SDL_SCANCODE_LSHIFT: + return K_SHIFT; + case SDL_SCANCODE_RSHIFT: + return K_SHIFT; - case SDL_SCANCODE_F1: return K_F1; - case SDL_SCANCODE_F2: return K_F2; - case SDL_SCANCODE_F3: return K_F3; - case SDL_SCANCODE_F4: return K_F4; - case SDL_SCANCODE_F5: return K_F5; - case SDL_SCANCODE_F6: return K_F6; - case SDL_SCANCODE_F7: return K_F7; - case SDL_SCANCODE_F8: return K_F8; - case SDL_SCANCODE_F9: return K_F9; - case SDL_SCANCODE_F10: return K_F10; - case SDL_SCANCODE_F11: return K_F11; - case SDL_SCANCODE_F12: return K_F12; - case SDL_SCANCODE_INSERT: return K_INS; - case SDL_SCANCODE_DELETE: return K_DEL; - case SDL_SCANCODE_PAGEDOWN: return K_PGDN; - case SDL_SCANCODE_PAGEUP: return K_PGUP; - case SDL_SCANCODE_HOME: return K_HOME; - case SDL_SCANCODE_END: return K_END; + case SDL_SCANCODE_F1: + return K_F1; + case SDL_SCANCODE_F2: + return K_F2; + case SDL_SCANCODE_F3: + return K_F3; + case SDL_SCANCODE_F4: + return K_F4; + case SDL_SCANCODE_F5: + return K_F5; + case SDL_SCANCODE_F6: + return K_F6; + case SDL_SCANCODE_F7: + return K_F7; + case SDL_SCANCODE_F8: + return K_F8; + case SDL_SCANCODE_F9: + return K_F9; + case SDL_SCANCODE_F10: + return K_F10; + case SDL_SCANCODE_F11: + return K_F11; + case SDL_SCANCODE_F12: + return K_F12; + case SDL_SCANCODE_INSERT: + return K_INS; + case SDL_SCANCODE_DELETE: + return K_DEL; + case SDL_SCANCODE_PAGEDOWN: + return K_PGDN; + case SDL_SCANCODE_PAGEUP: + return K_PGUP; + case SDL_SCANCODE_HOME: + return K_HOME; + case SDL_SCANCODE_END: + return K_END; - case SDL_SCANCODE_NUMLOCKCLEAR: return K_KP_NUMLOCK; - case SDL_SCANCODE_KP_DIVIDE: return K_KP_SLASH; - case SDL_SCANCODE_KP_MULTIPLY: return K_KP_STAR; - case SDL_SCANCODE_KP_MINUS: return K_KP_MINUS; - case SDL_SCANCODE_KP_7: return K_KP_HOME; - case SDL_SCANCODE_KP_8: return K_KP_UPARROW; - case SDL_SCANCODE_KP_9: return K_KP_PGUP; - case SDL_SCANCODE_KP_PLUS: return K_KP_PLUS; - case SDL_SCANCODE_KP_4: return K_KP_LEFTARROW; - case SDL_SCANCODE_KP_5: return K_KP_5; - case SDL_SCANCODE_KP_6: return K_KP_RIGHTARROW; - case SDL_SCANCODE_KP_1: return K_KP_END; - case SDL_SCANCODE_KP_2: return K_KP_DOWNARROW; - case SDL_SCANCODE_KP_3: return K_KP_PGDN; - case SDL_SCANCODE_KP_ENTER: return K_KP_ENTER; - case SDL_SCANCODE_KP_0: return K_KP_INS; - case SDL_SCANCODE_KP_PERIOD: return K_KP_DEL; + case SDL_SCANCODE_NUMLOCKCLEAR: + return K_KP_NUMLOCK; + case SDL_SCANCODE_KP_DIVIDE: + return K_KP_SLASH; + case SDL_SCANCODE_KP_MULTIPLY: + return K_KP_STAR; + case SDL_SCANCODE_KP_MINUS: + return K_KP_MINUS; + case SDL_SCANCODE_KP_7: + return K_KP_HOME; + case SDL_SCANCODE_KP_8: + return K_KP_UPARROW; + case SDL_SCANCODE_KP_9: + return K_KP_PGUP; + case SDL_SCANCODE_KP_PLUS: + return K_KP_PLUS; + case SDL_SCANCODE_KP_4: + return K_KP_LEFTARROW; + case SDL_SCANCODE_KP_5: + return K_KP_5; + case SDL_SCANCODE_KP_6: + return K_KP_RIGHTARROW; + case SDL_SCANCODE_KP_1: + return K_KP_END; + case SDL_SCANCODE_KP_2: + return K_KP_DOWNARROW; + case SDL_SCANCODE_KP_3: + return K_KP_PGDN; + case SDL_SCANCODE_KP_ENTER: + return K_KP_ENTER; + case SDL_SCANCODE_KP_0: + return K_KP_INS; + case SDL_SCANCODE_KP_PERIOD: + return K_KP_DEL; - case SDL_SCANCODE_LGUI: return K_COMMAND; - case SDL_SCANCODE_RGUI: return K_COMMAND; + case SDL_SCANCODE_LGUI: + return K_COMMAND; + case SDL_SCANCODE_RGUI: + return K_COMMAND; - case SDL_SCANCODE_PAUSE: return K_PAUSE; + case SDL_SCANCODE_PAUSE: + return K_PAUSE; - default: return 0; + default: + return 0; } } static void IN_DebugTextEvent(SDL_Event *event) { - Con_Printf ("SDL_TEXTINPUT '%s' time: %g\n", event->text.text, Sys_DoubleTime()); + Con_Printf("SDL_TEXTINPUT '%s' time: %g\n", event->text.text, Sys_DoubleTime()); } static void IN_DebugKeyEvent(SDL_Event *event) { const char *eventtype = (event->key.state == SDL_PRESSED) ? "SDL_KEYDOWN" : "SDL_KEYUP"; - Con_Printf ("%s scancode: '%s' keycode: '%s' time: %g\n", - eventtype, - SDL_GetScancodeName(event->key.keysym.scancode), - SDL_GetKeyName(event->key.keysym.sym), - Sys_DoubleTime()); + Con_Printf("%s scancode: '%s' keycode: '%s' time: %g\n", + eventtype, + SDL_GetScancodeName(event->key.keysym.scancode), + SDL_GetKeyName(event->key.keysym.sym), + Sys_DoubleTime()); } -void IN_SendKeyEvents (void) +void IN_SendKeyEvents(void) { SDL_Event event; int32_t key; bool down; - while (SDL_PollEvent(&event)) + while(SDL_PollEvent(&event)) { - switch (event.type) + switch(event.type) { case SDL_WINDOWEVENT: - if (event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) + if(event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) S_UnblockSound(); - else if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) + else if(event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) S_BlockSound(); break; case SDL_TEXTINPUT: - if (in_debugkeys.value) + if(in_debugkeys.value) IN_DebugTextEvent(&event); - // SDL2: We use SDL_TEXTINPUT for typing in the console / chat. - // SDL2 uses the local keyboard layout and handles modifiers - // (shift for uppercase, etc.) for us. + // SDL2: We use SDL_TEXTINPUT for typing in the console / chat. + // SDL2 uses the local keyboard layout and handles modifiers + // (shift for uppercase, etc.) for us. { uint8_t *ch; - for (ch = (uint8_t *)event.text.text; *ch; ch++) - if ((*ch & ~0x7F) == 0) - Char_Event (*ch); + for(ch = (uint8_t *)event.text.text; *ch; ch++) + if((*ch & ~0x7F) == 0) + Char_Event(*ch); } break; case SDL_KEYDOWN: case SDL_KEYUP: down = (event.key.state == SDL_PRESSED); - if (in_debugkeys.value) + if(in_debugkeys.value) IN_DebugKeyEvent(&event); // SDL2: we interpret the keyboard as the US layout, so keybindings // are based on key position, not the label on the key cap. key = IN_SDL2_ScancodeToQuakeKey(event.key.keysym.scancode); - Key_Event (key, down); + Key_Event(key, down); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: - if (event.button.button < 1 || - event.button.button > sizeof(buttonremap) / sizeof(buttonremap[0])) + if(event.button.button < 1 || + event.button.button > sizeof(buttonremap) / sizeof(buttonremap[0])) { - Con_Printf ("Ignored event for mouse button %" PRIi32 "\n", - event.button.button); + Con_Printf("Ignored event for mouse button %" PRIi32 "\n", + event.button.button); break; } Key_Event(buttonremap[event.button.button - 1], event.button.state == SDL_PRESSED); break; case SDL_MOUSEWHEEL: - if (event.wheel.y > 0) + if(event.wheel.y > 0) { Key_Event(K_MWHEELUP, true); Key_Event(K_MWHEELUP, false); } - else if (event.wheel.y < 0) + else if(event.wheel.y < 0) { Key_Event(K_MWHEELDOWN, true); Key_Event(K_MWHEELDOWN, false); @@ -906,10 +1026,10 @@ void IN_SendKeyEvents (void) break; case SDL_CONTROLLERDEVICEADDED: - if (joy_active_instaceid == -1) + if(joy_active_instaceid == -1) { joy_active_controller = SDL_GameControllerOpen(event.cdevice.which); - if (joy_active_controller == NULL) + if(joy_active_controller == NULL) Con_DPrintf("Couldn't open game controller\n"); else { @@ -922,7 +1042,7 @@ void IN_SendKeyEvents (void) Con_DPrintf("Ignoring SDL_CONTROLLERDEVICEADDED\n"); break; case SDL_CONTROLLERDEVICEREMOVED: - if (joy_active_instaceid != -1 && event.cdevice.which == joy_active_instaceid) + if(joy_active_instaceid != -1 && event.cdevice.which == joy_active_instaceid) { SDL_GameControllerClose(joy_active_controller); joy_active_controller = NULL; @@ -936,8 +1056,8 @@ void IN_SendKeyEvents (void) break; case SDL_QUIT: - CL_Disconnect (); - Sys_Quit (); + CL_Disconnect(); + Sys_Quit(); break; default: diff --git a/source/input.h b/source/input.h index a5be65c..ea2f800 100644 --- a/source/input.h +++ b/source/input.h @@ -24,34 +24,34 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // input.h -- external (non-keyboard) input devices -void IN_Init (void); +void IN_Init(void); -void IN_Shutdown (void); +void IN_Shutdown(void); -void IN_Commands (void); +void IN_Commands(void); // oportunity for devices to stick commands on the script buffer // mouse moved by dx and dy pixels void IN_MouseMotion(int32_t dx, int32_t dy); -void IN_SendKeyEvents (void); +void IN_SendKeyEvents(void); // used as a callback for Sys_SendKeyEvents() by some drivers -void IN_UpdateInputMode (void); +void IN_UpdateInputMode(void); // do stuff if input mode (text/non-text) changes matter to the keyboard driver -void IN_Move (usercmd_t *cmd); +void IN_Move(usercmd_t *cmd); // add additional movement on top of the keyboard move cmd -void IN_ClearStates (void); +void IN_ClearStates(void); // restores all button and position states to defaults // called when the app becomes active -void IN_Activate (); +void IN_Activate(); // called when the app becomes inactive -void IN_Deactivate (bool free_cursor); +void IN_Deactivate(bool free_cursor); -#endif /* _QUAKE_INPUT_H */ +#endif /* _QUAKE_INPUT_H */ diff --git a/source/keys.c b/source/keys.c index 809d1d8..f5470a6 100644 --- a/source/keys.c +++ b/source/keys.c @@ -26,28 +26,28 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /* key up events are sent even if in console mode */ -#define HISTORY_FILE_NAME "history.txt" +#define HISTORY_FILE_NAME "history.txt" -char key_lines[CMDLINES][MAXCMDLINE]; +char key_lines[CMDLINES][MAXCMDLINE]; -int32_t key_linepos; -int32_t key_insert; //johnfitz -- insert key toggle (for editing) -double key_blinktime; //johnfitz -- fudge cursor blinking to make it easier to spot in certain cases +int32_t key_linepos; +int32_t key_insert; //johnfitz -- insert key toggle (for editing) +double key_blinktime; //johnfitz -- fudge cursor blinking to make it easier to spot in certain cases -int32_t edit_line = 0; -int32_t history_line = 0; +int32_t edit_line = 0; +int32_t history_line = 0; -keydest_t key_dest; +keydest_t key_dest; -char *keybindings[MAX_KEYS]; -bool consolekeys[MAX_KEYS]; // if true, can't be rebound while in console -bool menubound[MAX_KEYS]; // if true, can't be rebound while in menu -bool keydown[MAX_KEYS]; +char *keybindings[MAX_KEYS]; +bool consolekeys[MAX_KEYS]; // if true, can't be rebound while in console +bool menubound[MAX_KEYS]; // if true, can't be rebound while in menu +bool keydown[MAX_KEYS]; typedef struct { - const char *name; - int32_t keynum; + const char *name; + int32_t keynum; } keyname_t; keyname_t keynames[] = @@ -155,10 +155,10 @@ keyname_t keynames[] = {"MWHEELUP", K_MWHEELUP}, {"MWHEELDOWN", K_MWHEELDOWN}, - {"SEMICOLON", ';'}, // because a raw semicolon seperates commands + {"SEMICOLON", ';'}, // because a raw semicolon seperates commands - {"BACKQUOTE", '`'}, // because a raw backquote may toggle the console - {"TILDE", '~'}, // because a raw tilde may toggle the console + {"BACKQUOTE", '`'}, // because a raw backquote may toggle the console + {"TILDE", '~'}, // because a raw tilde may toggle the console {"LTHUMB", K_LTHUMB}, {"RTHUMB", K_RTHUMB}, @@ -171,32 +171,32 @@ keyname_t keynames[] = {"LTRIGGER", K_LTRIGGER}, {"RTRIGGER", K_RTRIGGER}, - {NULL, 0} + {NULL, 0} }; /* ============================================================================== - LINE TYPING INTO THE CONSOLE + LINE TYPING INTO THE CONSOLE ============================================================================== */ -static void PasteToConsole (void) +static void PasteToConsole(void) { char *cbd, *p, *workline; int32_t mvlen, inslen; - if (key_linepos == MAXCMDLINE - 1) + if(key_linepos == MAXCMDLINE - 1) return; - if ((cbd = PL_GetClipboardData()) == NULL) + if((cbd = PL_GetClipboardData()) == NULL) return; p = cbd; - while (*p) + while(*p) { - if (*p == '\n' || *p == '\r' || *p == '\b') + if(*p == '\n' || *p == '\r' || *p == '\b') { *p = 0; break; @@ -204,27 +204,27 @@ static void PasteToConsole (void) p++; } - inslen = (int32_t) (p - cbd); - if (inslen + key_linepos > MAXCMDLINE - 1) + inslen = (int32_t)(p - cbd); + if(inslen + key_linepos > MAXCMDLINE - 1) inslen = MAXCMDLINE - 1 - key_linepos; - if (inslen <= 0) goto done; + if(inslen <= 0) goto done; workline = key_lines[edit_line]; workline += key_linepos; mvlen = (int32_t) strlen(workline); - if (mvlen + inslen + key_linepos > MAXCMDLINE - 1) + if(mvlen + inslen + key_linepos > MAXCMDLINE - 1) { mvlen = MAXCMDLINE - 1 - key_linepos - inslen; - if (mvlen < 0) mvlen = 0; + if(mvlen < 0) mvlen = 0; } // insert the string - if (mvlen != 0) - memmove (workline + inslen, workline, mvlen); - memcpy (workline, cbd, inslen); + if(mvlen != 0) + memmove(workline + inslen, workline, mvlen); + memcpy(workline, cbd, inslen); key_linepos += inslen; workline[mvlen + inslen] = '\0'; - done: +done: Z_Free(cbd); } @@ -235,53 +235,53 @@ Key_Console -- johnfitz -- heavy revision Interactive line editing and console scrollback ==================== */ -extern char *con_text, key_tabpartial[MAXCMDLINE]; -extern int32_t con_current, con_linewidth, con_vislines; +extern char *con_text, key_tabpartial[MAXCMDLINE]; +extern int32_t con_current, con_linewidth, con_vislines; -void Key_Console (int32_t key) +void Key_Console(int32_t key) { - static char current[MAXCMDLINE] = ""; - int32_t history_line_last; - size_t len; + static char current[MAXCMDLINE] = ""; + int32_t history_line_last; + size_t len; char *workline = key_lines[edit_line]; - switch (key) + switch(key) { case K_ENTER: case K_KP_ENTER: key_tabpartial[0] = 0; - Cbuf_AddText (workline + 1); // skip the prompt - Cbuf_AddText ("\n"); - Con_Printf ("%s\n", workline); + Cbuf_AddText(workline + 1); // skip the prompt + Cbuf_AddText("\n"); + Con_Printf("%s\n", workline); - // If the last two lines are identical, skip storing this line in history + // If the last two lines are identical, skip storing this line in history // by not incrementing edit_line - if (strcmp(workline, key_lines[(edit_line-1)&31])) + if(strcmp(workline, key_lines[(edit_line - 1) & 31])) edit_line = (edit_line + 1) & 31; history_line = edit_line; key_lines[edit_line][0] = ']'; key_lines[edit_line][1] = 0; //johnfitz -- otherwise old history items show up in the new edit line key_linepos = 1; - if (cls.state == ca_disconnected) - SCR_UpdateScreen (); // force an update, because the command may take some time + if(cls.state == ca_disconnected) + SCR_UpdateScreen(); // force an update, because the command may take some time return; case K_TAB: - Con_TabComplete (); + Con_TabComplete(); return; case K_BACKSPACE: key_tabpartial[0] = 0; - if (key_linepos > 1) + if(key_linepos > 1) { workline += key_linepos - 1; - if (workline[1]) + if(workline[1]) { len = strlen(workline); - memmove (workline, workline + 1, len); + memmove(workline, workline + 1, len); } - else *workline = 0; + else *workline = 0; key_linepos--; } return; @@ -289,62 +289,62 @@ void Key_Console (int32_t key) case K_DEL: key_tabpartial[0] = 0; workline += key_linepos; - if (*workline) + if(*workline) { - if (workline[1]) + if(workline[1]) { len = strlen(workline); - memmove (workline, workline + 1, len); + memmove(workline, workline + 1, len); } - else *workline = 0; + else *workline = 0; } return; case K_HOME: - if (keydown[K_CTRL]) + if(keydown[K_CTRL]) { //skip initial empty lines int32_t i, x; char *line; - for (i = con_current - con_totallines + 1; i <= con_current; i++) + for(i = con_current - con_totallines + 1; i <= con_current; i++) { line = con_text + (i % con_totallines) * con_linewidth; - for (x = 0; x < con_linewidth; x++) + for(x = 0; x < con_linewidth; x++) { - if (line[x] != ' ') + if(line[x] != ' ') break; } - if (x != con_linewidth) + if(x != con_linewidth) break; } - con_backscroll = CLAMP(0, con_current-i%con_totallines-2, con_totallines-(glheight>>3)-1); + con_backscroll = CLAMP(0, con_current - i % con_totallines - 2, con_totallines - (glheight >> 3) - 1); } - else key_linepos = 1; + else key_linepos = 1; return; case K_END: - if (keydown[K_CTRL]) + if(keydown[K_CTRL]) con_backscroll = 0; - else key_linepos = strlen(workline); + else key_linepos = strlen(workline); return; case K_PGUP: case K_MWHEELUP: - con_backscroll += keydown[K_CTRL] ? ((con_vislines>>3) - 4) : 2; - if (con_backscroll > con_totallines - (vid.height>>3) - 1) - con_backscroll = con_totallines - (vid.height>>3) - 1; + con_backscroll += keydown[K_CTRL] ? ((con_vislines >> 3) - 4) : 2; + if(con_backscroll > con_totallines - (vid.height >> 3) - 1) + con_backscroll = con_totallines - (vid.height >> 3) - 1; return; case K_PGDN: case K_MWHEELDOWN: - con_backscroll -= keydown[K_CTRL] ? ((con_vislines>>3) - 4) : 2; - if (con_backscroll < 0) + con_backscroll -= keydown[K_CTRL] ? ((con_vislines >> 3) - 4) : 2; + if(con_backscroll < 0) con_backscroll = 0; return; case K_LEFTARROW: - if (key_linepos > 1) + if(key_linepos > 1) { key_linepos--; key_blinktime = realtime; @@ -353,10 +353,10 @@ void Key_Console (int32_t key) case K_RIGHTARROW: len = strlen(workline); - if ((int32_t)len == key_linepos) + if((int32_t)len == key_linepos) { len = strlen(key_lines[(edit_line + 31) & 31]); - if ((int32_t)len <= key_linepos) + if((int32_t)len <= key_linepos) return; // no character to get workline += key_linepos; *workline = key_lines[(edit_line + 31) & 31][key_linepos]; @@ -371,16 +371,17 @@ void Key_Console (int32_t key) return; case K_UPARROW: - if (history_line == edit_line) + if(history_line == edit_line) Q_strcpy(current, workline); history_line_last = history_line; do { history_line = (history_line - 1) & 31; - } while (history_line != edit_line && !key_lines[history_line][1]); + } + while(history_line != edit_line && !key_lines[history_line][1]); - if (history_line == edit_line) + if(history_line == edit_line) { history_line = history_line_last; return; @@ -392,7 +393,7 @@ void Key_Console (int32_t key) return; case K_DOWNARROW: - if (history_line == edit_line) + if(history_line == edit_line) return; key_tabpartial[0] = 0; @@ -400,29 +401,32 @@ void Key_Console (int32_t key) do { history_line = (history_line + 1) & 31; - } while (history_line != edit_line && !key_lines[history_line][1]); + } + while(history_line != edit_line && !key_lines[history_line][1]); - if (history_line == edit_line) + if(history_line == edit_line) Q_strcpy(workline, current); - else Q_strcpy(workline, key_lines[history_line]); + else Q_strcpy(workline, key_lines[history_line]); key_linepos = Q_strlen(workline); return; case K_INS: - if (keydown[K_SHIFT]) /* Shift-Ins paste */ + if(keydown[K_SHIFT]) /* Shift-Ins paste */ PasteToConsole(); - else key_insert ^= 1; + else key_insert ^= 1; return; case 'v': case 'V': #if defined(PLATFORM_OSX) || defined(PLATFORM_MAC) - if (keydown[K_COMMAND]) { /* Cmd+v paste (Mac-only) */ + if(keydown[K_COMMAND]) /* Cmd+v paste (Mac-only) */ + { PasteToConsole(); return; } #endif - if (keydown[K_CTRL]) { /* Ctrl+v paste */ + if(keydown[K_CTRL]) /* Ctrl+v paste */ + { PasteToConsole(); return; } @@ -430,35 +434,36 @@ void Key_Console (int32_t key) case 'c': case 'C': - if (keydown[K_CTRL]) { /* Ctrl+C: abort the line -- S.A */ - Con_Printf ("%s\n", workline); + if(keydown[K_CTRL]) /* Ctrl+C: abort the line -- S.A */ + { + Con_Printf("%s\n", workline); workline[0] = ']'; workline[1] = 0; key_linepos = 1; - history_line= edit_line; + history_line = edit_line; return; } break; } } -void Char_Console (int32_t key) +void Char_Console(int32_t key) { - size_t len; + size_t len; char *workline = key_lines[edit_line]; - if (key_linepos < MAXCMDLINE-1) + if(key_linepos < MAXCMDLINE - 1) { bool endpos = !workline[key_linepos]; key_tabpartial[0] = 0; //johnfitz // if inserting, move the text to the right - if (key_insert && !endpos) + if(key_insert && !endpos) { workline[MAXCMDLINE - 2] = 0; workline += key_linepos; len = strlen(workline) + 1; - memmove (workline + 1, workline, len); + memmove(workline + 1, workline, len); *workline = key; } else @@ -466,7 +471,7 @@ void Char_Console (int32_t key) workline += key_linepos; *workline = key; // null terminate if at the end - if (endpos) + if(endpos) workline[1] = 0; } key_linepos++; @@ -475,57 +480,57 @@ void Char_Console (int32_t key) //============================================================================ -bool chat_team = false; -static char chat_buffer[MAXCMDLINE]; -static int32_t chat_bufferlen = 0; +bool chat_team = false; +static char chat_buffer[MAXCMDLINE]; +static int32_t chat_bufferlen = 0; -const char *Key_GetChatBuffer (void) +const char *Key_GetChatBuffer(void) { return chat_buffer; } -int32_t Key_GetChatMsgLen (void) +int32_t Key_GetChatMsgLen(void) { return chat_bufferlen; } -void Key_EndChat (void) +void Key_EndChat(void) { key_dest = key_game; chat_bufferlen = 0; chat_buffer[0] = 0; } -void Key_Message (int32_t key) +void Key_Message(int32_t key) { - switch (key) + switch(key) { case K_ENTER: case K_KP_ENTER: - if (chat_team) - Cbuf_AddText ("say_team \""); + if(chat_team) + Cbuf_AddText("say_team \""); else - Cbuf_AddText ("say \""); + Cbuf_AddText("say \""); Cbuf_AddText(chat_buffer); Cbuf_AddText("\"\n"); - Key_EndChat (); + Key_EndChat(); return; case K_ESCAPE: - Key_EndChat (); + Key_EndChat(); return; case K_BACKSPACE: - if (chat_bufferlen) + if(chat_bufferlen) chat_buffer[--chat_bufferlen] = 0; return; } } -void Char_Message (int32_t key) +void Char_Message(int32_t key) { - if (chat_bufferlen == sizeof(chat_buffer) - 1) + if(chat_bufferlen == sizeof(chat_buffer) - 1) return; // all full chat_buffer[chat_bufferlen++] = key; @@ -544,18 +549,18 @@ the given string. Single ascii characters return themselves, while the K_* names are matched up. =================== */ -int32_t Key_StringToKeynum (const char *str) +int32_t Key_StringToKeynum(const char *str) { - keyname_t *kn; + keyname_t *kn; - if (!str || !str[0]) + if(!str || !str[0]) return -1; - if (!str[1]) + if(!str[1]) return str[0]; - for (kn=keynames ; kn->name ; kn++) + for(kn = keynames ; kn->name ; kn++) { - if (!q_strcasecmp(str,kn->name)) + if(!q_strcasecmp(str, kn->name)) return kn->keynum; } return -1; @@ -570,23 +575,24 @@ given keynum. FIXME: handle quote special (general escape sequence?) =================== */ -const char *Key_KeynumToString (int32_t keynum) +const char *Key_KeynumToString(int32_t keynum) { - static char tinystr[2]; - keyname_t *kn; + static char tinystr[2]; + keyname_t *kn; - if (keynum == -1) + if(keynum == -1) return ""; - if (keynum > 32 && keynum < 127) - { // printable ascii + if(keynum > 32 && keynum < 127) + { + // printable ascii tinystr[0] = keynum; tinystr[1] = 0; return tinystr; } - for (kn = keynames; kn->name; kn++) + for(kn = keynames; kn->name; kn++) { - if (keynum == kn->keynum) + if(keynum == kn->keynum) return kn->name; } @@ -599,20 +605,20 @@ const char *Key_KeynumToString (int32_t keynum) Key_SetBinding =================== */ -void Key_SetBinding (int32_t keynum, const char *binding) +void Key_SetBinding(int32_t keynum, const char *binding) { - if (keynum == -1) + if(keynum == -1) return; // free old bindings - if (keybindings[keynum]) + if(keybindings[keynum]) { - Z_Free (keybindings[keynum]); + Z_Free(keybindings[keynum]); keybindings[keynum] = NULL; } // allocate memory for new binding - if (binding) + if(binding) keybindings[keynum] = Z_Strdup(binding); } @@ -621,34 +627,34 @@ void Key_SetBinding (int32_t keynum, const char *binding) Key_Unbind_f =================== */ -void Key_Unbind_f (void) +void Key_Unbind_f(void) { - int32_t b; + int32_t b; - if (Cmd_Argc() != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("unbind : remove commands from a key\n"); + Con_Printf("unbind : remove commands from a key\n"); return; } - b = Key_StringToKeynum (Cmd_Argv(1)); - if (b == -1) + b = Key_StringToKeynum(Cmd_Argv(1)); + if(b == -1) { - Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1)); + Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(1)); return; } - Key_SetBinding (b, NULL); + Key_SetBinding(b, NULL); } -void Key_Unbindall_f (void) +void Key_Unbindall_f(void) { - int32_t i; + int32_t i; - for (i = 0; i < MAX_KEYS; i++) + for(i = 0; i < MAX_KEYS; i++) { - if (keybindings[i]) - Key_SetBinding (i, NULL); + if(keybindings[i]) + Key_SetBinding(i, NULL); } } @@ -657,20 +663,20 @@ void Key_Unbindall_f (void) Key_Bindlist_f -- johnfitz ============ */ -void Key_Bindlist_f (void) +void Key_Bindlist_f(void) { - int32_t i, count; + int32_t i, count; count = 0; - for (i = 0; i < MAX_KEYS; i++) + for(i = 0; i < MAX_KEYS; i++) { - if (keybindings[i] && *keybindings[i]) + if(keybindings[i] && *keybindings[i]) { - Con_SafePrintf (" %s \"%s\"\n", Key_KeynumToString(i), keybindings[i]); + Con_SafePrintf(" %s \"%s\"\n", Key_KeynumToString(i), keybindings[i]); count++; } } - Con_SafePrintf ("%" PRIi32 " bindings\n", count); + Con_SafePrintf("%" PRIi32 " bindings\n", count); } /* @@ -678,44 +684,44 @@ void Key_Bindlist_f (void) Key_Bind_f =================== */ -void Key_Bind_f (void) +void Key_Bind_f(void) { - int32_t i, c, b; - char cmd[1024]; + int32_t i, c, b; + char cmd[1024]; c = Cmd_Argc(); - if (c != 2 && c != 3) + if(c != 2 && c != 3) { - Con_Printf ("bind [command] : attach a command to a key\n"); + Con_Printf("bind [command] : attach a command to a key\n"); return; } - b = Key_StringToKeynum (Cmd_Argv(1)); - if (b == -1) + b = Key_StringToKeynum(Cmd_Argv(1)); + if(b == -1) { - Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1)); + Con_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(1)); return; } - if (c == 2) + if(c == 2) { - if (keybindings[b]) - Con_Printf ("\"%s\" = \"%s\"\n", Cmd_Argv(1), keybindings[b] ); + if(keybindings[b]) + Con_Printf("\"%s\" = \"%s\"\n", Cmd_Argv(1), keybindings[b]); else - Con_Printf ("\"%s\" is not bound\n", Cmd_Argv(1) ); + Con_Printf("\"%s\" is not bound\n", Cmd_Argv(1)); return; } // copy the rest of the command line cmd[0] = 0; - for (i = 2; i < c; i++) + for(i = 2; i < c; i++) { - q_strlcat (cmd, Cmd_Argv(i), sizeof(cmd)); - if (i != (c-1)) - q_strlcat (cmd, " ", sizeof(cmd)); + q_strlcat(cmd, Cmd_Argv(i), sizeof(cmd)); + if(i != (c - 1)) + q_strlcat(cmd, " ", sizeof(cmd)); } - Key_SetBinding (b, cmd); + Key_SetBinding(b, cmd); } /* @@ -725,27 +731,27 @@ Key_WriteBindings Writes lines containing "bind key value" ============ */ -void Key_WriteBindings (FILE *f) +void Key_WriteBindings(FILE *f) { - int32_t i; + int32_t i; // unbindall before loading stored bindings: - if (cfg_unbindall.value) - fprintf (f, "unbindall\n"); - for (i = 0; i < MAX_KEYS; i++) + if(cfg_unbindall.value) + fprintf(f, "unbindall\n"); + for(i = 0; i < MAX_KEYS; i++) { - if (keybindings[i] && *keybindings[i]) - fprintf (f, "bind \"%s\" \"%s\"\n", Key_KeynumToString(i), keybindings[i]); + if(keybindings[i] && *keybindings[i]) + fprintf(f, "bind \"%s\" \"%s\"\n", Key_KeynumToString(i), keybindings[i]); } } -void History_Init (void) +void History_Init(void) { int32_t i, c; FILE *hf; - for (i = 0; i < CMDLINES; i++) + for(i = 0; i < CMDLINES; i++) { key_lines[i][0] = ']'; key_lines[i][1] = 0; @@ -753,7 +759,7 @@ void History_Init (void) key_linepos = 1; hf = fopen(va("%s/%s", host_parms->userdir, HISTORY_FILE_NAME), "rt"); - if (hf != NULL) + if(hf != NULL) { do { @@ -762,20 +768,22 @@ void History_Init (void) { c = fgetc(hf); key_lines[edit_line][i++] = c; - } while (c != '\r' && c != '\n' && c != EOF && i < MAXCMDLINE); + } + while(c != '\r' && c != '\n' && c != EOF && i < MAXCMDLINE); key_lines[edit_line][i - 1] = 0; edit_line = (edit_line + 1) & (CMDLINES - 1); /* for people using a windows-generated history file on unix: */ - if (c == '\r' || c == '\n') + if(c == '\r' || c == '\n') { do c = fgetc(hf); - while (c == '\r' || c == '\n'); - if (c != EOF) + while(c == '\r' || c == '\n'); + if(c != EOF) ungetc(c, hf); - else c = 0; /* loop once more, otherwise last line is lost */ + else c = 0; /* loop once more, otherwise last line is lost */ } - } while (c != EOF && edit_line < CMDLINES); + } + while(c != EOF && edit_line < CMDLINES); fclose(hf); history_line = edit_line = (edit_line - 1) & (CMDLINES - 1); @@ -784,21 +792,22 @@ void History_Init (void) } } -void History_Shutdown (void) +void History_Shutdown(void) { int32_t i; FILE *hf; hf = fopen(va("%s/%s", host_parms->userdir, HISTORY_FILE_NAME), "wt"); - if (hf != NULL) + if(hf != NULL) { i = edit_line; do { i = (i + 1) & (CMDLINES - 1); - } while (i != edit_line && !key_lines[i][1]); + } + while(i != edit_line && !key_lines[i][1]); - while (i != edit_line && key_lines[i][1]) + while(i != edit_line && key_lines[i][1]) { fprintf(hf, "%s\n", key_lines[i] + 1); i = (i + 1) & (CMDLINES - 1); @@ -812,18 +821,18 @@ void History_Shutdown (void) Key_Init =================== */ -void Key_Init (void) +void Key_Init(void) { - int32_t i; + int32_t i; - History_Init (); + History_Init(); key_blinktime = realtime; //johnfitz // // initialize consolekeys[] // - for (i = 32; i < 127; i++) // ascii characters + for(i = 32; i < 127; i++) // ascii characters consolekeys[i] = true; consolekeys['`'] = false; consolekeys['~'] = false; @@ -870,19 +879,20 @@ void Key_Init (void) // initialize menubound[] // menubound[K_ESCAPE] = true; - for (i = 0; i < 12; i++) - menubound[K_F1+i] = true; + for(i = 0; i < 12; i++) + menubound[K_F1 + i] = true; // // register our functions // - Cmd_AddCommand ("bindlist",Key_Bindlist_f); //johnfitz - Cmd_AddCommand ("bind",Key_Bind_f); - Cmd_AddCommand ("unbind",Key_Unbind_f); - Cmd_AddCommand ("unbindall",Key_Unbindall_f); + Cmd_AddCommand("bindlist", Key_Bindlist_f); //johnfitz + Cmd_AddCommand("bind", Key_Bind_f); + Cmd_AddCommand("unbind", Key_Unbind_f); + Cmd_AddCommand("unbindall", Key_Unbindall_f); } -static struct { +static struct +{ bool active; int32_t lastkey; int32_t lastchar; @@ -893,15 +903,15 @@ static struct { Key_BeginInputGrab =================== */ -void Key_BeginInputGrab (void) +void Key_BeginInputGrab(void) { - Key_ClearStates (); + Key_ClearStates(); key_inputgrab.active = true; key_inputgrab.lastkey = -1; key_inputgrab.lastchar = -1; - IN_UpdateInputMode (); + IN_UpdateInputMode(); } /* @@ -909,13 +919,13 @@ void Key_BeginInputGrab (void) Key_EndInputGrab =================== */ -void Key_EndInputGrab (void) +void Key_EndInputGrab(void) { - Key_ClearStates (); + Key_ClearStates(); key_inputgrab.active = false; - IN_UpdateInputMode (); + IN_UpdateInputMode(); } /* @@ -923,11 +933,11 @@ void Key_EndInputGrab (void) Key_GetGrabbedInput =================== */ -void Key_GetGrabbedInput (int32_t *lastkey, int32_t *lastchar) +void Key_GetGrabbedInput(int32_t *lastkey, int32_t *lastchar) { - if (lastkey) + if(lastkey) *lastkey = key_inputgrab.lastkey; - if (lastchar) + if(lastchar) *lastchar = key_inputgrab.lastchar; } @@ -939,70 +949,70 @@ Called by the system between frames for both key up and key down events Should NOT be called during an interrupt! =================== */ -void Key_Event (int32_t key, bool down) +void Key_Event(int32_t key, bool down) { - char *kb; - char cmd[1024]; + char *kb; + char cmd[1024]; - if (key < 0 || key >= MAX_KEYS) + if(key < 0 || key >= MAX_KEYS) return; // handle fullscreen toggle - if (down && (key == K_ENTER || key == K_KP_ENTER) && keydown[K_ALT]) + if(down && (key == K_ENTER || key == K_KP_ENTER) && keydown[K_ALT]) { VID_Toggle(); return; } // handle autorepeats and stray key up events - if (down) + if(down) { - if (keydown[key]) + if(keydown[key]) { - if (key_dest == key_game && !con_forcedup) + if(key_dest == key_game && !con_forcedup) return; // ignore autorepeats in game mode } - else if (key >= 200 && !keybindings[key]) - Con_Printf ("%s is unbound, hit F4 to set.\n", Key_KeynumToString(key)); + else if(key >= 200 && !keybindings[key]) + Con_Printf("%s is unbound, hit F4 to set.\n", Key_KeynumToString(key)); } - else if (!keydown[key]) + else if(!keydown[key]) return; // ignore stray key up events keydown[key] = down; - if (key_inputgrab.active) + if(key_inputgrab.active) { - if (down) + if(down) key_inputgrab.lastkey = key; return; } // handle escape specialy, so the user can never unbind it - if (key == K_ESCAPE) + if(key == K_ESCAPE) { - if (!down) + if(!down) return; - if (keydown[K_SHIFT]) + if(keydown[K_SHIFT]) { Con_ToggleConsole_f(); return; } - switch (key_dest) + switch(key_dest) { case key_message: - Key_Message (key); + Key_Message(key); break; case key_menu: - M_Keydown (key); + M_Keydown(key); break; case key_game: case key_console: - M_ToggleMenu_f (); + M_ToggleMenu_f(); break; default: - Sys_Error ("Bad key_dest"); + Sys_Error("Bad key_dest"); } return; @@ -1013,64 +1023,65 @@ void Key_Event (int32_t key, bool down) // to keep the character from continuing an action started before a console // switch. Button commands include the kenum as a parameter, so multiple // downs can be matched with ups - if (!down) + if(!down) { kb = keybindings[key]; - if (kb && kb[0] == '+') + if(kb && kb[0] == '+') { - sprintf (cmd, "-%s %" PRIi32 "\n", kb+1, key); - Cbuf_AddText (cmd); + sprintf(cmd, "-%s %" PRIi32 "\n", kb + 1, key); + Cbuf_AddText(cmd); } return; } // during demo playback, most keys bring up the main menu - if (cls.demoplayback && down && consolekeys[key] && key_dest == key_game && key != K_TAB) + if(cls.demoplayback && down && consolekeys[key] && key_dest == key_game && key != K_TAB) { - M_ToggleMenu_f (); + M_ToggleMenu_f(); return; } // if not a consolekey, send to the interpreter no matter what mode is - if ((key_dest == key_menu && menubound[key]) || - (key_dest == key_console && !consolekeys[key]) || - (key_dest == key_game && (!con_forcedup || !consolekeys[key]))) + if((key_dest == key_menu && menubound[key]) || + (key_dest == key_console && !consolekeys[key]) || + (key_dest == key_game && (!con_forcedup || !consolekeys[key]))) { kb = keybindings[key]; - if (kb) + if(kb) { - if (kb[0] == '+') - { // button commands add keynum as a parm - sprintf (cmd, "%s %" PRIi32 "\n", kb, key); - Cbuf_AddText (cmd); + if(kb[0] == '+') + { + // button commands add keynum as a parm + sprintf(cmd, "%s %" PRIi32 "\n", kb, key); + Cbuf_AddText(cmd); } else { - Cbuf_AddText (kb); - Cbuf_AddText ("\n"); + Cbuf_AddText(kb); + Cbuf_AddText("\n"); } } return; } - if (!down) - return; // other systems only care about key down events + if(!down) + return; // other systems only care about key down events - switch (key_dest) + switch(key_dest) { case key_message: - Key_Message (key); + Key_Message(key); break; case key_menu: - M_Keydown (key); + M_Keydown(key); break; case key_game: case key_console: - Key_Console (key); + Key_Console(key); break; default: - Sys_Error ("Bad key_dest"); + Sys_Error("Bad key_dest"); } } @@ -1081,38 +1092,38 @@ Char_Event Called by the backend when the user has input a character. =================== */ -void Char_Event (int32_t key) +void Char_Event(int32_t key) { - if (key < 32 || key > 126) + if(key < 32 || key > 126) return; #if defined(PLATFORM_OSX) || defined(PLATFORM_MAC) - if (keydown[K_COMMAND]) + if(keydown[K_COMMAND]) return; #endif - if (keydown[K_CTRL]) + if(keydown[K_CTRL]) return; - if (key_inputgrab.active) + if(key_inputgrab.active) { key_inputgrab.lastchar = key; return; } - switch (key_dest) + switch(key_dest) { case key_message: - Char_Message (key); + Char_Message(key); break; case key_menu: - M_Charinput (key); + M_Charinput(key); break; case key_game: - if (!con_forcedup) + if(!con_forcedup) break; - /* fallthrough */ + /* fallthrough */ case key_console: - Char_Console (key); + Char_Console(key); break; default: break; @@ -1124,21 +1135,21 @@ void Char_Event (int32_t key) Key_TextEntry =================== */ -bool Key_TextEntry (void) +bool Key_TextEntry(void) { - if (key_inputgrab.active) + if(key_inputgrab.active) return true; - switch (key_dest) + switch(key_dest) { case key_message: return true; case key_menu: return M_TextEntry(); case key_game: - if (!con_forcedup) + if(!con_forcedup) return false; - /* fallthrough */ + /* fallthrough */ case key_console: return true; default: @@ -1151,14 +1162,14 @@ bool Key_TextEntry (void) Key_ClearStates =================== */ -void Key_ClearStates (void) +void Key_ClearStates(void) { - int32_t i; + int32_t i; - for (i = 0; i < MAX_KEYS; i++) + for(i = 0; i < MAX_KEYS; i++) { - if (keydown[i]) - Key_Event (i, false); + if(keydown[i]) + Key_Event(i, false); } } @@ -1167,17 +1178,17 @@ void Key_ClearStates (void) Key_UpdateForDest =================== */ -void Key_UpdateForDest (void) +void Key_UpdateForDest(void) { static bool forced = false; - if (cls.state == ca_dedicated) + if(cls.state == ca_dedicated) return; - switch (key_dest) + switch(key_dest) { case key_console: - if (forced && cls.state == ca_connected) + if(forced && cls.state == ca_connected) { forced = false; IN_Activate(); @@ -1185,7 +1196,7 @@ void Key_UpdateForDest (void) } break; case key_game: - if (cls.state != ca_connected) + if(cls.state != ca_connected) { forced = true; IN_Deactivate(modestate == MS_WINDOWED); diff --git a/source/keys.h b/source/keys.h index ad15b63..7f87443 100644 --- a/source/keys.h +++ b/source/keys.h @@ -26,175 +26,175 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // these are the key numbers that should be passed to Key_Event // -#define K_TAB 9 -#define K_ENTER 13 -#define K_ESCAPE 27 -#define K_SPACE 32 +#define K_TAB 9 +#define K_ENTER 13 +#define K_ESCAPE 27 +#define K_SPACE 32 // normal keys should be passed as lowercased ascii -#define K_BACKSPACE 127 -#define K_UPARROW 128 -#define K_DOWNARROW 129 -#define K_LEFTARROW 130 -#define K_RIGHTARROW 131 +#define K_BACKSPACE 127 +#define K_UPARROW 128 +#define K_DOWNARROW 129 +#define K_LEFTARROW 130 +#define K_RIGHTARROW 131 -#define K_ALT 132 -#define K_CTRL 133 -#define K_SHIFT 134 -#define K_F1 135 -#define K_F2 136 -#define K_F3 137 -#define K_F4 138 -#define K_F5 139 -#define K_F6 140 -#define K_F7 141 -#define K_F8 142 -#define K_F9 143 -#define K_F10 144 -#define K_F11 145 -#define K_F12 146 -#define K_INS 147 -#define K_DEL 148 -#define K_PGDN 149 -#define K_PGUP 150 -#define K_HOME 151 -#define K_END 152 +#define K_ALT 132 +#define K_CTRL 133 +#define K_SHIFT 134 +#define K_F1 135 +#define K_F2 136 +#define K_F3 137 +#define K_F4 138 +#define K_F5 139 +#define K_F6 140 +#define K_F7 141 +#define K_F8 142 +#define K_F9 143 +#define K_F10 144 +#define K_F11 145 +#define K_F12 146 +#define K_INS 147 +#define K_DEL 148 +#define K_PGDN 149 +#define K_PGUP 150 +#define K_HOME 151 +#define K_END 152 -#define K_KP_NUMLOCK 153 -#define K_KP_SLASH 154 -#define K_KP_STAR 155 -#define K_KP_MINUS 156 -#define K_KP_HOME 157 -#define K_KP_UPARROW 158 -#define K_KP_PGUP 159 -#define K_KP_PLUS 160 -#define K_KP_LEFTARROW 161 -#define K_KP_5 162 -#define K_KP_RIGHTARROW 163 -#define K_KP_END 164 -#define K_KP_DOWNARROW 165 -#define K_KP_PGDN 166 -#define K_KP_ENTER 167 -#define K_KP_INS 168 -#define K_KP_DEL 169 +#define K_KP_NUMLOCK 153 +#define K_KP_SLASH 154 +#define K_KP_STAR 155 +#define K_KP_MINUS 156 +#define K_KP_HOME 157 +#define K_KP_UPARROW 158 +#define K_KP_PGUP 159 +#define K_KP_PLUS 160 +#define K_KP_LEFTARROW 161 +#define K_KP_5 162 +#define K_KP_RIGHTARROW 163 +#define K_KP_END 164 +#define K_KP_DOWNARROW 165 +#define K_KP_PGDN 166 +#define K_KP_ENTER 167 +#define K_KP_INS 168 +#define K_KP_DEL 169 -#define K_COMMAND 170 +#define K_COMMAND 170 -#define K_PAUSE 255 +#define K_PAUSE 255 // // mouse buttons generate virtual keys // -#define K_MOUSE1 200 -#define K_MOUSE2 201 -#define K_MOUSE3 202 +#define K_MOUSE1 200 +#define K_MOUSE2 201 +#define K_MOUSE3 202 // // joystick buttons // -#define K_JOY1 203 -#define K_JOY2 204 -#define K_JOY3 205 -#define K_JOY4 206 +#define K_JOY1 203 +#define K_JOY2 204 +#define K_JOY3 205 +#define K_JOY4 206 // aux keys are for multi-buttoned joysticks to generate so they can use // the normal binding process // aux29-32: reserved for the HAT (POV) switch motion -#define K_AUX1 207 -#define K_AUX2 208 -#define K_AUX3 209 -#define K_AUX4 210 -#define K_AUX5 211 -#define K_AUX6 212 -#define K_AUX7 213 -#define K_AUX8 214 -#define K_AUX9 215 -#define K_AUX10 216 -#define K_AUX11 217 -#define K_AUX12 218 -#define K_AUX13 219 -#define K_AUX14 220 -#define K_AUX15 221 -#define K_AUX16 222 -#define K_AUX17 223 -#define K_AUX18 224 -#define K_AUX19 225 -#define K_AUX20 226 -#define K_AUX21 227 -#define K_AUX22 228 -#define K_AUX23 229 -#define K_AUX24 230 -#define K_AUX25 231 -#define K_AUX26 232 -#define K_AUX27 233 -#define K_AUX28 234 -#define K_AUX29 235 -#define K_AUX30 236 -#define K_AUX31 237 -#define K_AUX32 238 +#define K_AUX1 207 +#define K_AUX2 208 +#define K_AUX3 209 +#define K_AUX4 210 +#define K_AUX5 211 +#define K_AUX6 212 +#define K_AUX7 213 +#define K_AUX8 214 +#define K_AUX9 215 +#define K_AUX10 216 +#define K_AUX11 217 +#define K_AUX12 218 +#define K_AUX13 219 +#define K_AUX14 220 +#define K_AUX15 221 +#define K_AUX16 222 +#define K_AUX17 223 +#define K_AUX18 224 +#define K_AUX19 225 +#define K_AUX20 226 +#define K_AUX21 227 +#define K_AUX22 228 +#define K_AUX23 229 +#define K_AUX24 230 +#define K_AUX25 231 +#define K_AUX26 232 +#define K_AUX27 233 +#define K_AUX28 234 +#define K_AUX29 235 +#define K_AUX30 236 +#define K_AUX31 237 +#define K_AUX32 238 // JACK: Intellimouse(c) Mouse Wheel Support -#define K_MWHEELUP 239 -#define K_MWHEELDOWN 240 +#define K_MWHEELUP 239 +#define K_MWHEELDOWN 240 // thumb buttons -#define K_MOUSE4 241 -#define K_MOUSE5 242 +#define K_MOUSE4 241 +#define K_MOUSE5 242 // SDL2 game controller keys -#define K_LTHUMB 243 -#define K_RTHUMB 244 -#define K_LSHOULDER 245 -#define K_RSHOULDER 246 -#define K_ABUTTON 247 -#define K_BBUTTON 248 -#define K_XBUTTON 249 -#define K_YBUTTON 250 -#define K_LTRIGGER 251 -#define K_RTRIGGER 252 +#define K_LTHUMB 243 +#define K_RTHUMB 244 +#define K_LSHOULDER 245 +#define K_RSHOULDER 246 +#define K_ABUTTON 247 +#define K_BBUTTON 248 +#define K_XBUTTON 249 +#define K_YBUTTON 250 +#define K_LTRIGGER 251 +#define K_RTRIGGER 252 -#define MAX_KEYS 256 +#define MAX_KEYS 256 -#define MAXCMDLINE 256 +#define MAXCMDLINE 256 typedef enum {key_game, key_console, key_message, key_menu} keydest_t; -extern keydest_t key_dest; -extern char *keybindings[MAX_KEYS]; +extern keydest_t key_dest; +extern char *keybindings[MAX_KEYS]; -#define CMDLINES 64 +#define CMDLINES 64 -extern char key_lines[CMDLINES][MAXCMDLINE]; -extern int32_t edit_line; -extern int32_t key_linepos; -extern int32_t key_insert; -extern double key_blinktime; +extern char key_lines[CMDLINES][MAXCMDLINE]; +extern int32_t edit_line; +extern int32_t key_linepos; +extern int32_t key_insert; +extern double key_blinktime; -extern bool chat_team; +extern bool chat_team; -void Key_Init (void); -void Key_ClearStates (void); -void Key_UpdateForDest (void); +void Key_Init(void); +void Key_ClearStates(void); +void Key_UpdateForDest(void); -void Key_BeginInputGrab (void); -void Key_EndInputGrab (void); -void Key_GetGrabbedInput (int32_t *lastkey, int32_t *lastchar); +void Key_BeginInputGrab(void); +void Key_EndInputGrab(void); +void Key_GetGrabbedInput(int32_t *lastkey, int32_t *lastchar); -void Key_Event (int32_t key, bool down); -void Char_Event (int32_t key); -bool Key_TextEntry (void); +void Key_Event(int32_t key, bool down); +void Char_Event(int32_t key); +bool Key_TextEntry(void); -void Key_SetBinding (int32_t keynum, const char *binding); -const char *Key_KeynumToString (int32_t keynum); -void Key_WriteBindings (FILE *f); +void Key_SetBinding(int32_t keynum, const char *binding); +const char *Key_KeynumToString(int32_t keynum); +void Key_WriteBindings(FILE *f); -void Key_EndChat (void); -const char *Key_GetChatBuffer (void); -int32_t Key_GetChatMsgLen (void); +void Key_EndChat(void); +const char *Key_GetChatBuffer(void); +int32_t Key_GetChatMsgLen(void); -void History_Init (void); -void History_Shutdown (void); +void History_Init(void); +void History_Shutdown(void); -#endif /* _QUAKE_KEYS_H */ +#endif /* _QUAKE_KEYS_H */ diff --git a/source/linux/pl_linux.c b/source/linux/pl_linux.c index e222b67..a44ec71 100644 --- a/source/linux/pl_linux.c +++ b/source/linux/pl_linux.c @@ -29,18 +29,18 @@ static const Uint8 bmp_bytes[] = #include "qs_bmp.h" }; -void PL_SetWindowIcon (void) +void PL_SetWindowIcon(void) { - SDL_RWops *rwop; - SDL_Surface *icon; - Uint32 colorkey; + SDL_RWops *rwop; + SDL_Surface *icon; + Uint32 colorkey; /* SDL_RWFromConstMem() requires SDL >= 1.2.7 */ rwop = SDL_RWFromConstMem(bmp_bytes, sizeof(bmp_bytes)); - if (rwop == NULL) + if(rwop == NULL) return; icon = SDL_LoadBMP_RW(rwop, 1); - if (icon == NULL) + if(icon == NULL) return; /* make pure magenta (#ff00ff) tranparent */ colorkey = SDL_MapRGB(icon->format, 255, 0, 255); @@ -49,32 +49,32 @@ void PL_SetWindowIcon (void) SDL_FreeSurface(icon); } -void PL_VID_Shutdown (void) +void PL_VID_Shutdown(void) { } -#define MAX_CLIPBOARDTXT MAXCMDLINE /* 256 */ -char *PL_GetClipboardData (void) +#define MAX_CLIPBOARDTXT MAXCMDLINE /* 256 */ +char *PL_GetClipboardData(void) { char *data = NULL; char *cliptext = SDL_GetClipboardText(); - if (cliptext != NULL) + if(cliptext != NULL) { size_t size = strlen(cliptext) + 1; - /* this is intended for simple small text copies - * such as an ip address, etc: do chop the size - * here, otherwise we may experience Z_Malloc() - * failures and all other not-oh-so-fun stuff. */ + /* this is intended for simple small text copies + * such as an ip address, etc: do chop the size + * here, otherwise we may experience Z_Malloc() + * failures and all other not-oh-so-fun stuff. */ size = q_min(MAX_CLIPBOARDTXT, size); data = (char *) Z_Malloc(size); - q_strlcpy (data, cliptext, size); + q_strlcpy(data, cliptext, size); } return data; } -void PL_ErrorDialog (const char *errorMsg) +void PL_ErrorDialog(const char *errorMsg) { (void)errorMsg; } diff --git a/source/lodepng.c b/source/lodepng.c index 2ebc78c..0b658e1 100644 --- a/source/lodepng.c +++ b/source/lodepng.c @@ -62,17 +62,17 @@ from here.*/ #ifdef LODEPNG_COMPILE_ALLOCATORS static void* lodepng_malloc(size_t size) { - return malloc(size); + return malloc(size); } static void* lodepng_realloc(void* ptr, size_t new_size) { - return realloc(ptr, new_size); + return realloc(ptr, new_size); } static void lodepng_free(void* ptr) { - free(ptr); + free(ptr); } #else /*LODEPNG_COMPILE_ALLOCATORS*/ void* lodepng_malloc(size_t size); @@ -136,65 +136,65 @@ About uivector, ucvector and string: /*dynamic vector of unsigned ints*/ typedef struct uivector { - unsigned* data; - size_t size; /*size in number of unsigned longs*/ - size_t allocsize; /*allocated size in bytes*/ + unsigned* data; + size_t size; /*size in number of unsigned longs*/ + size_t allocsize; /*allocated size in bytes*/ } uivector; static void uivector_cleanup(void* p) { - ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; - lodepng_free(((uivector*)p)->data); - ((uivector*)p)->data = NULL; + ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; + lodepng_free(((uivector*)p)->data); + ((uivector*)p)->data = NULL; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_reserve(uivector* p, size_t allocsize) { - if(allocsize > p->allocsize) - { - size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); - void* data = lodepng_realloc(p->data, newsize); - if(data) - { - p->allocsize = newsize; - p->data = (unsigned*)data; - } - else return 0; /*error: not enough memory*/ - } - return 1; + if(allocsize > p->allocsize) + { + size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); + void* data = lodepng_realloc(p->data, newsize); + if(data) + { + p->allocsize = newsize; + p->data = (unsigned*)data; + } + else return 0; /*error: not enough memory*/ + } + return 1; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_resize(uivector* p, size_t size) { - if(!uivector_reserve(p, size * sizeof(unsigned))) return 0; - p->size = size; - return 1; /*success*/ + if(!uivector_reserve(p, size * sizeof(unsigned))) return 0; + p->size = size; + return 1; /*success*/ } /*resize and give all new elements the value*/ static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) { - size_t oldsize = p->size, i; - if(!uivector_resize(p, size)) return 0; - for(i = oldsize; i < size; ++i) p->data[i] = value; - return 1; + size_t oldsize = p->size, i; + if(!uivector_resize(p, size)) return 0; + for(i = oldsize; i < size; ++i) p->data[i] = value; + return 1; } static void uivector_init(uivector* p) { - p->data = NULL; - p->size = p->allocsize = 0; + p->data = NULL; + p->size = p->allocsize = 0; } #ifdef LODEPNG_COMPILE_ENCODER /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_push_back(uivector* p, unsigned c) { - if(!uivector_resize(p, p->size + 1)) return 0; - p->data[p->size - 1] = c; - return 1; + if(!uivector_resize(p, p->size + 1)) return 0; + p->data[p->size - 1] = c; + return 1; } #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ZLIB*/ @@ -204,49 +204,49 @@ static unsigned uivector_push_back(uivector* p, unsigned c) /*dynamic vector of unsigned chars*/ typedef struct ucvector { - uint8_t* data; - size_t size; /*used size*/ - size_t allocsize; /*allocated size*/ + uint8_t* data; + size_t size; /*used size*/ + size_t allocsize; /*allocated size*/ } ucvector; /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_reserve(ucvector* p, size_t allocsize) { - if(allocsize > p->allocsize) - { - size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); - void* data = lodepng_realloc(p->data, newsize); - if(data) - { - p->allocsize = newsize; - p->data = (uint8_t*)data; - } - else return 0; /*error: not enough memory*/ - } - return 1; + if(allocsize > p->allocsize) + { + size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); + void* data = lodepng_realloc(p->data, newsize); + if(data) + { + p->allocsize = newsize; + p->data = (uint8_t*)data; + } + else return 0; /*error: not enough memory*/ + } + return 1; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_resize(ucvector* p, size_t size) { - if(!ucvector_reserve(p, size * sizeof(uint8_t))) return 0; - p->size = size; - return 1; /*success*/ + if(!ucvector_reserve(p, size * sizeof(uint8_t))) return 0; + p->size = size; + return 1; /*success*/ } #ifdef LODEPNG_COMPILE_PNG static void ucvector_cleanup(void* p) { - ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0; - lodepng_free(((ucvector*)p)->data); - ((ucvector*)p)->data = NULL; + ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0; + lodepng_free(((ucvector*)p)->data); + ((ucvector*)p)->data = NULL; } static void ucvector_init(ucvector* p) { - p->data = NULL; - p->size = p->allocsize = 0; + p->data = NULL; + p->size = p->allocsize = 0; } #endif /*LODEPNG_COMPILE_PNG*/ @@ -255,8 +255,8 @@ static void ucvector_init(ucvector* p) init_buffer to take over a buffer and size, it is not needed to use cleanup*/ static void ucvector_init_buffer(ucvector* p, uint8_t* buffer, size_t size) { - p->data = buffer; - p->allocsize = p->size = size; + p->data = buffer; + p->allocsize = p->size = size; } #endif /*LODEPNG_COMPILE_ZLIB*/ @@ -264,9 +264,9 @@ static void ucvector_init_buffer(ucvector* p, uint8_t* buffer, size_t size) /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_push_back(ucvector* p, uint8_t c) { - if(!ucvector_resize(p, p->size + 1)) return 0; - p->data[p->size - 1] = c; - return 1; + if(!ucvector_resize(p, p->size + 1)) return 0; + p->data[p->size - 1] = c; + return 1; } #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ @@ -278,39 +278,39 @@ static unsigned ucvector_push_back(ucvector* p, uint8_t c) /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned string_resize(char** out, size_t size) { - char* data = (char*)lodepng_realloc(*out, size + 1); - if(data) - { - data[size] = 0; /*null termination char*/ - *out = data; - } - return data != 0; + char* data = (char*)lodepng_realloc(*out, size + 1); + if(data) + { + data[size] = 0; /*null termination char*/ + *out = data; + } + return data != 0; } /*init a {char*, size_t} pair for use as string*/ static void string_init(char** out) { - *out = NULL; - string_resize(out, 0); + *out = NULL; + string_resize(out, 0); } /*free the above pair again*/ static void string_cleanup(char** out) { - lodepng_free(*out); - *out = NULL; + lodepng_free(*out); + *out = NULL; } static void string_set(char** out, const char* in) { - size_t insize = strlen(in), i; - if(string_resize(out, insize)) - { - for(i = 0; i != insize; ++i) - { - (*out)[i] = in[i]; - } - } + size_t insize = strlen(in), i; + if(string_resize(out, insize)) + { + for(i = 0; i != insize; ++i) + { + (*out)[i] = in[i]; + } + } } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_PNG*/ @@ -319,25 +319,25 @@ static void string_set(char** out, const char* in) static unsigned lodepng_read32bitInt(const uint8_t* buffer) { - return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); + return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); } #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER) /*buffer must have at least 4 allocated bytes available*/ static void lodepng_set32bitInt(uint8_t* buffer, unsigned value) { - buffer[0] = (uint8_t)((value >> 24) & 0xff); - buffer[1] = (uint8_t)((value >> 16) & 0xff); - buffer[2] = (uint8_t)((value >> 8) & 0xff); - buffer[3] = (uint8_t)((value ) & 0xff); + buffer[0] = (uint8_t)((value >> 24) & 0xff); + buffer[1] = (uint8_t)((value >> 16) & 0xff); + buffer[2] = (uint8_t)((value >> 8) & 0xff); + buffer[3] = (uint8_t)((value) & 0xff); } #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ #ifdef LODEPNG_COMPILE_ENCODER static void lodepng_add32bitInt(ucvector* buffer, unsigned value) { - ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/ - lodepng_set32bitInt(&buffer->data[buffer->size - 4], value); + ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/ + lodepng_set32bitInt(&buffer->data[buffer->size - 4], value); } #endif /*LODEPNG_COMPILE_ENCODER*/ @@ -350,61 +350,61 @@ static void lodepng_add32bitInt(ucvector* buffer, unsigned value) /* returns negative value on error. This should be pure C compatible, so no fstat. */ static long lodepng_filesize(const char* filename) { - FILE* file; - long size; - file = fopen(filename, "rb"); - if(!file) return -1; + FILE* file; + long size; + file = fopen(filename, "rb"); + if(!file) return -1; - if(fseek(file, 0, SEEK_END) != 0) - { - fclose(file); - return -1; - } + if(fseek(file, 0, SEEK_END) != 0) + { + fclose(file); + return -1; + } - size = ftell(file); - /* It may give LONG_MAX as directory size, this is invalid for us. */ - if(size == LONG_MAX) size = -1; + size = ftell(file); + /* It may give LONG_MAX as directory size, this is invalid for us. */ + if(size == LONG_MAX) size = -1; - fclose(file); - return size; + fclose(file); + return size; } /* load file into buffer that already has the correct allocated size. Returns error code.*/ static unsigned lodepng_buffer_file(uint8_t* out, size_t size, const char* filename) { - FILE* file; - size_t readsize; - file = fopen(filename, "rb"); - if(!file) return 78; + FILE* file; + size_t readsize; + file = fopen(filename, "rb"); + if(!file) return 78; - readsize = fread(out, 1, size, file); - fclose(file); + readsize = fread(out, 1, size, file); + fclose(file); - if (readsize != size) return 78; - return 0; + if(readsize != size) return 78; + return 0; } unsigned lodepng_load_file(uint8_t** out, size_t* outsize, const char* filename) { - long size = lodepng_filesize(filename); - if (size < 0) return 78; - *outsize = (size_t)size; + long size = lodepng_filesize(filename); + if(size < 0) return 78; + *outsize = (size_t)size; - *out = (uint8_t*)lodepng_malloc((size_t)size); - if(!(*out) && size > 0) return 83; /*the above malloc failed*/ + *out = (uint8_t*)lodepng_malloc((size_t)size); + if(!(*out) && size > 0) return 83; /*the above malloc failed*/ - return lodepng_buffer_file(*out, (size_t)size, filename); + return lodepng_buffer_file(*out, (size_t)size, filename); } /*write given buffer to the file, overwriting the file, it doesn't append to it.*/ unsigned lodepng_save_file(const uint8_t* buffer, size_t buffersize, const char* filename) { - FILE* file; - file = fopen(filename, "wb" ); - if(!file) return 79; - fwrite(buffer , 1 , buffersize, file); - fclose(file); - return 0; + FILE* file; + file = fopen(filename, "wb"); + if(!file) return 79; + fwrite(buffer, 1, buffersize, file); + fclose(file); + return 0; } #endif /*LODEPNG_COMPILE_DISK*/ @@ -429,14 +429,14 @@ unsigned lodepng_save_file(const uint8_t* buffer, size_t buffersize, const char* static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) { - size_t i; - for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (uint8_t)((value >> i) & 1)); + size_t i; + for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (uint8_t)((value >> i) & 1)); } static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) { - size_t i; - for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (uint8_t)((value >> (nbits - 1 - i)) & 1)); + size_t i; + for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (uint8_t)((value >> (nbits - 1 - i)) & 1)); } #endif /*LODEPNG_COMPILE_ENCODER*/ @@ -446,20 +446,20 @@ static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, uns static uint8_t readBitFromStream(size_t* bitpointer, const uint8_t* bitstream) { - uint8_t result = (uint8_t)(READBIT(*bitpointer, bitstream)); - ++(*bitpointer); - return result; + uint8_t result = (uint8_t)(READBIT(*bitpointer, bitstream)); + ++(*bitpointer); + return result; } static unsigned readBitsFromStream(size_t* bitpointer, const uint8_t* bitstream, size_t nbits) { - unsigned result = 0, i; - for(i = 0; i != nbits; ++i) - { - result += ((unsigned)READBIT(*bitpointer, bitstream)) << i; - ++(*bitpointer); - } - return result; + unsigned result = 0, i; + for(i = 0; i != nbits; ++i) + { + result += ((unsigned)READBIT(*bitpointer, bitstream)) << i; + ++(*bitpointer); + } + return result; } #endif /*LODEPNG_COMPILE_DECODER*/ @@ -478,28 +478,32 @@ static unsigned readBitsFromStream(size_t* bitpointer, const uint8_t* bitstream, /*the base lengths represented by codes 257-285*/ static const unsigned LENGTHBASE[29] - = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, - 67, 83, 99, 115, 131, 163, 195, 227, 258}; + = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, + 67, 83, 99, 115, 131, 163, 195, 227, 258 + }; /*the extra bits used by codes 257-285 (added to base length)*/ static const unsigned LENGTHEXTRA[29] - = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, - 4, 4, 4, 4, 5, 5, 5, 5, 0}; + = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, + 4, 4, 4, 4, 5, 5, 5, 5, 0 + }; /*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/ static const unsigned DISTANCEBASE[30] - = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, - 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, + 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 + }; /*the extra bits of backwards distances (added to base)*/ static const unsigned DISTANCEEXTRA[30] - = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, - 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 + }; /*the order in which "code length alphabet code lengths" are stored, out of this the huffman tree of the dynamic huffman tree lengths is generated*/ static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES] - = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; /* ////////////////////////////////////////////////////////////////////////// */ @@ -508,11 +512,11 @@ Huffman tree struct, containing multiple representations of the tree */ typedef struct HuffmanTree { - unsigned* tree2d; - unsigned* tree1d; - unsigned* lengths; /*the lengths of the codes of the 1d-tree*/ - unsigned maxbitlen; /*maximum number of bits a single code can get*/ - unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ + unsigned* tree2d; + unsigned* tree1d; + unsigned* lengths; /*the lengths of the codes of the 1d-tree*/ + unsigned maxbitlen; /*maximum number of bits a single code can get*/ + unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ } HuffmanTree; /*function used for debug purposes to draw the tree in ascii art with C++*/ @@ -530,77 +534,77 @@ static void HuffmanTree_draw(HuffmanTree* tree) static void HuffmanTree_init(HuffmanTree* tree) { - tree->tree2d = 0; - tree->tree1d = 0; - tree->lengths = 0; + tree->tree2d = 0; + tree->tree1d = 0; + tree->lengths = 0; } static void HuffmanTree_cleanup(HuffmanTree* tree) { - lodepng_free(tree->tree2d); - lodepng_free(tree->tree1d); - lodepng_free(tree->lengths); + lodepng_free(tree->tree2d); + lodepng_free(tree->tree1d); + lodepng_free(tree->lengths); } /*the tree representation used by the decoder. return value is error*/ static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) { - unsigned nodefilled = 0; /*up to which node it is filled*/ - unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/ - unsigned n, i; + unsigned nodefilled = 0; /*up to which node it is filled*/ + unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/ + unsigned n, i; - tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned)); - if(!tree->tree2d) return 83; /*alloc fail*/ + tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned)); + if(!tree->tree2d) return 83; /*alloc fail*/ - /* - convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means - uninited, a value >= numcodes is an address to another bit, a value < numcodes - is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as - many columns as codes - 1. - A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. - Here, the internal nodes are stored (what their 0 and 1 option point to). - There is only memory for such good tree currently, if there are more nodes - (due to too long length codes), error 55 will happen - */ - for(n = 0; n < tree->numcodes * 2; ++n) - { - tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/ - } + /* + convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means + uninited, a value >= numcodes is an address to another bit, a value < numcodes + is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as + many columns as codes - 1. + A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. + Here, the internal nodes are stored (what their 0 and 1 option point to). + There is only memory for such good tree currently, if there are more nodes + (due to too long length codes), error 55 will happen + */ + for(n = 0; n < tree->numcodes * 2; ++n) + { + tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/ + } - for(n = 0; n < tree->numcodes; ++n) /*the codes*/ - { - for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ - { - uint8_t bit = (uint8_t)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1); - /*oversubscribed, see comment in lodepng_error_text*/ - if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55; - if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ - { - if(i + 1 == tree->lengths[n]) /*last bit*/ - { - tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/ - treepos = 0; - } - else - { - /*put address of the next step in here, first that address has to be found of course - (it's just nodefilled + 1)...*/ - ++nodefilled; - /*addresses encoded with numcodes added to it*/ - tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes; - treepos = nodefilled; - } - } - else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes; - } - } + for(n = 0; n < tree->numcodes; ++n) /*the codes*/ + { + for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ + { + uint8_t bit = (uint8_t)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1); + /*oversubscribed, see comment in lodepng_error_text*/ + if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55; + if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ + { + if(i + 1 == tree->lengths[n]) /*last bit*/ + { + tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/ + treepos = 0; + } + else + { + /*put address of the next step in here, first that address has to be found of course + (it's just nodefilled + 1)...*/ + ++nodefilled; + /*addresses encoded with numcodes added to it*/ + tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes; + treepos = nodefilled; + } + } + else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes; + } + } - for(n = 0; n < tree->numcodes * 2; ++n) - { - if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/ - } + for(n = 0; n < tree->numcodes * 2; ++n) + { + if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/ + } - return 0; + return 0; } /* @@ -610,42 +614,42 @@ value is error. */ static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) { - uivector blcount; - uivector nextcode; - unsigned error = 0; - unsigned bits, n; + uivector blcount; + uivector nextcode; + unsigned error = 0; + unsigned bits, n; - uivector_init(&blcount); - uivector_init(&nextcode); + uivector_init(&blcount); + uivector_init(&nextcode); - tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned)); - if(!tree->tree1d) error = 83; /*alloc fail*/ + tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned)); + if(!tree->tree1d) error = 83; /*alloc fail*/ - if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0) - || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0)) - error = 83; /*alloc fail*/ + if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0) + || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0)) + error = 83; /*alloc fail*/ - if(!error) - { - /*step 1: count number of instances of each code length*/ - for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]]; - /*step 2: generate the nextcode values*/ - for(bits = 1; bits <= tree->maxbitlen; ++bits) - { - nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1; - } - /*step 3: generate all the codes*/ - for(n = 0; n != tree->numcodes; ++n) - { - if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++; - } - } + if(!error) + { + /*step 1: count number of instances of each code length*/ + for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]]; + /*step 2: generate the nextcode values*/ + for(bits = 1; bits <= tree->maxbitlen; ++bits) + { + nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1; + } + /*step 3: generate all the codes*/ + for(n = 0; n != tree->numcodes; ++n) + { + if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++; + } + } - uivector_cleanup(&blcount); - uivector_cleanup(&nextcode); + uivector_cleanup(&blcount); + uivector_cleanup(&nextcode); - if(!error) return HuffmanTree_make2DTree(tree); - else return error; + if(!error) return HuffmanTree_make2DTree(tree); + else return error; } /* @@ -654,15 +658,15 @@ by Deflate. maxbitlen is the maximum bits that a code in the tree can have. return value is error. */ static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, - size_t numcodes, unsigned maxbitlen) + size_t numcodes, unsigned maxbitlen) { - unsigned i; - tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); - if(!tree->lengths) return 83; /*alloc fail*/ - for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i]; - tree->numcodes = (unsigned)numcodes; /*number of symbols*/ - tree->maxbitlen = maxbitlen; - return HuffmanTree_makeFromLengths2(tree); + unsigned i; + tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i]; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + tree->maxbitlen = maxbitlen; + return HuffmanTree_makeFromLengths2(tree); } #ifdef LODEPNG_COMPILE_ENCODER @@ -673,269 +677,269 @@ Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/ /*chain node for boundary package merge*/ typedef struct BPMNode { - int32_t weight; /*the sum of all weights in this chain*/ - unsigned index; /*index of this leaf node (called "count" in the paper)*/ - struct BPMNode* tail; /*the next nodes in this chain (null if last)*/ - int32_t in_use; + int32_t weight; /*the sum of all weights in this chain*/ + unsigned index; /*index of this leaf node (called "count" in the paper)*/ + struct BPMNode* tail; /*the next nodes in this chain (null if last)*/ + int32_t in_use; } BPMNode; /*lists of chains*/ typedef struct BPMLists { - /*memory pool*/ - unsigned memsize; - BPMNode* memory; - unsigned numfree; - unsigned nextfree; - BPMNode** freelist; - /*two heads of lookahead chains per list*/ - unsigned listsize; - BPMNode** chains0; - BPMNode** chains1; + /*memory pool*/ + unsigned memsize; + BPMNode* memory; + unsigned numfree; + unsigned nextfree; + BPMNode** freelist; + /*two heads of lookahead chains per list*/ + unsigned listsize; + BPMNode** chains0; + BPMNode** chains1; } BPMLists; /*creates a new chain node with the given parameters, from the memory in the lists */ static BPMNode* bpmnode_create(BPMLists* lists, int32_t weight, unsigned index, BPMNode* tail) { - unsigned i; - BPMNode* result; + unsigned i; + BPMNode* result; - /*memory full, so garbage collect*/ - if(lists->nextfree >= lists->numfree) - { - /*mark only those that are in use*/ - for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0; - for(i = 0; i != lists->listsize; ++i) - { - BPMNode* node; - for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1; - for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1; - } - /*collect those that are free*/ - lists->numfree = 0; - for(i = 0; i != lists->memsize; ++i) - { - if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i]; - } - lists->nextfree = 0; - } + /*memory full, so garbage collect*/ + if(lists->nextfree >= lists->numfree) + { + /*mark only those that are in use*/ + for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0; + for(i = 0; i != lists->listsize; ++i) + { + BPMNode* node; + for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1; + for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1; + } + /*collect those that are free*/ + lists->numfree = 0; + for(i = 0; i != lists->memsize; ++i) + { + if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i]; + } + lists->nextfree = 0; + } - result = lists->freelist[lists->nextfree++]; - result->weight = weight; - result->index = index; - result->tail = tail; - return result; + result = lists->freelist[lists->nextfree++]; + result->weight = weight; + result->index = index; + result->tail = tail; + return result; } /*sort the leaves with stable mergesort*/ static void bpmnode_sort(BPMNode* leaves, size_t num) { - BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num); - size_t width, counter = 0; - for(width = 1; width < num; width *= 2) - { - BPMNode* a = (counter & 1) ? mem : leaves; - BPMNode* b = (counter & 1) ? leaves : mem; - size_t p; - for(p = 0; p < num; p += 2 * width) - { - size_t q = (p + width > num) ? num : (p + width); - size_t r = (p + 2 * width > num) ? num : (p + 2 * width); - size_t i = p, j = q, k; - for(k = p; k < r; k++) - { - if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++]; - else b[k] = a[j++]; - } - } - counter++; - } - if(counter & 1) memcpy(leaves, mem, sizeof(*leaves) * num); - lodepng_free(mem); + BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num); + size_t width, counter = 0; + for(width = 1; width < num; width *= 2) + { + BPMNode* a = (counter & 1) ? mem : leaves; + BPMNode* b = (counter & 1) ? leaves : mem; + size_t p; + for(p = 0; p < num; p += 2 * width) + { + size_t q = (p + width > num) ? num : (p + width); + size_t r = (p + 2 * width > num) ? num : (p + 2 * width); + size_t i = p, j = q, k; + for(k = p; k < r; k++) + { + if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++]; + else b[k] = a[j++]; + } + } + counter++; + } + if(counter & 1) memcpy(leaves, mem, sizeof(*leaves) * num); + lodepng_free(mem); } /*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/ static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int32_t c, int32_t num) { - unsigned lastindex = lists->chains1[c]->index; + unsigned lastindex = lists->chains1[c]->index; - if(c == 0) - { - if(lastindex >= numpresent) return; - lists->chains0[c] = lists->chains1[c]; - lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0); - } - else - { - /*sum of the weights of the head nodes of the previous lookahead chains.*/ - int32_t sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight; - lists->chains0[c] = lists->chains1[c]; - if(lastindex < numpresent && sum > leaves[lastindex].weight) - { - lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail); - return; - } - lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]); - /*in the end we are only interested in the chain of the last list, so no - need to recurse if we're at the last one (this gives measurable speedup)*/ - if(num + 1 < (int32_t)(2 * numpresent - 2)) - { - boundaryPM(lists, leaves, numpresent, c - 1, num); - boundaryPM(lists, leaves, numpresent, c - 1, num); - } - } + if(c == 0) + { + if(lastindex >= numpresent) return; + lists->chains0[c] = lists->chains1[c]; + lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0); + } + else + { + /*sum of the weights of the head nodes of the previous lookahead chains.*/ + int32_t sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight; + lists->chains0[c] = lists->chains1[c]; + if(lastindex < numpresent && sum > leaves[lastindex].weight) + { + lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail); + return; + } + lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]); + /*in the end we are only interested in the chain of the last list, so no + need to recurse if we're at the last one (this gives measurable speedup)*/ + if(num + 1 < (int32_t)(2 * numpresent - 2)) + { + boundaryPM(lists, leaves, numpresent, c - 1, num); + boundaryPM(lists, leaves, numpresent, c - 1, num); + } + } } unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, size_t numcodes, unsigned maxbitlen) { - unsigned error = 0; - unsigned i; - size_t numpresent = 0; /*number of symbols with non-zero frequency*/ - BPMNode* leaves; /*the symbols, only those with > 0 frequency*/ + unsigned error = 0; + unsigned i; + size_t numpresent = 0; /*number of symbols with non-zero frequency*/ + BPMNode* leaves; /*the symbols, only those with > 0 frequency*/ - if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ - if((1u << maxbitlen) < numcodes) return 80; /*error: represent all symbols*/ + if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ + if((1u << maxbitlen) < numcodes) return 80; /*error: represent all symbols*/ - leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves)); - if(!leaves) return 83; /*alloc fail*/ + leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves)); + if(!leaves) return 83; /*alloc fail*/ - for(i = 0; i != numcodes; ++i) - { - if(frequencies[i] > 0) - { - leaves[numpresent].weight = (int32_t)frequencies[i]; - leaves[numpresent].index = i; - ++numpresent; - } - } + for(i = 0; i != numcodes; ++i) + { + if(frequencies[i] > 0) + { + leaves[numpresent].weight = (int32_t)frequencies[i]; + leaves[numpresent].index = i; + ++numpresent; + } + } - for(i = 0; i != numcodes; ++i) lengths[i] = 0; + for(i = 0; i != numcodes; ++i) lengths[i] = 0; - /*ensure at least two present symbols. There should be at least one symbol - according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To - make these work as well ensure there are at least two symbols. The - Package-Merge code below also doesn't work correctly if there's only one - symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/ - if(numpresent == 0) - { - lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ - } - else if(numpresent == 1) - { - lengths[leaves[0].index] = 1; - lengths[leaves[0].index == 0 ? 1 : 0] = 1; - } - else - { - BPMLists lists; - BPMNode* node; + /*ensure at least two present symbols. There should be at least one symbol + according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To + make these work as well ensure there are at least two symbols. The + Package-Merge code below also doesn't work correctly if there's only one + symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/ + if(numpresent == 0) + { + lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ + } + else if(numpresent == 1) + { + lengths[leaves[0].index] = 1; + lengths[leaves[0].index == 0 ? 1 : 0] = 1; + } + else + { + BPMLists lists; + BPMNode* node; - bpmnode_sort(leaves, numpresent); + bpmnode_sort(leaves, numpresent); - lists.listsize = maxbitlen; - lists.memsize = 2 * maxbitlen * (maxbitlen + 1); - lists.nextfree = 0; - lists.numfree = lists.memsize; - lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory)); - lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*)); - lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); - lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); - if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/ + lists.listsize = maxbitlen; + lists.memsize = 2 * maxbitlen * (maxbitlen + 1); + lists.nextfree = 0; + lists.numfree = lists.memsize; + lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory)); + lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*)); + lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); + lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); + if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/ - if(!error) - { - for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i]; + if(!error) + { + for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i]; - bpmnode_create(&lists, leaves[0].weight, 1, 0); - bpmnode_create(&lists, leaves[1].weight, 2, 0); + bpmnode_create(&lists, leaves[0].weight, 1, 0); + bpmnode_create(&lists, leaves[1].weight, 2, 0); - for(i = 0; i != lists.listsize; ++i) - { - lists.chains0[i] = &lists.memory[0]; - lists.chains1[i] = &lists.memory[1]; - } + for(i = 0; i != lists.listsize; ++i) + { + lists.chains0[i] = &lists.memory[0]; + lists.chains1[i] = &lists.memory[1]; + } - /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/ - for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int32_t)maxbitlen - 1, (int32_t)i); + /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/ + for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int32_t)maxbitlen - 1, (int32_t)i); - for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) - { - for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index]; - } - } + for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) + { + for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index]; + } + } - lodepng_free(lists.memory); - lodepng_free(lists.freelist); - lodepng_free(lists.chains0); - lodepng_free(lists.chains1); - } + lodepng_free(lists.memory); + lodepng_free(lists.freelist); + lodepng_free(lists.chains0); + lodepng_free(lists.chains1); + } - lodepng_free(leaves); - return error; + lodepng_free(leaves); + return error; } /*Create the Huffman tree given the symbol frequencies*/ static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, - size_t mincodes, size_t numcodes, unsigned maxbitlen) + size_t mincodes, size_t numcodes, unsigned maxbitlen) { - unsigned error = 0; - while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/ - tree->maxbitlen = maxbitlen; - tree->numcodes = (unsigned)numcodes; /*number of symbols*/ - tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned)); - if(!tree->lengths) return 83; /*alloc fail*/ - /*initialize all lengths to 0*/ - memset(tree->lengths, 0, numcodes * sizeof(unsigned)); + unsigned error = 0; + while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/ + tree->maxbitlen = maxbitlen; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + /*initialize all lengths to 0*/ + memset(tree->lengths, 0, numcodes * sizeof(unsigned)); - error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); - if(!error) error = HuffmanTree_makeFromLengths2(tree); - return error; + error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); + if(!error) error = HuffmanTree_makeFromLengths2(tree); + return error; } static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) { - return tree->tree1d[index]; + return tree->tree1d[index]; } static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) { - return tree->lengths[index]; + return tree->lengths[index]; } #endif /*LODEPNG_COMPILE_ENCODER*/ /*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/ static unsigned generateFixedLitLenTree(HuffmanTree* tree) { - unsigned i, error = 0; - unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); - if(!bitlen) return 83; /*alloc fail*/ + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ - /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/ - for(i = 0; i <= 143; ++i) bitlen[i] = 8; - for(i = 144; i <= 255; ++i) bitlen[i] = 9; - for(i = 256; i <= 279; ++i) bitlen[i] = 7; - for(i = 280; i <= 287; ++i) bitlen[i] = 8; + /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/ + for(i = 0; i <= 143; ++i) bitlen[i] = 8; + for(i = 144; i <= 255; ++i) bitlen[i] = 9; + for(i = 256; i <= 279; ++i) bitlen[i] = 7; + for(i = 280; i <= 287; ++i) bitlen[i] = 8; - error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15); + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15); - lodepng_free(bitlen); - return error; + lodepng_free(bitlen); + return error; } /*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/ static unsigned generateFixedDistanceTree(HuffmanTree* tree) { - unsigned i, error = 0; - unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); - if(!bitlen) return 83; /*alloc fail*/ + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ - /*there are 32 distance codes, but 30-31 are unused*/ - for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5; - error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15); + /*there are 32 distance codes, but 30-31 are unused*/ + for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5; + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15); - lodepng_free(bitlen); - return error; + lodepng_free(bitlen); + return error; } #ifdef LODEPNG_COMPILE_DECODER @@ -947,21 +951,21 @@ inbitlength is the length of the complete buffer, in bits (so its byte length ti static unsigned huffmanDecodeSymbol(const uint8_t* in, size_t* bp, const HuffmanTree* codetree, size_t inbitlength) { - unsigned treepos = 0, ct; - for(;;) - { - if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/ - /* - decode the symbol from the tree. The "readBitFromStream" code is inlined in - the expression below because this is the biggest bottleneck while decoding - */ - ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)]; - ++(*bp); - if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/ - else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/ + unsigned treepos = 0, ct; + for(;;) + { + if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/ + /* + decode the symbol from the tree. The "readBitFromStream" code is inlined in + the expression below because this is the biggest bottleneck while decoding + */ + ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)]; + ++(*bp); + if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/ + else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/ - if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/ - } + if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/ + } } #endif /*LODEPNG_COMPILE_DECODER*/ @@ -974,337 +978,342 @@ static unsigned huffmanDecodeSymbol(const uint8_t* in, size_t* bp, /*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/ static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) { - /*TODO: check for out of memory errors*/ - generateFixedLitLenTree(tree_ll); - generateFixedDistanceTree(tree_d); + /*TODO: check for out of memory errors*/ + generateFixedLitLenTree(tree_ll); + generateFixedDistanceTree(tree_d); } /*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/ static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, const uint8_t* in, size_t* bp, size_t inlength) { - /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ - unsigned error = 0; - unsigned n, HLIT, HDIST, HCLEN, i; - size_t inbitlength = inlength * 8; + /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ + unsigned error = 0; + unsigned n, HLIT, HDIST, HCLEN, i; + size_t inbitlength = inlength * 8; - /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/ - unsigned* bitlen_ll = 0; /*lit,len code lengths*/ - unsigned* bitlen_d = 0; /*dist code lengths*/ - /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/ - unsigned* bitlen_cl = 0; - HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/ + /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/ + unsigned* bitlen_ll = 0; /*lit,len code lengths*/ + unsigned* bitlen_d = 0; /*dist code lengths*/ + /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/ + unsigned* bitlen_cl = 0; + HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/ - if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/ + if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/ - /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ - HLIT = readBitsFromStream(bp, in, 5) + 257; - /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ - HDIST = readBitsFromStream(bp, in, 5) + 1; - /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ - HCLEN = readBitsFromStream(bp, in, 4) + 4; + /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ + HLIT = readBitsFromStream(bp, in, 5) + 257; + /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ + HDIST = readBitsFromStream(bp, in, 5) + 1; + /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ + HCLEN = readBitsFromStream(bp, in, 4) + 4; - if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/ + if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/ - HuffmanTree_init(&tree_cl); + HuffmanTree_init(&tree_cl); - while(!error) - { - /*read the code length codes out of 3 * (amount of code length codes) bits*/ + while(!error) + { + /*read the code length codes out of 3 * (amount of code length codes) bits*/ - bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); - if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/); + bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); + if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i) - { - if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3); - else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/ - } + for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i) + { + if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3); + else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/ + } - error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7); - if(error) break; + error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7); + if(error) break; - /*now we can use this tree to read the lengths for the tree that this function will return*/ - bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); - bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); - if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0; - for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0; + /*now we can use this tree to read the lengths for the tree that this function will return*/ + bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/); + for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0; + for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0; - /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ - i = 0; - while(i < HLIT + HDIST) - { - unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength); - if(code <= 15) /*a length code*/ - { - if(i < HLIT) bitlen_ll[i] = code; - else bitlen_d[i - HLIT] = code; - ++i; - } - else if(code == 16) /*repeat previous*/ - { - unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ - unsigned value; /*set value to the previous code*/ + /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ + i = 0; + while(i < HLIT + HDIST) + { + unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength); + if(code <= 15) /*a length code*/ + { + if(i < HLIT) bitlen_ll[i] = code; + else bitlen_d[i - HLIT] = code; + ++i; + } + else if(code == 16) /*repeat previous*/ + { + unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ + unsigned value; /*set value to the previous code*/ - if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/ + if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/ - if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ - replength += readBitsFromStream(bp, in, 2); + if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + replength += readBitsFromStream(bp, in, 2); - if(i < HLIT + 1) value = bitlen_ll[i - 1]; - else value = bitlen_d[i - HLIT - 1]; - /*repeat this value in the next lengths*/ - for(n = 0; n < replength; ++n) - { - if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ - if(i < HLIT) bitlen_ll[i] = value; - else bitlen_d[i - HLIT] = value; - ++i; - } - } - else if(code == 17) /*repeat "0" 3-10 times*/ - { - unsigned replength = 3; /*read in the bits that indicate repeat length*/ - if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ - replength += readBitsFromStream(bp, in, 3); + if(i < HLIT + 1) value = bitlen_ll[i - 1]; + else value = bitlen_d[i - HLIT - 1]; + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) + { + if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ + if(i < HLIT) bitlen_ll[i] = value; + else bitlen_d[i - HLIT] = value; + ++i; + } + } + else if(code == 17) /*repeat "0" 3-10 times*/ + { + unsigned replength = 3; /*read in the bits that indicate repeat length*/ + if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + replength += readBitsFromStream(bp, in, 3); - /*repeat this value in the next lengths*/ - for(n = 0; n < replength; ++n) - { - if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) + { + if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ - if(i < HLIT) bitlen_ll[i] = 0; - else bitlen_d[i - HLIT] = 0; - ++i; - } - } - else if(code == 18) /*repeat "0" 11-138 times*/ - { - unsigned replength = 11; /*read in the bits that indicate repeat length*/ - if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ - replength += readBitsFromStream(bp, in, 7); + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } + else if(code == 18) /*repeat "0" 11-138 times*/ + { + unsigned replength = 11; /*read in the bits that indicate repeat length*/ + if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + replength += readBitsFromStream(bp, in, 7); - /*repeat this value in the next lengths*/ - for(n = 0; n < replength; ++n) - { - if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) + { + if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ - if(i < HLIT) bitlen_ll[i] = 0; - else bitlen_d[i - HLIT] = 0; - ++i; - } - } - else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ - { - if(code == (unsigned)(-1)) - { - /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol - (10=no endcode, 11=wrong jump outside of tree)*/ - error = (*bp) > inbitlength ? 10 : 11; - } - else error = 16; /*unexisting code, this can never happen*/ - break; - } - } - if(error) break; + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } + else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + { + if(code == (unsigned)(-1)) + { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + error = (*bp) > inbitlength ? 10 : 11; + } + else error = 16; /*unexisting code, this can never happen*/ + break; + } + } + if(error) break; - if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/ + if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/ - /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/ - error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15); - if(error) break; - error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15); + /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/ + error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15); + if(error) break; + error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15); - break; /*end of error-while*/ - } + break; /*end of error-while*/ + } - lodepng_free(bitlen_cl); - lodepng_free(bitlen_ll); - lodepng_free(bitlen_d); - HuffmanTree_cleanup(&tree_cl); + lodepng_free(bitlen_cl); + lodepng_free(bitlen_ll); + lodepng_free(bitlen_d); + HuffmanTree_cleanup(&tree_cl); - return error; + return error; } /*inflate a block with dynamic of fixed Huffman tree*/ static unsigned inflateHuffmanBlock(ucvector* out, const uint8_t* in, size_t* bp, size_t* pos, size_t inlength, unsigned btype) { - unsigned error = 0; - HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ - HuffmanTree tree_d; /*the huffman tree for distance codes*/ - size_t inbitlength = inlength * 8; + unsigned error = 0; + HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ + HuffmanTree tree_d; /*the huffman tree for distance codes*/ + size_t inbitlength = inlength * 8; - HuffmanTree_init(&tree_ll); - HuffmanTree_init(&tree_d); + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); - if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d); - else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength); + if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d); + else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength); - while(!error) /*decode all symbols until end reached, breaks at end code*/ - { - /*code_ll is literal, length or end code*/ - unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength); - if(code_ll <= 255) /*literal symbol*/ - { - /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/ - if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/); - out->data[*pos] = (uint8_t)code_ll; - ++(*pos); - } - else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ - { - unsigned code_d, distance; - unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ - size_t start, forward, backward, length; + while(!error) /*decode all symbols until end reached, breaks at end code*/ + { + /*code_ll is literal, length or end code*/ + unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength); + if(code_ll <= 255) /*literal symbol*/ + { + /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/ + if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/); + out->data[*pos] = (uint8_t)code_ll; + ++(*pos); + } + else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ + { + unsigned code_d, distance; + unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ + size_t start, forward, backward, length; - /*part 1: get length base*/ - length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX]; + /*part 1: get length base*/ + length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX]; - /*part 2: get extra bits and add the value of that to length*/ - numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX]; - if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ - length += readBitsFromStream(bp, in, numextrabits_l); + /*part 2: get extra bits and add the value of that to length*/ + numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX]; + if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ + length += readBitsFromStream(bp, in, numextrabits_l); - /*part 3: get distance code*/ - code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength); - if(code_d > 29) - { - if(code_d == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ - { - /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol - (10=no endcode, 11=wrong jump outside of tree)*/ - error = (*bp) > inlength * 8 ? 10 : 11; - } - else error = 18; /*error: invalid distance code (30-31 are never used)*/ - break; - } - distance = DISTANCEBASE[code_d]; + /*part 3: get distance code*/ + code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength); + if(code_d > 29) + { + if(code_d == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + error = (*bp) > inlength * 8 ? 10 : 11; + } + else error = 18; /*error: invalid distance code (30-31 are never used)*/ + break; + } + distance = DISTANCEBASE[code_d]; - /*part 4: get extra bits from distance*/ - numextrabits_d = DISTANCEEXTRA[code_d]; - if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ - distance += readBitsFromStream(bp, in, numextrabits_d); + /*part 4: get extra bits from distance*/ + numextrabits_d = DISTANCEEXTRA[code_d]; + if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ + distance += readBitsFromStream(bp, in, numextrabits_d); - /*part 5: fill in all the out[n] values based on the length and dist*/ - start = (*pos); - if(distance > start) ERROR_BREAK(52); /*too long backward distance*/ - backward = start - distance; + /*part 5: fill in all the out[n] values based on the length and dist*/ + start = (*pos); + if(distance > start) ERROR_BREAK(52); /*too long backward distance*/ + backward = start - distance; - if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/); - if (distance < length) { - for(forward = 0; forward < length; ++forward) - { - out->data[(*pos)++] = out->data[backward++]; - } - } else { - memcpy(out->data + *pos, out->data + backward, length); - *pos += length; - } - } - else if(code_ll == 256) - { - break; /*end code, break the loop*/ - } - else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ - { - /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol - (10=no endcode, 11=wrong jump outside of tree)*/ - error = ((*bp) > inlength * 8) ? 10 : 11; - break; - } - } + if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/); + if(distance < length) + { + for(forward = 0; forward < length; ++forward) + { + out->data[(*pos)++] = out->data[backward++]; + } + } + else + { + memcpy(out->data + *pos, out->data + backward, length); + *pos += length; + } + } + else if(code_ll == 256) + { + break; /*end code, break the loop*/ + } + else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + error = ((*bp) > inlength * 8) ? 10 : 11; + break; + } + } - HuffmanTree_cleanup(&tree_ll); - HuffmanTree_cleanup(&tree_d); + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); - return error; + return error; } static unsigned inflateNoCompression(ucvector* out, const uint8_t* in, size_t* bp, size_t* pos, size_t inlength) { - size_t p; - unsigned LEN, NLEN, n, error = 0; + size_t p; + unsigned LEN, NLEN, n, error = 0; - /*go to first boundary of byte*/ - while(((*bp) & 0x7) != 0) ++(*bp); - p = (*bp) / 8; /*byte position*/ + /*go to first boundary of byte*/ + while(((*bp) & 0x7) != 0) ++(*bp); + p = (*bp) / 8; /*byte position*/ - /*read LEN (2 bytes) and NLEN (2 bytes)*/ - if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/ - LEN = in[p] + 256u * in[p + 1]; p += 2; - NLEN = in[p] + 256u * in[p + 1]; p += 2; + /*read LEN (2 bytes) and NLEN (2 bytes)*/ + if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/ + LEN = in[p] + 256u * in[p + 1]; + p += 2; + NLEN = in[p] + 256u * in[p + 1]; + p += 2; - /*check if 16-bit NLEN is really the one's complement of LEN*/ - if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/ + /*check if 16-bit NLEN is really the one's complement of LEN*/ + if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/ - if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/ + if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/ - /*read the literal data: LEN bytes are now stored in the out buffer*/ - if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/ - for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++]; + /*read the literal data: LEN bytes are now stored in the out buffer*/ + if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/ + for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++]; - (*bp) = p * 8; + (*bp) = p * 8; - return error; + return error; } static unsigned lodepng_inflatev(ucvector* out, const uint8_t* in, size_t insize, const LodePNGDecompressSettings* settings) { - /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/ - size_t bp = 0; - unsigned BFINAL = 0; - size_t pos = 0; /*byte position in the out buffer*/ - unsigned error = 0; + /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/ + size_t bp = 0; + unsigned BFINAL = 0; + size_t pos = 0; /*byte position in the out buffer*/ + unsigned error = 0; - (void)settings; + (void)settings; - while(!BFINAL) - { - unsigned BTYPE; - if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/ - BFINAL = readBitFromStream(&bp, in); - BTYPE = 1u * readBitFromStream(&bp, in); - BTYPE += 2u * readBitFromStream(&bp, in); + while(!BFINAL) + { + unsigned BTYPE; + if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/ + BFINAL = readBitFromStream(&bp, in); + BTYPE = 1u * readBitFromStream(&bp, in); + BTYPE += 2u * readBitFromStream(&bp, in); - if(BTYPE == 3) return 20; /*error: invalid BTYPE*/ - else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/ - else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/ + if(BTYPE == 3) return 20; /*error: invalid BTYPE*/ + else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/ + else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/ - if(error) return error; - } + if(error) return error; + } - return error; + return error; } unsigned lodepng_inflate(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGDecompressSettings* settings) { - unsigned error; - ucvector v; - ucvector_init_buffer(&v, *out, *outsize); - error = lodepng_inflatev(&v, in, insize, settings); - *out = v.data; - *outsize = v.size; - return error; + unsigned error; + ucvector v; + ucvector_init_buffer(&v, *out, *outsize); + error = lodepng_inflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; } static unsigned inflate(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGDecompressSettings* settings) { - if(settings->custom_inflate) - { - return settings->custom_inflate(out, outsize, in, insize, settings); - } - else - { - return lodepng_inflate(out, outsize, in, insize, settings); - } + if(settings->custom_inflate) + { + return settings->custom_inflate(out, outsize, in, insize, settings); + } + else + { + return lodepng_inflate(out, outsize, in, insize, settings); + } } #endif /*LODEPNG_COMPILE_DECODER*/ @@ -1320,43 +1329,44 @@ static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258; /*bitlen is the size in bits of the code*/ static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen) { - addBitsToStreamReversed(bp, compressed, code, bitlen); + addBitsToStreamReversed(bp, compressed, code, bitlen); } /*search the index in the array, that has the largest value smaller than or equal to the given value, given array must be sorted (if no value is smaller, it returns the size of the given array)*/ static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) { - /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/ - size_t left = 1; - size_t right = array_size - 1; + /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/ + size_t left = 1; + size_t right = array_size - 1; - while(left <= right) { - size_t mid = (left + right) >> 1; - if (array[mid] >= value) right = mid - 1; - else left = mid + 1; - } - if(left >= array_size || array[left] > value) left--; - return left; + while(left <= right) + { + size_t mid = (left + right) >> 1; + if(array[mid] >= value) right = mid - 1; + else left = mid + 1; + } + if(left >= array_size || array[left] > value) left--; + return left; } static void addLengthDistance(uivector* values, size_t length, size_t distance) { - /*values in encoded vector are those used by deflate: - 0-255: literal bytes - 256: end - 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits) - 286-287: invalid*/ + /*values in encoded vector are those used by deflate: + 0-255: literal bytes + 256: end + 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits) + 286-287: invalid*/ - unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length); - unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]); - unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance); - unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]); + unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length); + unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]); + unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance); + unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]); - uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX); - uivector_push_back(values, extra_length); - uivector_push_back(values, dist_code); - uivector_push_back(values, extra_distance); + uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX); + uivector_push_back(values, extra_length); + uivector_push_back(values, dist_code); + uivector_push_back(values, extra_distance); } /*3 bytes of data get encoded into two bytes. The hash cannot use more than 3 @@ -1366,100 +1376,102 @@ static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does typedef struct Hash { - int32_t* head; /*hash value to head circular pos - can be outdated if went around window*/ - /*circular pos to prev circular pos*/ - uint16_t* chain; - int32_t* val; /*circular pos to hash value*/ + int32_t* head; /*hash value to head circular pos - can be outdated if went around window*/ + /*circular pos to prev circular pos*/ + uint16_t* chain; + int32_t* val; /*circular pos to hash value*/ - /*TODO: do this not only for zeros but for any repeated byte. However for PNG - it's always going to be the zeros that dominate, so not important for PNG*/ - int32_t* headz; /*similar to head, but for chainz*/ - uint16_t* chainz; /*those with same amount of zeros*/ - uint16_t* zeros; /*length of zeros streak, used as a second hash chain*/ + /*TODO: do this not only for zeros but for any repeated byte. However for PNG + it's always going to be the zeros that dominate, so not important for PNG*/ + int32_t* headz; /*similar to head, but for chainz*/ + uint16_t* chainz; /*those with same amount of zeros*/ + uint16_t* zeros; /*length of zeros streak, used as a second hash chain*/ } Hash; static unsigned hash_init(Hash* hash, unsigned windowsize) { - unsigned i; - hash->head = (int32_t*)lodepng_malloc(sizeof(int32_t) * HASH_NUM_VALUES); - hash->val = (int32_t*)lodepng_malloc(sizeof(int32_t) * windowsize); - hash->chain = (uint16_t*)lodepng_malloc(sizeof(uint16_t) * windowsize); + unsigned i; + hash->head = (int32_t*)lodepng_malloc(sizeof(int32_t) * HASH_NUM_VALUES); + hash->val = (int32_t*)lodepng_malloc(sizeof(int32_t) * windowsize); + hash->chain = (uint16_t*)lodepng_malloc(sizeof(uint16_t) * windowsize); - hash->zeros = (uint16_t*)lodepng_malloc(sizeof(uint16_t) * windowsize); - hash->headz = (int32_t*)lodepng_malloc(sizeof(int32_t) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); - hash->chainz = (uint16_t*)lodepng_malloc(sizeof(uint16_t) * windowsize); + hash->zeros = (uint16_t*)lodepng_malloc(sizeof(uint16_t) * windowsize); + hash->headz = (int32_t*)lodepng_malloc(sizeof(int32_t) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); + hash->chainz = (uint16_t*)lodepng_malloc(sizeof(uint16_t) * windowsize); - if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) - { - return 83; /*alloc fail*/ - } + if(!hash->head || !hash->chain || !hash->val || !hash->headz || !hash->chainz || !hash->zeros) + { + return 83; /*alloc fail*/ + } - /*initialize hash table*/ - for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1; - for(i = 0; i != windowsize; ++i) hash->val[i] = -1; - for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/ + /*initialize hash table*/ + for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1; + for(i = 0; i != windowsize; ++i) hash->val[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/ - for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1; - for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/ + for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/ - return 0; + return 0; } static void hash_cleanup(Hash* hash) { - lodepng_free(hash->head); - lodepng_free(hash->val); - lodepng_free(hash->chain); + lodepng_free(hash->head); + lodepng_free(hash->val); + lodepng_free(hash->chain); - lodepng_free(hash->zeros); - lodepng_free(hash->headz); - lodepng_free(hash->chainz); + lodepng_free(hash->zeros); + lodepng_free(hash->headz); + lodepng_free(hash->chainz); } static unsigned getHash(const uint8_t* data, size_t size, size_t pos) { - unsigned result = 0; - if(pos + 2 < size) - { - /*A simple shift and xor hash is used. Since the data of PNGs is dominated - by zeroes due to the filters, a better hash does not have a significant - effect on speed in traversing the chain, and causes more time spend on - calculating the hash.*/ - result ^= (unsigned)(data[pos + 0] << 0u); - result ^= (unsigned)(data[pos + 1] << 4u); - result ^= (unsigned)(data[pos + 2] << 8u); - } else { - size_t amount, i; - if(pos >= size) return 0; - amount = size - pos; - for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u)); - } - return result & HASH_BIT_MASK; + unsigned result = 0; + if(pos + 2 < size) + { + /*A simple shift and xor hash is used. Since the data of PNGs is dominated + by zeroes due to the filters, a better hash does not have a significant + effect on speed in traversing the chain, and causes more time spend on + calculating the hash.*/ + result ^= (unsigned)(data[pos + 0] << 0u); + result ^= (unsigned)(data[pos + 1] << 4u); + result ^= (unsigned)(data[pos + 2] << 8u); + } + else + { + size_t amount, i; + if(pos >= size) return 0; + amount = size - pos; + for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u)); + } + return result & HASH_BIT_MASK; } static unsigned countZeros(const uint8_t* data, size_t size, size_t pos) { - const uint8_t* start = data + pos; - const uint8_t* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; - if(end > data + size) end = data + size; - data = start; - while(data != end && *data == 0) ++data; - /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/ - return (unsigned)(data - start); + const uint8_t* start = data + pos; + const uint8_t* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; + if(end > data + size) end = data + size; + data = start; + while(data != end && *data == 0) ++data; + /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/ + return (unsigned)(data - start); } /*wpos = pos & (windowsize - 1)*/ static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, uint16_t numzeros) { - hash->val[wpos] = (int32_t)hashval; - if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; - hash->head[hashval] = wpos; + hash->val[wpos] = (int32_t)hashval; + if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; + hash->head[hashval] = wpos; - hash->zeros[wpos] = numzeros; - if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; - hash->headz[numzeros] = wpos; + hash->zeros[wpos] = numzeros; + if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; + hash->headz[numzeros] = wpos; } /* @@ -1475,216 +1487,216 @@ static unsigned encodeLZ77(uivector* out, Hash* hash, const uint8_t* in, size_t inpos, size_t insize, unsigned windowsize, unsigned minmatch, unsigned nicematch, unsigned lazymatching) { - size_t pos; - unsigned i, error = 0; - /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ - unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8; - unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64; + size_t pos; + unsigned i, error = 0; + /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ + unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8; + unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64; - unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/ - unsigned numzeros = 0; + unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/ + unsigned numzeros = 0; - unsigned offset; /*the offset represents the distance in LZ77 terminology*/ - unsigned length; - unsigned lazy = 0; - unsigned lazylength = 0, lazyoffset = 0; - unsigned hashval; - unsigned current_offset, current_length; - unsigned prev_offset; - const uint8_t *lastptr, *foreptr, *backptr; - unsigned hashpos; + unsigned offset; /*the offset represents the distance in LZ77 terminology*/ + unsigned length; + unsigned lazy = 0; + unsigned lazylength = 0, lazyoffset = 0; + unsigned hashval; + unsigned current_offset, current_length; + unsigned prev_offset; + const uint8_t *lastptr, *foreptr, *backptr; + unsigned hashpos; - if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/ - if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/ + if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/ + if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/ - if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; + if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; - for(pos = inpos; pos < insize; ++pos) - { - size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ - unsigned chainlength = 0; + for(pos = inpos; pos < insize; ++pos) + { + size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ + unsigned chainlength = 0; - hashval = getHash(in, insize, pos); + hashval = getHash(in, insize, pos); - if(usezeros && hashval == 0) - { - if(numzeros == 0) numzeros = countZeros(in, insize, pos); - else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; - } - else - { - numzeros = 0; - } + if(usezeros && hashval == 0) + { + if(numzeros == 0) numzeros = countZeros(in, insize, pos); + else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } + else + { + numzeros = 0; + } - updateHashChain(hash, wpos, hashval, numzeros); + updateHashChain(hash, wpos, hashval, numzeros); - /*the length and offset found for the current position*/ - length = 0; - offset = 0; + /*the length and offset found for the current position*/ + length = 0; + offset = 0; - hashpos = hash->chain[wpos]; + hashpos = hash->chain[wpos]; - lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH]; + lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH]; - /*search for the longest string*/ - prev_offset = 0; - for(;;) - { - if(chainlength++ >= maxchainlength) break; - current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize; + /*search for the longest string*/ + prev_offset = 0; + for(;;) + { + if(chainlength++ >= maxchainlength) break; + current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize; - if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ - prev_offset = current_offset; - if(current_offset > 0) - { - /*test the next characters*/ - foreptr = &in[pos]; - backptr = &in[pos - current_offset]; + if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ + prev_offset = current_offset; + if(current_offset > 0) + { + /*test the next characters*/ + foreptr = &in[pos]; + backptr = &in[pos - current_offset]; - /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ - if(numzeros >= 3) - { - unsigned skip = hash->zeros[hashpos]; - if(skip > numzeros) skip = numzeros; - backptr += skip; - foreptr += skip; - } + /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ + if(numzeros >= 3) + { + unsigned skip = hash->zeros[hashpos]; + if(skip > numzeros) skip = numzeros; + backptr += skip; + foreptr += skip; + } - while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ - { - ++backptr; - ++foreptr; - } - current_length = (unsigned)(foreptr - &in[pos]); + while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ + { + ++backptr; + ++foreptr; + } + current_length = (unsigned)(foreptr - &in[pos]); - if(current_length > length) - { - length = current_length; /*the longest length*/ - offset = current_offset; /*the offset that is related to this longest length*/ - /*jump out once a length of max length is found (speed gain). This also jumps - out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/ - if(current_length >= nicematch) break; - } - } + if(current_length > length) + { + length = current_length; /*the longest length*/ + offset = current_offset; /*the offset that is related to this longest length*/ + /*jump out once a length of max length is found (speed gain). This also jumps + out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/ + if(current_length >= nicematch) break; + } + } - if(hashpos == hash->chain[hashpos]) break; + if(hashpos == hash->chain[hashpos]) break; - if(numzeros >= 3 && length > numzeros) - { - hashpos = hash->chainz[hashpos]; - if(hash->zeros[hashpos] != numzeros) break; - } - else - { - hashpos = hash->chain[hashpos]; - /*outdated hash value, happens if particular value was not encountered in whole last window*/ - if(hash->val[hashpos] != (int32_t)hashval) break; - } - } + if(numzeros >= 3 && length > numzeros) + { + hashpos = hash->chainz[hashpos]; + if(hash->zeros[hashpos] != numzeros) break; + } + else + { + hashpos = hash->chain[hashpos]; + /*outdated hash value, happens if particular value was not encountered in whole last window*/ + if(hash->val[hashpos] != (int32_t)hashval) break; + } + } - if(lazymatching) - { - if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) - { - lazy = 1; - lazylength = length; - lazyoffset = offset; - continue; /*try the next byte*/ - } - if(lazy) - { - lazy = 0; - if(pos == 0) ERROR_BREAK(81); - if(length > lazylength + 1) - { - /*push the previous character as literal*/ - if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); - } - else - { - length = lazylength; - offset = lazyoffset; - hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ - hash->headz[numzeros] = -1; /*idem*/ - --pos; - } - } - } - if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); + if(lazymatching) + { + if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) + { + lazy = 1; + lazylength = length; + lazyoffset = offset; + continue; /*try the next byte*/ + } + if(lazy) + { + lazy = 0; + if(pos == 0) ERROR_BREAK(81); + if(length > lazylength + 1) + { + /*push the previous character as literal*/ + if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); + } + else + { + length = lazylength; + offset = lazyoffset; + hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ + hash->headz[numzeros] = -1; /*idem*/ + --pos; + } + } + } + if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); - /*encode it as length/distance pair or literal value*/ - if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ - { - if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); - } - else if(length < minmatch || (length == 3 && offset > 4096)) - { - /*compensate for the fact that longer offsets have more extra bits, a - length of only 3 may be not worth it then*/ - if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); - } - else - { - addLengthDistance(out, length, offset); - for(i = 1; i < length; ++i) - { - ++pos; - wpos = pos & (windowsize - 1); - hashval = getHash(in, insize, pos); - if(usezeros && hashval == 0) - { - if(numzeros == 0) numzeros = countZeros(in, insize, pos); - else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; - } - else - { - numzeros = 0; - } - updateHashChain(hash, wpos, hashval, numzeros); - } - } - } /*end of the loop through each character of input*/ + /*encode it as length/distance pair or literal value*/ + if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ + { + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } + else if(length < minmatch || (length == 3 && offset > 4096)) + { + /*compensate for the fact that longer offsets have more extra bits, a + length of only 3 may be not worth it then*/ + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } + else + { + addLengthDistance(out, length, offset); + for(i = 1; i < length; ++i) + { + ++pos; + wpos = pos & (windowsize - 1); + hashval = getHash(in, insize, pos); + if(usezeros && hashval == 0) + { + if(numzeros == 0) numzeros = countZeros(in, insize, pos); + else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } + else + { + numzeros = 0; + } + updateHashChain(hash, wpos, hashval, numzeros); + } + } + } /*end of the loop through each character of input*/ - return error; + return error; } /* /////////////////////////////////////////////////////////////////////////// */ static unsigned deflateNoCompression(ucvector* out, const uint8_t* data, size_t datasize) { - /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, - 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ + /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, + 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ - size_t i, j, numdeflateblocks = (datasize + 65534) / 65535; - unsigned datapos = 0; - for(i = 0; i != numdeflateblocks; ++i) - { - unsigned BFINAL, BTYPE, LEN, NLEN; - uint8_t firstbyte; + size_t i, j, numdeflateblocks = (datasize + 65534) / 65535; + unsigned datapos = 0; + for(i = 0; i != numdeflateblocks; ++i) + { + unsigned BFINAL, BTYPE, LEN, NLEN; + uint8_t firstbyte; - BFINAL = (i == numdeflateblocks - 1); - BTYPE = 0; + BFINAL = (i == numdeflateblocks - 1); + BTYPE = 0; - firstbyte = (uint8_t)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1)); - ucvector_push_back(out, firstbyte); + firstbyte = (uint8_t)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1)); + ucvector_push_back(out, firstbyte); - LEN = 65535; - if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos; - NLEN = 65535 - LEN; + LEN = 65535; + if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos; + NLEN = 65535 - LEN; - ucvector_push_back(out, (uint8_t)(LEN & 255)); - ucvector_push_back(out, (uint8_t)(LEN >> 8)); - ucvector_push_back(out, (uint8_t)(NLEN & 255)); - ucvector_push_back(out, (uint8_t)(NLEN >> 8)); + ucvector_push_back(out, (uint8_t)(LEN & 255)); + ucvector_push_back(out, (uint8_t)(LEN >> 8)); + ucvector_push_back(out, (uint8_t)(NLEN & 255)); + ucvector_push_back(out, (uint8_t)(NLEN >> 8)); - /*Decompressed data*/ - for(j = 0; j < 65535 && datapos < datasize; ++j) - { - ucvector_push_back(out, data[datapos++]); - } - } + /*Decompressed data*/ + for(j = 0; j < 65535 && datapos < datasize; ++j) + { + ucvector_push_back(out, data[datapos++]); + } + } - return 0; + return 0; } /* @@ -1695,29 +1707,29 @@ tree_d: the tree for distance codes. static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded, const HuffmanTree* tree_ll, const HuffmanTree* tree_d) { - size_t i = 0; - for(i = 0; i != lz77_encoded->size; ++i) - { - unsigned val = lz77_encoded->data[i]; - addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); - if(val > 256) /*for a length code, 3 more things have to be added*/ - { - unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; - unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; - unsigned length_extra_bits = lz77_encoded->data[++i]; + size_t i = 0; + for(i = 0; i != lz77_encoded->size; ++i) + { + unsigned val = lz77_encoded->data[i]; + addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); + if(val > 256) /*for a length code, 3 more things have to be added*/ + { + unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; + unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; + unsigned length_extra_bits = lz77_encoded->data[++i]; - unsigned distance_code = lz77_encoded->data[++i]; + unsigned distance_code = lz77_encoded->data[++i]; - unsigned distance_index = distance_code; - unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; - unsigned distance_extra_bits = lz77_encoded->data[++i]; + unsigned distance_index = distance_code; + unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; + unsigned distance_extra_bits = lz77_encoded->data[++i]; - addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits); - addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code), - HuffmanTree_getLength(tree_d, distance_code)); - addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits); - } - } + addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits); + addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code), + HuffmanTree_getLength(tree_d, distance_code)); + addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits); + } + } } /*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/ @@ -1725,245 +1737,247 @@ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, const uint8_t* data, size_t datapos, size_t dataend, const LodePNGCompressSettings* settings, unsigned final) { - unsigned error = 0; + unsigned error = 0; - /* - A block is compressed as follows: The PNG data is lz77 encoded, resulting in - literal bytes and length/distance pairs. This is then huffman compressed with - two huffman trees. One huffman tree is used for the lit and len values ("ll"), - another huffman tree is used for the dist values ("d"). These two trees are - stored using their code lengths, and to compress even more these code lengths - are also run-length encoded and huffman compressed. This gives a huffman tree - of code lengths "cl". The code lenghts used to describe this third tree are - the code length code lengths ("clcl"). - */ + /* + A block is compressed as follows: The PNG data is lz77 encoded, resulting in + literal bytes and length/distance pairs. This is then huffman compressed with + two huffman trees. One huffman tree is used for the lit and len values ("ll"), + another huffman tree is used for the dist values ("d"). These two trees are + stored using their code lengths, and to compress even more these code lengths + are also run-length encoded and huffman compressed. This gives a huffman tree + of code lengths "cl". The code lenghts used to describe this third tree are + the code length code lengths ("clcl"). + */ - /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/ - uivector lz77_encoded; - HuffmanTree tree_ll; /*tree for lit,len values*/ - HuffmanTree tree_d; /*tree for distance codes*/ - HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/ - uivector frequencies_ll; /*frequency of lit,len codes*/ - uivector frequencies_d; /*frequency of dist codes*/ - uivector frequencies_cl; /*frequency of code length codes*/ - uivector bitlen_lld; /*lit,len,dist code lenghts (int32_t bits), literally (without repeat codes).*/ - uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/ - /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl - (these are written as is in the file, it would be crazy to compress these using yet another huffman - tree that needs to be represented by yet another set of code lengths)*/ - uivector bitlen_cl; - size_t datasize = dataend - datapos; + /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/ + uivector lz77_encoded; + HuffmanTree tree_ll; /*tree for lit,len values*/ + HuffmanTree tree_d; /*tree for distance codes*/ + HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/ + uivector frequencies_ll; /*frequency of lit,len codes*/ + uivector frequencies_d; /*frequency of dist codes*/ + uivector frequencies_cl; /*frequency of code length codes*/ + uivector bitlen_lld; /*lit,len,dist code lenghts (int32_t bits), literally (without repeat codes).*/ + uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/ + /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl + (these are written as is in the file, it would be crazy to compress these using yet another huffman + tree that needs to be represented by yet another set of code lengths)*/ + uivector bitlen_cl; + size_t datasize = dataend - datapos; - /* - Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies: - bitlen_lld is to tree_cl what data is to tree_ll and tree_d. - bitlen_lld_e is to bitlen_lld what lz77_encoded is to data. - bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded. - */ + /* + Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies: + bitlen_lld is to tree_cl what data is to tree_ll and tree_d. + bitlen_lld_e is to bitlen_lld what lz77_encoded is to data. + bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded. + */ - unsigned BFINAL = final; - size_t numcodes_ll, numcodes_d, i; - unsigned HLIT, HDIST, HCLEN; + unsigned BFINAL = final; + size_t numcodes_ll, numcodes_d, i; + unsigned HLIT, HDIST, HCLEN; - uivector_init(&lz77_encoded); - HuffmanTree_init(&tree_ll); - HuffmanTree_init(&tree_d); - HuffmanTree_init(&tree_cl); - uivector_init(&frequencies_ll); - uivector_init(&frequencies_d); - uivector_init(&frequencies_cl); - uivector_init(&bitlen_lld); - uivector_init(&bitlen_lld_e); - uivector_init(&bitlen_cl); + uivector_init(&lz77_encoded); + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + HuffmanTree_init(&tree_cl); + uivector_init(&frequencies_ll); + uivector_init(&frequencies_d); + uivector_init(&frequencies_cl); + uivector_init(&bitlen_lld); + uivector_init(&bitlen_lld_e); + uivector_init(&bitlen_cl); - /*This while loop never loops due to a break at the end, it is here to - allow breaking out of it to the cleanup phase on error conditions.*/ - while(!error) - { - if(settings->use_lz77) - { - error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, - settings->minmatch, settings->nicematch, settings->lazymatching); - if(error) break; - } - else - { - if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); - for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/ - } + /*This while loop never loops due to a break at the end, it is here to + allow breaking out of it to the cleanup phase on error conditions.*/ + while(!error) + { + if(settings->use_lz77) + { + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(error) break; + } + else + { + if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); + for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/ + } - if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/); - if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/); + if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/); + if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/); - /*Count the frequencies of lit, len and dist codes*/ - for(i = 0; i != lz77_encoded.size; ++i) - { - unsigned symbol = lz77_encoded.data[i]; - ++frequencies_ll.data[symbol]; - if(symbol > 256) - { - unsigned dist = lz77_encoded.data[i + 2]; - ++frequencies_d.data[dist]; - i += 3; - } - } - frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/ + /*Count the frequencies of lit, len and dist codes*/ + for(i = 0; i != lz77_encoded.size; ++i) + { + unsigned symbol = lz77_encoded.data[i]; + ++frequencies_ll.data[symbol]; + if(symbol > 256) + { + unsigned dist = lz77_encoded.data[i + 2]; + ++frequencies_d.data[dist]; + i += 3; + } + } + frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/ - /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/ - error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15); - if(error) break; - /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/ - error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15); - if(error) break; + /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/ + error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15); + if(error) break; + /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/ + error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15); + if(error) break; - numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286; - numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30; - /*store the code lengths of both generated trees in bitlen_lld*/ - for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i)); - for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i)); + numcodes_ll = tree_ll.numcodes; + if(numcodes_ll > 286) numcodes_ll = 286; + numcodes_d = tree_d.numcodes; + if(numcodes_d > 30) numcodes_d = 30; + /*store the code lengths of both generated trees in bitlen_lld*/ + for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i)); + for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i)); - /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), - 17 (3-10 zeroes), 18 (11-138 zeroes)*/ - for(i = 0; i != (unsigned)bitlen_lld.size; ++i) - { - unsigned j = 0; /*amount of repititions*/ - while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j; + /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), + 17 (3-10 zeroes), 18 (11-138 zeroes)*/ + for(i = 0; i != (unsigned)bitlen_lld.size; ++i) + { + unsigned j = 0; /*amount of repititions*/ + while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j; - if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ - { - ++j; /*include the first zero*/ - if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ - { - uivector_push_back(&bitlen_lld_e, 17); - uivector_push_back(&bitlen_lld_e, j - 3); - } - else /*repeat code 18 supports max 138 zeroes*/ - { - if(j > 138) j = 138; - uivector_push_back(&bitlen_lld_e, 18); - uivector_push_back(&bitlen_lld_e, j - 11); - } - i += (j - 1); - } - else if(j >= 3) /*repeat code for value other than zero*/ - { - size_t k; - unsigned num = j / 6, rest = j % 6; - uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); - for(k = 0; k < num; ++k) - { - uivector_push_back(&bitlen_lld_e, 16); - uivector_push_back(&bitlen_lld_e, 6 - 3); - } - if(rest >= 3) - { - uivector_push_back(&bitlen_lld_e, 16); - uivector_push_back(&bitlen_lld_e, rest - 3); - } - else j -= rest; - i += j; - } - else /*too short to benefit from repeat code*/ - { - uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); - } - } + if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ + { + ++j; /*include the first zero*/ + if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ + { + uivector_push_back(&bitlen_lld_e, 17); + uivector_push_back(&bitlen_lld_e, j - 3); + } + else /*repeat code 18 supports max 138 zeroes*/ + { + if(j > 138) j = 138; + uivector_push_back(&bitlen_lld_e, 18); + uivector_push_back(&bitlen_lld_e, j - 11); + } + i += (j - 1); + } + else if(j >= 3) /*repeat code for value other than zero*/ + { + size_t k; + unsigned num = j / 6, rest = j % 6; + uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); + for(k = 0; k < num; ++k) + { + uivector_push_back(&bitlen_lld_e, 16); + uivector_push_back(&bitlen_lld_e, 6 - 3); + } + if(rest >= 3) + { + uivector_push_back(&bitlen_lld_e, 16); + uivector_push_back(&bitlen_lld_e, rest - 3); + } + else j -= rest; + i += j; + } + else /*too short to benefit from repeat code*/ + { + uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); + } + } - /*generate tree_cl, the huffmantree of huffmantrees*/ + /*generate tree_cl, the huffmantree of huffmantrees*/ - if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != bitlen_lld_e.size; ++i) - { - ++frequencies_cl.data[bitlen_lld_e.data[i]]; - /*after a repeat code come the bits that specify the number of repetitions, - those don't need to be in the frequencies_cl calculation*/ - if(bitlen_lld_e.data[i] >= 16) ++i; - } + if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/); + for(i = 0; i != bitlen_lld_e.size; ++i) + { + ++frequencies_cl.data[bitlen_lld_e.data[i]]; + /*after a repeat code come the bits that specify the number of repetitions, + those don't need to be in the frequencies_cl calculation*/ + if(bitlen_lld_e.data[i] >= 16) ++i; + } - error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data, - frequencies_cl.size, frequencies_cl.size, 7); - if(error) break; + error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data, + frequencies_cl.size, frequencies_cl.size, 7); + if(error) break; - if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != tree_cl.numcodes; ++i) - { - /*lenghts of code length tree is in the order as specified by deflate*/ - bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]); - } - while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) - { - /*remove zeros at the end, but minimum size must be 4*/ - if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/); - } - if(error) break; + if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/); + for(i = 0; i != tree_cl.numcodes; ++i) + { + /*lenghts of code length tree is in the order as specified by deflate*/ + bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]); + } + while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) + { + /*remove zeros at the end, but minimum size must be 4*/ + if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/); + } + if(error) break; - /* - Write everything into the output + /* + Write everything into the output - After the BFINAL and BTYPE, the dynamic block consists out of the following: - - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN - - (HCLEN+4)*3 bits code lengths of code length alphabet - - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length - alphabet, + possible repetition codes 16, 17, 18) - - HDIST + 1 code lengths of distance alphabet (encoded using the code length - alphabet, + possible repetition codes 16, 17, 18) - - compressed data - - 256 (end code) - */ + After the BFINAL and BTYPE, the dynamic block consists out of the following: + - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN + - (HCLEN+4)*3 bits code lengths of code length alphabet + - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - HDIST + 1 code lengths of distance alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - compressed data + - 256 (end code) + */ - /*Write block type*/ - addBitToStream(bp, out, BFINAL); - addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/ - addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/ + /*Write block type*/ + addBitToStream(bp, out, BFINAL); + addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/ + addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/ - /*write the HLIT, HDIST and HCLEN values*/ - HLIT = (unsigned)(numcodes_ll - 257); - HDIST = (unsigned)(numcodes_d - 1); - HCLEN = (unsigned)bitlen_cl.size - 4; - /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/ - while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN; - addBitsToStream(bp, out, HLIT, 5); - addBitsToStream(bp, out, HDIST, 5); - addBitsToStream(bp, out, HCLEN, 4); + /*write the HLIT, HDIST and HCLEN values*/ + HLIT = (unsigned)(numcodes_ll - 257); + HDIST = (unsigned)(numcodes_d - 1); + HCLEN = (unsigned)bitlen_cl.size - 4; + /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/ + while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN; + addBitsToStream(bp, out, HLIT, 5); + addBitsToStream(bp, out, HDIST, 5); + addBitsToStream(bp, out, HCLEN, 4); - /*write the code lenghts of the code length alphabet*/ - for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3); + /*write the code lenghts of the code length alphabet*/ + for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3); - /*write the lenghts of the lit/len AND the dist alphabet*/ - for(i = 0; i != bitlen_lld_e.size; ++i) - { - addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]), - HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i])); - /*extra bits of repeat codes*/ - if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2); - else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3); - else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7); - } + /*write the lenghts of the lit/len AND the dist alphabet*/ + for(i = 0; i != bitlen_lld_e.size; ++i) + { + addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]), + HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i])); + /*extra bits of repeat codes*/ + if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2); + else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3); + else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7); + } - /*write the compressed data symbols*/ - writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); - /*error: the length of the end code 256 must be larger than 0*/ - if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64); + /*write the compressed data symbols*/ + writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); + /*error: the length of the end code 256 must be larger than 0*/ + if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64); - /*write the end code*/ - addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); + /*write the end code*/ + addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); - break; /*end of error-while*/ - } + break; /*end of error-while*/ + } - /*cleanup*/ - uivector_cleanup(&lz77_encoded); - HuffmanTree_cleanup(&tree_ll); - HuffmanTree_cleanup(&tree_d); - HuffmanTree_cleanup(&tree_cl); - uivector_cleanup(&frequencies_ll); - uivector_cleanup(&frequencies_d); - uivector_cleanup(&frequencies_cl); - uivector_cleanup(&bitlen_lld_e); - uivector_cleanup(&bitlen_lld); - uivector_cleanup(&bitlen_cl); + /*cleanup*/ + uivector_cleanup(&lz77_encoded); + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + HuffmanTree_cleanup(&tree_cl); + uivector_cleanup(&frequencies_ll); + uivector_cleanup(&frequencies_d); + uivector_cleanup(&frequencies_cl); + uivector_cleanup(&bitlen_lld_e); + uivector_cleanup(&bitlen_lld); + uivector_cleanup(&bitlen_cl); - return error; + return error; } static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, @@ -1971,115 +1985,115 @@ static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, size_t datapos, size_t dataend, const LodePNGCompressSettings* settings, unsigned final) { - HuffmanTree tree_ll; /*tree for literal values and length codes*/ - HuffmanTree tree_d; /*tree for distance codes*/ + HuffmanTree tree_ll; /*tree for literal values and length codes*/ + HuffmanTree tree_d; /*tree for distance codes*/ - unsigned BFINAL = final; - unsigned error = 0; - size_t i; + unsigned BFINAL = final; + unsigned error = 0; + size_t i; - HuffmanTree_init(&tree_ll); - HuffmanTree_init(&tree_d); + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); - generateFixedLitLenTree(&tree_ll); - generateFixedDistanceTree(&tree_d); + generateFixedLitLenTree(&tree_ll); + generateFixedDistanceTree(&tree_d); - addBitToStream(bp, out, BFINAL); - addBitToStream(bp, out, 1); /*first bit of BTYPE*/ - addBitToStream(bp, out, 0); /*second bit of BTYPE*/ + addBitToStream(bp, out, BFINAL); + addBitToStream(bp, out, 1); /*first bit of BTYPE*/ + addBitToStream(bp, out, 0); /*second bit of BTYPE*/ - if(settings->use_lz77) /*LZ77 encoded*/ - { - uivector lz77_encoded; - uivector_init(&lz77_encoded); - error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, - settings->minmatch, settings->nicematch, settings->lazymatching); - if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); - uivector_cleanup(&lz77_encoded); - } - else /*no LZ77, but still will be Huffman compressed*/ - { - for(i = datapos; i < dataend; ++i) - { - addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i])); - } - } - /*add END code*/ - if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); + if(settings->use_lz77) /*LZ77 encoded*/ + { + uivector lz77_encoded; + uivector_init(&lz77_encoded); + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); + uivector_cleanup(&lz77_encoded); + } + else /*no LZ77, but still will be Huffman compressed*/ + { + for(i = datapos; i < dataend; ++i) + { + addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i])); + } + } + /*add END code*/ + if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); - /*cleanup*/ - HuffmanTree_cleanup(&tree_ll); - HuffmanTree_cleanup(&tree_d); + /*cleanup*/ + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); - return error; + return error; } static unsigned lodepng_deflatev(ucvector* out, const uint8_t* in, size_t insize, const LodePNGCompressSettings* settings) { - unsigned error = 0; - size_t i, blocksize, numdeflateblocks; - size_t bp = 0; /*the bit pointer*/ - Hash hash; + unsigned error = 0; + size_t i, blocksize, numdeflateblocks; + size_t bp = 0; /*the bit pointer*/ + Hash hash; - if(settings->btype > 2) return 61; - else if(settings->btype == 0) return deflateNoCompression(out, in, insize); - else if(settings->btype == 1) blocksize = insize; - else /*if(settings->btype == 2)*/ - { - /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/ - blocksize = insize / 8 + 8; - if(blocksize < 65536) blocksize = 65536; - if(blocksize > 262144) blocksize = 262144; - } + if(settings->btype > 2) return 61; + else if(settings->btype == 0) return deflateNoCompression(out, in, insize); + else if(settings->btype == 1) blocksize = insize; + else /*if(settings->btype == 2)*/ + { + /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/ + blocksize = insize / 8 + 8; + if(blocksize < 65536) blocksize = 65536; + if(blocksize > 262144) blocksize = 262144; + } - numdeflateblocks = (insize + blocksize - 1) / blocksize; - if(numdeflateblocks == 0) numdeflateblocks = 1; + numdeflateblocks = (insize + blocksize - 1) / blocksize; + if(numdeflateblocks == 0) numdeflateblocks = 1; - error = hash_init(&hash, settings->windowsize); - if(error) return error; + error = hash_init(&hash, settings->windowsize); + if(error) return error; - for(i = 0; i != numdeflateblocks && !error; ++i) - { - unsigned final = (i == numdeflateblocks - 1); - size_t start = i * blocksize; - size_t end = start + blocksize; - if(end > insize) end = insize; + for(i = 0; i != numdeflateblocks && !error; ++i) + { + unsigned final = (i == numdeflateblocks - 1); + size_t start = i * blocksize; + size_t end = start + blocksize; + if(end > insize) end = insize; - if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final); - else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final); - } + if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final); + else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final); + } - hash_cleanup(&hash); + hash_cleanup(&hash); - return error; + return error; } unsigned lodepng_deflate(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGCompressSettings* settings) { - unsigned error; - ucvector v; - ucvector_init_buffer(&v, *out, *outsize); - error = lodepng_deflatev(&v, in, insize, settings); - *out = v.data; - *outsize = v.size; - return error; + unsigned error; + ucvector v; + ucvector_init_buffer(&v, *out, *outsize); + error = lodepng_deflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; } static unsigned deflate(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGCompressSettings* settings) { - if(settings->custom_deflate) - { - return settings->custom_deflate(out, outsize, in, insize, settings); - } - else - { - return lodepng_deflate(out, outsize, in, insize, settings); - } + if(settings->custom_deflate) + { + return settings->custom_deflate(out, outsize, in, insize, settings); + } + else + { + return lodepng_deflate(out, outsize, in, insize, settings); + } } #endif /*LODEPNG_COMPILE_DECODER*/ @@ -2090,31 +2104,31 @@ static unsigned deflate(uint8_t** out, size_t* outsize, static unsigned update_adler32(unsigned adler, const uint8_t* data, unsigned len) { - unsigned s1 = adler & 0xffff; - unsigned s2 = (adler >> 16) & 0xffff; + unsigned s1 = adler & 0xffff; + unsigned s2 = (adler >> 16) & 0xffff; - while(len > 0) - { - /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/ - unsigned amount = len > 5552 ? 5552 : len; - len -= amount; - while(amount > 0) - { - s1 += (*data++); - s2 += s1; - --amount; - } - s1 %= 65521; - s2 %= 65521; - } + while(len > 0) + { + /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/ + unsigned amount = len > 5552 ? 5552 : len; + len -= amount; + while(amount > 0) + { + s1 += (*data++); + s2 += s1; + --amount; + } + s1 %= 65521; + s2 %= 65521; + } - return (s2 << 16) | s1; + return (s2 << 16) | s1; } /*Return the adler32 of the bytes data[0..len-1]*/ static unsigned adler32(const uint8_t* data, unsigned len) { - return update_adler32(1L, data, len); + return update_adler32(1L, data, len); } /* ////////////////////////////////////////////////////////////////////////// */ @@ -2126,59 +2140,59 @@ static unsigned adler32(const uint8_t* data, unsigned len) unsigned lodepng_zlib_decompress(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGDecompressSettings* settings) { - unsigned error = 0; - unsigned CM, CINFO, FDICT; + unsigned error = 0; + unsigned CM, CINFO, FDICT; - if(insize < 2) return 53; /*error, size of zlib data too small*/ - /*read information from zlib header*/ - if((in[0] * 256 + in[1]) % 31 != 0) - { - /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ - return 24; - } + if(insize < 2) return 53; /*error, size of zlib data too small*/ + /*read information from zlib header*/ + if((in[0] * 256 + in[1]) % 31 != 0) + { + /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ + return 24; + } - CM = in[0] & 15; - CINFO = (in[0] >> 4) & 15; - /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/ - FDICT = (in[1] >> 5) & 1; - /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ + CM = in[0] & 15; + CINFO = (in[0] >> 4) & 15; + /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/ + FDICT = (in[1] >> 5) & 1; + /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ - if(CM != 8 || CINFO > 7) - { - /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ - return 25; - } - if(FDICT != 0) - { - /*error: the specification of PNG says about the zlib stream: - "The additional flags shall not specify a preset dictionary."*/ - return 26; - } + if(CM != 8 || CINFO > 7) + { + /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ + return 25; + } + if(FDICT != 0) + { + /*error: the specification of PNG says about the zlib stream: + "The additional flags shall not specify a preset dictionary."*/ + return 26; + } - error = inflate(out, outsize, in + 2, insize - 2, settings); - if(error) return error; + error = inflate(out, outsize, in + 2, insize - 2, settings); + if(error) return error; - if(!settings->ignore_adler32) - { - unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); - unsigned checksum = adler32(*out, (unsigned)(*outsize)); - if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ - } + if(!settings->ignore_adler32) + { + unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); + unsigned checksum = adler32(*out, (unsigned)(*outsize)); + if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ + } - return 0; /*no error*/ + return 0; /*no error*/ } static unsigned zlib_decompress(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGDecompressSettings* settings) { - if(settings->custom_zlib) - { - return settings->custom_zlib(out, outsize, in, insize, settings); - } - else - { - return lodepng_zlib_decompress(out, outsize, in, insize, settings); - } + if(settings->custom_zlib) + { + return settings->custom_zlib(out, outsize, in, insize, settings); + } + else + { + return lodepng_zlib_decompress(out, outsize, in, insize, settings); + } } #endif /*LODEPNG_COMPILE_DECODER*/ @@ -2188,56 +2202,56 @@ static unsigned zlib_decompress(uint8_t** out, size_t* outsize, const uint8_t* i unsigned lodepng_zlib_compress(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGCompressSettings* settings) { - /*initially, *out must be NULL and outsize 0, if you just give some random *out - that's pointing to a non allocated buffer, this'll crash*/ - ucvector outv; - size_t i; - unsigned error; - uint8_t* deflatedata = 0; - size_t deflatesize = 0; + /*initially, *out must be NULL and outsize 0, if you just give some random *out + that's pointing to a non allocated buffer, this'll crash*/ + ucvector outv; + size_t i; + unsigned error; + uint8_t* deflatedata = 0; + size_t deflatesize = 0; - /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/ - unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/ - unsigned FLEVEL = 0; - unsigned FDICT = 0; - unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64; - unsigned FCHECK = 31 - CMFFLG % 31; - CMFFLG += FCHECK; + /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/ + unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/ + unsigned FLEVEL = 0; + unsigned FDICT = 0; + unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64; + unsigned FCHECK = 31 - CMFFLG % 31; + CMFFLG += FCHECK; - /*ucvector-controlled version of the output buffer, for dynamic array*/ - ucvector_init_buffer(&outv, *out, *outsize); + /*ucvector-controlled version of the output buffer, for dynamic array*/ + ucvector_init_buffer(&outv, *out, *outsize); - ucvector_push_back(&outv, (uint8_t)(CMFFLG >> 8)); - ucvector_push_back(&outv, (uint8_t)(CMFFLG & 255)); + ucvector_push_back(&outv, (uint8_t)(CMFFLG >> 8)); + ucvector_push_back(&outv, (uint8_t)(CMFFLG & 255)); - error = deflate(&deflatedata, &deflatesize, in, insize, settings); + error = deflate(&deflatedata, &deflatesize, in, insize, settings); - if(!error) - { - unsigned ADLER32 = adler32(in, (unsigned)insize); - for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]); - lodepng_free(deflatedata); - lodepng_add32bitInt(&outv, ADLER32); - } + if(!error) + { + unsigned ADLER32 = adler32(in, (unsigned)insize); + for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]); + lodepng_free(deflatedata); + lodepng_add32bitInt(&outv, ADLER32); + } - *out = outv.data; - *outsize = outv.size; + *out = outv.data; + *outsize = outv.size; - return error; + return error; } /* compress using the default or custom zlib function */ static unsigned zlib_compress(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGCompressSettings* settings) { - if(settings->custom_zlib) - { - return settings->custom_zlib(out, outsize, in, insize, settings); - } - else - { - return lodepng_zlib_compress(out, outsize, in, insize, settings); - } + if(settings->custom_zlib) + { + return settings->custom_zlib(out, outsize, in, insize, settings); + } + else + { + return lodepng_zlib_compress(out, outsize, in, insize, settings); + } } #endif /*LODEPNG_COMPILE_ENCODER*/ @@ -2248,16 +2262,16 @@ static unsigned zlib_compress(uint8_t** out, size_t* outsize, const uint8_t* in, static unsigned zlib_decompress(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGDecompressSettings* settings) { - if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ - return settings->custom_zlib(out, outsize, in, insize, settings); + if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ + return settings->custom_zlib(out, outsize, in, insize, settings); } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER static unsigned zlib_compress(uint8_t** out, size_t* outsize, const uint8_t* in, size_t insize, const LodePNGCompressSettings* settings) { - if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ - return settings->custom_zlib(out, outsize, in, insize, settings); + if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ + return settings->custom_zlib(out, outsize, in, insize, settings); } #endif /*LODEPNG_COMPILE_ENCODER*/ @@ -2272,17 +2286,17 @@ static unsigned zlib_compress(uint8_t** out, size_t* outsize, const uint8_t* in, void lodepng_compress_settings_init(LodePNGCompressSettings* settings) { - /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ - settings->btype = 2; - settings->use_lz77 = 1; - settings->windowsize = DEFAULT_WINDOWSIZE; - settings->minmatch = 3; - settings->nicematch = 128; - settings->lazymatching = 1; + /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ + settings->btype = 2; + settings->use_lz77 = 1; + settings->windowsize = DEFAULT_WINDOWSIZE; + settings->minmatch = 3; + settings->nicematch = 128; + settings->lazymatching = 1; - settings->custom_zlib = 0; - settings->custom_deflate = 0; - settings->custom_context = 0; + settings->custom_zlib = 0; + settings->custom_deflate = 0; + settings->custom_context = 0; } const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0}; @@ -2294,11 +2308,11 @@ const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) { - settings->ignore_adler32 = 0; + settings->ignore_adler32 = 0; - settings->custom_zlib = 0; - settings->custom_inflate = 0; - settings->custom_context = 0; + settings->custom_zlib = 0; + settings->custom_inflate = 0; + settings->custom_context = 0; } const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0}; @@ -2320,51 +2334,52 @@ const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, #ifndef LODEPNG_NO_COMPILE_CRC /* CRC polynomial: 0xedb88320 */ -static unsigned lodepng_crc32_table[256] = { - 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, - 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, - 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, - 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, - 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, - 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, - 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, - 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, - 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, - 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, - 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, - 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, - 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, - 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, - 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, - 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, - 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, - 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, - 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, - 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, - 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, - 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, - 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, - 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, - 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, - 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, - 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, - 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, - 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, - 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, - 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, - 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u +static unsigned lodepng_crc32_table[256] = +{ + 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, + 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, + 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, + 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, + 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, + 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, + 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, + 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, + 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, + 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, + 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, + 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, + 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, + 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, + 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, + 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, + 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, + 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, + 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, + 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, + 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, + 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, + 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, + 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, + 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, + 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, + 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, + 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, + 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, + 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, + 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, + 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u }; /*Return the CRC of the bytes buf[0..len-1].*/ unsigned lodepng_crc32(const uint8_t* data, size_t length) { - unsigned r = 0xffffffffu; - size_t i; - for(i = 0; i < length; ++i) - { - r = lodepng_crc32_table[(r ^ data[i]) & 0xff] ^ (r >> 8); - } - return r ^ 0xffffffffu; + unsigned r = 0xffffffffu; + size_t i; + for(i = 0; i < length; ++i) + { + r = lodepng_crc32_table[(r ^ data[i]) & 0xff] ^ (r >> 8); + } + return r ^ 0xffffffffu; } #else /* !LODEPNG_NO_COMPILE_CRC */ unsigned lodepng_crc32(const uint8_t* data, size_t length); @@ -2376,42 +2391,42 @@ unsigned lodepng_crc32(const uint8_t* data, size_t length); static uint8_t readBitFromReversedStream(size_t* bitpointer, const uint8_t* bitstream) { - uint8_t result = (uint8_t)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); - ++(*bitpointer); - return result; + uint8_t result = (uint8_t)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); + ++(*bitpointer); + return result; } static unsigned readBitsFromReversedStream(size_t* bitpointer, const uint8_t* bitstream, size_t nbits) { - unsigned result = 0; - size_t i; - for(i = 0 ; i < nbits; ++i) - { - result <<= 1; - result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream); - } - return result; + unsigned result = 0; + size_t i; + for(i = 0 ; i < nbits; ++i) + { + result <<= 1; + result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream); + } + return result; } #ifdef LODEPNG_COMPILE_DECODER static void setBitOfReversedStream0(size_t* bitpointer, uint8_t* bitstream, uint8_t bit) { - /*the current bit in bitstream must be 0 for this to work*/ - if(bit) - { - /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/ - bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7))); - } - ++(*bitpointer); + /*the current bit in bitstream must be 0 for this to work*/ + if(bit) + { + /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/ + bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7))); + } + ++(*bitpointer); } #endif /*LODEPNG_COMPILE_DECODER*/ static void setBitOfReversedStream(size_t* bitpointer, uint8_t* bitstream, uint8_t bit) { - /*the current bit in bitstream may be 0 or 1 for this to work*/ - if(bit == 0) bitstream[(*bitpointer) >> 3] &= (uint8_t)(~(1 << (7 - ((*bitpointer) & 0x7)))); - else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7))); - ++(*bitpointer); + /*the current bit in bitstream may be 0 or 1 for this to work*/ + if(bit == 0) bitstream[(*bitpointer) >> 3] &= (uint8_t)(~(1 << (7 - ((*bitpointer) & 0x7)))); + else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7))); + ++(*bitpointer); } /* ////////////////////////////////////////////////////////////////////////// */ @@ -2420,124 +2435,124 @@ static void setBitOfReversedStream(size_t* bitpointer, uint8_t* bitstream, uint8 unsigned lodepng_chunk_length(const uint8_t* chunk) { - return lodepng_read32bitInt(&chunk[0]); + return lodepng_read32bitInt(&chunk[0]); } void lodepng_chunk_type(char type[5], const uint8_t* chunk) { - unsigned i; - for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i]; - type[4] = 0; /*null termination char*/ + unsigned i; + for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i]; + type[4] = 0; /*null termination char*/ } uint8_t lodepng_chunk_type_equals(const uint8_t* chunk, const char* type) { - if(strlen(type) != 4) return 0; - return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); + if(strlen(type) != 4) return 0; + return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); } uint8_t lodepng_chunk_ancillary(const uint8_t* chunk) { - return((chunk[4] & 32) != 0); + return((chunk[4] & 32) != 0); } uint8_t lodepng_chunk_private(const uint8_t* chunk) { - return((chunk[6] & 32) != 0); + return((chunk[6] & 32) != 0); } uint8_t lodepng_chunk_safetocopy(const uint8_t* chunk) { - return((chunk[7] & 32) != 0); + return((chunk[7] & 32) != 0); } uint8_t* lodepng_chunk_data(uint8_t* chunk) { - return &chunk[8]; + return &chunk[8]; } const uint8_t* lodepng_chunk_data_const(const uint8_t* chunk) { - return &chunk[8]; + return &chunk[8]; } unsigned lodepng_chunk_check_crc(const uint8_t* chunk) { - unsigned length = lodepng_chunk_length(chunk); - unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); - /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ - unsigned checksum = lodepng_crc32(&chunk[4], length + 4); - if(CRC != checksum) return 1; - else return 0; + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); + /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ + unsigned checksum = lodepng_crc32(&chunk[4], length + 4); + if(CRC != checksum) return 1; + else return 0; } void lodepng_chunk_generate_crc(uint8_t* chunk) { - unsigned length = lodepng_chunk_length(chunk); - unsigned CRC = lodepng_crc32(&chunk[4], length + 4); - lodepng_set32bitInt(chunk + 8 + length, CRC); + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_crc32(&chunk[4], length + 4); + lodepng_set32bitInt(chunk + 8 + length, CRC); } uint8_t* lodepng_chunk_next(uint8_t* chunk) { - unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; - return &chunk[total_chunk_length]; + unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; + return &chunk[total_chunk_length]; } const uint8_t* lodepng_chunk_next_const(const uint8_t* chunk) { - unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; - return &chunk[total_chunk_length]; + unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; + return &chunk[total_chunk_length]; } unsigned lodepng_chunk_append(uint8_t** out, size_t* outlength, const uint8_t* chunk) { - unsigned i; - unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; - uint8_t *chunk_start, *new_buffer; - size_t new_length = (*outlength) + total_chunk_length; - if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/ + unsigned i; + unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; + uint8_t *chunk_start, *new_buffer; + size_t new_length = (*outlength) + total_chunk_length; + if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/ - new_buffer = (uint8_t*)lodepng_realloc(*out, new_length); - if(!new_buffer) return 83; /*alloc fail*/ - (*out) = new_buffer; - (*outlength) = new_length; - chunk_start = &(*out)[new_length - total_chunk_length]; + new_buffer = (uint8_t*)lodepng_realloc(*out, new_length); + if(!new_buffer) return 83; /*alloc fail*/ + (*out) = new_buffer; + (*outlength) = new_length; + chunk_start = &(*out)[new_length - total_chunk_length]; - for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i]; + for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i]; - return 0; + return 0; } unsigned lodepng_chunk_create(uint8_t** out, size_t* outlength, unsigned length, const char* type, const uint8_t* data) { - unsigned i; - uint8_t *chunk, *new_buffer; - size_t new_length = (*outlength) + length + 12; - if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/ - new_buffer = (uint8_t*)lodepng_realloc(*out, new_length); - if(!new_buffer) return 83; /*alloc fail*/ - (*out) = new_buffer; - (*outlength) = new_length; - chunk = &(*out)[(*outlength) - length - 12]; + unsigned i; + uint8_t *chunk, *new_buffer; + size_t new_length = (*outlength) + length + 12; + if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/ + new_buffer = (uint8_t*)lodepng_realloc(*out, new_length); + if(!new_buffer) return 83; /*alloc fail*/ + (*out) = new_buffer; + (*outlength) = new_length; + chunk = &(*out)[(*outlength) - length - 12]; - /*1: length*/ - lodepng_set32bitInt(chunk, (unsigned)length); + /*1: length*/ + lodepng_set32bitInt(chunk, (unsigned)length); - /*2: chunk name (4 letters)*/ - chunk[4] = (uint8_t)type[0]; - chunk[5] = (uint8_t)type[1]; - chunk[6] = (uint8_t)type[2]; - chunk[7] = (uint8_t)type[3]; + /*2: chunk name (4 letters)*/ + chunk[4] = (uint8_t)type[0]; + chunk[5] = (uint8_t)type[1]; + chunk[6] = (uint8_t)type[2]; + chunk[7] = (uint8_t)type[3]; - /*3: the data*/ - for(i = 0; i != length; ++i) chunk[8 + i] = data[i]; + /*3: the data*/ + for(i = 0; i != length; ++i) chunk[8 + i] = data[i]; - /*4: CRC (of the chunkname characters and the data)*/ - lodepng_chunk_generate_crc(chunk); + /*4: CRC (of the chunkname characters and the data)*/ + lodepng_chunk_generate_crc(chunk); - return 0; + return 0; } /* ////////////////////////////////////////////////////////////////////////// */ @@ -2547,165 +2562,181 @@ unsigned lodepng_chunk_create(uint8_t** out, size_t* outlength, unsigned length, /*return type is a LodePNG error code*/ static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/ { - switch(colortype) - { - case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/ - case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/ - case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/ - case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/ - case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/ - default: return 31; - } - return 0; /*allowed color type / bits combination*/ + switch(colortype) + { + case 0: + if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; + break; /*grey*/ + case 2: + if(!(bd == 8 || bd == 16)) return 37; + break; /*RGB*/ + case 3: + if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8)) return 37; + break; /*palette*/ + case 4: + if(!(bd == 8 || bd == 16)) return 37; + break; /*grey + alpha*/ + case 6: + if(!(bd == 8 || bd == 16)) return 37; + break; /*RGBA*/ + default: + return 31; + } + return 0; /*allowed color type / bits combination*/ } static unsigned getNumColorChannels(LodePNGColorType colortype) { - switch(colortype) - { - case 0: return 1; /*grey*/ - case 2: return 3; /*RGB*/ - case 3: return 1; /*palette*/ - case 4: return 2; /*grey + alpha*/ - case 6: return 4; /*RGBA*/ - } - return 0; /*unexisting color type*/ + switch(colortype) + { + case 0: + return 1; /*grey*/ + case 2: + return 3; /*RGB*/ + case 3: + return 1; /*palette*/ + case 4: + return 2; /*grey + alpha*/ + case 6: + return 4; /*RGBA*/ + } + return 0; /*unexisting color type*/ } static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) { - /*bits per pixel is amount of channels * bits per channel*/ - return getNumColorChannels(colortype) * bitdepth; + /*bits per pixel is amount of channels * bits per channel*/ + return getNumColorChannels(colortype) * bitdepth; } /* ////////////////////////////////////////////////////////////////////////// */ void lodepng_color_mode_init(LodePNGColorMode* info) { - info->key_defined = 0; - info->key_r = info->key_g = info->key_b = 0; - info->colortype = LCT_RGBA; - info->bitdepth = 8; - info->palette = 0; - info->palettesize = 0; + info->key_defined = 0; + info->key_r = info->key_g = info->key_b = 0; + info->colortype = LCT_RGBA; + info->bitdepth = 8; + info->palette = 0; + info->palettesize = 0; } void lodepng_color_mode_cleanup(LodePNGColorMode* info) { - lodepng_palette_clear(info); + lodepng_palette_clear(info); } unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) { - size_t i; - lodepng_color_mode_cleanup(dest); - *dest = *source; - if(source->palette) - { - dest->palette = (uint8_t*)lodepng_malloc(1024); - if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ - for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i]; - } - return 0; + size_t i; + lodepng_color_mode_cleanup(dest); + *dest = *source; + if(source->palette) + { + dest->palette = (uint8_t*)lodepng_malloc(1024); + if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ + for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i]; + } + return 0; } static int32_t lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) { - size_t i; - if(a->colortype != b->colortype) return 0; - if(a->bitdepth != b->bitdepth) return 0; - if(a->key_defined != b->key_defined) return 0; - if(a->key_defined) - { - if(a->key_r != b->key_r) return 0; - if(a->key_g != b->key_g) return 0; - if(a->key_b != b->key_b) return 0; - } - if(a->palettesize != b->palettesize) return 0; - for(i = 0; i != a->palettesize * 4; ++i) - { - if(a->palette[i] != b->palette[i]) return 0; - } - return 1; + size_t i; + if(a->colortype != b->colortype) return 0; + if(a->bitdepth != b->bitdepth) return 0; + if(a->key_defined != b->key_defined) return 0; + if(a->key_defined) + { + if(a->key_r != b->key_r) return 0; + if(a->key_g != b->key_g) return 0; + if(a->key_b != b->key_b) return 0; + } + if(a->palettesize != b->palettesize) return 0; + for(i = 0; i != a->palettesize * 4; ++i) + { + if(a->palette[i] != b->palette[i]) return 0; + } + return 1; } void lodepng_palette_clear(LodePNGColorMode* info) { - if(info->palette) lodepng_free(info->palette); - info->palette = 0; - info->palettesize = 0; + if(info->palette) lodepng_free(info->palette); + info->palette = 0; + info->palettesize = 0; } unsigned lodepng_palette_add(LodePNGColorMode* info, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { - uint8_t* data; - /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with - the max of 256 colors, it'll have the exact alloc size*/ - if(!info->palette) /*allocate palette if empty*/ - { - /*room for 256 colors with 4 bytes each*/ - data = (uint8_t*)lodepng_realloc(info->palette, 1024); - if(!data) return 83; /*alloc fail*/ - else info->palette = data; - } - info->palette[4 * info->palettesize + 0] = r; - info->palette[4 * info->palettesize + 1] = g; - info->palette[4 * info->palettesize + 2] = b; - info->palette[4 * info->palettesize + 3] = a; - ++info->palettesize; - return 0; + uint8_t* data; + /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with + the max of 256 colors, it'll have the exact alloc size*/ + if(!info->palette) /*allocate palette if empty*/ + { + /*room for 256 colors with 4 bytes each*/ + data = (uint8_t*)lodepng_realloc(info->palette, 1024); + if(!data) return 83; /*alloc fail*/ + else info->palette = data; + } + info->palette[4 * info->palettesize + 0] = r; + info->palette[4 * info->palettesize + 1] = g; + info->palette[4 * info->palettesize + 2] = b; + info->palette[4 * info->palettesize + 3] = a; + ++info->palettesize; + return 0; } unsigned lodepng_get_bpp(const LodePNGColorMode* info) { - /*calculate bits per pixel out of colortype and bitdepth*/ - return lodepng_get_bpp_lct(info->colortype, info->bitdepth); + /*calculate bits per pixel out of colortype and bitdepth*/ + return lodepng_get_bpp_lct(info->colortype, info->bitdepth); } unsigned lodepng_get_channels(const LodePNGColorMode* info) { - return getNumColorChannels(info->colortype); + return getNumColorChannels(info->colortype); } unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) { - return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; + return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; } unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) { - return (info->colortype & 4) != 0; /*4 or 6*/ + return (info->colortype & 4) != 0; /*4 or 6*/ } unsigned lodepng_is_palette_type(const LodePNGColorMode* info) { - return info->colortype == LCT_PALETTE; + return info->colortype == LCT_PALETTE; } unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) { - size_t i; - for(i = 0; i != info->palettesize; ++i) - { - if(info->palette[i * 4 + 3] < 255) return 1; - } - return 0; + size_t i; + for(i = 0; i != info->palettesize; ++i) + { + if(info->palette[i * 4 + 3] < 255) return 1; + } + return 0; } unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) { - return info->key_defined - || lodepng_is_alpha_type(info) - || lodepng_has_palette_alpha(info); + return info->key_defined + || lodepng_is_alpha_type(info) + || lodepng_has_palette_alpha(info); } size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) { - /*will not overflow for any color type if roughly w * h < 268435455*/ - size_t bpp = lodepng_get_bpp(color); - size_t n = w * h; - return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; + /*will not overflow for any color type if roughly w * h < 268435455*/ + size_t bpp = lodepng_get_bpp(color); + size_t n = w * h; + return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; } @@ -2714,10 +2745,10 @@ size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* colo /*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/ static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) { - /*will not overflow for any color type if roughly w * h < 268435455*/ - size_t bpp = lodepng_get_bpp(color); - size_t line = ((w / 8) * bpp) + ((w & 7) * bpp + 7) / 8; - return h * line; + /*will not overflow for any color type if roughly w * h < 268435455*/ + size_t bpp = lodepng_get_bpp(color); + size_t line = ((w / 8) * bpp) + ((w & 7) * bpp + 7) / 8; + return h * line; } #endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_PNG*/ @@ -2726,233 +2757,233 @@ static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGCol static void LodePNGUnknownChunks_init(LodePNGInfo* info) { - unsigned i; - for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0; - for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0; + unsigned i; + for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0; + for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0; } static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) { - unsigned i; - for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]); + unsigned i; + for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]); } static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) { - unsigned i; + unsigned i; - LodePNGUnknownChunks_cleanup(dest); + LodePNGUnknownChunks_cleanup(dest); - for(i = 0; i != 3; ++i) - { - size_t j; - dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; - dest->unknown_chunks_data[i] = (uint8_t*)lodepng_malloc(src->unknown_chunks_size[i]); - if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ - for(j = 0; j < src->unknown_chunks_size[i]; ++j) - { - dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; - } - } + for(i = 0; i != 3; ++i) + { + size_t j; + dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; + dest->unknown_chunks_data[i] = (uint8_t*)lodepng_malloc(src->unknown_chunks_size[i]); + if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ + for(j = 0; j < src->unknown_chunks_size[i]; ++j) + { + dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; + } + } - return 0; + return 0; } /******************************************************************************/ static void LodePNGText_init(LodePNGInfo* info) { - info->text_num = 0; - info->text_keys = NULL; - info->text_strings = NULL; + info->text_num = 0; + info->text_keys = NULL; + info->text_strings = NULL; } static void LodePNGText_cleanup(LodePNGInfo* info) { - size_t i; - for(i = 0; i != info->text_num; ++i) - { - string_cleanup(&info->text_keys[i]); - string_cleanup(&info->text_strings[i]); - } - lodepng_free(info->text_keys); - lodepng_free(info->text_strings); + size_t i; + for(i = 0; i != info->text_num; ++i) + { + string_cleanup(&info->text_keys[i]); + string_cleanup(&info->text_strings[i]); + } + lodepng_free(info->text_keys); + lodepng_free(info->text_strings); } static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { - size_t i = 0; - dest->text_keys = 0; - dest->text_strings = 0; - dest->text_num = 0; - for(i = 0; i != source->text_num; ++i) - { - CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); - } - return 0; + size_t i = 0; + dest->text_keys = 0; + dest->text_strings = 0; + dest->text_num = 0; + for(i = 0; i != source->text_num; ++i) + { + CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); + } + return 0; } void lodepng_clear_text(LodePNGInfo* info) { - LodePNGText_cleanup(info); + LodePNGText_cleanup(info); } unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) { - char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); - char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); - if(!new_keys || !new_strings) - { - lodepng_free(new_keys); - lodepng_free(new_strings); - return 83; /*alloc fail*/ - } + char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); + if(!new_keys || !new_strings) + { + lodepng_free(new_keys); + lodepng_free(new_strings); + return 83; /*alloc fail*/ + } - ++info->text_num; - info->text_keys = new_keys; - info->text_strings = new_strings; + ++info->text_num; + info->text_keys = new_keys; + info->text_strings = new_strings; - string_init(&info->text_keys[info->text_num - 1]); - string_set(&info->text_keys[info->text_num - 1], key); + string_init(&info->text_keys[info->text_num - 1]); + string_set(&info->text_keys[info->text_num - 1], key); - string_init(&info->text_strings[info->text_num - 1]); - string_set(&info->text_strings[info->text_num - 1], str); + string_init(&info->text_strings[info->text_num - 1]); + string_set(&info->text_strings[info->text_num - 1], str); - return 0; + return 0; } /******************************************************************************/ static void LodePNGIText_init(LodePNGInfo* info) { - info->itext_num = 0; - info->itext_keys = NULL; - info->itext_langtags = NULL; - info->itext_transkeys = NULL; - info->itext_strings = NULL; + info->itext_num = 0; + info->itext_keys = NULL; + info->itext_langtags = NULL; + info->itext_transkeys = NULL; + info->itext_strings = NULL; } static void LodePNGIText_cleanup(LodePNGInfo* info) { - size_t i; - for(i = 0; i != info->itext_num; ++i) - { - string_cleanup(&info->itext_keys[i]); - string_cleanup(&info->itext_langtags[i]); - string_cleanup(&info->itext_transkeys[i]); - string_cleanup(&info->itext_strings[i]); - } - lodepng_free(info->itext_keys); - lodepng_free(info->itext_langtags); - lodepng_free(info->itext_transkeys); - lodepng_free(info->itext_strings); + size_t i; + for(i = 0; i != info->itext_num; ++i) + { + string_cleanup(&info->itext_keys[i]); + string_cleanup(&info->itext_langtags[i]); + string_cleanup(&info->itext_transkeys[i]); + string_cleanup(&info->itext_strings[i]); + } + lodepng_free(info->itext_keys); + lodepng_free(info->itext_langtags); + lodepng_free(info->itext_transkeys); + lodepng_free(info->itext_strings); } static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { - size_t i = 0; - dest->itext_keys = 0; - dest->itext_langtags = 0; - dest->itext_transkeys = 0; - dest->itext_strings = 0; - dest->itext_num = 0; - for(i = 0; i != source->itext_num; ++i) - { - CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], - source->itext_transkeys[i], source->itext_strings[i])); - } - return 0; + size_t i = 0; + dest->itext_keys = 0; + dest->itext_langtags = 0; + dest->itext_transkeys = 0; + dest->itext_strings = 0; + dest->itext_num = 0; + for(i = 0; i != source->itext_num; ++i) + { + CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], + source->itext_transkeys[i], source->itext_strings[i])); + } + return 0; } void lodepng_clear_itext(LodePNGInfo* info) { - LodePNGIText_cleanup(info); + LodePNGIText_cleanup(info); } unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, const char* transkey, const char* str) { - char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); - char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); - char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); - char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); - if(!new_keys || !new_langtags || !new_transkeys || !new_strings) - { - lodepng_free(new_keys); - lodepng_free(new_langtags); - lodepng_free(new_transkeys); - lodepng_free(new_strings); - return 83; /*alloc fail*/ - } + char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); + char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); + char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); + if(!new_keys || !new_langtags || !new_transkeys || !new_strings) + { + lodepng_free(new_keys); + lodepng_free(new_langtags); + lodepng_free(new_transkeys); + lodepng_free(new_strings); + return 83; /*alloc fail*/ + } - ++info->itext_num; - info->itext_keys = new_keys; - info->itext_langtags = new_langtags; - info->itext_transkeys = new_transkeys; - info->itext_strings = new_strings; + ++info->itext_num; + info->itext_keys = new_keys; + info->itext_langtags = new_langtags; + info->itext_transkeys = new_transkeys; + info->itext_strings = new_strings; - string_init(&info->itext_keys[info->itext_num - 1]); - string_set(&info->itext_keys[info->itext_num - 1], key); + string_init(&info->itext_keys[info->itext_num - 1]); + string_set(&info->itext_keys[info->itext_num - 1], key); - string_init(&info->itext_langtags[info->itext_num - 1]); - string_set(&info->itext_langtags[info->itext_num - 1], langtag); + string_init(&info->itext_langtags[info->itext_num - 1]); + string_set(&info->itext_langtags[info->itext_num - 1], langtag); - string_init(&info->itext_transkeys[info->itext_num - 1]); - string_set(&info->itext_transkeys[info->itext_num - 1], transkey); + string_init(&info->itext_transkeys[info->itext_num - 1]); + string_set(&info->itext_transkeys[info->itext_num - 1], transkey); - string_init(&info->itext_strings[info->itext_num - 1]); - string_set(&info->itext_strings[info->itext_num - 1], str); + string_init(&info->itext_strings[info->itext_num - 1]); + string_set(&info->itext_strings[info->itext_num - 1], str); - return 0; + return 0; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ void lodepng_info_init(LodePNGInfo* info) { - lodepng_color_mode_init(&info->color); - info->interlace_method = 0; - info->compression_method = 0; - info->filter_method = 0; + lodepng_color_mode_init(&info->color); + info->interlace_method = 0; + info->compression_method = 0; + info->filter_method = 0; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - info->background_defined = 0; - info->background_r = info->background_g = info->background_b = 0; + info->background_defined = 0; + info->background_r = info->background_g = info->background_b = 0; - LodePNGText_init(info); - LodePNGIText_init(info); + LodePNGText_init(info); + LodePNGIText_init(info); - info->time_defined = 0; - info->phys_defined = 0; + info->time_defined = 0; + info->phys_defined = 0; - LodePNGUnknownChunks_init(info); + LodePNGUnknownChunks_init(info); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } void lodepng_info_cleanup(LodePNGInfo* info) { - lodepng_color_mode_cleanup(&info->color); + lodepng_color_mode_cleanup(&info->color); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - LodePNGText_cleanup(info); - LodePNGIText_cleanup(info); + LodePNGText_cleanup(info); + LodePNGIText_cleanup(info); - LodePNGUnknownChunks_cleanup(info); + LodePNGUnknownChunks_cleanup(info); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) { - lodepng_info_cleanup(dest); - *dest = *source; - lodepng_color_mode_init(&dest->color); - CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color)); + lodepng_info_cleanup(dest); + *dest = *source; + lodepng_color_mode_init(&dest->color); + CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color)); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); - CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); + CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); + CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); - LodePNGUnknownChunks_init(dest); - CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); + LodePNGUnknownChunks_init(dest); + CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - return 0; + return 0; } /* ////////////////////////////////////////////////////////////////////////// */ @@ -2960,13 +2991,13 @@ unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) /*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/ static void addColorBits(uint8_t* out, size_t index, unsigned bits, unsigned in) { - unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ - /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ - unsigned p = index & m; - in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/ - in = in << (bits * (m - p)); - if(p == 0) out[index * bits / 8] = in; - else out[index * bits / 8] |= in; + unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ + /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ + unsigned p = index & m; + in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/ + in = in << (bits * (m - p)); + if(p == 0) out[index * bits / 8] = in; + else out[index * bits / 8] |= in; } typedef struct ColorTree ColorTree; @@ -2979,47 +3010,47 @@ node has 16 instead of 8 children. */ struct ColorTree { - ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ - int32_t index; /*the payload. Only has a meaningful value if this is in the last level*/ + ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ + int32_t index; /*the payload. Only has a meaningful value if this is in the last level*/ }; static void color_tree_init(ColorTree* tree) { - int32_t i; - for(i = 0; i != 16; ++i) tree->children[i] = 0; - tree->index = -1; + int32_t i; + for(i = 0; i != 16; ++i) tree->children[i] = 0; + tree->index = -1; } static void color_tree_cleanup(ColorTree* tree) { - int32_t i; - for(i = 0; i != 16; ++i) - { - if(tree->children[i]) - { - color_tree_cleanup(tree->children[i]); - lodepng_free(tree->children[i]); - } - } + int32_t i; + for(i = 0; i != 16; ++i) + { + if(tree->children[i]) + { + color_tree_cleanup(tree->children[i]); + lodepng_free(tree->children[i]); + } + } } /*returns -1 if color not present, its index otherwise*/ static int32_t color_tree_get(ColorTree* tree, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { - int32_t bit = 0; - for(bit = 0; bit < 8; ++bit) - { - int32_t i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); - if(!tree->children[i]) return -1; - else tree = tree->children[i]; - } - return tree ? tree->index : -1; + int32_t bit = 0; + for(bit = 0; bit < 8; ++bit) + { + int32_t i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) return -1; + else tree = tree->children[i]; + } + return tree ? tree->index : -1; } #ifdef LODEPNG_COMPILE_ENCODER static int32_t color_tree_has(ColorTree* tree, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { - return color_tree_get(tree, r, g, b, a) >= 0; + return color_tree_get(tree, r, g, b, a) >= 0; } #endif /*LODEPNG_COMPILE_ENCODER*/ @@ -3028,18 +3059,18 @@ Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't ex static void color_tree_add(ColorTree* tree, uint8_t r, uint8_t g, uint8_t b, uint8_t a, unsigned index) { - int32_t bit; - for(bit = 0; bit < 8; ++bit) - { - int32_t i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); - if(!tree->children[i]) - { - tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree)); - color_tree_init(tree->children[i]); - } - tree = tree->children[i]; - } - tree->index = (int32_t)index; + int32_t bit; + for(bit = 0; bit < 8; ++bit) + { + int32_t i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) + { + tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree)); + color_tree_init(tree->children[i]); + } + tree = tree->children[i]; + } + tree->index = (int32_t)index; } /*put a pixel, given its RGBA color, into image of any color type*/ @@ -3047,114 +3078,114 @@ static unsigned rgba8ToPixel(uint8_t* out, size_t i, const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { - if(mode->colortype == LCT_GREY) - { - uint8_t grey = r; /*((uint16_t)r + g + b) / 3*/; - if(mode->bitdepth == 8) out[i] = grey; - else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey; - else - { - /*take the most significant bits of grey*/ - grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1); - addColorBits(out, i, mode->bitdepth, grey); - } - } - else if(mode->colortype == LCT_RGB) - { - if(mode->bitdepth == 8) - { - out[i * 3 + 0] = r; - out[i * 3 + 1] = g; - out[i * 3 + 2] = b; - } - else - { - out[i * 6 + 0] = out[i * 6 + 1] = r; - out[i * 6 + 2] = out[i * 6 + 3] = g; - out[i * 6 + 4] = out[i * 6 + 5] = b; - } - } - else if(mode->colortype == LCT_PALETTE) - { - int32_t index = color_tree_get(tree, r, g, b, a); - if(index < 0) return 82; /*color not in palette*/ - if(mode->bitdepth == 8) out[i] = index; - else addColorBits(out, i, mode->bitdepth, (unsigned)index); - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - uint8_t grey = r; /*((uint16_t)r + g + b) / 3*/; - if(mode->bitdepth == 8) - { - out[i * 2 + 0] = grey; - out[i * 2 + 1] = a; - } - else if(mode->bitdepth == 16) - { - out[i * 4 + 0] = out[i * 4 + 1] = grey; - out[i * 4 + 2] = out[i * 4 + 3] = a; - } - } - else if(mode->colortype == LCT_RGBA) - { - if(mode->bitdepth == 8) - { - out[i * 4 + 0] = r; - out[i * 4 + 1] = g; - out[i * 4 + 2] = b; - out[i * 4 + 3] = a; - } - else - { - out[i * 8 + 0] = out[i * 8 + 1] = r; - out[i * 8 + 2] = out[i * 8 + 3] = g; - out[i * 8 + 4] = out[i * 8 + 5] = b; - out[i * 8 + 6] = out[i * 8 + 7] = a; - } - } + if(mode->colortype == LCT_GREY) + { + uint8_t grey = r; /*((uint16_t)r + g + b) / 3*/; + if(mode->bitdepth == 8) out[i] = grey; + else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey; + else + { + /*take the most significant bits of grey*/ + grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1); + addColorBits(out, i, mode->bitdepth, grey); + } + } + else if(mode->colortype == LCT_RGB) + { + if(mode->bitdepth == 8) + { + out[i * 3 + 0] = r; + out[i * 3 + 1] = g; + out[i * 3 + 2] = b; + } + else + { + out[i * 6 + 0] = out[i * 6 + 1] = r; + out[i * 6 + 2] = out[i * 6 + 3] = g; + out[i * 6 + 4] = out[i * 6 + 5] = b; + } + } + else if(mode->colortype == LCT_PALETTE) + { + int32_t index = color_tree_get(tree, r, g, b, a); + if(index < 0) return 82; /*color not in palette*/ + if(mode->bitdepth == 8) out[i] = index; + else addColorBits(out, i, mode->bitdepth, (unsigned)index); + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + uint8_t grey = r; /*((uint16_t)r + g + b) / 3*/; + if(mode->bitdepth == 8) + { + out[i * 2 + 0] = grey; + out[i * 2 + 1] = a; + } + else if(mode->bitdepth == 16) + { + out[i * 4 + 0] = out[i * 4 + 1] = grey; + out[i * 4 + 2] = out[i * 4 + 3] = a; + } + } + else if(mode->colortype == LCT_RGBA) + { + if(mode->bitdepth == 8) + { + out[i * 4 + 0] = r; + out[i * 4 + 1] = g; + out[i * 4 + 2] = b; + out[i * 4 + 3] = a; + } + else + { + out[i * 8 + 0] = out[i * 8 + 1] = r; + out[i * 8 + 2] = out[i * 8 + 3] = g; + out[i * 8 + 4] = out[i * 8 + 5] = b; + out[i * 8 + 6] = out[i * 8 + 7] = a; + } + } - return 0; /*no error*/ + return 0; /*no error*/ } /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/ static void rgba16ToPixel(uint8_t* out, size_t i, - const LodePNGColorMode* mode, - uint16_t r, uint16_t g, uint16_t b, uint16_t a) + const LodePNGColorMode* mode, + uint16_t r, uint16_t g, uint16_t b, uint16_t a) { - if(mode->colortype == LCT_GREY) - { - uint16_t grey = r; /*((unsigned)r + g + b) / 3*/; - out[i * 2 + 0] = (grey >> 8) & 255; - out[i * 2 + 1] = grey & 255; - } - else if(mode->colortype == LCT_RGB) - { - out[i * 6 + 0] = (r >> 8) & 255; - out[i * 6 + 1] = r & 255; - out[i * 6 + 2] = (g >> 8) & 255; - out[i * 6 + 3] = g & 255; - out[i * 6 + 4] = (b >> 8) & 255; - out[i * 6 + 5] = b & 255; - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - uint16_t grey = r; /*((unsigned)r + g + b) / 3*/; - out[i * 4 + 0] = (grey >> 8) & 255; - out[i * 4 + 1] = grey & 255; - out[i * 4 + 2] = (a >> 8) & 255; - out[i * 4 + 3] = a & 255; - } - else if(mode->colortype == LCT_RGBA) - { - out[i * 8 + 0] = (r >> 8) & 255; - out[i * 8 + 1] = r & 255; - out[i * 8 + 2] = (g >> 8) & 255; - out[i * 8 + 3] = g & 255; - out[i * 8 + 4] = (b >> 8) & 255; - out[i * 8 + 5] = b & 255; - out[i * 8 + 6] = (a >> 8) & 255; - out[i * 8 + 7] = a & 255; - } + if(mode->colortype == LCT_GREY) + { + uint16_t grey = r; /*((unsigned)r + g + b) / 3*/; + out[i * 2 + 0] = (grey >> 8) & 255; + out[i * 2 + 1] = grey & 255; + } + else if(mode->colortype == LCT_RGB) + { + out[i * 6 + 0] = (r >> 8) & 255; + out[i * 6 + 1] = r & 255; + out[i * 6 + 2] = (g >> 8) & 255; + out[i * 6 + 3] = g & 255; + out[i * 6 + 4] = (b >> 8) & 255; + out[i * 6 + 5] = b & 255; + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + uint16_t grey = r; /*((unsigned)r + g + b) / 3*/; + out[i * 4 + 0] = (grey >> 8) & 255; + out[i * 4 + 1] = grey & 255; + out[i * 4 + 2] = (a >> 8) & 255; + out[i * 4 + 3] = a & 255; + } + else if(mode->colortype == LCT_RGBA) + { + out[i * 8 + 0] = (r >> 8) & 255; + out[i * 8 + 1] = r & 255; + out[i * 8 + 2] = (g >> 8) & 255; + out[i * 8 + 3] = g & 255; + out[i * 8 + 4] = (b >> 8) & 255; + out[i * 8 + 5] = b & 255; + out[i * 8 + 6] = (a >> 8) & 255; + out[i * 8 + 7] = a & 255; + } } /*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/ @@ -3163,104 +3194,106 @@ static void getPixelColorRGBA8(uint8_t* r, uint8_t* g, const uint8_t* in, size_t i, const LodePNGColorMode* mode) { - if(mode->colortype == LCT_GREY) - { - if(mode->bitdepth == 8) - { - *r = *g = *b = in[i]; - if(mode->key_defined && *r == mode->key_r) *a = 0; - else *a = 255; - } - else if(mode->bitdepth == 16) - { - *r = *g = *b = in[i * 2 + 0]; - if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; - else *a = 255; - } - else - { - unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ - size_t j = i * mode->bitdepth; - unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); - *r = *g = *b = (value * 255) / highest; - if(mode->key_defined && value == mode->key_r) *a = 0; - else *a = 255; - } - } - else if(mode->colortype == LCT_RGB) - { - if(mode->bitdepth == 8) - { - *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2]; - if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; - else *a = 255; - } - else - { - *r = in[i * 6 + 0]; - *g = in[i * 6 + 2]; - *b = in[i * 6 + 4]; - if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r - && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g - && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; - else *a = 255; - } - } - else if(mode->colortype == LCT_PALETTE) - { - unsigned index; - if(mode->bitdepth == 8) index = in[i]; - else - { - size_t j = i * mode->bitdepth; - index = readBitsFromReversedStream(&j, in, mode->bitdepth); - } + if(mode->colortype == LCT_GREY) + { + if(mode->bitdepth == 8) + { + *r = *g = *b = in[i]; + if(mode->key_defined && *r == mode->key_r) *a = 0; + else *a = 255; + } + else if(mode->bitdepth == 16) + { + *r = *g = *b = in[i * 2 + 0]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 255; + } + else + { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = i * mode->bitdepth; + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + *r = *g = *b = (value * 255) / highest; + if(mode->key_defined && value == mode->key_r) *a = 0; + else *a = 255; + } + } + else if(mode->colortype == LCT_RGB) + { + if(mode->bitdepth == 8) + { + *r = in[i * 3 + 0]; + *g = in[i * 3 + 1]; + *b = in[i * 3 + 2]; + if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; + else *a = 255; + } + else + { + *r = in[i * 6 + 0]; + *g = in[i * 6 + 2]; + *b = in[i * 6 + 4]; + if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 255; + } + } + else if(mode->colortype == LCT_PALETTE) + { + unsigned index; + if(mode->bitdepth == 8) index = in[i]; + else + { + size_t j = i * mode->bitdepth; + index = readBitsFromReversedStream(&j, in, mode->bitdepth); + } - if(index >= mode->palettesize) - { - /*This is an error according to the PNG spec, but common PNG decoders make it black instead. - Done here too, slightly faster due to no error handling needed.*/ - *r = *g = *b = 0; - *a = 255; - } - else - { - *r = mode->palette[index * 4 + 0]; - *g = mode->palette[index * 4 + 1]; - *b = mode->palette[index * 4 + 2]; - *a = mode->palette[index * 4 + 3]; - } - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - if(mode->bitdepth == 8) - { - *r = *g = *b = in[i * 2 + 0]; - *a = in[i * 2 + 1]; - } - else - { - *r = *g = *b = in[i * 4 + 0]; - *a = in[i * 4 + 2]; - } - } - else if(mode->colortype == LCT_RGBA) - { - if(mode->bitdepth == 8) - { - *r = in[i * 4 + 0]; - *g = in[i * 4 + 1]; - *b = in[i * 4 + 2]; - *a = in[i * 4 + 3]; - } - else - { - *r = in[i * 8 + 0]; - *g = in[i * 8 + 2]; - *b = in[i * 8 + 4]; - *a = in[i * 8 + 6]; - } - } + if(index >= mode->palettesize) + { + /*This is an error according to the PNG spec, but common PNG decoders make it black instead. + Done here too, slightly faster due to no error handling needed.*/ + *r = *g = *b = 0; + *a = 255; + } + else + { + *r = mode->palette[index * 4 + 0]; + *g = mode->palette[index * 4 + 1]; + *b = mode->palette[index * 4 + 2]; + *a = mode->palette[index * 4 + 3]; + } + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + if(mode->bitdepth == 8) + { + *r = *g = *b = in[i * 2 + 0]; + *a = in[i * 2 + 1]; + } + else + { + *r = *g = *b = in[i * 4 + 0]; + *a = in[i * 4 + 2]; + } + } + else if(mode->colortype == LCT_RGBA) + { + if(mode->bitdepth == 8) + { + *r = in[i * 4 + 0]; + *g = in[i * 4 + 1]; + *b = in[i * 4 + 2]; + *a = in[i * 4 + 3]; + } + else + { + *r = in[i * 8 + 0]; + *g = in[i * 8 + 2]; + *b = in[i * 8 + 4]; + *a = in[i * 8 + 6]; + } + } } /*Similar to getPixelColorRGBA8, but with all the for loops inside of the color @@ -3272,132 +3305,132 @@ static void getPixelColorsRGBA8(uint8_t* buffer, size_t numpixels, unsigned has_alpha, const uint8_t* in, const LodePNGColorMode* mode) { - unsigned num_channels = has_alpha ? 4 : 3; - size_t i; - if(mode->colortype == LCT_GREY) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = buffer[1] = buffer[2] = in[i]; - if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255; - } - } - else if(mode->bitdepth == 16) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = buffer[1] = buffer[2] = in[i * 2]; - if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; - } - } - else - { - unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ - size_t j = 0; - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); - buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; - if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; - } - } - } - else if(mode->colortype == LCT_RGB) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = in[i * 3 + 0]; - buffer[1] = in[i * 3 + 1]; - buffer[2] = in[i * 3 + 2]; - if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r - && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255; - } - } - else - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = in[i * 6 + 0]; - buffer[1] = in[i * 6 + 2]; - buffer[2] = in[i * 6 + 4]; - if(has_alpha) buffer[3] = mode->key_defined - && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r - && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g - && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; - } - } - } - else if(mode->colortype == LCT_PALETTE) - { - unsigned index; - size_t j = 0; - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - if(mode->bitdepth == 8) index = in[i]; - else index = readBitsFromReversedStream(&j, in, mode->bitdepth); + unsigned num_channels = has_alpha ? 4 : 3; + size_t i; + if(mode->colortype == LCT_GREY) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i]; + if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255; + } + } + else if(mode->bitdepth == 16) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i * 2]; + if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; + } + } + else + { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; + if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; + } + } + } + else if(mode->colortype == LCT_RGB) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 3 + 0]; + buffer[1] = in[i * 3 + 1]; + buffer[2] = in[i * 3 + 2]; + if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r + && buffer[1] == mode->key_g && buffer[2] == mode->key_b ? 0 : 255; + } + } + else + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 6 + 0]; + buffer[1] = in[i * 6 + 2]; + buffer[2] = in[i * 6 + 4]; + if(has_alpha) buffer[3] = mode->key_defined + && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; + } + } + } + else if(mode->colortype == LCT_PALETTE) + { + unsigned index; + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + if(mode->bitdepth == 8) index = in[i]; + else index = readBitsFromReversedStream(&j, in, mode->bitdepth); - if(index >= mode->palettesize) - { - /*This is an error according to the PNG spec, but most PNG decoders make it black instead. - Done here too, slightly faster due to no error handling needed.*/ - buffer[0] = buffer[1] = buffer[2] = 0; - if(has_alpha) buffer[3] = 255; - } - else - { - buffer[0] = mode->palette[index * 4 + 0]; - buffer[1] = mode->palette[index * 4 + 1]; - buffer[2] = mode->palette[index * 4 + 2]; - if(has_alpha) buffer[3] = mode->palette[index * 4 + 3]; - } - } - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; - if(has_alpha) buffer[3] = in[i * 2 + 1]; - } - } - else - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; - if(has_alpha) buffer[3] = in[i * 4 + 2]; - } - } - } - else if(mode->colortype == LCT_RGBA) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = in[i * 4 + 0]; - buffer[1] = in[i * 4 + 1]; - buffer[2] = in[i * 4 + 2]; - if(has_alpha) buffer[3] = in[i * 4 + 3]; - } - } - else - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = in[i * 8 + 0]; - buffer[1] = in[i * 8 + 2]; - buffer[2] = in[i * 8 + 4]; - if(has_alpha) buffer[3] = in[i * 8 + 6]; - } - } - } + if(index >= mode->palettesize) + { + /*This is an error according to the PNG spec, but most PNG decoders make it black instead. + Done here too, slightly faster due to no error handling needed.*/ + buffer[0] = buffer[1] = buffer[2] = 0; + if(has_alpha) buffer[3] = 255; + } + else + { + buffer[0] = mode->palette[index * 4 + 0]; + buffer[1] = mode->palette[index * 4 + 1]; + buffer[2] = mode->palette[index * 4 + 2]; + if(has_alpha) buffer[3] = mode->palette[index * 4 + 3]; + } + } + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; + if(has_alpha) buffer[3] = in[i * 2 + 1]; + } + } + else + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; + if(has_alpha) buffer[3] = in[i * 4 + 2]; + } + } + } + else if(mode->colortype == LCT_RGBA) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 4 + 0]; + buffer[1] = in[i * 4 + 1]; + buffer[2] = in[i * 4 + 2]; + if(has_alpha) buffer[3] = in[i * 4 + 3]; + } + } + else + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 8 + 0]; + buffer[1] = in[i * 8 + 2]; + buffer[2] = in[i * 8 + 4]; + if(has_alpha) buffer[3] = in[i * 8 + 6]; + } + } + } } /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with @@ -3405,130 +3438,130 @@ given color type, but the given color type must be 16-bit itself.*/ static void getPixelColorRGBA16(uint16_t* r, uint16_t* g, uint16_t* b, uint16_t* a, const uint8_t* in, size_t i, const LodePNGColorMode* mode) { - if(mode->colortype == LCT_GREY) - { - *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; - if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; - else *a = 65535; - } - else if(mode->colortype == LCT_RGB) - { - *r = 256u * in[i * 6 + 0] + in[i * 6 + 1]; - *g = 256u * in[i * 6 + 2] + in[i * 6 + 3]; - *b = 256u * in[i * 6 + 4] + in[i * 6 + 5]; - if(mode->key_defined - && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r - && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g - && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; - else *a = 65535; - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1]; - *a = 256u * in[i * 4 + 2] + in[i * 4 + 3]; - } - else if(mode->colortype == LCT_RGBA) - { - *r = 256u * in[i * 8 + 0] + in[i * 8 + 1]; - *g = 256u * in[i * 8 + 2] + in[i * 8 + 3]; - *b = 256u * in[i * 8 + 4] + in[i * 8 + 5]; - *a = 256u * in[i * 8 + 6] + in[i * 8 + 7]; - } + if(mode->colortype == LCT_GREY) + { + *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 65535; + } + else if(mode->colortype == LCT_RGB) + { + *r = 256u * in[i * 6 + 0] + in[i * 6 + 1]; + *g = 256u * in[i * 6 + 2] + in[i * 6 + 3]; + *b = 256u * in[i * 6 + 4] + in[i * 6 + 5]; + if(mode->key_defined + && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 65535; + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1]; + *a = 256u * in[i * 4 + 2] + in[i * 4 + 3]; + } + else if(mode->colortype == LCT_RGBA) + { + *r = 256u * in[i * 8 + 0] + in[i * 8 + 1]; + *g = 256u * in[i * 8 + 2] + in[i * 8 + 3]; + *b = 256u * in[i * 8 + 4] + in[i * 8 + 5]; + *a = 256u * in[i * 8 + 6] + in[i * 8 + 7]; + } } unsigned lodepng_convert(uint8_t* out, const uint8_t* in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, unsigned w, unsigned h) { - size_t i; - ColorTree tree; - size_t numpixels = w * h; - unsigned error = 0; + size_t i; + ColorTree tree; + size_t numpixels = w * h; + unsigned error = 0; - if(lodepng_color_mode_equal(mode_out, mode_in)) - { - size_t numbytes = lodepng_get_raw_size(w, h, mode_in); - for(i = 0; i != numbytes; ++i) out[i] = in[i]; - return 0; - } + if(lodepng_color_mode_equal(mode_out, mode_in)) + { + size_t numbytes = lodepng_get_raw_size(w, h, mode_in); + for(i = 0; i != numbytes; ++i) out[i] = in[i]; + return 0; + } - if(mode_out->colortype == LCT_PALETTE) - { - size_t palettesize = mode_out->palettesize; - const uint8_t* palette = mode_out->palette; - size_t palsize = (size_t)1u << mode_out->bitdepth; - /*if the user specified output palette but did not give the values, assume - they want the values of the input color type (assuming that one is palette). - Note that we never create a new palette ourselves.*/ - if(palettesize == 0) - { - palettesize = mode_in->palettesize; - palette = mode_in->palette; - /*if the input was also palette with same bitdepth, then the color types are also - equal, so copy literally. This to preserve the exact indices that were in the PNG - even in case there are duplicate colors in the palette.*/ - if (mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) - { - size_t numbytes = lodepng_get_raw_size(w, h, mode_in); - for(i = 0; i != numbytes; ++i) out[i] = in[i]; - return 0; - } - } - if(palettesize < palsize) palsize = palettesize; - color_tree_init(&tree); - for(i = 0; i != palsize; ++i) - { - const uint8_t* p = &palette[i * 4]; - color_tree_add(&tree, p[0], p[1], p[2], p[3], i); - } - } + if(mode_out->colortype == LCT_PALETTE) + { + size_t palettesize = mode_out->palettesize; + const uint8_t* palette = mode_out->palette; + size_t palsize = (size_t)1u << mode_out->bitdepth; + /*if the user specified output palette but did not give the values, assume + they want the values of the input color type (assuming that one is palette). + Note that we never create a new palette ourselves.*/ + if(palettesize == 0) + { + palettesize = mode_in->palettesize; + palette = mode_in->palette; + /*if the input was also palette with same bitdepth, then the color types are also + equal, so copy literally. This to preserve the exact indices that were in the PNG + even in case there are duplicate colors in the palette.*/ + if(mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) + { + size_t numbytes = lodepng_get_raw_size(w, h, mode_in); + for(i = 0; i != numbytes; ++i) out[i] = in[i]; + return 0; + } + } + if(palettesize < palsize) palsize = palettesize; + color_tree_init(&tree); + for(i = 0; i != palsize; ++i) + { + const uint8_t* p = &palette[i * 4]; + color_tree_add(&tree, p[0], p[1], p[2], p[3], i); + } + } - if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) - { - for(i = 0; i != numpixels; ++i) - { - uint16_t r = 0, g = 0, b = 0, a = 0; - getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); - rgba16ToPixel(out, i, mode_out, r, g, b, a); - } - } - else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) - { - getPixelColorsRGBA8(out, numpixels, 1, in, mode_in); - } - else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) - { - getPixelColorsRGBA8(out, numpixels, 0, in, mode_in); - } - else - { - uint8_t r = 0, g = 0, b = 0, a = 0; - for(i = 0; i != numpixels; ++i) - { - getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); - error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); - if (error) break; - } - } + if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) + { + for(i = 0; i != numpixels; ++i) + { + uint16_t r = 0, g = 0, b = 0, a = 0; + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + rgba16ToPixel(out, i, mode_out, r, g, b, a); + } + } + else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) + { + getPixelColorsRGBA8(out, numpixels, 1, in, mode_in); + } + else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) + { + getPixelColorsRGBA8(out, numpixels, 0, in, mode_in); + } + else + { + uint8_t r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); + error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); + if(error) break; + } + } - if(mode_out->colortype == LCT_PALETTE) - { - color_tree_cleanup(&tree); - } + if(mode_out->colortype == LCT_PALETTE) + { + color_tree_cleanup(&tree); + } - return error; + return error; } #ifdef LODEPNG_COMPILE_ENCODER void lodepng_color_profile_init(LodePNGColorProfile* profile) { - profile->colored = 0; - profile->key = 0; - profile->key_r = profile->key_g = profile->key_b = 0; - profile->alpha = 0; - profile->numcolors = 0; - profile->bits = 1; + profile->colored = 0; + profile->key = 0; + profile->key_r = profile->key_g = profile->key_b = 0; + profile->alpha = 0; + profile->numcolors = 0; + profile->bits = 1; } /*function used for debug purposes with C++*/ @@ -3547,10 +3580,10 @@ void lodepng_color_profile_init(LodePNGColorProfile* profile) /*Returns how many bits needed to represent given value (max 8 bit)*/ static unsigned getValueRequiredBits(uint8_t value) { - if(value == 0 || value == 255) return 1; - /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ - if(value % 17 == 0) return value % 85 == 0 ? 2 : 4; - return 8; + if(value == 0 || value == 255) return 1; + /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ + if(value % 17 == 0) return value % 85 == 0 ? 2 : 4; + return 8; } /*profile must already have been inited with mode. @@ -3559,191 +3592,191 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, const uint8_t* in, unsigned w, unsigned h, const LodePNGColorMode* mode) { - unsigned error = 0; - size_t i; - ColorTree tree; - size_t numpixels = w * h; + unsigned error = 0; + size_t i; + ColorTree tree; + size_t numpixels = w * h; - unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0; - unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1; - unsigned numcolors_done = 0; - unsigned bpp = lodepng_get_bpp(mode); - unsigned bits_done = bpp == 1 ? 1 : 0; - unsigned maxnumcolors = 257; - unsigned sixteen = 0; - if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256)); + unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0; + unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1; + unsigned numcolors_done = 0; + unsigned bpp = lodepng_get_bpp(mode); + unsigned bits_done = bpp == 1 ? 1 : 0; + unsigned maxnumcolors = 257; + unsigned sixteen = 0; + if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256)); - color_tree_init(&tree); + color_tree_init(&tree); - /*Check if the 16-bit input is truly 16-bit*/ - if(mode->bitdepth == 16) - { - uint16_t r, g, b, a; - for(i = 0; i != numpixels; ++i) - { - getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); - if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) || - (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ - { - sixteen = 1; - break; - } - } - } + /*Check if the 16-bit input is truly 16-bit*/ + if(mode->bitdepth == 16) + { + uint16_t r, g, b, a; + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); + if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) || + (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ + { + sixteen = 1; + break; + } + } + } - if(sixteen) - { - uint16_t r = 0, g = 0, b = 0, a = 0; - profile->bits = 16; - bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ + if(sixteen) + { + uint16_t r = 0, g = 0, b = 0, a = 0; + profile->bits = 16; + bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ - for(i = 0; i != numpixels; ++i) - { - getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); - if(!colored_done && (r != g || r != b)) - { - profile->colored = 1; - colored_done = 1; - } + if(!colored_done && (r != g || r != b)) + { + profile->colored = 1; + colored_done = 1; + } - if(!alpha_done) - { - unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); - if(a != 65535 && (a != 0 || (profile->key && !matchkey))) - { - profile->alpha = 1; - profile->key = 0; - alpha_done = 1; - } - else if(a == 0 && !profile->alpha && !profile->key) - { - profile->key = 1; - profile->key_r = r; - profile->key_g = g; - profile->key_b = b; - } - else if(a == 65535 && profile->key && matchkey) - { - /* Color key cannot be used if an opaque pixel also has that RGB color. */ - profile->alpha = 1; - profile->key = 0; - alpha_done = 1; - } - } - if(alpha_done && numcolors_done && colored_done && bits_done) break; - } + if(!alpha_done) + { + unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); + if(a != 65535 && (a != 0 || (profile->key && !matchkey))) + { + profile->alpha = 1; + profile->key = 0; + alpha_done = 1; + } + else if(a == 0 && !profile->alpha && !profile->key) + { + profile->key = 1; + profile->key_r = r; + profile->key_g = g; + profile->key_b = b; + } + else if(a == 65535 && profile->key && matchkey) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + profile->key = 0; + alpha_done = 1; + } + } + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } - if(profile->key && !profile->alpha) - { - for(i = 0; i != numpixels; ++i) - { - getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); - if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) - { - /* Color key cannot be used if an opaque pixel also has that RGB color. */ - profile->alpha = 1; - profile->key = 0; - alpha_done = 1; - } - } - } - } - else /* < 16-bit */ - { - uint8_t r = 0, g = 0, b = 0, a = 0; - for(i = 0; i != numpixels; ++i) - { - getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode); + if(profile->key && !profile->alpha) + { + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); + if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + profile->key = 0; + alpha_done = 1; + } + } + } + } + else /* < 16-bit */ + { + uint8_t r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode); - if(!bits_done && profile->bits < 8) - { - /*only r is checked, < 8 bits is only relevant for greyscale*/ - unsigned bits = getValueRequiredBits(r); - if(bits > profile->bits) profile->bits = bits; - } - bits_done = (profile->bits >= bpp); + if(!bits_done && profile->bits < 8) + { + /*only r is checked, < 8 bits is only relevant for greyscale*/ + unsigned bits = getValueRequiredBits(r); + if(bits > profile->bits) profile->bits = bits; + } + bits_done = (profile->bits >= bpp); - if(!colored_done && (r != g || r != b)) - { - profile->colored = 1; - colored_done = 1; - if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ - } + if(!colored_done && (r != g || r != b)) + { + profile->colored = 1; + colored_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ + } - if(!alpha_done) - { - unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); - if(a != 255 && (a != 0 || (profile->key && !matchkey))) - { - profile->alpha = 1; - profile->key = 0; - alpha_done = 1; - if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ - } - else if(a == 0 && !profile->alpha && !profile->key) - { - profile->key = 1; - profile->key_r = r; - profile->key_g = g; - profile->key_b = b; - } - else if(a == 255 && profile->key && matchkey) - { - /* Color key cannot be used if an opaque pixel also has that RGB color. */ - profile->alpha = 1; - profile->key = 0; - alpha_done = 1; - if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ - } - } + if(!alpha_done) + { + unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); + if(a != 255 && (a != 0 || (profile->key && !matchkey))) + { + profile->alpha = 1; + profile->key = 0; + alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + else if(a == 0 && !profile->alpha && !profile->key) + { + profile->key = 1; + profile->key_r = r; + profile->key_g = g; + profile->key_b = b; + } + else if(a == 255 && profile->key && matchkey) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + profile->key = 0; + alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + } - if(!numcolors_done) - { - if(!color_tree_has(&tree, r, g, b, a)) - { - color_tree_add(&tree, r, g, b, a, profile->numcolors); - if(profile->numcolors < 256) - { - uint8_t* p = profile->palette; - unsigned n = profile->numcolors; - p[n * 4 + 0] = r; - p[n * 4 + 1] = g; - p[n * 4 + 2] = b; - p[n * 4 + 3] = a; - } - ++profile->numcolors; - numcolors_done = profile->numcolors >= maxnumcolors; - } - } + if(!numcolors_done) + { + if(!color_tree_has(&tree, r, g, b, a)) + { + color_tree_add(&tree, r, g, b, a, profile->numcolors); + if(profile->numcolors < 256) + { + uint8_t* p = profile->palette; + unsigned n = profile->numcolors; + p[n * 4 + 0] = r; + p[n * 4 + 1] = g; + p[n * 4 + 2] = b; + p[n * 4 + 3] = a; + } + ++profile->numcolors; + numcolors_done = profile->numcolors >= maxnumcolors; + } + } - if(alpha_done && numcolors_done && colored_done && bits_done) break; - } + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } - if(profile->key && !profile->alpha) - { - for(i = 0; i != numpixels; ++i) - { - getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode); - if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) - { - /* Color key cannot be used if an opaque pixel also has that RGB color. */ - profile->alpha = 1; - profile->key = 0; - alpha_done = 1; - if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ - } - } - } + if(profile->key && !profile->alpha) + { + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode); + if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + profile->key = 0; + alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + } + } - /*make the profile's key always 16-bit for consistency - repeat each byte twice*/ - profile->key_r += (profile->key_r << 8); - profile->key_g += (profile->key_g << 8); - profile->key_b += (profile->key_b << 8); - } + /*make the profile's key always 16-bit for consistency - repeat each byte twice*/ + profile->key_r += (profile->key_r << 8); + profile->key_g += (profile->key_g << 8); + profile->key_b += (profile->key_b << 8); + } - color_tree_cleanup(&tree); - return error; + color_tree_cleanup(&tree); + return error; } /*Automatically chooses color type that gives smallest amount of bits in the @@ -3755,65 +3788,65 @@ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, const uint8_t* image, unsigned w, unsigned h, const LodePNGColorMode* mode_in) { - LodePNGColorProfile prof; - unsigned error = 0; - unsigned i, n, palettebits, palette_ok; + LodePNGColorProfile prof; + unsigned error = 0; + unsigned i, n, palettebits, palette_ok; - lodepng_color_profile_init(&prof); - error = lodepng_get_color_profile(&prof, image, w, h, mode_in); - if(error) return error; - mode_out->key_defined = 0; + lodepng_color_profile_init(&prof); + error = lodepng_get_color_profile(&prof, image, w, h, mode_in); + if(error) return error; + mode_out->key_defined = 0; - if(prof.key && w * h <= 16) - { - prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ - prof.key = 0; - if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ - } - n = prof.numcolors; - palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); - palette_ok = n <= 256 && prof.bits <= 8; - if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ - if(!prof.colored && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ + if(prof.key && w * h <= 16) + { + prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ + prof.key = 0; + if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + n = prof.numcolors; + palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); + palette_ok = n <= 256 && prof.bits <= 8; + if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ + if(!prof.colored && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ - if(palette_ok) - { - uint8_t* p = prof.palette; - lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ - for(i = 0; i != prof.numcolors; ++i) - { - error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); - if(error) break; - } + if(palette_ok) + { + uint8_t* p = prof.palette; + lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ + for(i = 0; i != prof.numcolors; ++i) + { + error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); + if(error) break; + } - mode_out->colortype = LCT_PALETTE; - mode_out->bitdepth = palettebits; + mode_out->colortype = LCT_PALETTE; + mode_out->bitdepth = palettebits; - if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize - && mode_in->bitdepth == mode_out->bitdepth) - { - /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ - lodepng_color_mode_cleanup(mode_out); - lodepng_color_mode_copy(mode_out, mode_in); - } - } - else /*8-bit or 16-bit per channel*/ - { - mode_out->bitdepth = prof.bits; - mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA) - : (prof.colored ? LCT_RGB : LCT_GREY); + if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize + && mode_in->bitdepth == mode_out->bitdepth) + { + /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ + lodepng_color_mode_cleanup(mode_out); + lodepng_color_mode_copy(mode_out, mode_in); + } + } + else /*8-bit or 16-bit per channel*/ + { + mode_out->bitdepth = prof.bits; + mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA) + : (prof.colored ? LCT_RGB : LCT_GREY); - if(prof.key) - { - unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/ - mode_out->key_r = prof.key_r & mask; - mode_out->key_g = prof.key_g & mask; - mode_out->key_b = prof.key_b & mask; - mode_out->key_defined = 1; - } - } + if(prof.key) + { + unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/ + mode_out->key_r = prof.key_r & mask; + mode_out->key_g = prof.key_g & mask; + mode_out->key_b = prof.key_b & mask; + mode_out->key_defined = 1; + } + } - return error; + return error; } #endif /* #ifdef LODEPNG_COMPILE_ENCODER */ @@ -3825,13 +3858,13 @@ are only needed to make the paeth calculation correct. */ static uint8_t paethPredictor(int16_t a, int16_t b, int16_t c) { - int16_t pa = abs(b - c); - int16_t pb = abs(a - c); - int16_t pc = abs(a + b - c - c); + int16_t pa = abs(b - c); + int16_t pb = abs(a - c); + int16_t pc = abs(a + b - c - c); - if(pc < pa && pc < pb) return (uint8_t)c; - else if(pb < pa) return (uint8_t)b; - else return (uint8_t)a; + if(pc < pa && pc < pb) return (uint8_t)c; + else if(pb < pa) return (uint8_t)b; + else return (uint8_t)a; } /*shared values used by multiple Adam7 related functions*/ @@ -3859,29 +3892,29 @@ bpp: bits per pixel static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) { - /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ - unsigned i; + /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ + unsigned i; - /*calculate width and height in pixels of each pass*/ - for(i = 0; i != 7; ++i) - { - passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; - passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; - if(passw[i] == 0) passh[i] = 0; - if(passh[i] == 0) passw[i] = 0; - } + /*calculate width and height in pixels of each pass*/ + for(i = 0; i != 7; ++i) + { + passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; + passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; + if(passw[i] == 0) passh[i] = 0; + if(passh[i] == 0) passw[i] = 0; + } - filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; - for(i = 0; i != 7; ++i) - { - /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ - filter_passstart[i + 1] = filter_passstart[i] - + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0); - /*bits padded if needed to fill full byte at end of each scanline*/ - padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8); - /*only padded at end of reduced image*/ - passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8; - } + filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; + for(i = 0; i != 7; ++i) + { + /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ + filter_passstart[i + 1] = filter_passstart[i] + + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0); + /*bits padded if needed to fill full byte at end of each scanline*/ + padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8); + /*only padded at end of reduced image*/ + passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8; + } } #ifdef LODEPNG_COMPILE_DECODER @@ -3894,172 +3927,173 @@ static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t fil unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, const uint8_t* in, size_t insize) { - LodePNGInfo* info = &state->info_png; - if(insize == 0 || in == 0) - { - CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ - } - if(insize < 33) - { - CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ - } + LodePNGInfo* info = &state->info_png; + if(insize == 0 || in == 0) + { + CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ + } + if(insize < 33) + { + CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ + } - /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/ - lodepng_info_cleanup(info); - lodepng_info_init(info); + /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/ + lodepng_info_cleanup(info); + lodepng_info_init(info); - if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 - || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) - { - CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ - } - if(lodepng_chunk_length(in + 8) != 13) - { - CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/ - } - if(!lodepng_chunk_type_equals(in + 8, "IHDR")) - { - CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ - } + if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 + || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) + { + CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ + } + if(lodepng_chunk_length(in + 8) != 13) + { + CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/ + } + if(!lodepng_chunk_type_equals(in + 8, "IHDR")) + { + CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ + } - /*read the values given in the header*/ - *w = lodepng_read32bitInt(&in[16]); - *h = lodepng_read32bitInt(&in[20]); - info->color.bitdepth = in[24]; - info->color.colortype = (LodePNGColorType)in[25]; - info->compression_method = in[26]; - info->filter_method = in[27]; - info->interlace_method = in[28]; + /*read the values given in the header*/ + *w = lodepng_read32bitInt(&in[16]); + *h = lodepng_read32bitInt(&in[20]); + info->color.bitdepth = in[24]; + info->color.colortype = (LodePNGColorType)in[25]; + info->compression_method = in[26]; + info->filter_method = in[27]; + info->interlace_method = in[28]; - if(*w == 0 || *h == 0) - { - CERROR_RETURN_ERROR(state->error, 93); - } + if(*w == 0 || *h == 0) + { + CERROR_RETURN_ERROR(state->error, 93); + } - if(!state->decoder.ignore_crc) - { - unsigned CRC = lodepng_read32bitInt(&in[29]); - unsigned checksum = lodepng_crc32(&in[12], 17); - if(CRC != checksum) - { - CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ - } - } + if(!state->decoder.ignore_crc) + { + unsigned CRC = lodepng_read32bitInt(&in[29]); + unsigned checksum = lodepng_crc32(&in[12], 17); + if(CRC != checksum) + { + CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ + } + } - /*error: only compression method 0 is allowed in the specification*/ - if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32); - /*error: only filter method 0 is allowed in the specification*/ - if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33); - /*error: only interlace methods 0 and 1 exist in the specification*/ - if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34); + /*error: only compression method 0 is allowed in the specification*/ + if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32); + /*error: only filter method 0 is allowed in the specification*/ + if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33); + /*error: only interlace methods 0 and 1 exist in the specification*/ + if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34); - state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); - return state->error; + state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); + return state->error; } static unsigned unfilterScanline(uint8_t* recon, const uint8_t* scanline, const uint8_t* precon, size_t bytewidth, uint8_t filterType, size_t length) { - /* - For PNG filter method 0 - unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, - the filter works byte per byte (bytewidth = 1) - precon is the previous unfiltered scanline, recon the result, scanline the current one - the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead - recon and scanline MAY be the same memory address! precon must be disjoint. - */ + /* + For PNG filter method 0 + unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, + the filter works byte per byte (bytewidth = 1) + precon is the previous unfiltered scanline, recon the result, scanline the current one + the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead + recon and scanline MAY be the same memory address! precon must be disjoint. + */ - size_t i; - switch(filterType) - { - case 0: - for(i = 0; i != length; ++i) recon[i] = scanline[i]; - break; - case 1: - for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; - for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth]; - break; - case 2: - if(precon) - { - for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i]; - } - else - { - for(i = 0; i != length; ++i) recon[i] = scanline[i]; - } - break; - case 3: - if(precon) - { - for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1); - for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1); - } - else - { - for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; - for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1); - } - break; - case 4: - if(precon) - { - for(i = 0; i != bytewidth; ++i) - { - recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ - } - for(i = bytewidth; i < length; ++i) - { - recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); - } - } - else - { - for(i = 0; i != bytewidth; ++i) - { - recon[i] = scanline[i]; - } - for(i = bytewidth; i < length; ++i) - { - /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ - recon[i] = (scanline[i] + recon[i - bytewidth]); - } - } - break; - default: return 36; /*error: unexisting filter type given*/ - } - return 0; + size_t i; + switch(filterType) + { + case 0: + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + break; + case 1: + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth]; + break; + case 2: + if(precon) + { + for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i]; + } + else + { + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + } + break; + case 3: + if(precon) + { + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1); + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1); + } + else + { + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1); + } + break; + case 4: + if(precon) + { + for(i = 0; i != bytewidth; ++i) + { + recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ + } + for(i = bytewidth; i < length; ++i) + { + recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); + } + } + else + { + for(i = 0; i != bytewidth; ++i) + { + recon[i] = scanline[i]; + } + for(i = bytewidth; i < length; ++i) + { + /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ + recon[i] = (scanline[i] + recon[i - bytewidth]); + } + } + break; + default: + return 36; /*error: unexisting filter type given*/ + } + return 0; } static unsigned unfilter(uint8_t* out, const uint8_t* in, unsigned w, unsigned h, unsigned bpp) { - /* - For PNG filter method 0 - this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) - out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline - w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel - in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) - */ + /* + For PNG filter method 0 + this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) + out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline + w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel + in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) + */ - unsigned y; - uint8_t* prevline = 0; + unsigned y; + uint8_t* prevline = 0; - /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ - size_t bytewidth = (bpp + 7) / 8; - size_t linebytes = (w * bpp + 7) / 8; + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7) / 8; + size_t linebytes = (w * bpp + 7) / 8; - for(y = 0; y < h; ++y) - { - size_t outindex = linebytes * y; - size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ - uint8_t filterType = in[inindex]; + for(y = 0; y < h; ++y) + { + size_t outindex = linebytes * y; + size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + uint8_t filterType = in[inindex]; - CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes)); + CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes)); - prevline = &out[outindex]; - } + prevline = &out[outindex]; + } - return 0; + return 0; } /* @@ -4075,79 +4109,79 @@ NOTE: comments about padding bits are only relevant if bpp < 8 */ static void Adam7_deinterlace(uint8_t* out, const uint8_t* in, unsigned w, unsigned h, unsigned bpp) { - unsigned passw[7], passh[7]; - size_t filter_passstart[8], padded_passstart[8], passstart[8]; - unsigned i; + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; - Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - if(bpp >= 8) - { - for(i = 0; i != 7; ++i) - { - unsigned x, y, b; - size_t bytewidth = bpp / 8; - for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { - size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; - size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; - for(b = 0; b < bytewidth; ++b) - { - out[pixeloutstart + b] = in[pixelinstart + b]; - } - } - } - } - else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ - { - for(i = 0; i != 7; ++i) - { - unsigned x, y, b; - unsigned ilinebits = bpp * passw[i]; - unsigned olinebits = bpp * w; - size_t obp, ibp; /*bit pointers (for out and in buffer)*/ - for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { - ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); - obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; - for(b = 0; b < bpp; ++b) - { - uint8_t bit = readBitFromReversedStream(&ibp, in); - /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/ - setBitOfReversedStream0(&obp, out, bit); - } - } - } - } + if(bpp >= 8) + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + size_t bytewidth = bpp / 8; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; + size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; + for(b = 0; b < bytewidth; ++b) + { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } + else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; + for(b = 0; b < bpp; ++b) + { + uint8_t bit = readBitFromReversedStream(&ibp, in); + /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/ + setBitOfReversedStream0(&obp, out, bit); + } + } + } + } } static void removePaddingBits(uint8_t* out, const uint8_t* in, size_t olinebits, size_t ilinebits, unsigned h) { - /* - After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need - to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers - for the Adam7 code, the color convert code and the output to the user. - in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must - have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits - also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7 - only useful if (ilinebits - olinebits) is a value in the range 1..7 - */ - unsigned y; - size_t diff = ilinebits - olinebits; - size_t ibp = 0, obp = 0; /*input and output bit pointers*/ - for(y = 0; y < h; ++y) - { - size_t x; - for(x = 0; x < olinebits; ++x) - { - uint8_t bit = readBitFromReversedStream(&ibp, in); - setBitOfReversedStream(&obp, out, bit); - } - ibp += diff; - } + /* + After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need + to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers + for the Adam7 code, the color convert code and the output to the user. + in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must + have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits + also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7 + only useful if (ilinebits - olinebits) is a value in the range 1..7 + */ + unsigned y; + size_t diff = ilinebits - olinebits; + size_t ibp = 0, obp = 0; /*input and output bit pointers*/ + for(y = 0; y < h; ++y) + { + size_t x; + for(x = 0; x < olinebits; ++x) + { + uint8_t bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + ibp += diff; + } } /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from @@ -4156,108 +4190,109 @@ return value is error*/ static unsigned postProcessScanlines(uint8_t* out, uint8_t* in, unsigned w, unsigned h, const LodePNGInfo* info_png) { - /* - This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. - Steps: - *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8) - *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace - NOTE: the in buffer will be overwritten with intermediate data! - */ - unsigned bpp = lodepng_get_bpp(&info_png->color); - if(bpp == 0) return 31; /*error: invalid colortype*/ + /* + This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. + Steps: + *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8) + *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace + NOTE: the in buffer will be overwritten with intermediate data! + */ + unsigned bpp = lodepng_get_bpp(&info_png->color); + if(bpp == 0) return 31; /*error: invalid colortype*/ - if(info_png->interlace_method == 0) - { - if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) - { - CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); - removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h); - } - /*we can immediately filter into the out buffer, no other steps needed*/ - else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); - } - else /*interlace_method is 1 (Adam7)*/ - { - unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; - unsigned i; + if(info_png->interlace_method == 0) + { + if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) + { + CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); + removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h); + } + /*we can immediately filter into the out buffer, no other steps needed*/ + else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); + } + else /*interlace_method is 1 (Adam7)*/ + { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; - Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - for(i = 0; i != 7; ++i) - { - CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); - /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, - move bytes instead of bits or move not at all*/ - if(bpp < 8) - { - /*remove padding bits in scanlines; after this there still may be padding - bits between the different reduced images: each reduced image still starts nicely at a byte*/ - removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, - ((passw[i] * bpp + 7) / 8) * 8, passh[i]); - } - } + for(i = 0; i != 7; ++i) + { + CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); + /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, + move bytes instead of bits or move not at all*/ + if(bpp < 8) + { + /*remove padding bits in scanlines; after this there still may be padding + bits between the different reduced images: each reduced image still starts nicely at a byte*/ + removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, + ((passw[i] * bpp + 7) / 8) * 8, passh[i]); + } + } - Adam7_deinterlace(out, in, w, h, bpp); - } + Adam7_deinterlace(out, in, w, h, bpp); + } - return 0; + return 0; } static unsigned readChunk_PLTE(LodePNGColorMode* color, const uint8_t* data, size_t chunkLength) { - unsigned pos = 0, i; - if(color->palette) lodepng_free(color->palette); - color->palettesize = chunkLength / 3; - color->palette = (uint8_t*)lodepng_malloc(4 * color->palettesize); - if(!color->palette && color->palettesize) - { - color->palettesize = 0; - return 83; /*alloc fail*/ - } - if(color->palettesize > 256) return 38; /*error: palette too big*/ + unsigned pos = 0, i; + if(color->palette) lodepng_free(color->palette); + color->palettesize = chunkLength / 3; + color->palette = (uint8_t*)lodepng_malloc(4 * color->palettesize); + if(!color->palette && color->palettesize) + { + color->palettesize = 0; + return 83; /*alloc fail*/ + } + if(color->palettesize > 256) return 38; /*error: palette too big*/ - for(i = 0; i != color->palettesize; ++i) - { - color->palette[4 * i + 0] = data[pos++]; /*R*/ - color->palette[4 * i + 1] = data[pos++]; /*G*/ - color->palette[4 * i + 2] = data[pos++]; /*B*/ - color->palette[4 * i + 3] = 255; /*alpha*/ - } + for(i = 0; i != color->palettesize; ++i) + { + color->palette[4 * i + 0] = data[pos++]; /*R*/ + color->palette[4 * i + 1] = data[pos++]; /*G*/ + color->palette[4 * i + 2] = data[pos++]; /*B*/ + color->palette[4 * i + 3] = 255; /*alpha*/ + } - return 0; /* OK */ + return 0; /* OK */ } static unsigned readChunk_tRNS(LodePNGColorMode* color, const uint8_t* data, size_t chunkLength) { - unsigned i; - if(color->colortype == LCT_PALETTE) - { - /*error: more alpha values given than there are palette entries*/ - if(chunkLength > color->palettesize) return 38; + unsigned i; + if(color->colortype == LCT_PALETTE) + { + /*error: more alpha values given than there are palette entries*/ + if(chunkLength > color->palettesize) return 38; - for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i]; - } - else if(color->colortype == LCT_GREY) - { - /*error: this chunk must be 2 bytes for greyscale image*/ - if(chunkLength != 2) return 30; + for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i]; + } + else if(color->colortype == LCT_GREY) + { + /*error: this chunk must be 2 bytes for greyscale image*/ + if(chunkLength != 2) return 30; - color->key_defined = 1; - color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; - } - else if(color->colortype == LCT_RGB) - { - /*error: this chunk must be 6 bytes for RGB image*/ - if(chunkLength != 6) return 41; + color->key_defined = 1; + color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; + } + else if(color->colortype == LCT_RGB) + { + /*error: this chunk must be 6 bytes for RGB image*/ + if(chunkLength != 6) return 41; - color->key_defined = 1; - color->key_r = 256u * data[0] + data[1]; - color->key_g = 256u * data[2] + data[3]; - color->key_b = 256u * data[4] + data[5]; - } - else return 42; /*error: tRNS chunk not allowed for other color models*/ + color->key_defined = 1; + color->key_r = 256u * data[0] + data[1]; + color->key_g = 256u * data[2] + data[3]; + color->key_b = 256u * data[4] + data[5]; + } + else return 42; /*error: tRNS chunk not allowed for other color models*/ - return 0; /* OK */ + return 0; /* OK */ } @@ -4265,247 +4300,247 @@ static unsigned readChunk_tRNS(LodePNGColorMode* color, const uint8_t* data, siz /*background color chunk (bKGD)*/ static unsigned readChunk_bKGD(LodePNGInfo* info, const uint8_t* data, size_t chunkLength) { - if(info->color.colortype == LCT_PALETTE) - { - /*error: this chunk must be 1 byte for indexed color image*/ - if(chunkLength != 1) return 43; + if(info->color.colortype == LCT_PALETTE) + { + /*error: this chunk must be 1 byte for indexed color image*/ + if(chunkLength != 1) return 43; - info->background_defined = 1; - info->background_r = info->background_g = info->background_b = data[0]; - } - else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) - { - /*error: this chunk must be 2 bytes for greyscale image*/ - if(chunkLength != 2) return 44; + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = data[0]; + } + else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) + { + /*error: this chunk must be 2 bytes for greyscale image*/ + if(chunkLength != 2) return 44; - info->background_defined = 1; - info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; - } - else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) - { - /*error: this chunk must be 6 bytes for greyscale image*/ - if(chunkLength != 6) return 45; + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; + } + else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) + { + /*error: this chunk must be 6 bytes for greyscale image*/ + if(chunkLength != 6) return 45; - info->background_defined = 1; - info->background_r = 256u * data[0] + data[1]; - info->background_g = 256u * data[2] + data[3]; - info->background_b = 256u * data[4] + data[5]; - } + info->background_defined = 1; + info->background_r = 256u * data[0] + data[1]; + info->background_g = 256u * data[2] + data[3]; + info->background_b = 256u * data[4] + data[5]; + } - return 0; /* OK */ + return 0; /* OK */ } /*text chunk (tEXt)*/ static unsigned readChunk_tEXt(LodePNGInfo* info, const uint8_t* data, size_t chunkLength) { - unsigned error = 0; - char *key = 0, *str = 0; - unsigned i; + unsigned error = 0; + char *key = 0, *str = 0; + unsigned i; - while(!error) /*not really a while loop, only used to break on error*/ - { - unsigned length, string2_begin; + while(!error) /*not really a while loop, only used to break on error*/ + { + unsigned length, string2_begin; - length = 0; - while(length < chunkLength && data[length] != 0) ++length; - /*even though it's not allowed by the standard, no error is thrown if - there's no null termination char, if the text is empty*/ - if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + length = 0; + while(length < chunkLength && data[length] != 0) ++length; + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ - key = (char*)lodepng_malloc(length + 1); - if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ - key[length] = 0; - for(i = 0; i != length; ++i) key[i] = (char)data[i]; + key[length] = 0; + for(i = 0; i != length; ++i) key[i] = (char)data[i]; - string2_begin = length + 1; /*skip keyword null terminator*/ + string2_begin = length + 1; /*skip keyword null terminator*/ - length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin; - str = (char*)lodepng_malloc(length + 1); - if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ + length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin; + str = (char*)lodepng_malloc(length + 1); + if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ - str[length] = 0; - for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i]; + str[length] = 0; + for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i]; - error = lodepng_add_text(info, key, str); + error = lodepng_add_text(info, key, str); - break; - } + break; + } - lodepng_free(key); - lodepng_free(str); + lodepng_free(key); + lodepng_free(str); - return error; + return error; } /*compressed text chunk (zTXt)*/ static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, const uint8_t* data, size_t chunkLength) { - unsigned error = 0; - unsigned i; + unsigned error = 0; + unsigned i; - unsigned length, string2_begin; - char *key = 0; - ucvector decoded; + unsigned length, string2_begin; + char *key = 0; + ucvector decoded; - ucvector_init(&decoded); + ucvector_init(&decoded); - while(!error) /*not really a while loop, only used to break on error*/ - { - for(length = 0; length < chunkLength && data[length] != 0; ++length) ; - if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ - if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + while(!error) /*not really a while loop, only used to break on error*/ + { + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ - key = (char*)lodepng_malloc(length + 1); - if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ - key[length] = 0; - for(i = 0; i != length; ++i) key[i] = (char)data[i]; + key[length] = 0; + for(i = 0; i != length; ++i) key[i] = (char)data[i]; - if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ - string2_begin = length + 2; - if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + string2_begin = length + 2; + if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ - length = chunkLength - string2_begin; - /*will fail if zlib error, e.g. if length is too small*/ - error = zlib_decompress(&decoded.data, &decoded.size, - (const uint8_t*)(&data[string2_begin]), - length, zlibsettings); - if(error) break; - ucvector_push_back(&decoded, 0); + length = chunkLength - string2_begin; + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&decoded.data, &decoded.size, + (const uint8_t*)(&data[string2_begin]), + length, zlibsettings); + if(error) break; + ucvector_push_back(&decoded, 0); - error = lodepng_add_text(info, key, (char*)decoded.data); + error = lodepng_add_text(info, key, (char*)decoded.data); - break; - } + break; + } - lodepng_free(key); - ucvector_cleanup(&decoded); + lodepng_free(key); + ucvector_cleanup(&decoded); - return error; + return error; } /*international text chunk (iTXt)*/ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, const uint8_t* data, size_t chunkLength) { - unsigned error = 0; - unsigned i; + unsigned error = 0; + unsigned i; - unsigned length, begin, compressed; - char *key = 0, *langtag = 0, *transkey = 0; - ucvector decoded; - ucvector_init(&decoded); + unsigned length, begin, compressed; + char *key = 0, *langtag = 0, *transkey = 0; + ucvector decoded; + ucvector_init(&decoded); - while(!error) /*not really a while loop, only used to break on error*/ - { - /*Quick check if the chunk length isn't too small. Even without check - it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ - if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ + while(!error) /*not really a while loop, only used to break on error*/ + { + /*Quick check if the chunk length isn't too small. Even without check + it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ + if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ - /*read the key*/ - for(length = 0; length < chunkLength && data[length] != 0; ++length) ; - if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/ - if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + /*read the key*/ + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ - key = (char*)lodepng_malloc(length + 1); - if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ - key[length] = 0; - for(i = 0; i != length; ++i) key[i] = (char)data[i]; + key[length] = 0; + for(i = 0; i != length; ++i) key[i] = (char)data[i]; - /*read the compression method*/ - compressed = data[length + 1]; - if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + /*read the compression method*/ + compressed = data[length + 1]; + if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ - /*even though it's not allowed by the standard, no error is thrown if - there's no null termination char, if the text is empty for the next 3 texts*/ + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty for the next 3 texts*/ - /*read the langtag*/ - begin = length + 3; - length = 0; - for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + /*read the langtag*/ + begin = length + 3; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; - langtag = (char*)lodepng_malloc(length + 1); - if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/ + langtag = (char*)lodepng_malloc(length + 1); + if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/ - langtag[length] = 0; - for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i]; + langtag[length] = 0; + for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i]; - /*read the transkey*/ - begin += length + 1; - length = 0; - for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + /*read the transkey*/ + begin += length + 1; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; - transkey = (char*)lodepng_malloc(length + 1); - if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/ + transkey = (char*)lodepng_malloc(length + 1); + if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/ - transkey[length] = 0; - for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i]; + transkey[length] = 0; + for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i]; - /*read the actual text*/ - begin += length + 1; + /*read the actual text*/ + begin += length + 1; - length = chunkLength < begin ? 0 : chunkLength - begin; + length = chunkLength < begin ? 0 : chunkLength - begin; - if(compressed) - { - /*will fail if zlib error, e.g. if length is too small*/ - error = zlib_decompress(&decoded.data, &decoded.size, - (const uint8_t*)(&data[begin]), - length, zlibsettings); - if(error) break; - if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size; - ucvector_push_back(&decoded, 0); - } - else - { - if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/); + if(compressed) + { + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&decoded.data, &decoded.size, + (const uint8_t*)(&data[begin]), + length, zlibsettings); + if(error) break; + if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size; + ucvector_push_back(&decoded, 0); + } + else + { + if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/); - decoded.data[length] = 0; - for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i]; - } + decoded.data[length] = 0; + for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i]; + } - error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data); + error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data); - break; - } + break; + } - lodepng_free(key); - lodepng_free(langtag); - lodepng_free(transkey); - ucvector_cleanup(&decoded); + lodepng_free(key); + lodepng_free(langtag); + lodepng_free(transkey); + ucvector_cleanup(&decoded); - return error; + return error; } static unsigned readChunk_tIME(LodePNGInfo* info, const uint8_t* data, size_t chunkLength) { - if(chunkLength != 7) return 73; /*invalid tIME chunk size*/ + if(chunkLength != 7) return 73; /*invalid tIME chunk size*/ - info->time_defined = 1; - info->time.year = 256u * data[0] + data[1]; - info->time.month = data[2]; - info->time.day = data[3]; - info->time.hour = data[4]; - info->time.minute = data[5]; - info->time.second = data[6]; + info->time_defined = 1; + info->time.year = 256u * data[0] + data[1]; + info->time.month = data[2]; + info->time.day = data[3]; + info->time.hour = data[4]; + info->time.minute = data[5]; + info->time.second = data[6]; - return 0; /* OK */ + return 0; /* OK */ } static unsigned readChunk_pHYs(LodePNGInfo* info, const uint8_t* data, size_t chunkLength) { - if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/ + if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/ - info->phys_defined = 1; - info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; - info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; - info->phys_unit = data[8]; + info->phys_defined = 1; + info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; + info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; + info->phys_unit = data[8]; - return 0; /* OK */ + return 0; /* OK */ } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ @@ -4514,317 +4549,317 @@ static void decodeGeneric(uint8_t** out, unsigned* w, unsigned* h, LodePNGState* state, const uint8_t* in, size_t insize) { - uint8_t IEND = 0; - const uint8_t* chunk; - size_t i; - ucvector idat; /*the data from idat chunks*/ - ucvector scanlines; - size_t predict; - size_t numpixels; - size_t outsize = 0; + uint8_t IEND = 0; + const uint8_t* chunk; + size_t i; + ucvector idat; /*the data from idat chunks*/ + ucvector scanlines; + size_t predict; + size_t numpixels; + size_t outsize = 0; - /*for unknown chunk order*/ - unsigned unknown = 0; + /*for unknown chunk order*/ + unsigned unknown = 0; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/ + unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - /*provide some proper output values if error will happen*/ - *out = 0; + /*provide some proper output values if error will happen*/ + *out = 0; - state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ - if(state->error) return; + state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ + if(state->error) return; - numpixels = *w * *h; + numpixels = *w * *h; - /*multiplication overflow*/ - if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92); - /*multiplication overflow possible further below. Allows up to 2^31-1 pixel - bytes with 16-bit RGBA, the rest is room for filter bytes.*/ - if(numpixels > 268435455) CERROR_RETURN(state->error, 92); + /*multiplication overflow*/ + if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92); + /*multiplication overflow possible further below. Allows up to 2^31-1 pixel + bytes with 16-bit RGBA, the rest is room for filter bytes.*/ + if(numpixels > 268435455) CERROR_RETURN(state->error, 92); - ucvector_init(&idat); - chunk = &in[33]; /*first byte of the first chunk after the header*/ + ucvector_init(&idat); + chunk = &in[33]; /*first byte of the first chunk after the header*/ - /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. - IDAT data is put at the start of the in buffer*/ - while(!IEND && !state->error) - { - unsigned chunkLength; - const uint8_t* data; /*the data in the chunk*/ + /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. + IDAT data is put at the start of the in buffer*/ + while(!IEND && !state->error) + { + unsigned chunkLength; + const uint8_t* data; /*the data in the chunk*/ - /*error: size of the in buffer too small to contain next chunk*/ - if((size_t)((chunk - in) + 12) > insize || chunk < in) - { - if(state->decoder.ignore_end) break; /*other errors may still happen though*/ - CERROR_BREAK(state->error, 30); - } + /*error: size of the in buffer too small to contain next chunk*/ + if((size_t)((chunk - in) + 12) > insize || chunk < in) + { + if(state->decoder.ignore_end) break; /*other errors may still happen though*/ + CERROR_BREAK(state->error, 30); + } - /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ - chunkLength = lodepng_chunk_length(chunk); - /*error: chunk length larger than the max PNG chunk size*/ - if(chunkLength > 2147483647) - { - if(state->decoder.ignore_end) break; /*other errors may still happen though*/ - CERROR_BREAK(state->error, 63); - } + /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ + chunkLength = lodepng_chunk_length(chunk); + /*error: chunk length larger than the max PNG chunk size*/ + if(chunkLength > 2147483647) + { + if(state->decoder.ignore_end) break; /*other errors may still happen though*/ + CERROR_BREAK(state->error, 63); + } - if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) - { - CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/ - } + if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) + { + CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/ + } - data = lodepng_chunk_data_const(chunk); + data = lodepng_chunk_data_const(chunk); - /*IDAT chunk, containing compressed image data*/ - if(lodepng_chunk_type_equals(chunk, "IDAT")) - { - size_t oldsize = idat.size; - if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/); - for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i]; + /*IDAT chunk, containing compressed image data*/ + if(lodepng_chunk_type_equals(chunk, "IDAT")) + { + size_t oldsize = idat.size; + if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/); + for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i]; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - critical_pos = 3; + critical_pos = 3; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - } - /*IEND chunk*/ - else if(lodepng_chunk_type_equals(chunk, "IEND")) - { - IEND = 1; - } - /*palette chunk (PLTE)*/ - else if(lodepng_chunk_type_equals(chunk, "PLTE")) - { - state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); - if(state->error) break; + } + /*IEND chunk*/ + else if(lodepng_chunk_type_equals(chunk, "IEND")) + { + IEND = 1; + } + /*palette chunk (PLTE)*/ + else if(lodepng_chunk_type_equals(chunk, "PLTE")) + { + state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); + if(state->error) break; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - critical_pos = 2; + critical_pos = 2; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - } - /*palette transparency chunk (tRNS)*/ - else if(lodepng_chunk_type_equals(chunk, "tRNS")) - { - state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); - if(state->error) break; - } + } + /*palette transparency chunk (tRNS)*/ + else if(lodepng_chunk_type_equals(chunk, "tRNS")) + { + state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); + if(state->error) break; + } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*background color chunk (bKGD)*/ - else if(lodepng_chunk_type_equals(chunk, "bKGD")) - { - state->error = readChunk_bKGD(&state->info_png, data, chunkLength); - if(state->error) break; - } - /*text chunk (tEXt)*/ - else if(lodepng_chunk_type_equals(chunk, "tEXt")) - { - if(state->decoder.read_text_chunks) - { - state->error = readChunk_tEXt(&state->info_png, data, chunkLength); - if(state->error) break; - } - } - /*compressed text chunk (zTXt)*/ - else if(lodepng_chunk_type_equals(chunk, "zTXt")) - { - if(state->decoder.read_text_chunks) - { - state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); - if(state->error) break; - } - } - /*international text chunk (iTXt)*/ - else if(lodepng_chunk_type_equals(chunk, "iTXt")) - { - if(state->decoder.read_text_chunks) - { - state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); - if(state->error) break; - } - } - else if(lodepng_chunk_type_equals(chunk, "tIME")) - { - state->error = readChunk_tIME(&state->info_png, data, chunkLength); - if(state->error) break; - } - else if(lodepng_chunk_type_equals(chunk, "pHYs")) - { - state->error = readChunk_pHYs(&state->info_png, data, chunkLength); - if(state->error) break; - } + /*background color chunk (bKGD)*/ + else if(lodepng_chunk_type_equals(chunk, "bKGD")) + { + state->error = readChunk_bKGD(&state->info_png, data, chunkLength); + if(state->error) break; + } + /*text chunk (tEXt)*/ + else if(lodepng_chunk_type_equals(chunk, "tEXt")) + { + if(state->decoder.read_text_chunks) + { + state->error = readChunk_tEXt(&state->info_png, data, chunkLength); + if(state->error) break; + } + } + /*compressed text chunk (zTXt)*/ + else if(lodepng_chunk_type_equals(chunk, "zTXt")) + { + if(state->decoder.read_text_chunks) + { + state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + if(state->error) break; + } + } + /*international text chunk (iTXt)*/ + else if(lodepng_chunk_type_equals(chunk, "iTXt")) + { + if(state->decoder.read_text_chunks) + { + state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + if(state->error) break; + } + } + else if(lodepng_chunk_type_equals(chunk, "tIME")) + { + state->error = readChunk_tIME(&state->info_png, data, chunkLength); + if(state->error) break; + } + else if(lodepng_chunk_type_equals(chunk, "pHYs")) + { + state->error = readChunk_pHYs(&state->info_png, data, chunkLength); + if(state->error) break; + } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - else /*it's not an implemented chunk type, so ignore it: skip over the data*/ - { - /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ - if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) - { - CERROR_BREAK(state->error, 69); - } + else /*it's not an implemented chunk type, so ignore it: skip over the data*/ + { + /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ + if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) + { + CERROR_BREAK(state->error, 69); + } - unknown = 1; + unknown = 1; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - if(state->decoder.remember_unknown_chunks) - { - state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], - &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); - if(state->error) break; - } + if(state->decoder.remember_unknown_chunks) + { + state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], + &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); + if(state->error) break; + } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - } + } - if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ - { - if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ - } + if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ + { + if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ + } - if(!IEND) chunk = lodepng_chunk_next_const(chunk); - } + if(!IEND) chunk = lodepng_chunk_next_const(chunk); + } - ucvector_init(&scanlines); - /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. - If the decompressed size does not match the prediction, the image must be corrupt.*/ - if(state->info_png.interlace_method == 0) - { - /*The extra *h is added because this are the filter bytes every scanline starts with*/ - predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h; - } - else - { - /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/ - const LodePNGColorMode* color = &state->info_png.color; - predict = 0; - predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3); - if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3); - predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color) + ((*h + 3) >> 3); - if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color) + ((*h + 3) >> 2); - predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color) + ((*h + 1) >> 2); - if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color) + ((*h + 1) >> 1); - predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color) + ((*h + 0) >> 1); - } - if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/ - if(!state->error) - { - state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data, - idat.size, &state->decoder.zlibsettings); - if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/ - } - ucvector_cleanup(&idat); + ucvector_init(&scanlines); + /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. + If the decompressed size does not match the prediction, the image must be corrupt.*/ + if(state->info_png.interlace_method == 0) + { + /*The extra *h is added because this are the filter bytes every scanline starts with*/ + predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h; + } + else + { + /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/ + const LodePNGColorMode* color = &state->info_png.color; + predict = 0; + predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3); + if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3); + predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color) + ((*h + 3) >> 3); + if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color) + ((*h + 3) >> 2); + predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color) + ((*h + 1) >> 2); + if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color) + ((*h + 1) >> 1); + predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color) + ((*h + 0) >> 1); + } + if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/ + if(!state->error) + { + state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data, + idat.size, &state->decoder.zlibsettings); + if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/ + } + ucvector_cleanup(&idat); - if(!state->error) - { - outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); - *out = (uint8_t*)lodepng_malloc(outsize); - if(!*out) state->error = 83; /*alloc fail*/ - } - if(!state->error) - { - for(i = 0; i < outsize; i++) (*out)[i] = 0; - state->error = postProcessScanlines(*out, scanlines.data, *w, *h, &state->info_png); - } - ucvector_cleanup(&scanlines); + if(!state->error) + { + outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); + *out = (uint8_t*)lodepng_malloc(outsize); + if(!*out) state->error = 83; /*alloc fail*/ + } + if(!state->error) + { + for(i = 0; i < outsize; i++)(*out)[i] = 0; + state->error = postProcessScanlines(*out, scanlines.data, *w, *h, &state->info_png); + } + ucvector_cleanup(&scanlines); } unsigned lodepng_decode(uint8_t** out, unsigned* w, unsigned* h, LodePNGState* state, const uint8_t* in, size_t insize) { - *out = 0; - decodeGeneric(out, w, h, state, in, insize); - if(state->error) return state->error; - if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) - { - /*same color type, no copying or converting of data needed*/ - /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype - the raw image has to the end user*/ - if(!state->decoder.color_convert) - { - state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); - if(state->error) return state->error; - } - } - else - { - /*color conversion needed; sort of copy of the data*/ - uint8_t* data = *out; - size_t outsize; + *out = 0; + decodeGeneric(out, w, h, state, in, insize); + if(state->error) return state->error; + if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) + { + /*same color type, no copying or converting of data needed*/ + /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype + the raw image has to the end user*/ + if(!state->decoder.color_convert) + { + state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); + if(state->error) return state->error; + } + } + else + { + /*color conversion needed; sort of copy of the data*/ + uint8_t* data = *out; + size_t outsize; - /*TODO: check if this works according to the statement in the documentation: "The converter can convert - from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/ - if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) - && !(state->info_raw.bitdepth == 8)) - { - return 56; /*unsupported color mode conversion*/ - } + /*TODO: check if this works according to the statement in the documentation: "The converter can convert + from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/ + if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) + && !(state->info_raw.bitdepth == 8)) + { + return 56; /*unsupported color mode conversion*/ + } - outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); - *out = (uint8_t*)lodepng_malloc(outsize); - if(!(*out)) - { - state->error = 83; /*alloc fail*/ - } - else state->error = lodepng_convert(*out, data, &state->info_raw, - &state->info_png.color, *w, *h); - lodepng_free(data); - } - return state->error; + outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); + *out = (uint8_t*)lodepng_malloc(outsize); + if(!(*out)) + { + state->error = 83; /*alloc fail*/ + } + else state->error = lodepng_convert(*out, data, &state->info_raw, + &state->info_png.color, *w, *h); + lodepng_free(data); + } + return state->error; } unsigned lodepng_decode_memory(uint8_t** out, unsigned* w, unsigned* h, const uint8_t* in, size_t insize, LodePNGColorType colortype, unsigned bitdepth) { - unsigned error; - LodePNGState state; - lodepng_state_init(&state); - state.info_raw.colortype = colortype; - state.info_raw.bitdepth = bitdepth; - error = lodepng_decode(out, w, h, &state, in, insize); - lodepng_state_cleanup(&state); - return error; + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + error = lodepng_decode(out, w, h, &state, in, insize); + lodepng_state_cleanup(&state); + return error; } unsigned lodepng_decode32(uint8_t** out, unsigned* w, unsigned* h, const uint8_t* in, size_t insize) { - return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); } unsigned lodepng_decode24(uint8_t** out, unsigned* w, unsigned* h, const uint8_t* in, size_t insize) { - return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); } #ifdef LODEPNG_COMPILE_DISK unsigned lodepng_decode_file(uint8_t** out, unsigned* w, unsigned* h, const char* filename, LodePNGColorType colortype, unsigned bitdepth) { - uint8_t* buffer = 0; - size_t buffersize; - unsigned error; - error = lodepng_load_file(&buffer, &buffersize, filename); - if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth); - lodepng_free(buffer); - return error; + uint8_t* buffer = 0; + size_t buffersize; + unsigned error; + error = lodepng_load_file(&buffer, &buffersize, filename); + if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth); + lodepng_free(buffer); + return error; } unsigned lodepng_decode32_file(uint8_t** out, unsigned* w, unsigned* h, const char* filename) { - return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); + return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); } unsigned lodepng_decode24_file(uint8_t** out, unsigned* w, unsigned* h, const char* filename) { - return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); + return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); } #endif /*LODEPNG_COMPILE_DISK*/ void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) { - settings->color_convert = 1; + settings->color_convert = 1; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - settings->read_text_chunks = 1; - settings->remember_unknown_chunks = 0; + settings->read_text_chunks = 1; + settings->remember_unknown_chunks = 0; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - settings->ignore_crc = 0; - settings->ignore_critical = 0; - settings->ignore_end = 0; - lodepng_decompress_settings_init(&settings->zlibsettings); + settings->ignore_crc = 0; + settings->ignore_critical = 0; + settings->ignore_end = 0; + lodepng_decompress_settings_init(&settings->zlibsettings); } #endif /*LODEPNG_COMPILE_DECODER*/ @@ -4834,30 +4869,32 @@ void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) void lodepng_state_init(LodePNGState* state) { #ifdef LODEPNG_COMPILE_DECODER - lodepng_decoder_settings_init(&state->decoder); + lodepng_decoder_settings_init(&state->decoder); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER - lodepng_encoder_settings_init(&state->encoder); + lodepng_encoder_settings_init(&state->encoder); #endif /*LODEPNG_COMPILE_ENCODER*/ - lodepng_color_mode_init(&state->info_raw); - lodepng_info_init(&state->info_png); - state->error = 1; + lodepng_color_mode_init(&state->info_raw); + lodepng_info_init(&state->info_png); + state->error = 1; } void lodepng_state_cleanup(LodePNGState* state) { - lodepng_color_mode_cleanup(&state->info_raw); - lodepng_info_cleanup(&state->info_png); + lodepng_color_mode_cleanup(&state->info_raw); + lodepng_info_cleanup(&state->info_png); } void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) { - lodepng_state_cleanup(dest); - *dest = *source; - lodepng_color_mode_init(&dest->info_raw); - lodepng_info_init(&dest->info_png); - dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return; - dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return; + lodepng_state_cleanup(dest); + *dest = *source; + lodepng_color_mode_init(&dest->info_raw); + lodepng_info_init(&dest->info_png); + dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); + if(dest->error) return; + dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); + if(dest->error) return; } #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ @@ -4871,276 +4908,276 @@ void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) /*chunkName must be string of 4 characters*/ static unsigned addChunk(ucvector* out, const char* chunkName, const uint8_t* data, size_t length) { - CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data)); - out->allocsize = out->size; /*fix the allocsize again*/ - return 0; + CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data)); + out->allocsize = out->size; /*fix the allocsize again*/ + return 0; } static void writeSignature(ucvector* out) { - /*8 bytes PNG signature, aka the magic bytes*/ - ucvector_push_back(out, 137); - ucvector_push_back(out, 80); - ucvector_push_back(out, 78); - ucvector_push_back(out, 71); - ucvector_push_back(out, 13); - ucvector_push_back(out, 10); - ucvector_push_back(out, 26); - ucvector_push_back(out, 10); + /*8 bytes PNG signature, aka the magic bytes*/ + ucvector_push_back(out, 137); + ucvector_push_back(out, 80); + ucvector_push_back(out, 78); + ucvector_push_back(out, 71); + ucvector_push_back(out, 13); + ucvector_push_back(out, 10); + ucvector_push_back(out, 26); + ucvector_push_back(out, 10); } static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) { - unsigned error = 0; - ucvector header; - ucvector_init(&header); + unsigned error = 0; + ucvector header; + ucvector_init(&header); - lodepng_add32bitInt(&header, w); /*width*/ - lodepng_add32bitInt(&header, h); /*height*/ - ucvector_push_back(&header, (uint8_t)bitdepth); /*bit depth*/ - ucvector_push_back(&header, (uint8_t)colortype); /*color type*/ - ucvector_push_back(&header, 0); /*compression method*/ - ucvector_push_back(&header, 0); /*filter method*/ - ucvector_push_back(&header, interlace_method); /*interlace method*/ + lodepng_add32bitInt(&header, w); /*width*/ + lodepng_add32bitInt(&header, h); /*height*/ + ucvector_push_back(&header, (uint8_t)bitdepth); /*bit depth*/ + ucvector_push_back(&header, (uint8_t)colortype); /*color type*/ + ucvector_push_back(&header, 0); /*compression method*/ + ucvector_push_back(&header, 0); /*filter method*/ + ucvector_push_back(&header, interlace_method); /*interlace method*/ - error = addChunk(out, "IHDR", header.data, header.size); - ucvector_cleanup(&header); + error = addChunk(out, "IHDR", header.data, header.size); + ucvector_cleanup(&header); - return error; + return error; } static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) { - unsigned error = 0; - size_t i; - ucvector PLTE; - ucvector_init(&PLTE); - for(i = 0; i != info->palettesize * 4; ++i) - { - /*add all channels except alpha channel*/ - if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]); - } - error = addChunk(out, "PLTE", PLTE.data, PLTE.size); - ucvector_cleanup(&PLTE); + unsigned error = 0; + size_t i; + ucvector PLTE; + ucvector_init(&PLTE); + for(i = 0; i != info->palettesize * 4; ++i) + { + /*add all channels except alpha channel*/ + if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]); + } + error = addChunk(out, "PLTE", PLTE.data, PLTE.size); + ucvector_cleanup(&PLTE); - return error; + return error; } static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) { - unsigned error = 0; - size_t i; - ucvector tRNS; - ucvector_init(&tRNS); - if(info->colortype == LCT_PALETTE) - { - size_t amount = info->palettesize; - /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ - for(i = info->palettesize; i != 0; --i) - { - if(info->palette[4 * (i - 1) + 3] == 255) --amount; - else break; - } - /*add only alpha channel*/ - for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]); - } - else if(info->colortype == LCT_GREY) - { - if(info->key_defined) - { - ucvector_push_back(&tRNS, (uint8_t)(info->key_r >> 8)); - ucvector_push_back(&tRNS, (uint8_t)(info->key_r & 255)); - } - } - else if(info->colortype == LCT_RGB) - { - if(info->key_defined) - { - ucvector_push_back(&tRNS, (uint8_t)(info->key_r >> 8)); - ucvector_push_back(&tRNS, (uint8_t)(info->key_r & 255)); - ucvector_push_back(&tRNS, (uint8_t)(info->key_g >> 8)); - ucvector_push_back(&tRNS, (uint8_t)(info->key_g & 255)); - ucvector_push_back(&tRNS, (uint8_t)(info->key_b >> 8)); - ucvector_push_back(&tRNS, (uint8_t)(info->key_b & 255)); - } - } + unsigned error = 0; + size_t i; + ucvector tRNS; + ucvector_init(&tRNS); + if(info->colortype == LCT_PALETTE) + { + size_t amount = info->palettesize; + /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ + for(i = info->palettesize; i != 0; --i) + { + if(info->palette[4 * (i - 1) + 3] == 255) --amount; + else break; + } + /*add only alpha channel*/ + for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]); + } + else if(info->colortype == LCT_GREY) + { + if(info->key_defined) + { + ucvector_push_back(&tRNS, (uint8_t)(info->key_r >> 8)); + ucvector_push_back(&tRNS, (uint8_t)(info->key_r & 255)); + } + } + else if(info->colortype == LCT_RGB) + { + if(info->key_defined) + { + ucvector_push_back(&tRNS, (uint8_t)(info->key_r >> 8)); + ucvector_push_back(&tRNS, (uint8_t)(info->key_r & 255)); + ucvector_push_back(&tRNS, (uint8_t)(info->key_g >> 8)); + ucvector_push_back(&tRNS, (uint8_t)(info->key_g & 255)); + ucvector_push_back(&tRNS, (uint8_t)(info->key_b >> 8)); + ucvector_push_back(&tRNS, (uint8_t)(info->key_b & 255)); + } + } - error = addChunk(out, "tRNS", tRNS.data, tRNS.size); - ucvector_cleanup(&tRNS); + error = addChunk(out, "tRNS", tRNS.data, tRNS.size); + ucvector_cleanup(&tRNS); - return error; + return error; } static unsigned addChunk_IDAT(ucvector* out, const uint8_t* data, size_t datasize, LodePNGCompressSettings* zlibsettings) { - ucvector zlibdata; - unsigned error = 0; + ucvector zlibdata; + unsigned error = 0; - /*compress with the Zlib compressor*/ - ucvector_init(&zlibdata); - error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings); - if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size); - ucvector_cleanup(&zlibdata); + /*compress with the Zlib compressor*/ + ucvector_init(&zlibdata); + error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings); + if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size); + ucvector_cleanup(&zlibdata); - return error; + return error; } static unsigned addChunk_IEND(ucvector* out) { - unsigned error = 0; - error = addChunk(out, "IEND", 0, 0); - return error; + unsigned error = 0; + error = addChunk(out, "IEND", 0, 0); + return error; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) { - unsigned error = 0; - size_t i; - ucvector text; - ucvector_init(&text); - for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (uint8_t)keyword[i]); - if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ - ucvector_push_back(&text, 0); /*0 termination char*/ - for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (uint8_t)textstring[i]); - error = addChunk(out, "tEXt", text.data, text.size); - ucvector_cleanup(&text); + unsigned error = 0; + size_t i; + ucvector text; + ucvector_init(&text); + for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (uint8_t)keyword[i]); + if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ + ucvector_push_back(&text, 0); /*0 termination char*/ + for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (uint8_t)textstring[i]); + error = addChunk(out, "tEXt", text.data, text.size); + ucvector_cleanup(&text); - return error; + return error; } static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, LodePNGCompressSettings* zlibsettings) { - unsigned error = 0; - ucvector data, compressed; - size_t i, textsize = strlen(textstring); + unsigned error = 0; + ucvector data, compressed; + size_t i, textsize = strlen(textstring); - ucvector_init(&data); - ucvector_init(&compressed); - for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)keyword[i]); - if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ - ucvector_push_back(&data, 0); /*0 termination char*/ - ucvector_push_back(&data, 0); /*compression method: 0*/ + ucvector_init(&data); + ucvector_init(&compressed); + for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)keyword[i]); + if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ + ucvector_push_back(&data, 0); /*0 termination char*/ + ucvector_push_back(&data, 0); /*compression method: 0*/ - error = zlib_compress(&compressed.data, &compressed.size, - (const uint8_t*)textstring, textsize, zlibsettings); - if(!error) - { - for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]); - error = addChunk(out, "zTXt", data.data, data.size); - } + error = zlib_compress(&compressed.data, &compressed.size, + (const uint8_t*)textstring, textsize, zlibsettings); + if(!error) + { + for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]); + error = addChunk(out, "zTXt", data.data, data.size); + } - ucvector_cleanup(&compressed); - ucvector_cleanup(&data); - return error; + ucvector_cleanup(&compressed); + ucvector_cleanup(&data); + return error; } static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag, const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) { - unsigned error = 0; - ucvector data; - size_t i, textsize = strlen(textstring); + unsigned error = 0; + ucvector data; + size_t i, textsize = strlen(textstring); - ucvector_init(&data); + ucvector_init(&data); - for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)keyword[i]); - if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ - ucvector_push_back(&data, 0); /*null termination char*/ - ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/ - ucvector_push_back(&data, 0); /*compression method*/ - for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)langtag[i]); - ucvector_push_back(&data, 0); /*null termination char*/ - for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)transkey[i]); - ucvector_push_back(&data, 0); /*null termination char*/ + for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)keyword[i]); + if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ + ucvector_push_back(&data, 0); /*null termination char*/ + ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/ + ucvector_push_back(&data, 0); /*compression method*/ + for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)langtag[i]); + ucvector_push_back(&data, 0); /*null termination char*/ + for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)transkey[i]); + ucvector_push_back(&data, 0); /*null termination char*/ - if(compressed) - { - ucvector compressed_data; - ucvector_init(&compressed_data); - error = zlib_compress(&compressed_data.data, &compressed_data.size, - (const uint8_t*)textstring, textsize, zlibsettings); - if(!error) - { - for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]); - } - ucvector_cleanup(&compressed_data); - } - else /*not compressed*/ - { - for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)textstring[i]); - } + if(compressed) + { + ucvector compressed_data; + ucvector_init(&compressed_data); + error = zlib_compress(&compressed_data.data, &compressed_data.size, + (const uint8_t*)textstring, textsize, zlibsettings); + if(!error) + { + for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]); + } + ucvector_cleanup(&compressed_data); + } + else /*not compressed*/ + { + for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (uint8_t)textstring[i]); + } - if(!error) error = addChunk(out, "iTXt", data.data, data.size); - ucvector_cleanup(&data); - return error; + if(!error) error = addChunk(out, "iTXt", data.data, data.size); + ucvector_cleanup(&data); + return error; } static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) { - unsigned error = 0; - ucvector bKGD; - ucvector_init(&bKGD); - if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) - { - ucvector_push_back(&bKGD, (uint8_t)(info->background_r >> 8)); - ucvector_push_back(&bKGD, (uint8_t)(info->background_r & 255)); - } - else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) - { - ucvector_push_back(&bKGD, (uint8_t)(info->background_r >> 8)); - ucvector_push_back(&bKGD, (uint8_t)(info->background_r & 255)); - ucvector_push_back(&bKGD, (uint8_t)(info->background_g >> 8)); - ucvector_push_back(&bKGD, (uint8_t)(info->background_g & 255)); - ucvector_push_back(&bKGD, (uint8_t)(info->background_b >> 8)); - ucvector_push_back(&bKGD, (uint8_t)(info->background_b & 255)); - } - else if(info->color.colortype == LCT_PALETTE) - { - ucvector_push_back(&bKGD, (uint8_t)(info->background_r & 255)); /*palette index*/ - } + unsigned error = 0; + ucvector bKGD; + ucvector_init(&bKGD); + if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) + { + ucvector_push_back(&bKGD, (uint8_t)(info->background_r >> 8)); + ucvector_push_back(&bKGD, (uint8_t)(info->background_r & 255)); + } + else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) + { + ucvector_push_back(&bKGD, (uint8_t)(info->background_r >> 8)); + ucvector_push_back(&bKGD, (uint8_t)(info->background_r & 255)); + ucvector_push_back(&bKGD, (uint8_t)(info->background_g >> 8)); + ucvector_push_back(&bKGD, (uint8_t)(info->background_g & 255)); + ucvector_push_back(&bKGD, (uint8_t)(info->background_b >> 8)); + ucvector_push_back(&bKGD, (uint8_t)(info->background_b & 255)); + } + else if(info->color.colortype == LCT_PALETTE) + { + ucvector_push_back(&bKGD, (uint8_t)(info->background_r & 255)); /*palette index*/ + } - error = addChunk(out, "bKGD", bKGD.data, bKGD.size); - ucvector_cleanup(&bKGD); + error = addChunk(out, "bKGD", bKGD.data, bKGD.size); + ucvector_cleanup(&bKGD); - return error; + return error; } static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) { - unsigned error = 0; - uint8_t* data = (uint8_t*)lodepng_malloc(7); - if(!data) return 83; /*alloc fail*/ - data[0] = (uint8_t)(time->year >> 8); - data[1] = (uint8_t)(time->year & 255); - data[2] = (uint8_t)time->month; - data[3] = (uint8_t)time->day; - data[4] = (uint8_t)time->hour; - data[5] = (uint8_t)time->minute; - data[6] = (uint8_t)time->second; - error = addChunk(out, "tIME", data, 7); - lodepng_free(data); - return error; + unsigned error = 0; + uint8_t* data = (uint8_t*)lodepng_malloc(7); + if(!data) return 83; /*alloc fail*/ + data[0] = (uint8_t)(time->year >> 8); + data[1] = (uint8_t)(time->year & 255); + data[2] = (uint8_t)time->month; + data[3] = (uint8_t)time->day; + data[4] = (uint8_t)time->hour; + data[5] = (uint8_t)time->minute; + data[6] = (uint8_t)time->second; + error = addChunk(out, "tIME", data, 7); + lodepng_free(data); + return error; } static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) { - unsigned error = 0; - ucvector data; - ucvector_init(&data); + unsigned error = 0; + ucvector data; + ucvector_init(&data); - lodepng_add32bitInt(&data, info->phys_x); - lodepng_add32bitInt(&data, info->phys_y); - ucvector_push_back(&data, info->phys_unit); + lodepng_add32bitInt(&data, info->phys_x); + lodepng_add32bitInt(&data, info->phys_y); + ucvector_push_back(&data, info->phys_unit); - error = addChunk(out, "pHYs", data.data, data.size); - ucvector_cleanup(&data); + error = addChunk(out, "pHYs", data.data, data.size); + ucvector_cleanup(&data); - return error; + return error; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ @@ -5148,308 +5185,317 @@ static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) static void filterScanline(uint8_t* out, const uint8_t* scanline, const uint8_t* prevline, size_t length, size_t bytewidth, uint8_t filterType) { - size_t i; - switch(filterType) - { - case 0: /*None*/ - for(i = 0; i != length; ++i) out[i] = scanline[i]; - break; - case 1: /*Sub*/ - for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; - for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth]; - break; - case 2: /*Up*/ - if(prevline) - { - for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i]; - } - else - { - for(i = 0; i != length; ++i) out[i] = scanline[i]; - } - break; - case 3: /*Average*/ - if(prevline) - { - for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1); - for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1); - } - else - { - for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; - for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1); - } - break; - case 4: /*Paeth*/ - if(prevline) - { - /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ - for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]); - for(i = bytewidth; i < length; ++i) - { - out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); - } - } - else - { - for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; - /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ - for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]); - } - break; - default: return; /*unexisting filter type given*/ - } + size_t i; + switch(filterType) + { + case 0: /*None*/ + for(i = 0; i != length; ++i) out[i] = scanline[i]; + break; + case 1: /*Sub*/ + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth]; + break; + case 2: /*Up*/ + if(prevline) + { + for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i]; + } + else + { + for(i = 0; i != length; ++i) out[i] = scanline[i]; + } + break; + case 3: /*Average*/ + if(prevline) + { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1); + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1); + } + else + { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1); + } + break; + case 4: /*Paeth*/ + if(prevline) + { + /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ + for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]); + for(i = bytewidth; i < length; ++i) + { + out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); + } + } + else + { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ + for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]); + } + break; + default: + return; /*unexisting filter type given*/ + } } /* log2 approximation. A slight bit faster than std::log. */ static float flog2(float f) { - float result = 0; - while(f > 32) { result += 4; f /= 16; } - while(f > 2) { ++result; f /= 2; } - return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f); + float result = 0; + while(f > 32) + { + result += 4; + f /= 16; + } + while(f > 2) + { + ++result; + f /= 2; + } + return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f); } static unsigned filter(uint8_t* out, const uint8_t* in, unsigned w, unsigned h, const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) { - /* - For PNG filter method 0 - out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are - the scanlines with 1 extra byte per scanline - */ + /* + For PNG filter method 0 + out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are + the scanlines with 1 extra byte per scanline + */ - unsigned bpp = lodepng_get_bpp(info); - /*the width of a scanline in bytes, not including the filter type*/ - size_t linebytes = (w * bpp + 7) / 8; - /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ - size_t bytewidth = (bpp + 7) / 8; - const uint8_t* prevline = 0; - unsigned x, y; - unsigned error = 0; - LodePNGFilterStrategy strategy = settings->filter_strategy; + unsigned bpp = lodepng_get_bpp(info); + /*the width of a scanline in bytes, not including the filter type*/ + size_t linebytes = (w * bpp + 7) / 8; + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7) / 8; + const uint8_t* prevline = 0; + unsigned x, y; + unsigned error = 0; + LodePNGFilterStrategy strategy = settings->filter_strategy; - /* - There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard: - * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e. - use fixed filtering, with the filter None). - * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is - not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply - all five filters and select the filter that produces the smallest sum of absolute values per row. - This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true. + /* + There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard: + * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e. + use fixed filtering, with the filter None). + * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is + not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply + all five filters and select the filter that produces the smallest sum of absolute values per row. + This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true. - If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed, - but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum - heuristic is used. - */ - if(settings->filter_palette_zero && - (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO; + If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed, + but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum + heuristic is used. + */ + if(settings->filter_palette_zero && + (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO; - if(bpp == 0) return 31; /*error: invalid color type*/ + if(bpp == 0) return 31; /*error: invalid color type*/ - if(strategy == LFS_ZERO) - { - for(y = 0; y != h; ++y) - { - size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ - size_t inindex = linebytes * y; - out[outindex] = 0; /*filter type byte*/ - filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0); - prevline = &in[inindex]; - } - } - else if(strategy == LFS_MINSUM) - { - /*adaptive filtering*/ - size_t sum[5]; - uint8_t* attempt[5]; /*five filtering attempts, one for each filter type*/ - size_t smallest = 0; - uint8_t type, bestType = 0; + if(strategy == LFS_ZERO) + { + for(y = 0; y != h; ++y) + { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + out[outindex] = 0; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0); + prevline = &in[inindex]; + } + } + else if(strategy == LFS_MINSUM) + { + /*adaptive filtering*/ + size_t sum[5]; + uint8_t* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + uint8_t type, bestType = 0; - for(type = 0; type != 5; ++type) - { - attempt[type] = (uint8_t*)lodepng_malloc(linebytes); - if(!attempt[type]) return 83; /*alloc fail*/ - } + for(type = 0; type != 5; ++type) + { + attempt[type] = (uint8_t*)lodepng_malloc(linebytes); + if(!attempt[type]) return 83; /*alloc fail*/ + } - if(!error) - { - for(y = 0; y != h; ++y) - { - /*try the 5 filter types*/ - for(type = 0; type != 5; ++type) - { - filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + if(!error) + { + for(y = 0; y != h; ++y) + { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) + { + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); - /*calculate the sum of the result*/ - sum[type] = 0; - if(type == 0) - { - for(x = 0; x != linebytes; ++x) sum[type] += (uint8_t)(attempt[type][x]); - } - else - { - for(x = 0; x != linebytes; ++x) - { - /*For differences, each byte should be treated as signed, values above 127 are negative - (converted to int8_t). Filtertype 0 isn't a difference though, so use unsigned there. - This means filtertype 0 is almost never chosen, but that is justified.*/ - uint8_t s = attempt[type][x]; - sum[type] += s < 128 ? s : (255U - s); - } - } + /*calculate the sum of the result*/ + sum[type] = 0; + if(type == 0) + { + for(x = 0; x != linebytes; ++x) sum[type] += (uint8_t)(attempt[type][x]); + } + else + { + for(x = 0; x != linebytes; ++x) + { + /*For differences, each byte should be treated as signed, values above 127 are negative + (converted to int8_t). Filtertype 0 isn't a difference though, so use unsigned there. + This means filtertype 0 is almost never chosen, but that is justified.*/ + uint8_t s = attempt[type][x]; + sum[type] += s < 128 ? s : (255U - s); + } + } - /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ - if(type == 0 || sum[type] < smallest) - { - bestType = type; - smallest = sum[type]; - } - } + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum[type] < smallest) + { + bestType = type; + smallest = sum[type]; + } + } - prevline = &in[y * linebytes]; + prevline = &in[y * linebytes]; - /*now fill the out values*/ - out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ - for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; - } - } + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + } - for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); - } - else if(strategy == LFS_ENTROPY) - { - float sum[5]; - uint8_t* attempt[5]; /*five filtering attempts, one for each filter type*/ - float smallest = 0; - unsigned type, bestType = 0; - unsigned count[256]; + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } + else if(strategy == LFS_ENTROPY) + { + float sum[5]; + uint8_t* attempt[5]; /*five filtering attempts, one for each filter type*/ + float smallest = 0; + unsigned type, bestType = 0; + unsigned count[256]; - for(type = 0; type != 5; ++type) - { - attempt[type] = (uint8_t*)lodepng_malloc(linebytes); - if(!attempt[type]) return 83; /*alloc fail*/ - } + for(type = 0; type != 5; ++type) + { + attempt[type] = (uint8_t*)lodepng_malloc(linebytes); + if(!attempt[type]) return 83; /*alloc fail*/ + } - for(y = 0; y != h; ++y) - { - /*try the 5 filter types*/ - for(type = 0; type != 5; ++type) - { - filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); - for(x = 0; x != 256; ++x) count[x] = 0; - for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]]; - ++count[type]; /*the filter type itself is part of the scanline*/ - sum[type] = 0; - for(x = 0; x != 256; ++x) - { - float p = count[x] / (float)(linebytes + 1); - sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p; - } - /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ - if(type == 0 || sum[type] < smallest) - { - bestType = type; - smallest = sum[type]; - } - } + for(y = 0; y != h; ++y) + { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) + { + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + for(x = 0; x != 256; ++x) count[x] = 0; + for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]]; + ++count[type]; /*the filter type itself is part of the scanline*/ + sum[type] = 0; + for(x = 0; x != 256; ++x) + { + float p = count[x] / (float)(linebytes + 1); + sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p; + } + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum[type] < smallest) + { + bestType = type; + smallest = sum[type]; + } + } - prevline = &in[y * linebytes]; + prevline = &in[y * linebytes]; - /*now fill the out values*/ - out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ - for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; - } + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } - for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); - } - else if(strategy == LFS_PREDEFINED) - { - for(y = 0; y != h; ++y) - { - size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ - size_t inindex = linebytes * y; - uint8_t type = settings->predefined_filters[y]; - out[outindex] = type; /*filter type byte*/ - filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); - prevline = &in[inindex]; - } - } - else if(strategy == LFS_BRUTE_FORCE) - { - /*brute force filter chooser. - deflate the scanline after every filter attempt to see which one deflates best. - This is very slow and gives only slightly smaller, sometimes even larger, result*/ - size_t size[5]; - uint8_t* attempt[5]; /*five filtering attempts, one for each filter type*/ - size_t smallest = 0; - unsigned type = 0, bestType = 0; - uint8_t* dummy; - LodePNGCompressSettings zlibsettings = settings->zlibsettings; - /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose, - to simulate the true case where the tree is the same for the whole image. Sometimes it gives - better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare - cases better compression. It does make this a bit less slow, so it's worth doing this.*/ - zlibsettings.btype = 1; - /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG - images only, so disable it*/ - zlibsettings.custom_zlib = 0; - zlibsettings.custom_deflate = 0; - for(type = 0; type != 5; ++type) - { - attempt[type] = (uint8_t*)lodepng_malloc(linebytes); - if(!attempt[type]) return 83; /*alloc fail*/ - } - for(y = 0; y != h; ++y) /*try the 5 filter types*/ - { - for(type = 0; type != 5; ++type) - { - unsigned testsize = linebytes; - /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } + else if(strategy == LFS_PREDEFINED) + { + for(y = 0; y != h; ++y) + { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + uint8_t type = settings->predefined_filters[y]; + out[outindex] = type; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); + prevline = &in[inindex]; + } + } + else if(strategy == LFS_BRUTE_FORCE) + { + /*brute force filter chooser. + deflate the scanline after every filter attempt to see which one deflates best. + This is very slow and gives only slightly smaller, sometimes even larger, result*/ + size_t size[5]; + uint8_t* attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + unsigned type = 0, bestType = 0; + uint8_t* dummy; + LodePNGCompressSettings zlibsettings = settings->zlibsettings; + /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose, + to simulate the true case where the tree is the same for the whole image. Sometimes it gives + better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare + cases better compression. It does make this a bit less slow, so it's worth doing this.*/ + zlibsettings.btype = 1; + /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG + images only, so disable it*/ + zlibsettings.custom_zlib = 0; + zlibsettings.custom_deflate = 0; + for(type = 0; type != 5; ++type) + { + attempt[type] = (uint8_t*)lodepng_malloc(linebytes); + if(!attempt[type]) return 83; /*alloc fail*/ + } + for(y = 0; y != h; ++y) /*try the 5 filter types*/ + { + for(type = 0; type != 5; ++type) + { + unsigned testsize = linebytes; + /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ - filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); - size[type] = 0; - dummy = 0; - zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings); - lodepng_free(dummy); - /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ - if(type == 0 || size[type] < smallest) - { - bestType = type; - smallest = size[type]; - } - } - prevline = &in[y * linebytes]; - out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ - for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; - } - for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); - } - else return 88; /* unknown filter strategy */ + filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); + size[type] = 0; + dummy = 0; + zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings); + lodepng_free(dummy); + /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || size[type] < smallest) + { + bestType = type; + smallest = size[type]; + } + } + prevline = &in[y * linebytes]; + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; + } + for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); + } + else return 88; /* unknown filter strategy */ - return error; + return error; } static void addPaddingBits(uint8_t* out, const uint8_t* in, size_t olinebits, size_t ilinebits, unsigned h) { - /*The opposite of the removePaddingBits function - olinebits must be >= ilinebits*/ - unsigned y; - size_t diff = olinebits - ilinebits; - size_t obp = 0, ibp = 0; /*bit pointers*/ - for(y = 0; y != h; ++y) - { - size_t x; - for(x = 0; x < ilinebits; ++x) - { - uint8_t bit = readBitFromReversedStream(&ibp, in); - setBitOfReversedStream(&obp, out, bit); - } - /*obp += diff; --> no, fill in some value in the padding bits too, to avoid - "Use of uninitialised value of size ###" warning from valgrind*/ - for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0); - } + /*The opposite of the removePaddingBits function + olinebits must be >= ilinebits*/ + unsigned y; + size_t diff = olinebits - ilinebits; + size_t obp = 0, ibp = 0; /*bit pointers*/ + for(y = 0; y != h; ++y) + { + size_t x; + for(x = 0; x < ilinebits; ++x) + { + uint8_t bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + /*obp += diff; --> no, fill in some value in the padding bits too, to avoid + "Use of uninitialised value of size ###" warning from valgrind*/ + for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0); + } } /* @@ -5465,51 +5511,51 @@ NOTE: comments about padding bits are only relevant if bpp < 8 */ static void Adam7_interlace(uint8_t* out, const uint8_t* in, unsigned w, unsigned h, unsigned bpp) { - unsigned passw[7], passh[7]; - size_t filter_passstart[8], padded_passstart[8], passstart[8]; - unsigned i; + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; - Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - if(bpp >= 8) - { - for(i = 0; i != 7; ++i) - { - unsigned x, y, b; - size_t bytewidth = bpp / 8; - for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { - size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; - size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; - for(b = 0; b < bytewidth; ++b) - { - out[pixeloutstart + b] = in[pixelinstart + b]; - } - } - } - } - else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ - { - for(i = 0; i != 7; ++i) - { - unsigned x, y, b; - unsigned ilinebits = bpp * passw[i]; - unsigned olinebits = bpp * w; - size_t obp, ibp; /*bit pointers (for out and in buffer)*/ - for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { - ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; - obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); - for(b = 0; b < bpp; ++b) - { - uint8_t bit = readBitFromReversedStream(&ibp, in); - setBitOfReversedStream(&obp, out, bit); - } - } - } - } + if(bpp >= 8) + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + size_t bytewidth = bpp / 8; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; + size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; + for(b = 0; b < bytewidth; ++b) + { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } + else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; + obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + for(b = 0; b < bpp; ++b) + { + uint8_t bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + } + } + } } /*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image. @@ -5518,87 +5564,87 @@ static unsigned preProcessScanlines(uint8_t** out, size_t* outsize, const uint8_ unsigned w, unsigned h, const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) { - /* - This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: - *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter - *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter - */ - unsigned bpp = lodepng_get_bpp(&info_png->color); - unsigned error = 0; + /* + This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: + *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter + *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter + */ + unsigned bpp = lodepng_get_bpp(&info_png->color); + unsigned error = 0; - if(info_png->interlace_method == 0) - { - *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/ - *out = (uint8_t*)lodepng_malloc(*outsize); - if(!(*out) && (*outsize)) error = 83; /*alloc fail*/ + if(info_png->interlace_method == 0) + { + *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/ + *out = (uint8_t*)lodepng_malloc(*outsize); + if(!(*out) && (*outsize)) error = 83; /*alloc fail*/ - if(!error) - { - /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ - if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) - { - uint8_t* padded = (uint8_t*)lodepng_malloc(h * ((w * bpp + 7) / 8)); - if(!padded) error = 83; /*alloc fail*/ - if(!error) - { - addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h); - error = filter(*out, padded, w, h, &info_png->color, settings); - } - lodepng_free(padded); - } - else - { - /*we can immediately filter into the out buffer, no other steps needed*/ - error = filter(*out, in, w, h, &info_png->color, settings); - } - } - } - else /*interlace_method is 1 (Adam7)*/ - { - unsigned passw[7], passh[7]; - size_t filter_passstart[8], padded_passstart[8], passstart[8]; - uint8_t* adam7; + if(!error) + { + /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ + if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) + { + uint8_t* padded = (uint8_t*)lodepng_malloc(h * ((w * bpp + 7) / 8)); + if(!padded) error = 83; /*alloc fail*/ + if(!error) + { + addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h); + error = filter(*out, padded, w, h, &info_png->color, settings); + } + lodepng_free(padded); + } + else + { + /*we can immediately filter into the out buffer, no other steps needed*/ + error = filter(*out, in, w, h, &info_png->color, settings); + } + } + } + else /*interlace_method is 1 (Adam7)*/ + { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + uint8_t* adam7; - Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/ - *out = (uint8_t*)lodepng_malloc(*outsize); - if(!(*out)) error = 83; /*alloc fail*/ + *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/ + *out = (uint8_t*)lodepng_malloc(*outsize); + if(!(*out)) error = 83; /*alloc fail*/ - adam7 = (uint8_t*)lodepng_malloc(passstart[7]); - if(!adam7 && passstart[7]) error = 83; /*alloc fail*/ + adam7 = (uint8_t*)lodepng_malloc(passstart[7]); + if(!adam7 && passstart[7]) error = 83; /*alloc fail*/ - if(!error) - { - unsigned i; + if(!error) + { + unsigned i; - Adam7_interlace(adam7, in, w, h, bpp); - for(i = 0; i != 7; ++i) - { - if(bpp < 8) - { - uint8_t* padded = (uint8_t*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]); - if(!padded) ERROR_BREAK(83); /*alloc fail*/ - addPaddingBits(padded, &adam7[passstart[i]], - ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]); - error = filter(&(*out)[filter_passstart[i]], padded, - passw[i], passh[i], &info_png->color, settings); - lodepng_free(padded); - } - else - { - error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], - passw[i], passh[i], &info_png->color, settings); - } + Adam7_interlace(adam7, in, w, h, bpp); + for(i = 0; i != 7; ++i) + { + if(bpp < 8) + { + uint8_t* padded = (uint8_t*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]); + if(!padded) ERROR_BREAK(83); /*alloc fail*/ + addPaddingBits(padded, &adam7[passstart[i]], + ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]); + error = filter(&(*out)[filter_passstart[i]], padded, + passw[i], passh[i], &info_png->color, settings); + lodepng_free(padded); + } + else + { + error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], + passw[i], passh[i], &info_png->color, settings); + } - if(error) break; - } - } + if(error) break; + } + } - lodepng_free(adam7); - } + lodepng_free(adam7); + } - return error; + return error; } /* @@ -5609,35 +5655,37 @@ returns 2 if the palette is semi-translucent. */ static unsigned getPaletteTranslucency(const uint8_t* palette, size_t palettesize) { - size_t i; - unsigned key = 0; - unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/ - for(i = 0; i != palettesize; ++i) - { - if(!key && palette[4 * i + 3] == 0) - { - r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2]; - key = 1; - i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/ - } - else if(palette[4 * i + 3] != 255) return 2; - /*when key, no opaque RGB may have key's RGB*/ - else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2; - } - return key; + size_t i; + unsigned key = 0; + unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/ + for(i = 0; i != palettesize; ++i) + { + if(!key && palette[4 * i + 3] == 0) + { + r = palette[4 * i + 0]; + g = palette[4 * i + 1]; + b = palette[4 * i + 2]; + key = 1; + i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/ + } + else if(palette[4 * i + 3] != 255) return 2; + /*when key, no opaque RGB may have key's RGB*/ + else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2; + } + return key; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS static unsigned addUnknownChunks(ucvector* out, uint8_t* data, size_t datasize) { - uint8_t* inchunk = data; - while((size_t)(inchunk - data) < datasize) - { - CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); - out->allocsize = out->size; /*fix the allocsize again*/ - inchunk = lodepng_chunk_next(inchunk); - } - return 0; + uint8_t* inchunk = data; + while((size_t)(inchunk - data) < datasize) + { + CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); + out->allocsize = out->size; /*fix the allocsize again*/ + inchunk = lodepng_chunk_next(inchunk); + } + return 0; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ @@ -5645,261 +5693,261 @@ unsigned lodepng_encode(uint8_t** out, size_t* outsize, const uint8_t* image, unsigned w, unsigned h, LodePNGState* state) { - LodePNGInfo info; - ucvector outv; - uint8_t* data = 0; /*uncompressed version of the IDAT chunk data*/ - size_t datasize = 0; + LodePNGInfo info; + ucvector outv; + uint8_t* data = 0; /*uncompressed version of the IDAT chunk data*/ + size_t datasize = 0; - /*provide some proper output values if error will happen*/ - *out = 0; - *outsize = 0; - state->error = 0; + /*provide some proper output values if error will happen*/ + *out = 0; + *outsize = 0; + state->error = 0; - /*check input values validity*/ - if((state->info_png.color.colortype == LCT_PALETTE || state->encoder.force_palette) - && (state->info_png.color.palettesize == 0 || state->info_png.color.palettesize > 256)) - { - CERROR_RETURN_ERROR(state->error, 68); /*invalid palette size, it is only allowed to be 1-256*/ - } - if(state->encoder.zlibsettings.btype > 2) - { - CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/ - } - if(state->info_png.interlace_method > 1) - { - CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/ - } - state->error = checkColorValidity(state->info_png.color.colortype, state->info_png.color.bitdepth); - if(state->error) return state->error; /*error: unexisting color type given*/ - state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); - if(state->error) return state->error; /*error: unexisting color type given*/ + /*check input values validity*/ + if((state->info_png.color.colortype == LCT_PALETTE || state->encoder.force_palette) + && (state->info_png.color.palettesize == 0 || state->info_png.color.palettesize > 256)) + { + CERROR_RETURN_ERROR(state->error, 68); /*invalid palette size, it is only allowed to be 1-256*/ + } + if(state->encoder.zlibsettings.btype > 2) + { + CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/ + } + if(state->info_png.interlace_method > 1) + { + CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/ + } + state->error = checkColorValidity(state->info_png.color.colortype, state->info_png.color.bitdepth); + if(state->error) return state->error; /*error: unexisting color type given*/ + state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); + if(state->error) return state->error; /*error: unexisting color type given*/ - /* color convert and compute scanline filter types */ - lodepng_info_init(&info); - lodepng_info_copy(&info, &state->info_png); - if(state->encoder.auto_convert) - { - state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw); - } - if (!state->error) - { - if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) - { - uint8_t* converted; - size_t size = (w * h * (size_t)lodepng_get_bpp(&info.color) + 7) / 8; + /* color convert and compute scanline filter types */ + lodepng_info_init(&info); + lodepng_info_copy(&info, &state->info_png); + if(state->encoder.auto_convert) + { + state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw); + } + if(!state->error) + { + if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) + { + uint8_t* converted; + size_t size = (w * h * (size_t)lodepng_get_bpp(&info.color) + 7) / 8; - converted = (uint8_t*)lodepng_malloc(size); - if(!converted && size) state->error = 83; /*alloc fail*/ - if(!state->error) - { - state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); - } - if(!state->error) - { - state->error = preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); - } - lodepng_free(converted); - } - else - { - state->error = preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); - } - } + converted = (uint8_t*)lodepng_malloc(size); + if(!converted && size) state->error = 83; /*alloc fail*/ + if(!state->error) + { + state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); + } + if(!state->error) + { + state->error = preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); + } + lodepng_free(converted); + } + else + { + state->error = preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); + } + } - /* output all PNG chunks */ - ucvector_init(&outv); - while(!state->error) /*while only executed once, to break on error*/ - { + /* output all PNG chunks */ + ucvector_init(&outv); + while(!state->error) /*while only executed once, to break on error*/ + { #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - size_t i; + size_t i; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - /*write signature and chunks*/ - writeSignature(&outv); - /*IHDR*/ - addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); + /*write signature and chunks*/ + writeSignature(&outv); + /*IHDR*/ + addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*unknown chunks between IHDR and PLTE*/ - if(info.unknown_chunks_data[0]) - { - state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); - if(state->error) break; - } + /*unknown chunks between IHDR and PLTE*/ + if(info.unknown_chunks_data[0]) + { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); + if(state->error) break; + } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - /*PLTE*/ - if(info.color.colortype == LCT_PALETTE) - { - addChunk_PLTE(&outv, &info.color); - } - if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) - { - addChunk_PLTE(&outv, &info.color); - } - /*tRNS*/ - if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) - { - addChunk_tRNS(&outv, &info.color); - } - if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) - { - addChunk_tRNS(&outv, &info.color); - } + /*PLTE*/ + if(info.color.colortype == LCT_PALETTE) + { + addChunk_PLTE(&outv, &info.color); + } + if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) + { + addChunk_PLTE(&outv, &info.color); + } + /*tRNS*/ + if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) + { + addChunk_tRNS(&outv, &info.color); + } + if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) + { + addChunk_tRNS(&outv, &info.color); + } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*bKGD (must come between PLTE and the IDAt chunks*/ - if(info.background_defined) addChunk_bKGD(&outv, &info); - /*pHYs (must come before the IDAT chunks)*/ - if(info.phys_defined) addChunk_pHYs(&outv, &info); + /*bKGD (must come between PLTE and the IDAt chunks*/ + if(info.background_defined) addChunk_bKGD(&outv, &info); + /*pHYs (must come before the IDAT chunks)*/ + if(info.phys_defined) addChunk_pHYs(&outv, &info); - /*unknown chunks between PLTE and IDAT*/ - if(info.unknown_chunks_data[1]) - { - state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); - if(state->error) break; - } + /*unknown chunks between PLTE and IDAT*/ + if(info.unknown_chunks_data[1]) + { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); + if(state->error) break; + } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - /*IDAT (multiple IDAT chunks must be consecutive)*/ - state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings); - if(state->error) break; + /*IDAT (multiple IDAT chunks must be consecutive)*/ + state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings); + if(state->error) break; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*tIME*/ - if(info.time_defined) addChunk_tIME(&outv, &info.time); - /*tEXt and/or zTXt*/ - for(i = 0; i != info.text_num; ++i) - { - if(strlen(info.text_keys[i]) > 79) - { - state->error = 66; /*text chunk too large*/ - break; - } - if(strlen(info.text_keys[i]) < 1) - { - state->error = 67; /*text chunk too small*/ - break; - } - if(state->encoder.text_compression) - { - addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); - } - else - { - addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); - } - } - /*LodePNG version id in text chunk*/ - if(state->encoder.add_id) - { - unsigned alread_added_id_text = 0; - for(i = 0; i != info.text_num; ++i) - { - if(!strcmp(info.text_keys[i], "LodePNG")) - { - alread_added_id_text = 1; - break; - } - } - if(alread_added_id_text == 0) - { - addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ - } - } - /*iTXt*/ - for(i = 0; i != info.itext_num; ++i) - { - if(strlen(info.itext_keys[i]) > 79) - { - state->error = 66; /*text chunk too large*/ - break; - } - if(strlen(info.itext_keys[i]) < 1) - { - state->error = 67; /*text chunk too small*/ - break; - } - addChunk_iTXt(&outv, state->encoder.text_compression, - info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i], - &state->encoder.zlibsettings); - } + /*tIME*/ + if(info.time_defined) addChunk_tIME(&outv, &info.time); + /*tEXt and/or zTXt*/ + for(i = 0; i != info.text_num; ++i) + { + if(strlen(info.text_keys[i]) > 79) + { + state->error = 66; /*text chunk too large*/ + break; + } + if(strlen(info.text_keys[i]) < 1) + { + state->error = 67; /*text chunk too small*/ + break; + } + if(state->encoder.text_compression) + { + addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); + } + else + { + addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); + } + } + /*LodePNG version id in text chunk*/ + if(state->encoder.add_id) + { + unsigned alread_added_id_text = 0; + for(i = 0; i != info.text_num; ++i) + { + if(!strcmp(info.text_keys[i], "LodePNG")) + { + alread_added_id_text = 1; + break; + } + } + if(alread_added_id_text == 0) + { + addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ + } + } + /*iTXt*/ + for(i = 0; i != info.itext_num; ++i) + { + if(strlen(info.itext_keys[i]) > 79) + { + state->error = 66; /*text chunk too large*/ + break; + } + if(strlen(info.itext_keys[i]) < 1) + { + state->error = 67; /*text chunk too small*/ + break; + } + addChunk_iTXt(&outv, state->encoder.text_compression, + info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i], + &state->encoder.zlibsettings); + } - /*unknown chunks between IDAT and IEND*/ - if(info.unknown_chunks_data[2]) - { - state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); - if(state->error) break; - } + /*unknown chunks between IDAT and IEND*/ + if(info.unknown_chunks_data[2]) + { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); + if(state->error) break; + } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - addChunk_IEND(&outv); + addChunk_IEND(&outv); - break; /*this isn't really a while loop; no error happened so break out now!*/ - } + break; /*this isn't really a while loop; no error happened so break out now!*/ + } - lodepng_info_cleanup(&info); - lodepng_free(data); - /*instead of cleaning the vector up, give it to the output*/ - *out = outv.data; - *outsize = outv.size; + lodepng_info_cleanup(&info); + lodepng_free(data); + /*instead of cleaning the vector up, give it to the output*/ + *out = outv.data; + *outsize = outv.size; - return state->error; + return state->error; } unsigned lodepng_encode_memory(uint8_t** out, size_t* outsize, const uint8_t* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { - unsigned error; - LodePNGState state; - lodepng_state_init(&state); - state.info_raw.colortype = colortype; - state.info_raw.bitdepth = bitdepth; - state.info_png.color.colortype = colortype; - state.info_png.color.bitdepth = bitdepth; - lodepng_encode(out, outsize, image, w, h, &state); - error = state.error; - lodepng_state_cleanup(&state); - return error; + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + state.info_png.color.colortype = colortype; + state.info_png.color.bitdepth = bitdepth; + lodepng_encode(out, outsize, image, w, h, &state); + error = state.error; + lodepng_state_cleanup(&state); + return error; } unsigned lodepng_encode32(uint8_t** out, size_t* outsize, const uint8_t* image, unsigned w, unsigned h) { - return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); } unsigned lodepng_encode24(uint8_t** out, size_t* outsize, const uint8_t* image, unsigned w, unsigned h) { - return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); } #ifdef LODEPNG_COMPILE_DISK unsigned lodepng_encode_file(const char* filename, const uint8_t* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { - uint8_t* buffer; - size_t buffersize; - unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); - if(!error) error = lodepng_save_file(buffer, buffersize, filename); - lodepng_free(buffer); - return error; + uint8_t* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); + if(!error) error = lodepng_save_file(buffer, buffersize, filename); + lodepng_free(buffer); + return error; } unsigned lodepng_encode32_file(const char* filename, const uint8_t* image, unsigned w, unsigned h) { - return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); + return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); } unsigned lodepng_encode24_file(const char* filename, const uint8_t* image, unsigned w, unsigned h) { - return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); + return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); } #endif /*LODEPNG_COMPILE_DISK*/ void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) { - lodepng_compress_settings_init(&settings->zlibsettings); - settings->filter_palette_zero = 1; - settings->filter_strategy = LFS_MINSUM; - settings->auto_convert = 1; - settings->force_palette = 0; - settings->predefined_filters = 0; + lodepng_compress_settings_init(&settings->zlibsettings); + settings->filter_palette_zero = 1; + settings->filter_strategy = LFS_MINSUM; + settings->auto_convert = 1; + settings->force_palette = 0; + settings->predefined_filters = 0; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - settings->add_id = 0; - settings->text_compression = 1; + settings->add_id = 0; + settings->text_compression = 1; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } @@ -5913,103 +5961,184 @@ the documentation of all the error codes. */ const char* lodepng_error_text(unsigned code) { - switch(code) - { - case 0: return "no error, everything went ok"; - case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ - case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/ - case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/ - case 13: return "problem while processing dynamic deflate block"; - case 14: return "problem while processing dynamic deflate block"; - case 15: return "problem while processing dynamic deflate block"; - case 16: return "unexisting code while processing dynamic deflate block"; - case 17: return "end of out buffer memory reached while inflating"; - case 18: return "invalid distance code while inflating"; - case 19: return "end of out buffer memory reached while inflating"; - case 20: return "invalid deflate block BTYPE encountered while decoding"; - case 21: return "NLEN is not ones complement of LEN in a deflate block"; - /*end of out buffer memory reached while inflating: - This can happen if the inflated deflate data is longer than the amount of bytes required to fill up - all the pixels of the image, given the color depth and image dimensions. Something that doesn't - happen in a normal, well encoded, PNG image.*/ - case 22: return "end of out buffer memory reached while inflating"; - case 23: return "end of in buffer memory reached while inflating"; - case 24: return "invalid FCHECK in zlib header"; - case 25: return "invalid compression method in zlib header"; - case 26: return "FDICT encountered in zlib header while it's not used for PNG"; - case 27: return "PNG file is smaller than a PNG header"; - /*Checks the magic file header, the first 8 bytes of the PNG file*/ - case 28: return "incorrect PNG signature, it's no PNG or corrupted"; - case 29: return "first chunk is not the header chunk"; - case 30: return "chunk length too large, chunk broken off at end of file"; - case 31: return "illegal PNG color type or bpp"; - case 32: return "illegal PNG compression method"; - case 33: return "illegal PNG filter method"; - case 34: return "illegal PNG interlace method"; - case 35: return "chunk length of a chunk is too large or the chunk too small"; - case 36: return "illegal PNG filter type encountered"; - case 37: return "illegal bit depth for this color type given"; - case 38: return "the palette is too big"; /*more than 256 colors*/ - case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette"; - case 40: return "tRNS chunk has wrong size for greyscale image"; - case 41: return "tRNS chunk has wrong size for RGB image"; - case 42: return "tRNS chunk appeared while it was not allowed for this color type"; - case 43: return "bKGD chunk has wrong size for palette image"; - case 44: return "bKGD chunk has wrong size for greyscale image"; - case 45: return "bKGD chunk has wrong size for RGB image"; - case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?"; - case 49: return "jumped past memory while generating dynamic huffman tree"; - case 50: return "jumped past memory while generating dynamic huffman tree"; - case 51: return "jumped past memory while inflating huffman block"; - case 52: return "jumped past memory while inflating"; - case 53: return "size of zlib data too small"; - case 54: return "repeat symbol in tree while there was no value symbol yet"; - /*jumped past tree while generating huffman tree, this could be when the - tree will have more leaves than symbols after generating it out of the - given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/ - case 55: return "jumped past tree while generating huffman tree"; - case 56: return "given output image colortype or bitdepth not supported for color conversion"; - case 57: return "invalid CRC encountered (checking CRC can be disabled)"; - case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)"; - case 59: return "requested color conversion not supported"; - case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)"; - case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; - /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/ - case 62: return "conversion from color to greyscale not supported"; - case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/ - /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ - case 64: return "the length of the END symbol 256 in the Huffman tree is 0"; - case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; - case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte"; - case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors"; - case 69: return "unknown chunk type with 'critical' flag encountered by the decoder"; - case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)"; - case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)"; - case 73: return "invalid tIME chunk size"; - case 74: return "invalid pHYs chunk size"; - /*length could be wrong, or data chopped off*/ - case 75: return "no null termination char found while decoding text chunk"; - case 76: return "iTXt chunk too short to contain required bytes"; - case 77: return "integer overflow in buffer size"; - case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/ - case 79: return "failed to open file for writing"; - case 80: return "tried creating a tree of 0 symbols"; - case 81: return "lazy matching at pos 0 is impossible"; - case 82: return "color conversion to palette requested while a color isn't in palette"; - case 83: return "memory allocation failed"; - case 84: return "given image too small to contain all pixels to be encoded"; - case 86: return "impossible offset in lz77 encoding (internal bug)"; - case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined"; - case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy"; - case 89: return "text chunk keyword too short or long: must have size 1-79"; - /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ - case 90: return "windowsize must be a power of two"; - case 91: return "invalid decompressed idat size"; - case 92: return "too many pixels, not supported"; - case 93: return "zero width or height is invalid"; - case 94: return "header chunk must have a size of 13 bytes"; - } - return "unknown error code"; + switch(code) + { + case 0: + return "no error, everything went ok"; + case 1: + return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ + case 10: + return "end of input memory reached without huffman end code"; /*while huffman decoding*/ + case 11: + return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/ + case 13: + return "problem while processing dynamic deflate block"; + case 14: + return "problem while processing dynamic deflate block"; + case 15: + return "problem while processing dynamic deflate block"; + case 16: + return "unexisting code while processing dynamic deflate block"; + case 17: + return "end of out buffer memory reached while inflating"; + case 18: + return "invalid distance code while inflating"; + case 19: + return "end of out buffer memory reached while inflating"; + case 20: + return "invalid deflate block BTYPE encountered while decoding"; + case 21: + return "NLEN is not ones complement of LEN in a deflate block"; + /*end of out buffer memory reached while inflating: + This can happen if the inflated deflate data is longer than the amount of bytes required to fill up + all the pixels of the image, given the color depth and image dimensions. Something that doesn't + happen in a normal, well encoded, PNG image.*/ + case 22: + return "end of out buffer memory reached while inflating"; + case 23: + return "end of in buffer memory reached while inflating"; + case 24: + return "invalid FCHECK in zlib header"; + case 25: + return "invalid compression method in zlib header"; + case 26: + return "FDICT encountered in zlib header while it's not used for PNG"; + case 27: + return "PNG file is smaller than a PNG header"; + /*Checks the magic file header, the first 8 bytes of the PNG file*/ + case 28: + return "incorrect PNG signature, it's no PNG or corrupted"; + case 29: + return "first chunk is not the header chunk"; + case 30: + return "chunk length too large, chunk broken off at end of file"; + case 31: + return "illegal PNG color type or bpp"; + case 32: + return "illegal PNG compression method"; + case 33: + return "illegal PNG filter method"; + case 34: + return "illegal PNG interlace method"; + case 35: + return "chunk length of a chunk is too large or the chunk too small"; + case 36: + return "illegal PNG filter type encountered"; + case 37: + return "illegal bit depth for this color type given"; + case 38: + return "the palette is too big"; /*more than 256 colors*/ + case 39: + return "more palette alpha values given in tRNS chunk than there are colors in the palette"; + case 40: + return "tRNS chunk has wrong size for greyscale image"; + case 41: + return "tRNS chunk has wrong size for RGB image"; + case 42: + return "tRNS chunk appeared while it was not allowed for this color type"; + case 43: + return "bKGD chunk has wrong size for palette image"; + case 44: + return "bKGD chunk has wrong size for greyscale image"; + case 45: + return "bKGD chunk has wrong size for RGB image"; + case 48: + return "empty input buffer given to decoder. Maybe caused by non-existing file?"; + case 49: + return "jumped past memory while generating dynamic huffman tree"; + case 50: + return "jumped past memory while generating dynamic huffman tree"; + case 51: + return "jumped past memory while inflating huffman block"; + case 52: + return "jumped past memory while inflating"; + case 53: + return "size of zlib data too small"; + case 54: + return "repeat symbol in tree while there was no value symbol yet"; + /*jumped past tree while generating huffman tree, this could be when the + tree will have more leaves than symbols after generating it out of the + given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/ + case 55: + return "jumped past tree while generating huffman tree"; + case 56: + return "given output image colortype or bitdepth not supported for color conversion"; + case 57: + return "invalid CRC encountered (checking CRC can be disabled)"; + case 58: + return "invalid ADLER32 encountered (checking ADLER32 can be disabled)"; + case 59: + return "requested color conversion not supported"; + case 60: + return "invalid window size given in the settings of the encoder (must be 0-32768)"; + case 61: + return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; + /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/ + case 62: + return "conversion from color to greyscale not supported"; + case 63: + return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/ + /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ + case 64: + return "the length of the END symbol 256 in the Huffman tree is 0"; + case 66: + return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; + case 67: + return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte"; + case 68: + return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors"; + case 69: + return "unknown chunk type with 'critical' flag encountered by the decoder"; + case 71: + return "unexisting interlace mode given to encoder (must be 0 or 1)"; + case 72: + return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)"; + case 73: + return "invalid tIME chunk size"; + case 74: + return "invalid pHYs chunk size"; + /*length could be wrong, or data chopped off*/ + case 75: + return "no null termination char found while decoding text chunk"; + case 76: + return "iTXt chunk too short to contain required bytes"; + case 77: + return "integer overflow in buffer size"; + case 78: + return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/ + case 79: + return "failed to open file for writing"; + case 80: + return "tried creating a tree of 0 symbols"; + case 81: + return "lazy matching at pos 0 is impossible"; + case 82: + return "color conversion to palette requested while a color isn't in palette"; + case 83: + return "memory allocation failed"; + case 84: + return "given image too small to contain all pixels to be encoded"; + case 86: + return "impossible offset in lz77 encoding (internal bug)"; + case 87: + return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined"; + case 88: + return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy"; + case 89: + return "text chunk keyword too short or long: must have size 1-79"; + /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ + case 90: + return "windowsize must be a power of two"; + case 91: + return "invalid decompressed idat size"; + case 92: + return "too many pixels, not supported"; + case 93: + return "zero width or height is invalid"; + case 94: + return "header chunk must have a size of 13 bytes"; + } + return "unknown error code"; } #endif /*LODEPNG_COMPILE_ERROR_TEXT*/ @@ -6026,16 +6155,16 @@ namespace lodepng #ifdef LODEPNG_COMPILE_DISK unsigned load_file(std::vector& buffer, const std::string& filename) { - long size = lodepng_filesize(filename.c_str()); - if(size < 0) return 78; - buffer.resize((size_t)size); - return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str()); + long size = lodepng_filesize(filename.c_str()); + if(size < 0) return 78; + buffer.resize((size_t)size); + return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str()); } /*write given buffer to the file, overwriting the file, it doesn't append to it.*/ unsigned save_file(const std::vector& buffer, const std::string& filename) { - return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str()); + return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str()); } #endif /* LODEPNG_COMPILE_DISK */ @@ -6044,21 +6173,21 @@ unsigned save_file(const std::vector& buffer, const std::string& filena unsigned decompress(std::vector& out, const uint8_t* in, size_t insize, const LodePNGDecompressSettings& settings) { - uint8_t* buffer = 0; - size_t buffersize = 0; - unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings); - if(buffer) - { - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; + uint8_t* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; } unsigned decompress(std::vector& out, const std::vector& in, const LodePNGDecompressSettings& settings) { - return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings); + return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings); } #endif /* LODEPNG_COMPILE_DECODER */ @@ -6066,21 +6195,21 @@ unsigned decompress(std::vector& out, const std::vector& in, unsigned compress(std::vector& out, const uint8_t* in, size_t insize, const LodePNGCompressSettings& settings) { - uint8_t* buffer = 0; - size_t buffersize = 0; - unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings); - if(buffer) - { - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; + uint8_t* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; } unsigned compress(std::vector& out, const std::vector& in, const LodePNGCompressSettings& settings) { - return compress(out, in.empty() ? 0 : &in[0], in.size(), settings); + return compress(out, in.empty() ? 0 : &in[0], in.size(), settings); } #endif /* LODEPNG_COMPILE_ENCODER */ #endif /* LODEPNG_COMPILE_ZLIB */ @@ -6090,24 +6219,24 @@ unsigned compress(std::vector& out, const std::vector& in, State::State() { - lodepng_state_init(this); + lodepng_state_init(this); } State::State(const State& other) { - lodepng_state_init(this); - lodepng_state_copy(this, &other); + lodepng_state_init(this); + lodepng_state_copy(this, &other); } State::~State() { - lodepng_state_cleanup(this); + lodepng_state_cleanup(this); } State& State::operator=(const State& other) { - lodepng_state_copy(this, &other); - return *this; + lodepng_state_copy(this, &other); + return *this; } #ifdef LODEPNG_COMPILE_DECODER @@ -6115,56 +6244,56 @@ State& State::operator=(const State& other) unsigned decode(std::vector& out, unsigned& w, unsigned& h, const uint8_t* in, size_t insize, LodePNGColorType colortype, unsigned bitdepth) { - uint8_t* buffer; - unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth); - if(buffer && !error) - { - State state; - state.info_raw.colortype = colortype; - state.info_raw.bitdepth = bitdepth; - size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; + uint8_t* buffer; + unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth); + if(buffer && !error) + { + State state; + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; } unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::vector& in, LodePNGColorType colortype, unsigned bitdepth) { - return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth); + return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth); } unsigned decode(std::vector& out, unsigned& w, unsigned& h, State& state, const uint8_t* in, size_t insize) { - uint8_t* buffer = NULL; - unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize); - if(buffer && !error) - { - size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - } - lodepng_free(buffer); - return error; + uint8_t* buffer = NULL; + unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize); + if(buffer && !error) + { + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + } + lodepng_free(buffer); + return error; } unsigned decode(std::vector& out, unsigned& w, unsigned& h, State& state, const std::vector& in) { - return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size()); + return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size()); } #ifdef LODEPNG_COMPILE_DISK unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::string& filename, LodePNGColorType colortype, unsigned bitdepth) { - std::vector buffer; - unsigned error = load_file(buffer, filename); - if(error) return error; - return decode(out, w, h, buffer, colortype, bitdepth); + std::vector buffer; + unsigned error = load_file(buffer, filename); + if(error) return error; + return decode(out, w, h, buffer, colortype, bitdepth); } #endif /* LODEPNG_COMPILE_DECODER */ #endif /* LODEPNG_COMPILE_DISK */ @@ -6172,55 +6301,55 @@ unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std:: #ifdef LODEPNG_COMPILE_ENCODER static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { - /*will not overflow for any color type if roughly w * h < 268435455*/ - size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); - size_t n = w * h; - return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; + /*will not overflow for any color type if roughly w * h < 268435455*/ + size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); + size_t n = w * h; + return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; } unsigned encode(std::vector& out, const uint8_t* in, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { - uint8_t* buffer; - size_t buffersize; - unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth); - if(buffer) - { - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; + uint8_t* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; } unsigned encode(std::vector& out, const std::vector& in, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { - if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; - return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); } unsigned encode(std::vector& out, const uint8_t* in, unsigned w, unsigned h, State& state) { - uint8_t* buffer; - size_t buffersize; - unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state); - if(buffer) - { - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; + uint8_t* buffer; + size_t buffersize; + unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; } unsigned encode(std::vector& out, const std::vector& in, unsigned w, unsigned h, State& state) { - if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84; - return encode(out, in.empty() ? 0 : &in[0], w, h, state); + if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, state); } #ifdef LODEPNG_COMPILE_DISK @@ -6228,18 +6357,18 @@ unsigned encode(const std::string& filename, const uint8_t* in, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { - std::vector buffer; - unsigned error = encode(buffer, in, w, h, colortype, bitdepth); - if(!error) error = save_file(buffer, filename); - return error; + std::vector buffer; + unsigned error = encode(buffer, in, w, h, colortype, bitdepth); + if(!error) error = save_file(buffer, filename); + return error; } unsigned encode(const std::string& filename, const std::vector& in, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { - if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; - return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); } #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_ENCODER */ diff --git a/source/lodepng.h b/source/lodepng.h index dbbe8bf..0868f4f 100644 --- a/source/lodepng.h +++ b/source/lodepng.h @@ -90,11 +90,11 @@ source files with custom allocators.*/ /*The PNG color types (also used for raw).*/ typedef enum LodePNGColorType { - LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/ - LCT_RGB = 2, /*RGB: 8,16 bit*/ - LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ - LCT_GREY_ALPHA = 4, /*greyscale with alpha: 8,16 bit*/ - LCT_RGBA = 6 /*RGB with alpha: 8,16 bit*/ + LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/ + LCT_RGB = 2, /*RGB: 8,16 bit*/ + LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ + LCT_GREY_ALPHA = 4, /*greyscale with alpha: 8,16 bit*/ + LCT_RGBA = 6 /*RGB with alpha: 8,16 bit*/ } LodePNGColorType; #ifdef LODEPNG_COMPILE_DECODER @@ -255,21 +255,21 @@ const char* lodepng_error_text(unsigned code); typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; struct LodePNGDecompressSettings { - /* Check LodePNGDecoderSettings for more ignorable errors */ - unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ + /* Check LodePNGDecoderSettings for more ignorable errors */ + unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ - /*use custom zlib decoder instead of built in one (default: null)*/ - unsigned (*custom_zlib)(uint8_t**, size_t*, - const uint8_t*, size_t, - const LodePNGDecompressSettings*); - /*use custom deflate decoder instead of built in one (default: null) - if custom_zlib is used, custom_deflate is ignored since only the built in - zlib function will call custom_deflate*/ - unsigned (*custom_inflate)(uint8_t**, size_t*, - const uint8_t*, size_t, - const LodePNGDecompressSettings*); + /*use custom zlib decoder instead of built in one (default: null)*/ + unsigned(*custom_zlib)(uint8_t**, size_t*, + const uint8_t*, size_t, + const LodePNGDecompressSettings*); + /*use custom deflate decoder instead of built in one (default: null) + if custom_zlib is used, custom_deflate is ignored since only the built in + zlib function will call custom_deflate*/ + unsigned(*custom_inflate)(uint8_t**, size_t*, + const uint8_t*, size_t, + const LodePNGDecompressSettings*); - const void* custom_context; /*optional custom settings for custom functions*/ + const void* custom_context; /*optional custom settings for custom functions*/ }; extern const LodePNGDecompressSettings lodepng_default_decompress_settings; @@ -284,26 +284,26 @@ between speed and compression ratio. typedef struct LodePNGCompressSettings LodePNGCompressSettings; struct LodePNGCompressSettings /*deflate = compress*/ { - /*LZ77 related settings*/ - unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ - unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ - unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ - unsigned minmatch; /*mininum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ - unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ - unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ + /*LZ77 related settings*/ + unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ + unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ + unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ + unsigned minmatch; /*mininum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ + unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ + unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ - /*use custom zlib encoder instead of built in one (default: null)*/ - unsigned (*custom_zlib)(uint8_t**, size_t*, - const uint8_t*, size_t, - const LodePNGCompressSettings*); - /*use custom deflate encoder instead of built in one (default: null) - if custom_zlib is used, custom_deflate is ignored since only the built in - zlib function will call custom_deflate*/ - unsigned (*custom_deflate)(uint8_t**, size_t*, - const uint8_t*, size_t, - const LodePNGCompressSettings*); + /*use custom zlib encoder instead of built in one (default: null)*/ + unsigned(*custom_zlib)(uint8_t**, size_t*, + const uint8_t*, size_t, + const LodePNGCompressSettings*); + /*use custom deflate encoder instead of built in one (default: null) + if custom_zlib is used, custom_deflate is ignored since only the built in + zlib function will call custom_deflate*/ + unsigned(*custom_deflate)(uint8_t**, size_t*, + const uint8_t*, size_t, + const LodePNGCompressSettings*); - const void* custom_context; /*optional custom settings for custom functions*/ + const void* custom_context; /*optional custom settings for custom functions*/ }; extern const LodePNGCompressSettings lodepng_default_compress_settings; @@ -318,41 +318,41 @@ format, and is used both for PNG and raw image data in LodePNG. */ typedef struct LodePNGColorMode { - /*header (IHDR)*/ - LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ - unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ + /*header (IHDR)*/ + LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ + unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ - /* - palette (PLTE and tRNS) + /* + palette (PLTE and tRNS) - Dynamically allocated with the colors of the palette, including alpha. - When encoding a PNG, to store your colors in the palette of the LodePNGColorMode, first use - lodepng_palette_clear, then for each color use lodepng_palette_add. - If you encode an image without alpha with palette, don't forget to put value 255 in each A byte of the palette. + Dynamically allocated with the colors of the palette, including alpha. + When encoding a PNG, to store your colors in the palette of the LodePNGColorMode, first use + lodepng_palette_clear, then for each color use lodepng_palette_add. + If you encode an image without alpha with palette, don't forget to put value 255 in each A byte of the palette. - When decoding, by default you can ignore this palette, since LodePNG already - fills the palette colors in the pixels of the raw RGBA output. + When decoding, by default you can ignore this palette, since LodePNG already + fills the palette colors in the pixels of the raw RGBA output. - The palette is only supported for color type 3. - */ - uint8_t* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/ - size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/ + The palette is only supported for color type 3. + */ + uint8_t* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/ + size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/ - /* - transparent color key (tRNS) + /* + transparent color key (tRNS) - This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. - For greyscale PNGs, r, g and b will all 3 be set to the same. + This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. + For greyscale PNGs, r, g and b will all 3 be set to the same. - When decoding, by default you can ignore this information, since LodePNG sets - pixels with this key to transparent already in the raw RGBA output. + When decoding, by default you can ignore this information, since LodePNG sets + pixels with this key to transparent already in the raw RGBA output. - The color key is only supported for color types 0 and 2. - */ - unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ - unsigned key_r; /*red/greyscale component of color key*/ - unsigned key_g; /*green component of color key*/ - unsigned key_b; /*blue component of color key*/ + The color key is only supported for color types 0 and 2. + */ + unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ + unsigned key_r; /*red/greyscale component of color key*/ + unsigned key_g; /*green component of color key*/ + unsigned key_b; /*blue component of color key*/ } LodePNGColorMode; /*init, cleanup and copy functions to use with this struct*/ @@ -395,90 +395,90 @@ size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* colo /*The information of a Time chunk in PNG.*/ typedef struct LodePNGTime { - unsigned year; /*2 bytes used (0-65535)*/ - unsigned month; /*1-12*/ - unsigned day; /*1-31*/ - unsigned hour; /*0-23*/ - unsigned minute; /*0-59*/ - unsigned second; /*0-60 (to allow for leap seconds)*/ + unsigned year; /*2 bytes used (0-65535)*/ + unsigned month; /*1-12*/ + unsigned day; /*1-31*/ + unsigned hour; /*0-23*/ + unsigned minute; /*0-59*/ + unsigned second; /*0-60 (to allow for leap seconds)*/ } LodePNGTime; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*Information about the PNG image, except pixels, width and height.*/ typedef struct LodePNGInfo { - /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ - unsigned compression_method;/*compression method of the original file. Always 0.*/ - unsigned filter_method; /*filter method of the original file*/ - unsigned interlace_method; /*interlace method of the original file*/ - LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ + /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ + unsigned compression_method;/*compression method of the original file. Always 0.*/ + unsigned filter_method; /*filter method of the original file*/ + unsigned interlace_method; /*interlace method of the original file*/ + LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /* - suggested background color chunk (bKGD) - This color uses the same color mode as the PNG (except alpha channel), which can be 1-bit to 16-bit. + /* + suggested background color chunk (bKGD) + This color uses the same color mode as the PNG (except alpha channel), which can be 1-bit to 16-bit. - For greyscale PNGs, r, g and b will all 3 be set to the same. When encoding - the encoder writes the red one. For palette PNGs: When decoding, the RGB value - will be stored, not a palette index. But when encoding, specify the index of - the palette in background_r, the other two are then ignored. + For greyscale PNGs, r, g and b will all 3 be set to the same. When encoding + the encoder writes the red one. For palette PNGs: When decoding, the RGB value + will be stored, not a palette index. But when encoding, specify the index of + the palette in background_r, the other two are then ignored. - The decoder does not use this background color to edit the color of pixels. - */ - unsigned background_defined; /*is a suggested background color given?*/ - unsigned background_r; /*red component of suggested background color*/ - unsigned background_g; /*green component of suggested background color*/ - unsigned background_b; /*blue component of suggested background color*/ + The decoder does not use this background color to edit the color of pixels. + */ + unsigned background_defined; /*is a suggested background color given?*/ + unsigned background_r; /*red component of suggested background color*/ + unsigned background_g; /*green component of suggested background color*/ + unsigned background_b; /*blue component of suggested background color*/ - /* - non-international text chunks (tEXt and zTXt) + /* + non-international text chunks (tEXt and zTXt) - The char** arrays each contain num strings. The actual messages are in - text_strings, while text_keys are keywords that give a short description what - the actual text represents, e.g. Title, Author, Description, or anything else. + The char** arrays each contain num strings. The actual messages are in + text_strings, while text_keys are keywords that give a short description what + the actual text represents, e.g. Title, Author, Description, or anything else. - A keyword is minimum 1 character and maximum 79 characters long. It's - discouraged to use a single line length longer than 79 characters for texts. + A keyword is minimum 1 character and maximum 79 characters long. It's + discouraged to use a single line length longer than 79 characters for texts. - Don't allocate these text buffers yourself. Use the init/cleanup functions - correctly and use lodepng_add_text and lodepng_clear_text. - */ - size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ - char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ - char** text_strings; /*the actual text*/ + Don't allocate these text buffers yourself. Use the init/cleanup functions + correctly and use lodepng_add_text and lodepng_clear_text. + */ + size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ + char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ + char** text_strings; /*the actual text*/ - /* - international text chunks (iTXt) - Similar to the non-international text chunks, but with additional strings - "langtags" and "transkeys". - */ - size_t itext_num; /*the amount of international texts in this PNG*/ - char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ - char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ - char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ - char** itext_strings; /*the actual international text - UTF-8 string*/ + /* + international text chunks (iTXt) + Similar to the non-international text chunks, but with additional strings + "langtags" and "transkeys". + */ + size_t itext_num; /*the amount of international texts in this PNG*/ + char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ + char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ + char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ + char** itext_strings; /*the actual international text - UTF-8 string*/ - /*time chunk (tIME)*/ - unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ - LodePNGTime time; + /*time chunk (tIME)*/ + unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ + LodePNGTime time; - /*phys chunk (pHYs)*/ - unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ - unsigned phys_x; /*pixels per unit in x direction*/ - unsigned phys_y; /*pixels per unit in y direction*/ - unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ + /*phys chunk (pHYs)*/ + unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ + unsigned phys_x; /*pixels per unit in x direction*/ + unsigned phys_y; /*pixels per unit in y direction*/ + unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ - /* - unknown chunks - There are 3 buffers, one for each position in the PNG where unknown chunks can appear - each buffer contains all unknown chunks for that position consecutively - The 3 buffers are the unknown chunks between certain critical chunks: - 0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND - Do not allocate or traverse this data yourself. Use the chunk traversing functions declared - later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. - */ - uint8_t* unknown_chunks_data[3]; - size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ + /* + unknown chunks + There are 3 buffers, one for each position in the PNG where unknown chunks can appear + each buffer contains all unknown chunks for that position consecutively + The 3 buffers are the unknown chunks between certain critical chunks: + 0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND + Do not allocate or traverse this data yourself. Use the chunk traversing functions declared + later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. + */ + uint8_t* unknown_chunks_data[3]; + size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGInfo; @@ -519,19 +519,19 @@ decoder, but not the Info settings from the Info structs. */ typedef struct LodePNGDecoderSettings { - LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ + LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ - /* Check LodePNGDecompressSettings for more ignorable errors */ - unsigned ignore_crc; /*ignore CRC checksums*/ - unsigned ignore_critical; /*ignore unknown critical chunks*/ - unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/ + /* Check LodePNGDecompressSettings for more ignorable errors */ + unsigned ignore_crc; /*ignore CRC checksums*/ + unsigned ignore_critical; /*ignore unknown critical chunks*/ + unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/ - unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ + unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ - /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ - unsigned remember_unknown_chunks; + unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ + /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ + unsigned remember_unknown_chunks; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGDecoderSettings; @@ -542,35 +542,35 @@ void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); /*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ typedef enum LodePNGFilterStrategy { - /*every filter at zero*/ - LFS_ZERO, - /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/ - LFS_MINSUM, - /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending - on the image, this is better or worse than minsum.*/ - LFS_ENTROPY, - /* - Brute-force-search PNG filters by compressing each filter for each scanline. - Experimental, very slow, and only rarely gives better compression than MINSUM. - */ - LFS_BRUTE_FORCE, - /*use predefined_filters buffer: you specify the filter type for each scanline*/ - LFS_PREDEFINED + /*every filter at zero*/ + LFS_ZERO, + /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/ + LFS_MINSUM, + /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending + on the image, this is better or worse than minsum.*/ + LFS_ENTROPY, + /* + Brute-force-search PNG filters by compressing each filter for each scanline. + Experimental, very slow, and only rarely gives better compression than MINSUM. + */ + LFS_BRUTE_FORCE, + /*use predefined_filters buffer: you specify the filter type for each scanline*/ + LFS_PREDEFINED } LodePNGFilterStrategy; /*Gives characteristics about the colors of the image, which helps decide which color model to use for encoding. Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/ typedef struct LodePNGColorProfile { - unsigned colored; /*not greyscale*/ - unsigned key; /*image is not opaque and color key is possible instead of full alpha*/ - uint16_t key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/ - uint16_t key_g; - uint16_t key_b; - unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/ - unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/ - uint8_t palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/ - unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/ + unsigned colored; /*not greyscale*/ + unsigned key; /*image is not opaque and color key is possible instead of full alpha*/ + uint16_t key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/ + uint16_t key_g; + uint16_t key_b; + unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/ + unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/ + uint8_t palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/ + unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/ } LodePNGColorProfile; void lodepng_color_profile_init(LodePNGColorProfile* profile); @@ -588,32 +588,32 @@ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, /*Settings for the encoder.*/ typedef struct LodePNGEncoderSettings { - LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ + LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ - unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ + unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ - /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than - 8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to - completely follow the official PNG heuristic, filter_palette_zero must be true and - filter_strategy must be LFS_MINSUM*/ - unsigned filter_palette_zero; - /*Which filter strategy to use when not using zeroes due to filter_palette_zero. - Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ - LodePNGFilterStrategy filter_strategy; - /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with - the same length as the amount of scanlines in the image, and each value must <= 5. You - have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero - must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ - const uint8_t* predefined_filters; + /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than + 8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to + completely follow the official PNG heuristic, filter_palette_zero must be true and + filter_strategy must be LFS_MINSUM*/ + unsigned filter_palette_zero; + /*Which filter strategy to use when not using zeroes due to filter_palette_zero. + Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ + LodePNGFilterStrategy filter_strategy; + /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with + the same length as the amount of scanlines in the image, and each value must <= 5. You + have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero + must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ + const uint8_t* predefined_filters; - /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). - If colortype is 3, PLTE is _always_ created.*/ - unsigned force_palette; + /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). + If colortype is 3, PLTE is _always_ created.*/ + unsigned force_palette; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*add LodePNG identifier and version as a text chunk, for debugging*/ - unsigned add_id; - /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ - unsigned text_compression; + /*add LodePNG identifier and version as a text chunk, for debugging*/ + unsigned add_id; + /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ + unsigned text_compression; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGEncoderSettings; @@ -626,17 +626,17 @@ void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); typedef struct LodePNGState { #ifdef LODEPNG_COMPILE_DECODER - LodePNGDecoderSettings decoder; /*the decoding settings*/ + LodePNGDecoderSettings decoder; /*the decoding settings*/ #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER - LodePNGEncoderSettings encoder; /*the encoding settings*/ + LodePNGEncoderSettings encoder; /*the encoding settings*/ #endif /*LODEPNG_COMPILE_ENCODER*/ - LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ - LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ - unsigned error; + LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ + LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ + unsigned error; #ifdef LODEPNG_COMPILE_CPP - /* For the lodepng::State subclass. */ - virtual ~LodePNGState(){} + /* For the lodepng::State subclass. */ + virtual ~LodePNGState() {} #endif } LodePNGState; @@ -823,11 +823,11 @@ namespace lodepng #ifdef LODEPNG_COMPILE_PNG class State : public LodePNGState { - public: - State(); - State(const State& other); - virtual ~State(); - State& operator=(const State& other); +public: + State(); + State(const State& other); + virtual ~State(); + State& operator=(const State& other); }; #ifdef LODEPNG_COMPILE_DECODER diff --git a/source/main_sdl.c b/source/main_sdl.c index f96b521..391b2c3 100644 --- a/source/main_sdl.c +++ b/source/main_sdl.c @@ -26,35 +26,37 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include /* need at least SDL_2.0.0 */ -#define SDL_MIN_X 2 -#define SDL_MIN_Y 0 -#define SDL_MIN_Z 0 -#define SDL_REQUIREDVERSION (SDL_VERSIONNUM(SDL_MIN_X,SDL_MIN_Y,SDL_MIN_Z)) -#define SDL_NEW_VERSION_REJECT (SDL_VERSIONNUM(3,0,0)) +#define SDL_MIN_X 2 +#define SDL_MIN_Y 0 +#define SDL_MIN_Z 0 +#define SDL_REQUIREDVERSION (SDL_VERSIONNUM(SDL_MIN_X,SDL_MIN_Y,SDL_MIN_Z)) +#define SDL_NEW_VERSION_REJECT (SDL_VERSIONNUM(3,0,0)) -static void Sys_AtExit (void) +static void Sys_AtExit(void) { SDL_Quit(); } -static void Sys_InitSDL (void) +static void Sys_InitSDL(void) { SDL_version v; SDL_version *sdl_version = &v; SDL_GetVersion(&v); - Sys_Printf("Found SDL version %" PRIi32 ".%" PRIi32 ".%" PRIi32 "\n",sdl_version->major,sdl_version->minor,sdl_version->patch); - if (SDL_VERSIONNUM(sdl_version->major,sdl_version->minor,sdl_version->patch) < SDL_REQUIREDVERSION) - { /*reject running under older SDL versions */ - Sys_Error("You need at least v%" PRIi32 ".%" PRIi32 ".%" PRIi32 " of SDL to run this game.", SDL_MIN_X,SDL_MIN_Y,SDL_MIN_Z); + Sys_Printf("Found SDL version %" PRIi32 ".%" PRIi32 ".%" PRIi32 "\n", sdl_version->major, sdl_version->minor, sdl_version->patch); + if(SDL_VERSIONNUM(sdl_version->major, sdl_version->minor, sdl_version->patch) < SDL_REQUIREDVERSION) + { + /*reject running under older SDL versions */ + Sys_Error("You need at least v%" PRIi32 ".%" PRIi32 ".%" PRIi32 " of SDL to run this game.", SDL_MIN_X, SDL_MIN_Y, SDL_MIN_Z); } - if (SDL_VERSIONNUM(sdl_version->major,sdl_version->minor,sdl_version->patch) >= SDL_NEW_VERSION_REJECT) - { /*reject running under newer (1.3.x) SDL */ + if(SDL_VERSIONNUM(sdl_version->major, sdl_version->minor, sdl_version->patch) >= SDL_NEW_VERSION_REJECT) + { + /*reject running under newer (1.3.x) SDL */ Sys_Error("Your version of SDL library is incompatible with me.\n" - "You need a library version in the line of %" PRIi32 ".%" PRIi32 ".%" PRIi32 "\n", SDL_MIN_X,SDL_MIN_Y,SDL_MIN_Z); + "You need a library version in the line of %" PRIi32 ".%" PRIi32 ".%" PRIi32 "\n", SDL_MIN_X, SDL_MIN_Y, SDL_MIN_Z); } - if (SDL_Init(0) < 0) + if(SDL_Init(0) < 0) { Sys_Error("Couldn't init SDL: %s", SDL_GetError()); } @@ -63,7 +65,7 @@ static void Sys_InitSDL (void) #define DEFAULT_MEMORY (256 * 1024 * 1024) // ericw -- was 72MB (64-bit) / 64MB (32-bit) -static quakeparms_t parms; +static quakeparms_t parms; // On OS X we call SDL_main from the launcher, but SDL2 doesn't redefine main // as SDL_main on OS X anymore, so we do it ourselves. @@ -73,8 +75,8 @@ static quakeparms_t parms; int32_t main(int32_t argc, char *argv[]) { - int32_t t; - double time, oldtime, newtime; + int32_t t; + double time, oldtime, newtime; host_parms = &parms; parms.basedir = "."; @@ -88,22 +90,22 @@ int32_t main(int32_t argc, char *argv[]) isDedicated = (COM_CheckParm("-dedicated") != 0); - Sys_InitSDL (); + Sys_InitSDL(); Sys_Init(); parms.memsize = DEFAULT_MEMORY; - if (COM_CheckParm("-heapsize")) + if(COM_CheckParm("-heapsize")) { t = COM_CheckParm("-heapsize") + 1; - if (t < com_argc) + if(t < com_argc) parms.memsize = Q_atoi(com_argv[t]) * 1024; } - parms.membase = malloc (parms.memsize); + parms.membase = malloc(parms.memsize); - if (!parms.membase) - Sys_Error ("Not enough memory free; check disk space\n"); + if(!parms.membase) + Sys_Error("Not enough memory free; check disk space\n"); Sys_Printf("Quake " VERSION " (c) id Software\n"); Sys_Printf("FitzQuake " FITZQUAKE_VERSION " (c) John Fitzgibbons\n"); @@ -114,52 +116,52 @@ int32_t main(int32_t argc, char *argv[]) Host_Init(); oldtime = Sys_DoubleTime(); - if (isDedicated) + if(isDedicated) { - while (1) + while(1) { - newtime = Sys_DoubleTime (); + newtime = Sys_DoubleTime(); time = newtime - oldtime; - while (time < sys_ticrate.value ) + while(time < sys_ticrate.value) { SDL_Delay(1); - newtime = Sys_DoubleTime (); + newtime = Sys_DoubleTime(); time = newtime - oldtime; } - Host_Frame (time); + Host_Frame(time); oldtime = newtime; } } else - while (1) - { - /* If we have no input focus at all, sleep a bit */ - if (!VID_HasMouseOrInputFocus() || cl.paused) + while(1) { - SDL_Delay(16); - } - /* If we're minimised, sleep a bit more */ - if (VID_IsMinimized()) - { - scr_skipupdate = 1; - SDL_Delay(32); - } - else - { - scr_skipupdate = 0; - } - newtime = Sys_DoubleTime (); - time = newtime - oldtime; + /* If we have no input focus at all, sleep a bit */ + if(!VID_HasMouseOrInputFocus() || cl.paused) + { + SDL_Delay(16); + } + /* If we're minimised, sleep a bit more */ + if(VID_IsMinimized()) + { + scr_skipupdate = 1; + SDL_Delay(32); + } + else + { + scr_skipupdate = 0; + } + newtime = Sys_DoubleTime(); + time = newtime - oldtime; - Host_Frame (time); + Host_Frame(time); - if (time < sys_throttle.value && !cls.timedemo) - SDL_Delay(1); + if(time < sys_throttle.value && !cls.timedemo) + SDL_Delay(1); - oldtime = newtime; - } + oldtime = newtime; + } return 0; } diff --git a/source/mathlib.c b/source/mathlib.c index 47479aa..8e20c56 100644 --- a/source/mathlib.c +++ b/source/mathlib.c @@ -24,7 +24,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -vec3_t vec3_origin = {0,0,0}; +vec3_t vec3_origin = {0, 0, 0}; /*-----------------------------------------------------------------*/ @@ -32,15 +32,15 @@ vec3_t vec3_origin = {0,0,0}; //#define DEG2RAD( a ) ( a * M_PI ) / 180.0F #define DEG2RAD( a ) ( (a) * M_PI_DIV_180 ) //johnfitz -void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ) +void ProjectPointOnPlane(vec3_t dst, const vec3_t p, const vec3_t normal) { float d; vec3_t n; float inv_denom; - inv_denom = 1.0F / DotProduct( normal, normal ); + inv_denom = 1.0F / DotProduct(normal, normal); - d = DotProduct( normal, p ) * inv_denom; + d = DotProduct(normal, p) * inv_denom; n[0] = normal[0] * inv_denom; n[1] = normal[1] * inv_denom; @@ -54,9 +54,9 @@ void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ) /* ** assumes "src" is normalized */ -void PerpendicularVector( vec3_t dst, const vec3_t src ) +void PerpendicularVector(vec3_t dst, const vec3_t src) { - int32_t pos; + int32_t pos; int32_t i; float minelem = 1.0F; vec3_t tempvec; @@ -64,12 +64,12 @@ void PerpendicularVector( vec3_t dst, const vec3_t src ) /* ** find the smallest magnitude axially aligned vector */ - for ( pos = 0, i = 0; i < 3; i++ ) + for(pos = 0, i = 0; i < 3; i++) { - if ( fabs( src[i] ) < minelem ) + if(fabs(src[i]) < minelem) { pos = i; - minelem = fabs( src[i] ); + minelem = fabs(src[i]); } } tempvec[0] = tempvec[1] = tempvec[2] = 0.0F; @@ -78,12 +78,12 @@ void PerpendicularVector( vec3_t dst, const vec3_t src ) /* ** project the point onto the plane defined by src */ - ProjectPointOnPlane( dst, tempvec, src ); + ProjectPointOnPlane(dst, tempvec, src); /* ** normalize the result */ - VectorNormalize( dst ); + VectorNormalize(dst); } //johnfitz -- removed RotatePointAroundVector() becuase it's no longer used and my compiler fucked it up anyway @@ -91,15 +91,15 @@ void PerpendicularVector( vec3_t dst, const vec3_t src ) /*-----------------------------------------------------------------*/ -float anglemod(float a) +float anglemod(float a) { #if 0 - if (a >= 0) - a -= 360*(int32_t)(a/360); + if(a >= 0) + a -= 360 * (int32_t)(a / 360); else - a += 360*( 1 + (int32_t)(-a/360) ); + a += 360 * (1 + (int32_t)(-a / 360)); #endif - a = (360.0/65536) * ((int32_t)(a*(65536/360.0)) & 65535); + a = (360.0 / 65536) * ((int32_t)(a * (65536 / 360.0)) & 65535); return a; } @@ -111,72 +111,72 @@ BoxOnPlaneSide Returns 1, 2, or 1 + 2 ================== */ -int32_t BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, mplane_t *p) +int32_t BoxOnPlaneSide(vec3_t emins, vec3_t emaxs, mplane_t *p) { - float dist1, dist2; - int32_t sides; + float dist1, dist2; + int32_t sides; -#if 0 // this is done by the BOX_ON_PLANE_SIDE macro before calling this - // function +#if 0 // this is done by the BOX_ON_PLANE_SIDE macro before calling this + // function // fast axial cases - if (p->type < 3) + if(p->type < 3) { - if (p->dist <= emins[p->type]) + if(p->dist <= emins[p->type]) return 1; - if (p->dist >= emaxs[p->type]) + if(p->dist >= emaxs[p->type]) return 2; return 3; } #endif // general case - switch (p->signbits) + switch(p->signbits) { case 0: - dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; - dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; + dist1 = p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + p->normal[2] * emaxs[2]; + dist2 = p->normal[0] * emins[0] + p->normal[1] * emins[1] + p->normal[2] * emins[2]; break; case 1: - dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; - dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; + dist1 = p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + p->normal[2] * emaxs[2]; + dist2 = p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + p->normal[2] * emins[2]; break; case 2: - dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; - dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; + dist1 = p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + p->normal[2] * emaxs[2]; + dist2 = p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + p->normal[2] * emins[2]; break; case 3: - dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; - dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; + dist1 = p->normal[0] * emins[0] + p->normal[1] * emins[1] + p->normal[2] * emaxs[2]; + dist2 = p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + p->normal[2] * emins[2]; break; case 4: - dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; - dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; + dist1 = p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + p->normal[2] * emins[2]; + dist2 = p->normal[0] * emins[0] + p->normal[1] * emins[1] + p->normal[2] * emaxs[2]; break; case 5: - dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; - dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; + dist1 = p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + p->normal[2] * emins[2]; + dist2 = p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + p->normal[2] * emaxs[2]; break; case 6: - dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; - dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; + dist1 = p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + p->normal[2] * emins[2]; + dist2 = p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + p->normal[2] * emaxs[2]; break; case 7: - dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; - dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; + dist1 = p->normal[0] * emins[0] + p->normal[1] * emins[1] + p->normal[2] * emins[2]; + dist2 = p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + p->normal[2] * emaxs[2]; break; default: - dist1 = dist2 = 0; // shut up compiler - Sys_Error ("BoxOnPlaneSide: Bad signbits"); + dist1 = dist2 = 0; // shut up compiler + Sys_Error("BoxOnPlaneSide: Bad signbits"); break; } #if 0 - int32_t i; - vec3_t corners[2]; + int32_t i; + vec3_t corners[2]; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { - if (plane->normal[i] < 0) + if(plane->normal[i] < 0) { corners[0][i] = emins[i]; corners[1][i] = emaxs[i]; @@ -187,24 +187,24 @@ int32_t BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, mplane_t *p) corners[0][i] = emaxs[i]; } } - dist = DotProduct (plane->normal, corners[0]) - plane->dist; - dist2 = DotProduct (plane->normal, corners[1]) - plane->dist; + dist = DotProduct(plane->normal, corners[0]) - plane->dist; + dist2 = DotProduct(plane->normal, corners[1]) - plane->dist; sides = 0; - if (dist1 >= 0) + if(dist1 >= 0) sides = 1; - if (dist2 < 0) + if(dist2 < 0) sides |= 2; #endif sides = 0; - if (dist1 >= p->dist) + if(dist1 >= p->dist) sides = 1; - if (dist2 < p->dist) + if(dist2 < p->dist) sides |= 2; #ifdef PARANOID - if (sides == 0) - Sys_Error ("BoxOnPlaneSide: sides==0"); + if(sides == 0) + Sys_Error("BoxOnPlaneSide: sides==0"); #endif return sides; @@ -212,7 +212,7 @@ int32_t BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, mplane_t *p) //johnfitz -- the opposite of AngleVectors. this takes forward and generates pitch yaw roll //TODO: take right and up vectors to properly set yaw and roll -void VectorAngles (const vec3_t forward, vec3_t angles) +void VectorAngles(const vec3_t forward, vec3_t angles) { vec3_t temp; @@ -224,98 +224,98 @@ void VectorAngles (const vec3_t forward, vec3_t angles) angles[ROLL] = 0; } -void AngleVectors (vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) +void AngleVectors(vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) { - float angle; - float sr, sp, sy, cr, cp, cy; + float angle; + float sr, sp, sy, cr, cp, cy; - angle = angles[YAW] * (M_PI*2 / 360); + angle = angles[YAW] * (M_PI * 2 / 360); sy = sin(angle); cy = cos(angle); - angle = angles[PITCH] * (M_PI*2 / 360); + angle = angles[PITCH] * (M_PI * 2 / 360); sp = sin(angle); cp = cos(angle); - angle = angles[ROLL] * (M_PI*2 / 360); + angle = angles[ROLL] * (M_PI * 2 / 360); sr = sin(angle); cr = cos(angle); - forward[0] = cp*cy; - forward[1] = cp*sy; + forward[0] = cp * cy; + forward[1] = cp * sy; forward[2] = -sp; - right[0] = (-1*sr*sp*cy+-1*cr*-sy); - right[1] = (-1*sr*sp*sy+-1*cr*cy); - right[2] = -1*sr*cp; - up[0] = (cr*sp*cy+-sr*-sy); - up[1] = (cr*sp*sy+-sr*cy); - up[2] = cr*cp; + right[0] = (-1 * sr * sp * cy + -1 * cr * -sy); + right[1] = (-1 * sr * sp * sy + -1 * cr * cy); + right[2] = -1 * sr * cp; + up[0] = (cr * sp * cy + -sr * -sy); + up[1] = (cr * sp * sy + -sr * cy); + up[2] = cr * cp; } -int32_t VectorCompare (vec3_t v1, vec3_t v2) +int32_t VectorCompare(vec3_t v1, vec3_t v2) { - int32_t i; + int32_t i; - for (i=0 ; i<3 ; i++) - if (v1[i] != v2[i]) + for(i = 0 ; i < 3 ; i++) + if(v1[i] != v2[i]) return 0; return 1; } -void VectorMA (vec3_t veca, float scale, vec3_t vecb, vec3_t vecc) +void VectorMA(vec3_t veca, float scale, vec3_t vecb, vec3_t vecc) { - vecc[0] = veca[0] + scale*vecb[0]; - vecc[1] = veca[1] + scale*vecb[1]; - vecc[2] = veca[2] + scale*vecb[2]; + vecc[0] = veca[0] + scale * vecb[0]; + vecc[1] = veca[1] + scale * vecb[1]; + vecc[2] = veca[2] + scale * vecb[2]; } -vec_t _DotProduct (vec3_t v1, vec3_t v2) +vec_t _DotProduct(vec3_t v1, vec3_t v2) { - return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; + return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; } -void _VectorSubtract (vec3_t veca, vec3_t vecb, vec3_t out) +void _VectorSubtract(vec3_t veca, vec3_t vecb, vec3_t out) { - out[0] = veca[0]-vecb[0]; - out[1] = veca[1]-vecb[1]; - out[2] = veca[2]-vecb[2]; + out[0] = veca[0] - vecb[0]; + out[1] = veca[1] - vecb[1]; + out[2] = veca[2] - vecb[2]; } -void _VectorAdd (vec3_t veca, vec3_t vecb, vec3_t out) +void _VectorAdd(vec3_t veca, vec3_t vecb, vec3_t out) { - out[0] = veca[0]+vecb[0]; - out[1] = veca[1]+vecb[1]; - out[2] = veca[2]+vecb[2]; + out[0] = veca[0] + vecb[0]; + out[1] = veca[1] + vecb[1]; + out[2] = veca[2] + vecb[2]; } -void _VectorCopy (vec3_t in, vec3_t out) +void _VectorCopy(vec3_t in, vec3_t out) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; } -void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross) +void CrossProduct(vec3_t v1, vec3_t v2, vec3_t cross) { - cross[0] = v1[1]*v2[2] - v1[2]*v2[1]; - cross[1] = v1[2]*v2[0] - v1[0]*v2[2]; - cross[2] = v1[0]*v2[1] - v1[1]*v2[0]; + cross[0] = v1[1] * v2[2] - v1[2] * v2[1]; + cross[1] = v1[2] * v2[0] - v1[0] * v2[2]; + cross[2] = v1[0] * v2[1] - v1[1] * v2[0]; } vec_t VectorLength(vec3_t v) { - return sqrt(DotProduct(v,v)); + return sqrt(DotProduct(v, v)); } -float VectorNormalize (vec3_t v) +float VectorNormalize(vec3_t v) { - float length, ilength; + float length, ilength; - length = sqrt(DotProduct(v,v)); + length = sqrt(DotProduct(v, v)); - if (length) + if(length) { - ilength = 1/length; + ilength = 1 / length; v[0] *= ilength; v[1] *= ilength; v[2] *= ilength; @@ -325,25 +325,25 @@ float VectorNormalize (vec3_t v) } -void VectorInverse (vec3_t v) +void VectorInverse(vec3_t v) { v[0] = -v[0]; v[1] = -v[1]; v[2] = -v[2]; } -void VectorScale (vec3_t in, vec_t scale, vec3_t out) +void VectorScale(vec3_t in, vec_t scale, vec3_t out) { - out[0] = in[0]*scale; - out[1] = in[1]*scale; - out[2] = in[2]*scale; + out[0] = in[0] * scale; + out[1] = in[1] * scale; + out[2] = in[2] * scale; } int32_t Q_log2(int32_t val) { - int32_t answer=0; - while (val>>=1) + int32_t answer = 0; + while(val >>= 1) answer++; return answer; } @@ -354,26 +354,26 @@ int32_t Q_log2(int32_t val) R_ConcatRotations ================ */ -void R_ConcatRotations (float in1[3][3], float in2[3][3], float out[3][3]) +void R_ConcatRotations(float in1[3][3], float in2[3][3], float out[3][3]) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + - in1[0][2] * in2[2][0]; + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + - in1[0][2] * in2[2][1]; + in1[0][2] * in2[2][1]; out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + - in1[0][2] * in2[2][2]; + in1[0][2] * in2[2][2]; out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + - in1[1][2] * in2[2][0]; + in1[1][2] * in2[2][0]; out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + - in1[1][2] * in2[2][1]; + in1[1][2] * in2[2][1]; out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + - in1[1][2] * in2[2][2]; + in1[1][2] * in2[2][2]; out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + - in1[2][2] * in2[2][0]; + in1[2][2] * in2[2][0]; out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + - in1[2][2] * in2[2][1]; + in1[2][2] * in2[2][1]; out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + - in1[2][2] * in2[2][2]; + in1[2][2] * in2[2][2]; } @@ -382,32 +382,32 @@ void R_ConcatRotations (float in1[3][3], float in2[3][3], float out[3][3]) R_ConcatTransforms ================ */ -void R_ConcatTransforms (float in1[3][4], float in2[3][4], float out[3][4]) +void R_ConcatTransforms(float in1[3][4], float in2[3][4], float out[3][4]) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + - in1[0][2] * in2[2][0]; + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + - in1[0][2] * in2[2][1]; + in1[0][2] * in2[2][1]; out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + - in1[0][2] * in2[2][2]; + in1[0][2] * in2[2][2]; out[0][3] = in1[0][0] * in2[0][3] + in1[0][1] * in2[1][3] + - in1[0][2] * in2[2][3] + in1[0][3]; + in1[0][2] * in2[2][3] + in1[0][3]; out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + - in1[1][2] * in2[2][0]; + in1[1][2] * in2[2][0]; out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + - in1[1][2] * in2[2][1]; + in1[1][2] * in2[2][1]; out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + - in1[1][2] * in2[2][2]; + in1[1][2] * in2[2][2]; out[1][3] = in1[1][0] * in2[0][3] + in1[1][1] * in2[1][3] + - in1[1][2] * in2[2][3] + in1[1][3]; + in1[1][2] * in2[2][3] + in1[1][3]; out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + - in1[2][2] * in2[2][0]; + in1[2][2] * in2[2][0]; out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + - in1[2][2] * in2[2][1]; + in1[2][2] * in2[2][1]; out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + - in1[2][2] * in2[2][2]; + in1[2][2] * in2[2][2]; out[2][3] = in1[2][0] * in2[0][3] + in1[2][1] * in2[1][3] + - in1[2][2] * in2[2][3] + in1[2][3]; + in1[2][2] * in2[2][3] + in1[2][3]; } @@ -421,22 +421,22 @@ quotient must fit in 32 bits. ==================== */ -void FloorDivMod (double numer, double denom, int32_t *quotient, - int32_t *rem) +void FloorDivMod(double numer, double denom, int32_t *quotient, + int32_t *rem) { - int32_t q, r; - double x; + int32_t q, r; + double x; #ifndef PARANOID - if (denom <= 0.0) - Sys_Error ("FloorDivMod: bad denominator %f\n", denom); + if(denom <= 0.0) + Sys_Error("FloorDivMod: bad denominator %f\n", denom); // if ((floor(numer) != numer) || (floor(denom) != denom)) // Sys_Error ("FloorDivMod: non-integer numer or denom %f %f\n", // numer, denom); #endif - if (numer >= 0.0) + if(numer >= 0.0) { x = floor(numer / denom); @@ -445,13 +445,13 @@ void FloorDivMod (double numer, double denom, int32_t *quotient, } else { - // - // perform operations with positive values, and fix mod to make floor-based - // + // + // perform operations with positive values, and fix mod to make floor-based + // x = floor(-numer / denom); q = -(int32_t)x; r = (int32_t)floor(-numer - (x * denom)); - if (r != 0) + if(r != 0) { q--; r = (int32_t)denom - r; @@ -468,18 +468,18 @@ void FloorDivMod (double numer, double denom, int32_t *quotient, GreatestCommonDivisor ==================== */ -int32_t GreatestCommonDivisor (int32_t i1, int32_t i2) +int32_t GreatestCommonDivisor(int32_t i1, int32_t i2) { - if (i1 > i2) + if(i1 > i2) { - if (i2 == 0) + if(i2 == 0) return (i1); - return GreatestCommonDivisor (i2, i1 % i2); + return GreatestCommonDivisor(i2, i1 % i2); } else { - if (i1 == 0) + if(i1 == 0) return (i2); - return GreatestCommonDivisor (i1, i2 % i1); + return GreatestCommonDivisor(i1, i2 % i1); } } diff --git a/source/mathlib.h b/source/mathlib.h index 46a12bc..ca5befa 100644 --- a/source/mathlib.h +++ b/source/mathlib.h @@ -29,7 +29,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include #ifndef M_PI -#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h +#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h #endif #define M_PI_DIV_180 (M_PI / 180.0) //johnfitz @@ -38,12 +38,17 @@ struct mplane_s; extern vec3_t vec3_origin; -#define nanmask (255 << 23) /* 7F800000 */ -#if 0 /* macro is violating strict aliasing rules */ -#define IS_NAN(x) (((*(int32_t *) (char *) &x) & nanmask) == nanmask) +#define nanmask (255 << 23) /* 7F800000 */ +#if 0 /* macro is violating strict aliasing rules */ +#define IS_NAN(x) (((*(int32_t *) (char *) &x) & nanmask) == nanmask) #else -static inline int32_t IS_NAN (float x) { - union { float f; int32_t i; } num; +static inline int32_t IS_NAN(float x) +{ + union + { + float f; + int32_t i; + } num; num.f = x; return ((num.i & nanmask) == nanmask); } @@ -61,61 +66,61 @@ static inline int32_t IS_NAN (float x) { // QuakeSpasm: To avoid strict aliasing violations, use a float/int32_t union instead of type punning. #define VectorNormalizeFast(_v)\ {\ - union { float f; int32_t i; } _y, _number;\ - _number.f = DotProduct(_v, _v);\ - if (_number.f != 0.0)\ - {\ - _y.i = 0x5f3759df - (_number.i >> 1);\ - _y.f = _y.f * (1.5f - (_number.f * 0.5f * _y.f * _y.f));\ - VectorScale(_v, _y.f, _v);\ - }\ + union { float f; int32_t i; } _y, _number;\ + _number.f = DotProduct(_v, _v);\ + if (_number.f != 0.0)\ + {\ + _y.i = 0x5f3759df - (_number.i >> 1);\ + _y.f = _y.f * (1.5f - (_number.f * 0.5f * _y.f * _y.f));\ + VectorScale(_v, _y.f, _v);\ + }\ } -void TurnVector (vec3_t out, const vec3_t forward, const vec3_t side, float angle); //johnfitz -void VectorAngles (const vec3_t forward, vec3_t angles); //johnfitz +void TurnVector(vec3_t out, const vec3_t forward, const vec3_t side, float angle); //johnfitz +void VectorAngles(const vec3_t forward, vec3_t angles); //johnfitz -void VectorMA (vec3_t veca, float scale, vec3_t vecb, vec3_t vecc); +void VectorMA(vec3_t veca, float scale, vec3_t vecb, vec3_t vecc); -vec_t _DotProduct (vec3_t v1, vec3_t v2); -void _VectorSubtract (vec3_t veca, vec3_t vecb, vec3_t out); -void _VectorAdd (vec3_t veca, vec3_t vecb, vec3_t out); -void _VectorCopy (vec3_t in, vec3_t out); +vec_t _DotProduct(vec3_t v1, vec3_t v2); +void _VectorSubtract(vec3_t veca, vec3_t vecb, vec3_t out); +void _VectorAdd(vec3_t veca, vec3_t vecb, vec3_t out); +void _VectorCopy(vec3_t in, vec3_t out); -int32_t VectorCompare (vec3_t v1, vec3_t v2); -vec_t VectorLength (vec3_t v); -void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross); -float VectorNormalize (vec3_t v); // returns vector length -void VectorInverse (vec3_t v); -void VectorScale (vec3_t in, vec_t scale, vec3_t out); +int32_t VectorCompare(vec3_t v1, vec3_t v2); +vec_t VectorLength(vec3_t v); +void CrossProduct(vec3_t v1, vec3_t v2, vec3_t cross); +float VectorNormalize(vec3_t v); // returns vector length +void VectorInverse(vec3_t v); +void VectorScale(vec3_t in, vec_t scale, vec3_t out); int32_t Q_log2(int32_t val); -void R_ConcatRotations (float in1[3][3], float in2[3][3], float out[3][3]); -void R_ConcatTransforms (float in1[3][4], float in2[3][4], float out[3][4]); +void R_ConcatRotations(float in1[3][3], float in2[3][3], float out[3][3]); +void R_ConcatTransforms(float in1[3][4], float in2[3][4], float out[3][4]); -void FloorDivMod (double numer, double denom, int32_t *quotient, - int32_t *rem); -int32_t GreatestCommonDivisor (int32_t i1, int32_t i2); +void FloorDivMod(double numer, double denom, int32_t *quotient, + int32_t *rem); +int32_t GreatestCommonDivisor(int32_t i1, int32_t i2); -void AngleVectors (vec3_t angles, vec3_t forward, vec3_t right, vec3_t up); -int32_t BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, struct mplane_s *plane); -float anglemod(float a); +void AngleVectors(vec3_t angles, vec3_t forward, vec3_t right, vec3_t up); +int32_t BoxOnPlaneSide(vec3_t emins, vec3_t emaxs, struct mplane_s *plane); +float anglemod(float a); -#define BOX_ON_PLANE_SIDE(emins, emaxs, p) \ - (((p)->type < 3)? \ - ( \ - ((p)->dist <= (emins)[(p)->type])? \ - 1 \ - : \ - ( \ - ((p)->dist >= (emaxs)[(p)->type])?\ - 2 \ - : \ - 3 \ - ) \ - ) \ - : \ - BoxOnPlaneSide( (emins), (emaxs), (p))) +#define BOX_ON_PLANE_SIDE(emins, emaxs, p) \ + (((p)->type < 3)? \ + ( \ + ((p)->dist <= (emins)[(p)->type])? \ + 1 \ + : \ + ( \ + ((p)->dist >= (emaxs)[(p)->type])?\ + 2 \ + : \ + 3 \ + ) \ + ) \ + : \ + BoxOnPlaneSide( (emins), (emaxs), (p))) -#endif /* __MATHLIB_H */ +#endif /* __MATHLIB_H */ diff --git a/source/menu.c b/source/menu.c index 55e36c9..4ecba8c 100644 --- a/source/menu.c +++ b/source/menu.c @@ -29,69 +29,69 @@ void (*vid_menukeyfn)(int32_t key); enum m_state_e m_state; -void M_Menu_Main_f (void); - void M_Menu_SinglePlayer_f (void); - void M_Menu_Load_f (void); - void M_Menu_Save_f (void); - void M_Menu_MultiPlayer_f (void); - void M_Menu_Setup_f (void); - void M_Menu_Net_f (void); - void M_Menu_LanConfig_f (void); - void M_Menu_GameOptions_f (void); - void M_Menu_Search_f (void); - void M_Menu_ServerList_f (void); - void M_Menu_Options_f (void); - void M_Menu_Keys_f (void); - void M_Menu_Video_f (void); - void M_Menu_Help_f (void); - void M_Menu_Quit_f (void); +void M_Menu_Main_f(void); +void M_Menu_SinglePlayer_f(void); +void M_Menu_Load_f(void); +void M_Menu_Save_f(void); +void M_Menu_MultiPlayer_f(void); +void M_Menu_Setup_f(void); +void M_Menu_Net_f(void); +void M_Menu_LanConfig_f(void); +void M_Menu_GameOptions_f(void); +void M_Menu_Search_f(void); +void M_Menu_ServerList_f(void); +void M_Menu_Options_f(void); +void M_Menu_Keys_f(void); +void M_Menu_Video_f(void); +void M_Menu_Help_f(void); +void M_Menu_Quit_f(void); -void M_Main_Draw (void); - void M_SinglePlayer_Draw (void); - void M_Load_Draw (void); - void M_Save_Draw (void); - void M_MultiPlayer_Draw (void); - void M_Setup_Draw (void); - void M_Net_Draw (void); - void M_LanConfig_Draw (void); - void M_GameOptions_Draw (void); - void M_Search_Draw (void); - void M_ServerList_Draw (void); - void M_Options_Draw (void); - void M_Keys_Draw (void); - void M_Video_Draw (void); - void M_Help_Draw (void); - void M_Quit_Draw (void); +void M_Main_Draw(void); +void M_SinglePlayer_Draw(void); +void M_Load_Draw(void); +void M_Save_Draw(void); +void M_MultiPlayer_Draw(void); +void M_Setup_Draw(void); +void M_Net_Draw(void); +void M_LanConfig_Draw(void); +void M_GameOptions_Draw(void); +void M_Search_Draw(void); +void M_ServerList_Draw(void); +void M_Options_Draw(void); +void M_Keys_Draw(void); +void M_Video_Draw(void); +void M_Help_Draw(void); +void M_Quit_Draw(void); -void M_Main_Key (int32_t key); - void M_SinglePlayer_Key (int32_t key); - void M_Load_Key (int32_t key); - void M_Save_Key (int32_t key); - void M_MultiPlayer_Key (int32_t key); - void M_Setup_Key (int32_t key); - void M_Net_Key (int32_t key); - void M_LanConfig_Key (int32_t key); - void M_GameOptions_Key (int32_t key); - void M_Search_Key (int32_t key); - void M_ServerList_Key (int32_t key); - void M_Options_Key (int32_t key); - void M_Keys_Key (int32_t key); - void M_Video_Key (int32_t key); - void M_Help_Key (int32_t key); - void M_Quit_Key (int32_t key); +void M_Main_Key(int32_t key); +void M_SinglePlayer_Key(int32_t key); +void M_Load_Key(int32_t key); +void M_Save_Key(int32_t key); +void M_MultiPlayer_Key(int32_t key); +void M_Setup_Key(int32_t key); +void M_Net_Key(int32_t key); +void M_LanConfig_Key(int32_t key); +void M_GameOptions_Key(int32_t key); +void M_Search_Key(int32_t key); +void M_ServerList_Key(int32_t key); +void M_Options_Key(int32_t key); +void M_Keys_Key(int32_t key); +void M_Video_Key(int32_t key); +void M_Help_Key(int32_t key); +void M_Quit_Key(int32_t key); -bool m_entersound; // play after drawing a frame, so caching - // won't disrupt the sound -bool m_recursiveDraw; +bool m_entersound; // play after drawing a frame, so caching +// won't disrupt the sound +bool m_recursiveDraw; -enum m_state_e m_return_state; -bool m_return_onerror; -char m_return_reason [32]; +enum m_state_e m_return_state; +bool m_return_onerror; +char m_return_reason [32]; -#define StartingGame (m_multiplayer_cursor == 1) -#define JoiningGame (m_multiplayer_cursor == 0) -#define IPXConfig (m_net_cursor == 0) -#define TCPIPConfig (m_net_cursor == 1) +#define StartingGame (m_multiplayer_cursor == 1) +#define JoiningGame (m_multiplayer_cursor == 0) +#define IPXConfig (m_net_cursor == 0) +#define TCPIPConfig (m_net_cursor == 1) void M_ConfigureNetSubsystem(void); @@ -102,99 +102,99 @@ M_DrawCharacter Draws one solid graphics character ================ */ -void M_DrawCharacter (int32_t cx, int32_t line, int32_t num) +void M_DrawCharacter(int32_t cx, int32_t line, int32_t num) { - Draw_Character (cx, line, num); + Draw_Character(cx, line, num); } -void M_Print (int32_t cx, int32_t cy, const char *str) +void M_Print(int32_t cx, int32_t cy, const char *str) { - while (*str) + while(*str) { - M_DrawCharacter (cx, cy, (*str)+128); + M_DrawCharacter(cx, cy, (*str) + 128); str++; cx += 8; } } -void M_PrintWhite (int32_t cx, int32_t cy, const char *str) +void M_PrintWhite(int32_t cx, int32_t cy, const char *str) { - while (*str) + while(*str) { - M_DrawCharacter (cx, cy, *str); + M_DrawCharacter(cx, cy, *str); str++; cx += 8; } } -void M_DrawTransPic (int32_t x, int32_t y, qpic_t *pic) +void M_DrawTransPic(int32_t x, int32_t y, qpic_t *pic) { - Draw_Pic (x, y, pic); //johnfitz -- simplified becuase centering is handled elsewhere + Draw_Pic(x, y, pic); //johnfitz -- simplified becuase centering is handled elsewhere } -void M_DrawPic (int32_t x, int32_t y, qpic_t *pic) +void M_DrawPic(int32_t x, int32_t y, qpic_t *pic) { - Draw_Pic (x, y, pic); //johnfitz -- simplified becuase centering is handled elsewhere + Draw_Pic(x, y, pic); //johnfitz -- simplified becuase centering is handled elsewhere } -void M_DrawTransPicTranslate (int32_t x, int32_t y, qpic_t *pic, int32_t top, int32_t bottom) //johnfitz -- more parameters +void M_DrawTransPicTranslate(int32_t x, int32_t y, qpic_t *pic, int32_t top, int32_t bottom) //johnfitz -- more parameters { - Draw_TransPicTranslate (x, y, pic, top, bottom); //johnfitz -- simplified becuase centering is handled elsewhere + Draw_TransPicTranslate(x, y, pic, top, bottom); //johnfitz -- simplified becuase centering is handled elsewhere } -void M_DrawTextBox (int32_t x, int32_t y, int32_t width, int32_t lines) +void M_DrawTextBox(int32_t x, int32_t y, int32_t width, int32_t lines) { - qpic_t *p; - int32_t cx, cy; - int32_t n; + qpic_t *p; + int32_t cx, cy; + int32_t n; // draw left side cx = x; cy = y; - p = Draw_CachePic ("gfx/box_tl.lmp"); - M_DrawTransPic (cx, cy, p); - p = Draw_CachePic ("gfx/box_ml.lmp"); - for (n = 0; n < lines; n++) + p = Draw_CachePic("gfx/box_tl.lmp"); + M_DrawTransPic(cx, cy, p); + p = Draw_CachePic("gfx/box_ml.lmp"); + for(n = 0; n < lines; n++) { cy += 8; - M_DrawTransPic (cx, cy, p); + M_DrawTransPic(cx, cy, p); } - p = Draw_CachePic ("gfx/box_bl.lmp"); - M_DrawTransPic (cx, cy+8, p); + p = Draw_CachePic("gfx/box_bl.lmp"); + M_DrawTransPic(cx, cy + 8, p); // draw middle cx += 8; - while (width > 0) + while(width > 0) { cy = y; - p = Draw_CachePic ("gfx/box_tm.lmp"); - M_DrawTransPic (cx, cy, p); - p = Draw_CachePic ("gfx/box_mm.lmp"); - for (n = 0; n < lines; n++) + p = Draw_CachePic("gfx/box_tm.lmp"); + M_DrawTransPic(cx, cy, p); + p = Draw_CachePic("gfx/box_mm.lmp"); + for(n = 0; n < lines; n++) { cy += 8; - if (n == 1) - p = Draw_CachePic ("gfx/box_mm2.lmp"); - M_DrawTransPic (cx, cy, p); + if(n == 1) + p = Draw_CachePic("gfx/box_mm2.lmp"); + M_DrawTransPic(cx, cy, p); } - p = Draw_CachePic ("gfx/box_bm.lmp"); - M_DrawTransPic (cx, cy+8, p); + p = Draw_CachePic("gfx/box_bm.lmp"); + M_DrawTransPic(cx, cy + 8, p); width -= 2; cx += 16; } // draw right side cy = y; - p = Draw_CachePic ("gfx/box_tr.lmp"); - M_DrawTransPic (cx, cy, p); - p = Draw_CachePic ("gfx/box_mr.lmp"); - for (n = 0; n < lines; n++) + p = Draw_CachePic("gfx/box_tr.lmp"); + M_DrawTransPic(cx, cy, p); + p = Draw_CachePic("gfx/box_mr.lmp"); + for(n = 0; n < lines; n++) { cy += 8; - M_DrawTransPic (cx, cy, p); + M_DrawTransPic(cx, cy, p); } - p = Draw_CachePic ("gfx/box_br.lmp"); - M_DrawTransPic (cx, cy+8, p); + p = Draw_CachePic("gfx/box_br.lmp"); + M_DrawTransPic(cx, cy + 8, p); } //============================================================================= @@ -206,15 +206,15 @@ int32_t m_save_demonum; M_ToggleMenu_f ================ */ -void M_ToggleMenu_f (void) +void M_ToggleMenu_f(void) { m_entersound = true; - if (key_dest == key_menu) + if(key_dest == key_menu) { - if (m_state != m_main) + if(m_state != m_main) { - M_Menu_Main_f (); + M_Menu_Main_f(); return; } @@ -223,13 +223,13 @@ void M_ToggleMenu_f (void) m_state = m_none; return; } - if (key_dest == key_console) + if(key_dest == key_console) { - Con_ToggleConsole_f (); + Con_ToggleConsole_f(); } else { - M_Menu_Main_f (); + M_Menu_Main_f(); } } @@ -237,13 +237,13 @@ void M_ToggleMenu_f (void) //============================================================================= /* MAIN MENU */ -int32_t m_main_cursor; -#define MAIN_ITEMS 5 +int32_t m_main_cursor; +#define MAIN_ITEMS 5 -void M_Menu_Main_f (void) +void M_Menu_Main_f(void) { - if (key_dest != key_menu) + if(key_dest != key_menu) { m_save_demonum = cls.demonum; cls.demonum = -1; @@ -255,25 +255,25 @@ void M_Menu_Main_f (void) } -void M_Main_Draw (void) +void M_Main_Draw(void) { - int32_t f; - qpic_t *p; + int32_t f; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/ttl_main.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - M_DrawTransPic (72, 32, Draw_CachePic ("gfx/mainmenu.lmp") ); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/ttl_main.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + M_DrawTransPic(72, 32, Draw_CachePic("gfx/mainmenu.lmp")); - f = (int32_t)(realtime * 10)%6; + f = (int32_t)(realtime * 10) % 6; - M_DrawTransPic (54, 32 + m_main_cursor * 20,Draw_CachePic( va("gfx/menudot%" PRIi32 ".lmp", f+1 ) ) ); + M_DrawTransPic(54, 32 + m_main_cursor * 20, Draw_CachePic(va("gfx/menudot%" PRIi32 ".lmp", f + 1))); } -void M_Main_Key (int32_t key) +void M_Main_Key(int32_t key) { - switch (key) + switch(key) { case K_ESCAPE: case K_BBUTTON: @@ -281,21 +281,21 @@ void M_Main_Key (int32_t key) key_dest = key_game; m_state = m_none; cls.demonum = m_save_demonum; - if (!fitzmode) /* QuakeSpasm customization: */ + if(!fitzmode) /* QuakeSpasm customization: */ break; - if (cls.demonum != -1 && !cls.demoplayback && cls.state != ca_connected) - CL_NextDemo (); + if(cls.demonum != -1 && !cls.demoplayback && cls.state != ca_connected) + CL_NextDemo(); break; case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - if (++m_main_cursor >= MAIN_ITEMS) + S_LocalSound("misc/menu1.wav"); + if(++m_main_cursor >= MAIN_ITEMS) m_main_cursor = 0; break; case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - if (--m_main_cursor < 0) + S_LocalSound("misc/menu1.wav"); + if(--m_main_cursor < 0) m_main_cursor = MAIN_ITEMS - 1; break; @@ -304,26 +304,26 @@ void M_Main_Key (int32_t key) case K_ABUTTON: m_entersound = true; - switch (m_main_cursor) + switch(m_main_cursor) { case 0: - M_Menu_SinglePlayer_f (); + M_Menu_SinglePlayer_f(); break; case 1: - M_Menu_MultiPlayer_f (); + M_Menu_MultiPlayer_f(); break; case 2: - M_Menu_Options_f (); + M_Menu_Options_f(); break; case 3: - M_Menu_Help_f (); + M_Menu_Help_f(); break; case 4: - M_Menu_Quit_f (); + M_Menu_Quit_f(); break; } } @@ -332,11 +332,11 @@ void M_Main_Key (int32_t key) //============================================================================= /* SINGLE PLAYER MENU */ -int32_t m_singleplayer_cursor; -#define SINGLEPLAYER_ITEMS 3 +int32_t m_singleplayer_cursor; +#define SINGLEPLAYER_ITEMS 3 -void M_Menu_SinglePlayer_f (void) +void M_Menu_SinglePlayer_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -345,40 +345,40 @@ void M_Menu_SinglePlayer_f (void) } -void M_SinglePlayer_Draw (void) +void M_SinglePlayer_Draw(void) { - int32_t f; - qpic_t *p; + int32_t f; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/ttl_sgl.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - M_DrawTransPic (72, 32, Draw_CachePic ("gfx/sp_menu.lmp") ); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/ttl_sgl.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + M_DrawTransPic(72, 32, Draw_CachePic("gfx/sp_menu.lmp")); - f = (int32_t)(realtime * 10)%6; + f = (int32_t)(realtime * 10) % 6; - M_DrawTransPic (54, 32 + m_singleplayer_cursor * 20,Draw_CachePic( va("gfx/menudot%" PRIi32 ".lmp", f+1 ) ) ); + M_DrawTransPic(54, 32 + m_singleplayer_cursor * 20, Draw_CachePic(va("gfx/menudot%" PRIi32 ".lmp", f + 1))); } -void M_SinglePlayer_Key (int32_t key) +void M_SinglePlayer_Key(int32_t key) { - switch (key) + switch(key) { case K_ESCAPE: case K_BBUTTON: - M_Menu_Main_f (); + M_Menu_Main_f(); break; case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - if (++m_singleplayer_cursor >= SINGLEPLAYER_ITEMS) + S_LocalSound("misc/menu1.wav"); + if(++m_singleplayer_cursor >= SINGLEPLAYER_ITEMS) m_singleplayer_cursor = 0; break; case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - if (--m_singleplayer_cursor < 0) + S_LocalSound("misc/menu1.wav"); + if(--m_singleplayer_cursor < 0) m_singleplayer_cursor = SINGLEPLAYER_ITEMS - 1; break; @@ -387,28 +387,28 @@ void M_SinglePlayer_Key (int32_t key) case K_ABUTTON: m_entersound = true; - switch (m_singleplayer_cursor) + switch(m_singleplayer_cursor) { case 0: - if (sv.active) - if (!SCR_ModalMessage("Are you sure you want to\nstart a new game?\n", 0.0f)) + if(sv.active) + if(!SCR_ModalMessage("Are you sure you want to\nstart a new game?\n", 0.0f)) break; IN_Activate(); key_dest = key_game; - if (sv.active) - Cbuf_AddText ("disconnect\n"); - Cbuf_AddText ("maxplayers 1\n"); - Cbuf_AddText ("deathmatch 0\n"); //johnfitz - Cbuf_AddText ("coop 0\n"); //johnfitz - Cbuf_AddText ("map start\n"); + if(sv.active) + Cbuf_AddText("disconnect\n"); + Cbuf_AddText("maxplayers 1\n"); + Cbuf_AddText("deathmatch 0\n"); //johnfitz + Cbuf_AddText("coop 0\n"); //johnfitz + Cbuf_AddText("map start\n"); break; case 1: - M_Menu_Load_f (); + M_Menu_Load_f(); break; case 2: - M_Menu_Save_f (); + M_Menu_Save_f(); break; } } @@ -417,155 +417,155 @@ void M_SinglePlayer_Key (int32_t key) //============================================================================= /* LOAD/SAVE MENU */ -int32_t load_cursor; // 0 < load_cursor < MAX_SAVEGAMES +int32_t load_cursor; // 0 < load_cursor < MAX_SAVEGAMES -#define MAX_SAVEGAMES 20 /* johnfitz -- increased from 12 */ -char m_filenames[MAX_SAVEGAMES][SAVEGAME_COMMENT_LENGTH+1]; -int32_t loadable[MAX_SAVEGAMES]; +#define MAX_SAVEGAMES 20 /* johnfitz -- increased from 12 */ +char m_filenames[MAX_SAVEGAMES][SAVEGAME_COMMENT_LENGTH + 1]; +int32_t loadable[MAX_SAVEGAMES]; -void M_ScanSaves (void) +void M_ScanSaves(void) { - int32_t i, j; - char name[MAX_OSPATH]; - FILE *f; - int32_t version; + int32_t i, j; + char name[MAX_OSPATH]; + FILE *f; + int32_t version; - for (i = 0; i < MAX_SAVEGAMES; i++) + for(i = 0; i < MAX_SAVEGAMES; i++) { - strcpy (m_filenames[i], "--- UNUSED SLOT ---"); + strcpy(m_filenames[i], "--- UNUSED SLOT ---"); loadable[i] = false; - q_snprintf (name, sizeof(name), "%s/s%" PRIi32 ".sav", com_gamedir, i); - f = fopen (name, "r"); - if (!f) + q_snprintf(name, sizeof(name), "%s/s%" PRIi32 ".sav", com_gamedir, i); + f = fopen(name, "r"); + if(!f) continue; - fscanf (f, "%" PRIi32 "\n", &version); - fscanf (f, "%79s\n", name); - strncpy (m_filenames[i], name, sizeof(m_filenames[i])-1); + fscanf(f, "%" PRIi32 "\n", &version); + fscanf(f, "%79s\n", name); + strncpy(m_filenames[i], name, sizeof(m_filenames[i]) - 1); - // change _ back to space - for (j = 0; j < SAVEGAME_COMMENT_LENGTH; j++) + // change _ back to space + for(j = 0; j < SAVEGAME_COMMENT_LENGTH; j++) { - if (m_filenames[i][j] == '_') + if(m_filenames[i][j] == '_') m_filenames[i][j] = ' '; } loadable[i] = true; - fclose (f); + fclose(f); } } -void M_Menu_Load_f (void) +void M_Menu_Load_f(void) { m_entersound = true; m_state = m_load; IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; - M_ScanSaves (); + M_ScanSaves(); } -void M_Menu_Save_f (void) +void M_Menu_Save_f(void) { - if (!sv.active) + if(!sv.active) return; - if (cl.intermission) + if(cl.intermission) return; - if (svs.maxclients != 1) + if(svs.maxclients != 1) return; m_entersound = true; m_state = m_save; IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; - M_ScanSaves (); + M_ScanSaves(); } -void M_Load_Draw (void) +void M_Load_Draw(void) { - int32_t i; - qpic_t *p; + int32_t i; + qpic_t *p; - p = Draw_CachePic ("gfx/p_load.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + p = Draw_CachePic("gfx/p_load.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - for (i = 0; i < MAX_SAVEGAMES; i++) - M_Print (16, 32 + 8*i, m_filenames[i]); + for(i = 0; i < MAX_SAVEGAMES; i++) + M_Print(16, 32 + 8 * i, m_filenames[i]); // line cursor - M_DrawCharacter (8, 32 + load_cursor*8, 12+((int32_t)(realtime*4)&1)); + M_DrawCharacter(8, 32 + load_cursor * 8, 12 + ((int32_t)(realtime * 4) & 1)); } -void M_Save_Draw (void) +void M_Save_Draw(void) { - int32_t i; - qpic_t *p; + int32_t i; + qpic_t *p; - p = Draw_CachePic ("gfx/p_save.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + p = Draw_CachePic("gfx/p_save.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - for (i = 0; i < MAX_SAVEGAMES; i++) - M_Print (16, 32 + 8*i, m_filenames[i]); + for(i = 0; i < MAX_SAVEGAMES; i++) + M_Print(16, 32 + 8 * i, m_filenames[i]); // line cursor - M_DrawCharacter (8, 32 + load_cursor*8, 12+((int32_t)(realtime*4)&1)); + M_DrawCharacter(8, 32 + load_cursor * 8, 12 + ((int32_t)(realtime * 4) & 1)); } -void M_Load_Key (int32_t k) +void M_Load_Key(int32_t k) { - switch (k) + switch(k) { case K_ESCAPE: case K_BBUTTON: - M_Menu_SinglePlayer_f (); + M_Menu_SinglePlayer_f(); break; case K_ENTER: case K_KP_ENTER: case K_ABUTTON: - S_LocalSound ("misc/menu2.wav"); - if (!loadable[load_cursor]) + S_LocalSound("misc/menu2.wav"); + if(!loadable[load_cursor]) return; m_state = m_none; IN_Activate(); key_dest = key_game; - // Host_Loadgame_f can't bring up the loading plaque because too much - // stack space has been used, so do it now - SCR_BeginLoadingPlaque (); + // Host_Loadgame_f can't bring up the loading plaque because too much + // stack space has been used, so do it now + SCR_BeginLoadingPlaque(); - // issue the load command - Cbuf_AddText (va ("load s%" PRIi32 "\n", load_cursor) ); + // issue the load command + Cbuf_AddText(va("load s%" PRIi32 "\n", load_cursor)); return; case K_UPARROW: case K_LEFTARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); load_cursor--; - if (load_cursor < 0) - load_cursor = MAX_SAVEGAMES-1; + if(load_cursor < 0) + load_cursor = MAX_SAVEGAMES - 1; break; case K_DOWNARROW: case K_RIGHTARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); load_cursor++; - if (load_cursor >= MAX_SAVEGAMES) + if(load_cursor >= MAX_SAVEGAMES) load_cursor = 0; break; } } -void M_Save_Key (int32_t k) +void M_Save_Key(int32_t k) { - switch (k) + switch(k) { case K_ESCAPE: case K_BBUTTON: - M_Menu_SinglePlayer_f (); + M_Menu_SinglePlayer_f(); break; case K_ENTER: @@ -574,22 +574,22 @@ void M_Save_Key (int32_t k) m_state = m_none; IN_Activate(); key_dest = key_game; - Cbuf_AddText (va("save s%" PRIi32 "\n", load_cursor)); + Cbuf_AddText(va("save s%" PRIi32 "\n", load_cursor)); return; case K_UPARROW: case K_LEFTARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); load_cursor--; - if (load_cursor < 0) - load_cursor = MAX_SAVEGAMES-1; + if(load_cursor < 0) + load_cursor = MAX_SAVEGAMES - 1; break; case K_DOWNARROW: case K_RIGHTARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); load_cursor++; - if (load_cursor >= MAX_SAVEGAMES) + if(load_cursor >= MAX_SAVEGAMES) load_cursor = 0; break; } @@ -598,11 +598,11 @@ void M_Save_Key (int32_t k) //============================================================================= /* MULTIPLAYER MENU */ -int32_t m_multiplayer_cursor; -#define MULTIPLAYER_ITEMS 3 +int32_t m_multiplayer_cursor; +#define MULTIPLAYER_ITEMS 3 -void M_Menu_MultiPlayer_f (void) +void M_Menu_MultiPlayer_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -611,44 +611,44 @@ void M_Menu_MultiPlayer_f (void) } -void M_MultiPlayer_Draw (void) +void M_MultiPlayer_Draw(void) { - int32_t f; - qpic_t *p; + int32_t f; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - M_DrawTransPic (72, 32, Draw_CachePic ("gfx/mp_menu.lmp") ); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + M_DrawTransPic(72, 32, Draw_CachePic("gfx/mp_menu.lmp")); - f = (int32_t)(realtime * 10)%6; + f = (int32_t)(realtime * 10) % 6; - M_DrawTransPic (54, 32 + m_multiplayer_cursor * 20,Draw_CachePic( va("gfx/menudot%" PRIi32 ".lmp", f+1 ) ) ); + M_DrawTransPic(54, 32 + m_multiplayer_cursor * 20, Draw_CachePic(va("gfx/menudot%" PRIi32 ".lmp", f + 1))); - if (ipxAvailable || tcpipAvailable) + if(ipxAvailable || tcpipAvailable) return; - M_PrintWhite ((320/2) - ((27*8)/2), 148, "No Communications Available"); + M_PrintWhite((320 / 2) - ((27 * 8) / 2), 148, "No Communications Available"); } -void M_MultiPlayer_Key (int32_t key) +void M_MultiPlayer_Key(int32_t key) { - switch (key) + switch(key) { case K_ESCAPE: case K_BBUTTON: - M_Menu_Main_f (); + M_Menu_Main_f(); break; case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - if (++m_multiplayer_cursor >= MULTIPLAYER_ITEMS) + S_LocalSound("misc/menu1.wav"); + if(++m_multiplayer_cursor >= MULTIPLAYER_ITEMS) m_multiplayer_cursor = 0; break; case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - if (--m_multiplayer_cursor < 0) + S_LocalSound("misc/menu1.wav"); + if(--m_multiplayer_cursor < 0) m_multiplayer_cursor = MULTIPLAYER_ITEMS - 1; break; @@ -656,20 +656,20 @@ void M_MultiPlayer_Key (int32_t key) case K_KP_ENTER: case K_ABUTTON: m_entersound = true; - switch (m_multiplayer_cursor) + switch(m_multiplayer_cursor) { case 0: - if (ipxAvailable || tcpipAvailable) - M_Menu_Net_f (); + if(ipxAvailable || tcpipAvailable) + M_Menu_Net_f(); break; case 1: - if (ipxAvailable || tcpipAvailable) - M_Menu_Net_f (); + if(ipxAvailable || tcpipAvailable) + M_Menu_Net_f(); break; case 2: - M_Menu_Setup_f (); + M_Menu_Setup_f(); break; } } @@ -678,19 +678,19 @@ void M_MultiPlayer_Key (int32_t key) //============================================================================= /* SETUP MENU */ -int32_t setup_cursor = 4; -int32_t setup_cursor_table[] = {40, 56, 80, 104, 140}; +int32_t setup_cursor = 4; +int32_t setup_cursor_table[] = {40, 56, 80, 104, 140}; -char setup_hostname[16]; -char setup_myname[16]; -int32_t setup_oldtop; -int32_t setup_oldbottom; -int32_t setup_top; -int32_t setup_bottom; +char setup_hostname[16]; +char setup_myname[16]; +int32_t setup_oldtop; +int32_t setup_oldbottom; +int32_t setup_top; +int32_t setup_bottom; -#define NUM_SETUP_CMDS 5 +#define NUM_SETUP_CMDS 5 -void M_Menu_Setup_f (void) +void M_Menu_Setup_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -703,151 +703,151 @@ void M_Menu_Setup_f (void) } -void M_Setup_Draw (void) +void M_Setup_Draw(void) { - qpic_t *p; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - M_Print (64, 40, "Hostname"); - M_DrawTextBox (160, 32, 16, 1); - M_Print (168, 40, setup_hostname); + M_Print(64, 40, "Hostname"); + M_DrawTextBox(160, 32, 16, 1); + M_Print(168, 40, setup_hostname); - M_Print (64, 56, "Your name"); - M_DrawTextBox (160, 48, 16, 1); - M_Print (168, 56, setup_myname); + M_Print(64, 56, "Your name"); + M_DrawTextBox(160, 48, 16, 1); + M_Print(168, 56, setup_myname); - M_Print (64, 80, "Shirt color"); - M_Print (64, 104, "Pants color"); + M_Print(64, 80, "Shirt color"); + M_Print(64, 104, "Pants color"); - M_DrawTextBox (64, 140-8, 14, 1); - M_Print (72, 140, "Accept Changes"); + M_DrawTextBox(64, 140 - 8, 14, 1); + M_Print(72, 140, "Accept Changes"); - p = Draw_CachePic ("gfx/bigbox.lmp"); - M_DrawTransPic (160, 64, p); - p = Draw_CachePic ("gfx/menuplyr.lmp"); - M_DrawTransPicTranslate (172, 72, p, setup_top, setup_bottom); + p = Draw_CachePic("gfx/bigbox.lmp"); + M_DrawTransPic(160, 64, p); + p = Draw_CachePic("gfx/menuplyr.lmp"); + M_DrawTransPicTranslate(172, 72, p, setup_top, setup_bottom); - M_DrawCharacter (56, setup_cursor_table [setup_cursor], 12+((int32_t)(realtime*4)&1)); + M_DrawCharacter(56, setup_cursor_table [setup_cursor], 12 + ((int32_t)(realtime * 4) & 1)); - if (setup_cursor == 0) - M_DrawCharacter (168 + 8*strlen(setup_hostname), setup_cursor_table [setup_cursor], 10+((int32_t)(realtime*4)&1)); + if(setup_cursor == 0) + M_DrawCharacter(168 + 8 * strlen(setup_hostname), setup_cursor_table [setup_cursor], 10 + ((int32_t)(realtime * 4) & 1)); - if (setup_cursor == 1) - M_DrawCharacter (168 + 8*strlen(setup_myname), setup_cursor_table [setup_cursor], 10+((int32_t)(realtime*4)&1)); + if(setup_cursor == 1) + M_DrawCharacter(168 + 8 * strlen(setup_myname), setup_cursor_table [setup_cursor], 10 + ((int32_t)(realtime * 4) & 1)); } -void M_Setup_Key (int32_t k) +void M_Setup_Key(int32_t k) { - switch (k) + switch(k) { case K_ESCAPE: case K_BBUTTON: - M_Menu_MultiPlayer_f (); + M_Menu_MultiPlayer_f(); break; case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); setup_cursor--; - if (setup_cursor < 0) - setup_cursor = NUM_SETUP_CMDS-1; + if(setup_cursor < 0) + setup_cursor = NUM_SETUP_CMDS - 1; break; case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); setup_cursor++; - if (setup_cursor >= NUM_SETUP_CMDS) + if(setup_cursor >= NUM_SETUP_CMDS) setup_cursor = 0; break; case K_LEFTARROW: - if (setup_cursor < 2) + if(setup_cursor < 2) return; - S_LocalSound ("misc/menu3.wav"); - if (setup_cursor == 2) + S_LocalSound("misc/menu3.wav"); + if(setup_cursor == 2) setup_top = setup_top - 1; - if (setup_cursor == 3) + if(setup_cursor == 3) setup_bottom = setup_bottom - 1; break; case K_RIGHTARROW: - if (setup_cursor < 2) + if(setup_cursor < 2) return; forward: - S_LocalSound ("misc/menu3.wav"); - if (setup_cursor == 2) + S_LocalSound("misc/menu3.wav"); + if(setup_cursor == 2) setup_top = setup_top + 1; - if (setup_cursor == 3) + if(setup_cursor == 3) setup_bottom = setup_bottom + 1; break; case K_ENTER: case K_KP_ENTER: case K_ABUTTON: - if (setup_cursor == 0 || setup_cursor == 1) + if(setup_cursor == 0 || setup_cursor == 1) return; - if (setup_cursor == 2 || setup_cursor == 3) + if(setup_cursor == 2 || setup_cursor == 3) goto forward; // setup_cursor == 4 (OK) - if (Q_strcmp(cl_name.string, setup_myname) != 0) - Cbuf_AddText ( va ("name \"%s\"\n", setup_myname) ); - if (Q_strcmp(hostname.string, setup_hostname) != 0) + if(Q_strcmp(cl_name.string, setup_myname) != 0) + Cbuf_AddText(va("name \"%s\"\n", setup_myname)); + if(Q_strcmp(hostname.string, setup_hostname) != 0) Cvar_Set("hostname", setup_hostname); - if (setup_top != setup_oldtop || setup_bottom != setup_oldbottom) - Cbuf_AddText( va ("color %" PRIi32 " %" PRIi32 "\n", setup_top, setup_bottom) ); + if(setup_top != setup_oldtop || setup_bottom != setup_oldbottom) + Cbuf_AddText(va("color %" PRIi32 " %" PRIi32 "\n", setup_top, setup_bottom)); m_entersound = true; - M_Menu_MultiPlayer_f (); + M_Menu_MultiPlayer_f(); break; case K_BACKSPACE: - if (setup_cursor == 0) + if(setup_cursor == 0) { - if (strlen(setup_hostname)) - setup_hostname[strlen(setup_hostname)-1] = 0; + if(strlen(setup_hostname)) + setup_hostname[strlen(setup_hostname) - 1] = 0; } - if (setup_cursor == 1) + if(setup_cursor == 1) { - if (strlen(setup_myname)) - setup_myname[strlen(setup_myname)-1] = 0; + if(strlen(setup_myname)) + setup_myname[strlen(setup_myname) - 1] = 0; } break; } - if (setup_top > 13) + if(setup_top > 13) setup_top = 0; - if (setup_top < 0) + if(setup_top < 0) setup_top = 13; - if (setup_bottom > 13) + if(setup_bottom > 13) setup_bottom = 0; - if (setup_bottom < 0) + if(setup_bottom < 0) setup_bottom = 13; } -void M_Setup_Char (int32_t k) +void M_Setup_Char(int32_t k) { int32_t l; - switch (setup_cursor) + switch(setup_cursor) { case 0: l = strlen(setup_hostname); - if (l < 15) + if(l < 15) { - setup_hostname[l+1] = 0; + setup_hostname[l + 1] = 0; setup_hostname[l] = k; } break; case 1: l = strlen(setup_myname); - if (l < 15) + if(l < 15) { - setup_myname[l+1] = 0; + setup_myname[l + 1] = 0; setup_myname[l] = k; } break; @@ -855,7 +855,7 @@ void M_Setup_Char (int32_t k) } -bool M_Setup_TextEntry (void) +bool M_Setup_TextEntry(void) { return (setup_cursor == 0 || setup_cursor == 1); } @@ -863,24 +863,24 @@ bool M_Setup_TextEntry (void) //============================================================================= /* NET MENU */ -int32_t m_net_cursor; +int32_t m_net_cursor; int32_t m_net_items; const char *net_helpMessage [] = { -/* .........1.........2.... */ - " Novell network LANs ", - " or Windows 95 DOS-box. ", - " ", - "(LAN=Local Area Network)", + /* .........1.........2.... */ + " Novell network LANs ", + " or Windows 95 DOS-box. ", + " ", + "(LAN=Local Area Network)", - " Commonly used to play ", - " over the Internet, but ", - " also used on a Local ", - " Area Network. " + " Commonly used to play ", + " over the Internet, but ", + " also used on a Local ", + " Area Network. " }; -void M_Menu_Net_f (void) +void M_Menu_Net_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -888,69 +888,69 @@ void M_Menu_Net_f (void) m_entersound = true; m_net_items = 2; - if (m_net_cursor >= m_net_items) + if(m_net_cursor >= m_net_items) m_net_cursor = 0; m_net_cursor--; - M_Net_Key (K_DOWNARROW); + M_Net_Key(K_DOWNARROW); } -void M_Net_Draw (void) +void M_Net_Draw(void) { - int32_t f; - qpic_t *p; + int32_t f; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); f = 32; - if (ipxAvailable) - p = Draw_CachePic ("gfx/netmen3.lmp"); + if(ipxAvailable) + p = Draw_CachePic("gfx/netmen3.lmp"); else - p = Draw_CachePic ("gfx/dim_ipx.lmp"); - M_DrawTransPic (72, f, p); + p = Draw_CachePic("gfx/dim_ipx.lmp"); + M_DrawTransPic(72, f, p); f += 19; - if (tcpipAvailable) - p = Draw_CachePic ("gfx/netmen4.lmp"); + if(tcpipAvailable) + p = Draw_CachePic("gfx/netmen4.lmp"); else - p = Draw_CachePic ("gfx/dim_tcp.lmp"); - M_DrawTransPic (72, f, p); + p = Draw_CachePic("gfx/dim_tcp.lmp"); + M_DrawTransPic(72, f, p); - f = (320-26*8)/2; - M_DrawTextBox (f, 96, 24, 4); + f = (320 - 26 * 8) / 2; + M_DrawTextBox(f, 96, 24, 4); f += 8; - M_Print (f, 104, net_helpMessage[m_net_cursor*4+0]); - M_Print (f, 112, net_helpMessage[m_net_cursor*4+1]); - M_Print (f, 120, net_helpMessage[m_net_cursor*4+2]); - M_Print (f, 128, net_helpMessage[m_net_cursor*4+3]); + M_Print(f, 104, net_helpMessage[m_net_cursor * 4 + 0]); + M_Print(f, 112, net_helpMessage[m_net_cursor * 4 + 1]); + M_Print(f, 120, net_helpMessage[m_net_cursor * 4 + 2]); + M_Print(f, 128, net_helpMessage[m_net_cursor * 4 + 3]); - f = (int32_t)(realtime * 10)%6; - M_DrawTransPic (54, 32 + m_net_cursor * 20,Draw_CachePic( va("gfx/menudot%" PRIi32 ".lmp", f+1 ) ) ); + f = (int32_t)(realtime * 10) % 6; + M_DrawTransPic(54, 32 + m_net_cursor * 20, Draw_CachePic(va("gfx/menudot%" PRIi32 ".lmp", f + 1))); } -void M_Net_Key (int32_t k) +void M_Net_Key(int32_t k) { again: - switch (k) + switch(k) { case K_ESCAPE: case K_BBUTTON: - M_Menu_MultiPlayer_f (); + M_Menu_MultiPlayer_f(); break; case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - if (++m_net_cursor >= m_net_items) + S_LocalSound("misc/menu1.wav"); + if(++m_net_cursor >= m_net_items) m_net_cursor = 0; break; case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - if (--m_net_cursor < 0) + S_LocalSound("misc/menu1.wav"); + if(--m_net_cursor < 0) m_net_cursor = m_net_items - 1; break; @@ -958,13 +958,13 @@ again: case K_KP_ENTER: case K_ABUTTON: m_entersound = true; - M_Menu_LanConfig_f (); + M_Menu_LanConfig_f(); break; } - if (m_net_cursor == 0 && !ipxAvailable) + if(m_net_cursor == 0 && !ipxAvailable) goto again; - if (m_net_cursor == 1 && !tcpipAvailable) + if(m_net_cursor == 1 && !tcpipAvailable) goto again; } @@ -974,8 +974,8 @@ again: enum { OPT_CUSTOMIZE = 0, - OPT_CONSOLE, // 1 - OPT_DEFAULTS, // 2 + OPT_CONSOLE, // 1 + OPT_DEFAULTS, // 2 OPT_SCALE, OPT_SCRSIZE, OPT_GAMMA, @@ -993,7 +993,7 @@ enum //#ifdef _WIN32 // OPT_USEMOUSE, //#endif - OPT_VIDEO, // This is the last before OPTIONS_ITEMS + OPT_VIDEO, // This is the last before OPTIONS_ITEMS OPTIONS_ITEMS }; @@ -1005,11 +1005,11 @@ enum ALWAYSRUN_ITEMS }; -#define SLIDER_RANGE 10 +#define SLIDER_RANGE 10 -int32_t options_cursor; +int32_t options_cursor; -void M_Menu_Options_f (void) +void M_Menu_Options_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -1018,312 +1018,312 @@ void M_Menu_Options_f (void) } -void M_AdjustSliders (int32_t dir) +void M_AdjustSliders(int32_t dir) { - int32_t curr_alwaysrun, target_alwaysrun; - float f, l; + int32_t curr_alwaysrun, target_alwaysrun; + float f, l; - S_LocalSound ("misc/menu3.wav"); + S_LocalSound("misc/menu3.wav"); - switch (options_cursor) + switch(options_cursor) { - case OPT_SCALE: // console and menu scale + case OPT_SCALE: // console and menu scale l = ((vid.width + 31) / 32) / 10.0; f = scr_conscale.value + dir * .1; - if (f < 1) f = 1; - else if(f > l) f = l; - Cvar_SetValue ("scr_conscale", f); - Cvar_SetValue ("scr_menuscale", f); - Cvar_SetValue ("scr_sbarscale", f); + if(f < 1) f = 1; + else if(f > l) f = l; + Cvar_SetValue("scr_conscale", f); + Cvar_SetValue("scr_menuscale", f); + Cvar_SetValue("scr_sbarscale", f); break; - case OPT_SCRSIZE: // screen size + case OPT_SCRSIZE: // screen size f = scr_viewsize.value + dir * 10; - if (f > 120) f = 120; - else if(f < 30) f = 30; - Cvar_SetValue ("viewsize", f); + if(f > 120) f = 120; + else if(f < 30) f = 30; + Cvar_SetValue("viewsize", f); break; - case OPT_GAMMA: // gamma + case OPT_GAMMA: // gamma f = vid_gamma.value - dir * 0.05; - if (f < 0.5) f = 0.5; - else if (f > 1) f = 1; - Cvar_SetValue ("gamma", f); + if(f < 0.5) f = 0.5; + else if(f > 1) f = 1; + Cvar_SetValue("gamma", f); break; - case OPT_CONTRAST: // contrast + case OPT_CONTRAST: // contrast f = vid_contrast.value + dir * 0.1; - if (f < 1) f = 1; - else if (f > 2) f = 2; - Cvar_SetValue ("contrast", f); + if(f < 1) f = 1; + else if(f > 2) f = 2; + Cvar_SetValue("contrast", f); break; - case OPT_MOUSESPEED: // mouse speed + case OPT_MOUSESPEED: // mouse speed f = sensitivity.value + dir * 0.5; - if (f > 11) f = 11; - else if (f < 1) f = 1; - Cvar_SetValue ("sensitivity", f); + if(f > 11) f = 11; + else if(f < 1) f = 1; + Cvar_SetValue("sensitivity", f); break; - case OPT_SBALPHA: // statusbar alpha + case OPT_SBALPHA: // statusbar alpha f = scr_sbaralpha.value - dir * 0.05; - if (f < 0) f = 0; - else if (f > 1) f = 1; - Cvar_SetValue ("scr_sbaralpha", f); + if(f < 0) f = 0; + else if(f > 1) f = 1; + Cvar_SetValue("scr_sbaralpha", f); break; - case OPT_MUSICVOL: // music volume + case OPT_MUSICVOL: // music volume f = bgmvolume.value + dir * 0.1; - if (f < 0) f = 0; - else if (f > 1) f = 1; - Cvar_SetValue ("bgmvolume", f); + if(f < 0) f = 0; + else if(f > 1) f = 1; + Cvar_SetValue("bgmvolume", f); break; - case OPT_MUSICEXT: // enable external music vs cdaudio - Cvar_Set ("bgm_extmusic", bgm_extmusic.value ? "0" : "1"); + case OPT_MUSICEXT: // enable external music vs cdaudio + Cvar_Set("bgm_extmusic", bgm_extmusic.value ? "0" : "1"); break; - case OPT_SNDVOL: // sfx volume + case OPT_SNDVOL: // sfx volume f = sfxvolume.value + dir * 0.1; - if (f < 0) f = 0; - else if (f > 1) f = 1; - Cvar_SetValue ("volume", f); + if(f < 0) f = 0; + else if(f > 1) f = 1; + Cvar_SetValue("volume", f); break; - case OPT_ALWAYRUN: // always run - if (cl_alwaysrun.value) + case OPT_ALWAYRUN: // always run + if(cl_alwaysrun.value) curr_alwaysrun = ALWAYSRUN_QUAKESPASM; - else if (cl_forwardspeed.value > 200) + else if(cl_forwardspeed.value > 200) curr_alwaysrun = ALWAYSRUN_VANILLA; else curr_alwaysrun = ALWAYSRUN_OFF; target_alwaysrun = (ALWAYSRUN_ITEMS + curr_alwaysrun + dir) % ALWAYSRUN_ITEMS; - if (target_alwaysrun == ALWAYSRUN_VANILLA) + if(target_alwaysrun == ALWAYSRUN_VANILLA) { - Cvar_SetValue ("cl_alwaysrun", 0); - Cvar_SetValue ("cl_forwardspeed", 400); - Cvar_SetValue ("cl_backspeed", 400); + Cvar_SetValue("cl_alwaysrun", 0); + Cvar_SetValue("cl_forwardspeed", 400); + Cvar_SetValue("cl_backspeed", 400); } - else if (target_alwaysrun == ALWAYSRUN_QUAKESPASM) + else if(target_alwaysrun == ALWAYSRUN_QUAKESPASM) { - Cvar_SetValue ("cl_alwaysrun", 1); - Cvar_SetValue ("cl_forwardspeed", 200); - Cvar_SetValue ("cl_backspeed", 200); + Cvar_SetValue("cl_alwaysrun", 1); + Cvar_SetValue("cl_forwardspeed", 200); + Cvar_SetValue("cl_backspeed", 200); } else // ALWAYSRUN_OFF { - Cvar_SetValue ("cl_alwaysrun", 0); - Cvar_SetValue ("cl_forwardspeed", 200); - Cvar_SetValue ("cl_backspeed", 200); + Cvar_SetValue("cl_alwaysrun", 0); + Cvar_SetValue("cl_forwardspeed", 200); + Cvar_SetValue("cl_backspeed", 200); } break; - case OPT_INVMOUSE: // invert mouse - Cvar_SetValue ("m_pitch", -m_pitch.value); + case OPT_INVMOUSE: // invert mouse + Cvar_SetValue("m_pitch", -m_pitch.value); break; case OPT_ALWAYSMLOOK: - if (in_mlook.state & 1) + if(in_mlook.state & 1) Cbuf_AddText("-mlook"); else Cbuf_AddText("+mlook"); break; - case OPT_LOOKSPRING: // lookspring - Cvar_Set ("lookspring", lookspring.value ? "0" : "1"); + case OPT_LOOKSPRING: // lookspring + Cvar_Set("lookspring", lookspring.value ? "0" : "1"); break; - case OPT_LOOKSTRAFE: // lookstrafe - Cvar_Set ("lookstrafe", lookstrafe.value ? "0" : "1"); + case OPT_LOOKSTRAFE: // lookstrafe + Cvar_Set("lookstrafe", lookstrafe.value ? "0" : "1"); break; } } -void M_DrawSlider (int32_t x, int32_t y, float range) +void M_DrawSlider(int32_t x, int32_t y, float range) { - int32_t i; + int32_t i; - if (range < 0) + if(range < 0) range = 0; - if (range > 1) + if(range > 1) range = 1; - M_DrawCharacter (x-8, y, 128); - for (i = 0; i < SLIDER_RANGE; i++) - M_DrawCharacter (x + i*8, y, 129); - M_DrawCharacter (x+i*8, y, 130); - M_DrawCharacter (x + (SLIDER_RANGE-1)*8 * range, y, 131); + M_DrawCharacter(x - 8, y, 128); + for(i = 0; i < SLIDER_RANGE; i++) + M_DrawCharacter(x + i * 8, y, 129); + M_DrawCharacter(x + i * 8, y, 130); + M_DrawCharacter(x + (SLIDER_RANGE - 1) * 8 * range, y, 131); } -void M_DrawCheckbox (int32_t x, int32_t y, int32_t on) +void M_DrawCheckbox(int32_t x, int32_t y, int32_t on) { #if 0 - if (on) - M_DrawCharacter (x, y, 131); + if(on) + M_DrawCharacter(x, y, 131); else - M_DrawCharacter (x, y, 129); + M_DrawCharacter(x, y, 129); #endif - if (on) - M_Print (x, y, "on"); + if(on) + M_Print(x, y, "on"); else - M_Print (x, y, "off"); + M_Print(x, y, "off"); } -void M_Options_Draw (void) +void M_Options_Draw(void) { - float r, l; - qpic_t *p; + float r, l; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_option.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_option.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); // Draw the items in the order of the enum defined above: // OPT_CUSTOMIZE: - M_Print (16, 32, " Controls"); + M_Print(16, 32, " Controls"); // OPT_CONSOLE: - M_Print (16, 32 + 8*OPT_CONSOLE, " Goto console"); + M_Print(16, 32 + 8 * OPT_CONSOLE, " Goto console"); // OPT_DEFAULTS: - M_Print (16, 32 + 8*OPT_DEFAULTS, " Reset config"); + M_Print(16, 32 + 8 * OPT_DEFAULTS, " Reset config"); // OPT_SCALE: - M_Print (16, 32 + 8*OPT_SCALE, " Scale"); + M_Print(16, 32 + 8 * OPT_SCALE, " Scale"); l = (vid.width / 320.0) - 1; r = l > 0 ? (scr_conscale.value - 1) / l : 0; - M_DrawSlider (220, 32 + 8*OPT_SCALE, r); + M_DrawSlider(220, 32 + 8 * OPT_SCALE, r); // OPT_SCRSIZE: - M_Print (16, 32 + 8*OPT_SCRSIZE, " Screen size"); + M_Print(16, 32 + 8 * OPT_SCRSIZE, " Screen size"); r = (scr_viewsize.value - 30) / (120 - 30); - M_DrawSlider (220, 32 + 8*OPT_SCRSIZE, r); + M_DrawSlider(220, 32 + 8 * OPT_SCRSIZE, r); // OPT_GAMMA: - M_Print (16, 32 + 8*OPT_GAMMA, " Brightness"); + M_Print(16, 32 + 8 * OPT_GAMMA, " Brightness"); r = (1.0 - vid_gamma.value) / 0.5; - M_DrawSlider (220, 32 + 8*OPT_GAMMA, r); + M_DrawSlider(220, 32 + 8 * OPT_GAMMA, r); // OPT_CONTRAST: - M_Print (16, 32 + 8*OPT_CONTRAST, " Contrast"); + M_Print(16, 32 + 8 * OPT_CONTRAST, " Contrast"); r = vid_contrast.value - 1.0; - M_DrawSlider (220, 32 + 8*OPT_CONTRAST, r); + M_DrawSlider(220, 32 + 8 * OPT_CONTRAST, r); // OPT_MOUSESPEED: - M_Print (16, 32 + 8*OPT_MOUSESPEED, " Mouse Speed"); - r = (sensitivity.value - 1)/10; - M_DrawSlider (220, 32 + 8*OPT_MOUSESPEED, r); + M_Print(16, 32 + 8 * OPT_MOUSESPEED, " Mouse Speed"); + r = (sensitivity.value - 1) / 10; + M_DrawSlider(220, 32 + 8 * OPT_MOUSESPEED, r); // OPT_SBALPHA: - M_Print (16, 32 + 8*OPT_SBALPHA, " Statusbar alpha"); + M_Print(16, 32 + 8 * OPT_SBALPHA, " Statusbar alpha"); r = (1.0 - scr_sbaralpha.value) ; // scr_sbaralpha range is 1.0 to 0.0 - M_DrawSlider (220, 32 + 8*OPT_SBALPHA, r); + M_DrawSlider(220, 32 + 8 * OPT_SBALPHA, r); // OPT_SNDVOL: - M_Print (16, 32 + 8*OPT_SNDVOL, " Sound Volume"); + M_Print(16, 32 + 8 * OPT_SNDVOL, " Sound Volume"); r = sfxvolume.value; - M_DrawSlider (220, 32 + 8*OPT_SNDVOL, r); + M_DrawSlider(220, 32 + 8 * OPT_SNDVOL, r); // OPT_MUSICVOL: - M_Print (16, 32 + 8*OPT_MUSICVOL, " Music Volume"); + M_Print(16, 32 + 8 * OPT_MUSICVOL, " Music Volume"); r = bgmvolume.value; - M_DrawSlider (220, 32 + 8*OPT_MUSICVOL, r); + M_DrawSlider(220, 32 + 8 * OPT_MUSICVOL, r); // OPT_MUSICEXT: - M_Print (16, 32 + 8*OPT_MUSICEXT, " External Music"); - M_DrawCheckbox (220, 32 + 8*OPT_MUSICEXT, bgm_extmusic.value); + M_Print(16, 32 + 8 * OPT_MUSICEXT, " External Music"); + M_DrawCheckbox(220, 32 + 8 * OPT_MUSICEXT, bgm_extmusic.value); // OPT_ALWAYRUN: - M_Print (16, 32 + 8*OPT_ALWAYRUN, " Always Run"); - if (cl_alwaysrun.value) - M_Print (220, 32 + 8*OPT_ALWAYRUN, "quakespasm"); - else if (cl_forwardspeed.value > 200.0) - M_Print (220, 32 + 8*OPT_ALWAYRUN, "vanilla"); + M_Print(16, 32 + 8 * OPT_ALWAYRUN, " Always Run"); + if(cl_alwaysrun.value) + M_Print(220, 32 + 8 * OPT_ALWAYRUN, "quakespasm"); + else if(cl_forwardspeed.value > 200.0) + M_Print(220, 32 + 8 * OPT_ALWAYRUN, "vanilla"); else - M_Print (220, 32 + 8*OPT_ALWAYRUN, "off"); + M_Print(220, 32 + 8 * OPT_ALWAYRUN, "off"); // OPT_INVMOUSE: - M_Print (16, 32 + 8*OPT_INVMOUSE, " Invert Mouse"); - M_DrawCheckbox (220, 32 + 8*OPT_INVMOUSE, m_pitch.value < 0); + M_Print(16, 32 + 8 * OPT_INVMOUSE, " Invert Mouse"); + M_DrawCheckbox(220, 32 + 8 * OPT_INVMOUSE, m_pitch.value < 0); // OPT_ALWAYSMLOOK: - M_Print (16, 32 + 8*OPT_ALWAYSMLOOK, " Mouse Look"); - M_DrawCheckbox (220, 32 + 8*OPT_ALWAYSMLOOK, in_mlook.state & 1); + M_Print(16, 32 + 8 * OPT_ALWAYSMLOOK, " Mouse Look"); + M_DrawCheckbox(220, 32 + 8 * OPT_ALWAYSMLOOK, in_mlook.state & 1); // OPT_LOOKSPRING: - M_Print (16, 32 + 8*OPT_LOOKSPRING, " Lookspring"); - M_DrawCheckbox (220, 32 + 8*OPT_LOOKSPRING, lookspring.value); + M_Print(16, 32 + 8 * OPT_LOOKSPRING, " Lookspring"); + M_DrawCheckbox(220, 32 + 8 * OPT_LOOKSPRING, lookspring.value); // OPT_LOOKSTRAFE: - M_Print (16, 32 + 8*OPT_LOOKSTRAFE, " Lookstrafe"); - M_DrawCheckbox (220, 32 + 8*OPT_LOOKSTRAFE, lookstrafe.value); + M_Print(16, 32 + 8 * OPT_LOOKSTRAFE, " Lookstrafe"); + M_DrawCheckbox(220, 32 + 8 * OPT_LOOKSTRAFE, lookstrafe.value); // OPT_VIDEO: - if (vid_menudrawfn) - M_Print (16, 32 + 8*OPT_VIDEO, " Video Options"); + if(vid_menudrawfn) + M_Print(16, 32 + 8 * OPT_VIDEO, " Video Options"); // cursor - M_DrawCharacter (200, 32 + options_cursor*8, 12+((int32_t)(realtime*4)&1)); + M_DrawCharacter(200, 32 + options_cursor * 8, 12 + ((int32_t)(realtime * 4) & 1)); } -void M_Options_Key (int32_t k) +void M_Options_Key(int32_t k) { - switch (k) + switch(k) { case K_ESCAPE: case K_BBUTTON: - M_Menu_Main_f (); + M_Menu_Main_f(); break; case K_ENTER: case K_KP_ENTER: case K_ABUTTON: m_entersound = true; - switch (options_cursor) + switch(options_cursor) { case OPT_CUSTOMIZE: - M_Menu_Keys_f (); + M_Menu_Keys_f(); break; case OPT_CONSOLE: m_state = m_none; - Con_ToggleConsole_f (); + Con_ToggleConsole_f(); break; case OPT_DEFAULTS: - if (SCR_ModalMessage("This will reset all controls\n" - "and stored cvars. Continue? (y/n)\n", 15.0f)) + if(SCR_ModalMessage("This will reset all controls\n" + "and stored cvars. Continue? (y/n)\n", 15.0f)) { - Cbuf_AddText ("resetcfg\n"); - Cbuf_AddText ("exec default.cfg\n"); + Cbuf_AddText("resetcfg\n"); + Cbuf_AddText("exec default.cfg\n"); } break; case OPT_VIDEO: - M_Menu_Video_f (); + M_Menu_Video_f(); break; default: - M_AdjustSliders (1); + M_AdjustSliders(1); break; } return; case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); options_cursor--; - if (options_cursor < 0) - options_cursor = OPTIONS_ITEMS-1; + if(options_cursor < 0) + options_cursor = OPTIONS_ITEMS - 1; break; case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); options_cursor++; - if (options_cursor >= OPTIONS_ITEMS) + if(options_cursor >= OPTIONS_ITEMS) options_cursor = 0; break; case K_LEFTARROW: - M_AdjustSliders (-1); + M_AdjustSliders(-1); break; case K_RIGHTARROW: - M_AdjustSliders (1); + M_AdjustSliders(1); break; } - if (options_cursor == OPTIONS_ITEMS - 1 && vid_menudrawfn == NULL) + if(options_cursor == OPTIONS_ITEMS - 1 && vid_menudrawfn == NULL) { - if (k == K_UPARROW) + if(k == K_UPARROW) options_cursor = OPTIONS_ITEMS - 2; else options_cursor = 0; @@ -1335,33 +1335,33 @@ void M_Options_Key (int32_t k) const char *bindnames[][2] = { - {"+attack", "attack"}, - {"impulse 10", "next weapon"}, - {"impulse 12", "prev weapon"}, - {"+jump", "jump / swim up"}, - {"+forward", "walk forward"}, - {"+back", "backpedal"}, - {"+left", "turn left"}, - {"+right", "turn right"}, - {"+speed", "run"}, - {"+moveleft", "step left"}, - {"+moveright", "step right"}, - {"+strafe", "sidestep"}, - {"+lookup", "look up"}, - {"+lookdown", "look down"}, - {"centerview", "center view"}, - {"+mlook", "mouse look"}, - {"+klook", "keyboard look"}, - {"+moveup", "swim up"}, - {"+movedown", "swim down"} + {"+attack", "attack"}, + {"impulse 10", "next weapon"}, + {"impulse 12", "prev weapon"}, + {"+jump", "jump / swim up"}, + {"+forward", "walk forward"}, + {"+back", "backpedal"}, + {"+left", "turn left"}, + {"+right", "turn right"}, + {"+speed", "run"}, + {"+moveleft", "step left"}, + {"+moveright", "step right"}, + {"+strafe", "sidestep"}, + {"+lookup", "look up"}, + {"+lookdown", "look down"}, + {"centerview", "center view"}, + {"+mlook", "mouse look"}, + {"+klook", "keyboard look"}, + {"+moveup", "swim up"}, + {"+movedown", "swim down"} }; -#define NUMCOMMANDS (sizeof(bindnames)/sizeof(bindnames[0])) +#define NUMCOMMANDS (sizeof(bindnames)/sizeof(bindnames[0])) -static int32_t keys_cursor; -static bool bind_grab; +static int32_t keys_cursor; +static bool bind_grab; -void M_Menu_Keys_f (void) +void M_Menu_Keys_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -1370,119 +1370,120 @@ void M_Menu_Keys_f (void) } -void M_FindKeysForCommand (const char *command, int32_t *threekeys) +void M_FindKeysForCommand(const char *command, int32_t *threekeys) { - int32_t count; - int32_t j; - int32_t l; - char *b; + int32_t count; + int32_t j; + int32_t l; + char *b; threekeys[0] = threekeys[1] = threekeys[2] = -1; l = strlen(command); count = 0; - for (j = 0; j < MAX_KEYS; j++) + for(j = 0; j < MAX_KEYS; j++) { b = keybindings[j]; - if (!b) + if(!b) continue; - if (!strncmp (b, command, l) ) + if(!strncmp(b, command, l)) { threekeys[count] = j; count++; - if (count == 3) + if(count == 3) break; } } } -void M_UnbindCommand (const char *command) +void M_UnbindCommand(const char *command) { - int32_t j; - int32_t l; - char *b; + int32_t j; + int32_t l; + char *b; l = strlen(command); - for (j = 0; j < MAX_KEYS; j++) + for(j = 0; j < MAX_KEYS; j++) { b = keybindings[j]; - if (!b) + if(!b) continue; - if (!strncmp (b, command, l) ) - Key_SetBinding (j, NULL); + if(!strncmp(b, command, l)) + Key_SetBinding(j, NULL); } } -extern qpic_t *pic_up, *pic_down; +extern qpic_t *pic_up, *pic_down; -void M_Keys_Draw (void) +void M_Keys_Draw(void) { - int32_t i, x, y; - int32_t keys[3]; - const char *name; - qpic_t *p; + int32_t i, x, y; + int32_t keys[3]; + const char *name; + qpic_t *p; - p = Draw_CachePic ("gfx/ttl_cstm.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + p = Draw_CachePic("gfx/ttl_cstm.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - if (bind_grab) - M_Print (12, 32, "Press a key or button for this action"); + if(bind_grab) + M_Print(12, 32, "Press a key or button for this action"); else - M_Print (18, 32, "Enter to change, backspace to clear"); + M_Print(18, 32, "Enter to change, backspace to clear"); // search for known bindings - for (i = 0; i < (int32_t)NUMCOMMANDS; i++) + for(i = 0; i < (int32_t)NUMCOMMANDS; i++) { - y = 48 + 8*i; + y = 48 + 8 * i; - M_Print (16, y, bindnames[i][1]); + M_Print(16, y, bindnames[i][1]); - M_FindKeysForCommand (bindnames[i][0], keys); + M_FindKeysForCommand(bindnames[i][0], keys); - if (keys[0] == -1) + if(keys[0] == -1) { - M_Print (140, y, "???"); + M_Print(140, y, "???"); } else { - name = Key_KeynumToString (keys[0]); - M_Print (140, y, name); + name = Key_KeynumToString(keys[0]); + M_Print(140, y, name); x = strlen(name) * 8; - if (keys[1] != -1) + if(keys[1] != -1) { - name = Key_KeynumToString (keys[1]); - M_Print (140 + x + 8, y, "or"); - M_Print (140 + x + 32, y, name); + name = Key_KeynumToString(keys[1]); + M_Print(140 + x + 8, y, "or"); + M_Print(140 + x + 32, y, name); x = x + 32 + strlen(name) * 8; - if (keys[2] != -1) + if(keys[2] != -1) { - M_Print (140 + x + 8, y, "or"); - M_Print (140 + x + 32, y, Key_KeynumToString (keys[2])); + M_Print(140 + x + 8, y, "or"); + M_Print(140 + x + 32, y, Key_KeynumToString(keys[2])); } } } } - if (bind_grab) - M_DrawCharacter (130, 48 + keys_cursor*8, '='); + if(bind_grab) + M_DrawCharacter(130, 48 + keys_cursor * 8, '='); else - M_DrawCharacter (130, 48 + keys_cursor*8, 12+((int32_t)(realtime*4)&1)); + M_DrawCharacter(130, 48 + keys_cursor * 8, 12 + ((int32_t)(realtime * 4) & 1)); } -void M_Keys_Key (int32_t k) +void M_Keys_Key(int32_t k) { - char cmd[80]; - int32_t keys[3]; + char cmd[80]; + int32_t keys[3]; - if (bind_grab) - { // defining a key - S_LocalSound ("misc/menu1.wav"); - if ((k != K_ESCAPE) && (k != '`')) + if(bind_grab) + { + // defining a key + S_LocalSound("misc/menu1.wav"); + if((k != K_ESCAPE) && (k != '`')) { - sprintf (cmd, "bind \"%s\" \"%s\"\n", Key_KeynumToString (k), bindnames[keys_cursor][0]); - Cbuf_InsertText (cmd); + sprintf(cmd, "bind \"%s\" \"%s\"\n", Key_KeynumToString(k), bindnames[keys_cursor][0]); + Cbuf_InsertText(cmd); } bind_grab = false; @@ -1490,44 +1491,44 @@ void M_Keys_Key (int32_t k) return; } - switch (k) + switch(k) { case K_ESCAPE: case K_BBUTTON: - M_Menu_Options_f (); + M_Menu_Options_f(); break; case K_LEFTARROW: case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); keys_cursor--; - if (keys_cursor < 0) - keys_cursor = NUMCOMMANDS-1; + if(keys_cursor < 0) + keys_cursor = NUMCOMMANDS - 1; break; case K_DOWNARROW: case K_RIGHTARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); keys_cursor++; - if (keys_cursor >= (int32_t)NUMCOMMANDS) + if(keys_cursor >= (int32_t)NUMCOMMANDS) keys_cursor = 0; break; - case K_ENTER: // go into bind mode + case K_ENTER: // go into bind mode case K_KP_ENTER: case K_ABUTTON: - M_FindKeysForCommand (bindnames[keys_cursor][0], keys); - S_LocalSound ("misc/menu2.wav"); - if (keys[2] != -1) - M_UnbindCommand (bindnames[keys_cursor][0]); + M_FindKeysForCommand(bindnames[keys_cursor][0], keys); + S_LocalSound("misc/menu2.wav"); + if(keys[2] != -1) + M_UnbindCommand(bindnames[keys_cursor][0]); bind_grab = true; IN_Activate(); // activate to allow mouse key binding break; - case K_BACKSPACE: // delete bindings + case K_BACKSPACE: // delete bindings case K_DEL: - S_LocalSound ("misc/menu2.wav"); - M_UnbindCommand (bindnames[keys_cursor][0]); + S_LocalSound("misc/menu2.wav"); + M_UnbindCommand(bindnames[keys_cursor][0]); break; } } @@ -1535,31 +1536,31 @@ void M_Keys_Key (int32_t k) //============================================================================= /* VIDEO MENU */ -void M_Menu_Video_f (void) +void M_Menu_Video_f(void) { - (*vid_menucmdfn) (); //johnfitz + (*vid_menucmdfn)(); //johnfitz } -void M_Video_Draw (void) +void M_Video_Draw(void) { - (*vid_menudrawfn) (); + (*vid_menudrawfn)(); } -void M_Video_Key (int32_t key) +void M_Video_Key(int32_t key) { - (*vid_menukeyfn) (key); + (*vid_menukeyfn)(key); } //============================================================================= /* HELP MENU */ -int32_t help_page; -#define NUM_HELP_PAGES 6 +int32_t help_page; +#define NUM_HELP_PAGES 6 -void M_Menu_Help_f (void) +void M_Menu_Help_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -1570,33 +1571,33 @@ void M_Menu_Help_f (void) -void M_Help_Draw (void) +void M_Help_Draw(void) { - M_DrawPic (0, 0, Draw_CachePic ( va("gfx/help%" PRIi32 ".lmp", help_page)) ); + M_DrawPic(0, 0, Draw_CachePic(va("gfx/help%" PRIi32 ".lmp", help_page))); } -void M_Help_Key (int32_t key) +void M_Help_Key(int32_t key) { - switch (key) + switch(key) { case K_ESCAPE: case K_BBUTTON: - M_Menu_Main_f (); + M_Menu_Main_f(); break; case K_UPARROW: case K_RIGHTARROW: m_entersound = true; - if (++help_page >= NUM_HELP_PAGES) + if(++help_page >= NUM_HELP_PAGES) help_page = 0; break; case K_DOWNARROW: case K_LEFTARROW: m_entersound = true; - if (--help_page < 0) - help_page = NUM_HELP_PAGES-1; + if(--help_page < 0) + help_page = NUM_HELP_PAGES - 1; break; } @@ -1605,13 +1606,13 @@ void M_Help_Key (int32_t key) //============================================================================= /* QUIT MENU */ -int32_t msgNumber; -enum m_state_e m_quit_prevstate; -bool wasInMenus; +int32_t msgNumber; +enum m_state_e m_quit_prevstate; +bool wasInMenus; -void M_Menu_Quit_f (void) +void M_Menu_Quit_f(void) { - if (m_state == m_quit) + if(m_state == m_quit) return; wasInMenus = (key_dest == key_menu); IN_Deactivate(modestate == MS_WINDOWED); @@ -1619,15 +1620,15 @@ void M_Menu_Quit_f (void) m_quit_prevstate = m_state; m_state = m_quit; m_entersound = true; - msgNumber = rand()&7; + msgNumber = rand() & 7; } -void M_Quit_Key (int32_t key) +void M_Quit_Key(int32_t key) { - if (key == K_ESCAPE) + if(key == K_ESCAPE) { - if (wasInMenus) + if(wasInMenus) { m_state = m_quit_prevstate; m_entersound = true; @@ -1642,13 +1643,13 @@ void M_Quit_Key (int32_t key) } -void M_Quit_Char (int32_t key) +void M_Quit_Char(int32_t key) { - switch (key) + switch(key) { case 'n': case 'N': - if (wasInMenus) + if(wasInMenus) { m_state = m_quit_prevstate; m_entersound = true; @@ -1665,7 +1666,7 @@ void M_Quit_Char (int32_t key) case 'Y': IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_console; - Host_Quit_f (); + Host_Quit_f(); break; default: @@ -1675,24 +1676,24 @@ void M_Quit_Char (int32_t key) } -bool M_Quit_TextEntry (void) +bool M_Quit_TextEntry(void) { return true; } -void M_Quit_Draw (void) //johnfitz -- modified for new quit message +void M_Quit_Draw(void) //johnfitz -- modified for new quit message { - char msg1[40]; - char msg2[] = "by Ozkan, Ericw & Stevenaaus"; /* msg2/msg3 are mostly [40] */ - char msg3[] = "Press y to quit"; - int32_t boxlen; + char msg1[40]; + char msg2[] = "by Ozkan, Ericw & Stevenaaus"; /* msg2/msg3 are mostly [40] */ + char msg3[] = "Press y to quit"; + int32_t boxlen; - if (wasInMenus) + if(wasInMenus) { m_state = m_quit_prevstate; m_recursiveDraw = true; - M_Draw (); + M_Draw(); m_state = m_quit; } @@ -1701,41 +1702,41 @@ void M_Quit_Draw (void) //johnfitz -- modified for new quit message //okay, this is kind of fucked up. M_DrawTextBox will always act as if //width is even. Also, the width and lines values are for the interior of the box, //but the x and y values include the border. - boxlen = q_max(strlen(msg1), q_max((sizeof(msg2)-1),(sizeof(msg3)-1))) + 1; - if (boxlen & 1) boxlen++; - M_DrawTextBox (160-4*(boxlen+2), 76, boxlen, 4); + boxlen = q_max(strlen(msg1), q_max((sizeof(msg2) - 1), (sizeof(msg3) - 1))) + 1; + if(boxlen & 1) boxlen++; + M_DrawTextBox(160 - 4 * (boxlen + 2), 76, boxlen, 4); //now do the text - M_Print (160-4*strlen(msg1), 88, msg1); - M_Print (160-4*(sizeof(msg2)-1), 96, msg2); - M_PrintWhite (160-4*(sizeof(msg3)-1), 104, msg3); + M_Print(160 - 4 * strlen(msg1), 88, msg1); + M_Print(160 - 4 * (sizeof(msg2) - 1), 96, msg2); + M_PrintWhite(160 - 4 * (sizeof(msg3) - 1), 104, msg3); } //============================================================================= /* LAN CONFIG MENU */ -int32_t lanConfig_cursor = -1; -int32_t lanConfig_cursor_table [] = {72, 92, 124}; -#define NUM_LANCONFIG_CMDS 3 +int32_t lanConfig_cursor = -1; +int32_t lanConfig_cursor_table [] = {72, 92, 124}; +#define NUM_LANCONFIG_CMDS 3 -int32_t lanConfig_port; -char lanConfig_portname[6]; -char lanConfig_joinname[22]; +int32_t lanConfig_port; +char lanConfig_portname[6]; +char lanConfig_joinname[22]; -void M_Menu_LanConfig_f (void) +void M_Menu_LanConfig_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; m_state = m_lanconfig; m_entersound = true; - if (lanConfig_cursor == -1) + if(lanConfig_cursor == -1) { - if (JoiningGame && TCPIPConfig) + if(JoiningGame && TCPIPConfig) lanConfig_cursor = 2; else lanConfig_cursor = 1; } - if (StartingGame && lanConfig_cursor == 2) + if(StartingGame && lanConfig_cursor == 2) lanConfig_cursor = 1; lanConfig_port = DEFAULTnet_hostport; sprintf(lanConfig_portname, "%" PRIu32 "", lanConfig_port); @@ -1745,149 +1746,149 @@ void M_Menu_LanConfig_f (void) } -void M_LanConfig_Draw (void) +void M_LanConfig_Draw(void) { - qpic_t *p; - int32_t basex; - const char *startJoin; - const char *protocol; + qpic_t *p; + int32_t basex; + const char *startJoin; + const char *protocol; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - basex = (320-p->width)/2; - M_DrawPic (basex, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + basex = (320 - p->width) / 2; + M_DrawPic(basex, 4, p); - if (StartingGame) + if(StartingGame) startJoin = "New Game"; else startJoin = "Join Game"; - if (IPXConfig) + if(IPXConfig) protocol = "IPX"; else protocol = "TCP/IP"; - M_Print (basex, 32, va ("%s - %s", startJoin, protocol)); + M_Print(basex, 32, va("%s - %s", startJoin, protocol)); basex += 8; - M_Print (basex, 52, "Address:"); - if (IPXConfig) - M_Print (basex+9*8, 52, my_ipx_address); + M_Print(basex, 52, "Address:"); + if(IPXConfig) + M_Print(basex + 9 * 8, 52, my_ipx_address); else - M_Print (basex+9*8, 52, my_tcpip_address); + M_Print(basex + 9 * 8, 52, my_tcpip_address); - M_Print (basex, lanConfig_cursor_table[0], "Port"); - M_DrawTextBox (basex+8*8, lanConfig_cursor_table[0]-8, 6, 1); - M_Print (basex+9*8, lanConfig_cursor_table[0], lanConfig_portname); + M_Print(basex, lanConfig_cursor_table[0], "Port"); + M_DrawTextBox(basex + 8 * 8, lanConfig_cursor_table[0] - 8, 6, 1); + M_Print(basex + 9 * 8, lanConfig_cursor_table[0], lanConfig_portname); - if (JoiningGame) + if(JoiningGame) { - M_Print (basex, lanConfig_cursor_table[1], "Search for local games..."); - M_Print (basex, 108, "Join game at:"); - M_DrawTextBox (basex+8, lanConfig_cursor_table[2]-8, 22, 1); - M_Print (basex+16, lanConfig_cursor_table[2], lanConfig_joinname); + M_Print(basex, lanConfig_cursor_table[1], "Search for local games..."); + M_Print(basex, 108, "Join game at:"); + M_DrawTextBox(basex + 8, lanConfig_cursor_table[2] - 8, 22, 1); + M_Print(basex + 16, lanConfig_cursor_table[2], lanConfig_joinname); } else { - M_DrawTextBox (basex, lanConfig_cursor_table[1]-8, 2, 1); - M_Print (basex+8, lanConfig_cursor_table[1], "OK"); + M_DrawTextBox(basex, lanConfig_cursor_table[1] - 8, 2, 1); + M_Print(basex + 8, lanConfig_cursor_table[1], "OK"); } - M_DrawCharacter (basex-8, lanConfig_cursor_table [lanConfig_cursor], 12+((int32_t)(realtime*4)&1)); + M_DrawCharacter(basex - 8, lanConfig_cursor_table [lanConfig_cursor], 12 + ((int32_t)(realtime * 4) & 1)); - if (lanConfig_cursor == 0) - M_DrawCharacter (basex+9*8 + 8*strlen(lanConfig_portname), lanConfig_cursor_table [0], 10+((int32_t)(realtime*4)&1)); + if(lanConfig_cursor == 0) + M_DrawCharacter(basex + 9 * 8 + 8 * strlen(lanConfig_portname), lanConfig_cursor_table [0], 10 + ((int32_t)(realtime * 4) & 1)); - if (lanConfig_cursor == 2) - M_DrawCharacter (basex+16 + 8*strlen(lanConfig_joinname), lanConfig_cursor_table [2], 10+((int32_t)(realtime*4)&1)); + if(lanConfig_cursor == 2) + M_DrawCharacter(basex + 16 + 8 * strlen(lanConfig_joinname), lanConfig_cursor_table [2], 10 + ((int32_t)(realtime * 4) & 1)); - if (*m_return_reason) - M_PrintWhite (basex, 148, m_return_reason); + if(*m_return_reason) + M_PrintWhite(basex, 148, m_return_reason); } -void M_LanConfig_Key (int32_t key) +void M_LanConfig_Key(int32_t key) { - int32_t l; + int32_t l; - switch (key) + switch(key) { case K_ESCAPE: case K_BBUTTON: - M_Menu_Net_f (); + M_Menu_Net_f(); break; case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); lanConfig_cursor--; - if (lanConfig_cursor < 0) - lanConfig_cursor = NUM_LANCONFIG_CMDS-1; + if(lanConfig_cursor < 0) + lanConfig_cursor = NUM_LANCONFIG_CMDS - 1; break; case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); lanConfig_cursor++; - if (lanConfig_cursor >= NUM_LANCONFIG_CMDS) + if(lanConfig_cursor >= NUM_LANCONFIG_CMDS) lanConfig_cursor = 0; break; case K_ENTER: case K_KP_ENTER: case K_ABUTTON: - if (lanConfig_cursor == 0) + if(lanConfig_cursor == 0) break; m_entersound = true; - M_ConfigureNetSubsystem (); + M_ConfigureNetSubsystem(); - if (lanConfig_cursor == 1) + if(lanConfig_cursor == 1) { - if (StartingGame) + if(StartingGame) { - M_Menu_GameOptions_f (); + M_Menu_GameOptions_f(); break; } M_Menu_Search_f(); break; } - if (lanConfig_cursor == 2) + if(lanConfig_cursor == 2) { m_return_state = m_state; m_return_onerror = true; IN_Activate(); key_dest = key_game; m_state = m_none; - Cbuf_AddText ( va ("connect \"%s\"\n", lanConfig_joinname) ); + Cbuf_AddText(va("connect \"%s\"\n", lanConfig_joinname)); break; } break; case K_BACKSPACE: - if (lanConfig_cursor == 0) + if(lanConfig_cursor == 0) { - if (strlen(lanConfig_portname)) - lanConfig_portname[strlen(lanConfig_portname)-1] = 0; + if(strlen(lanConfig_portname)) + lanConfig_portname[strlen(lanConfig_portname) - 1] = 0; } - if (lanConfig_cursor == 2) + if(lanConfig_cursor == 2) { - if (strlen(lanConfig_joinname)) - lanConfig_joinname[strlen(lanConfig_joinname)-1] = 0; + if(strlen(lanConfig_joinname)) + lanConfig_joinname[strlen(lanConfig_joinname) - 1] = 0; } break; } - if (StartingGame && lanConfig_cursor == 2) + if(StartingGame && lanConfig_cursor == 2) { - if (key == K_UPARROW) + if(key == K_UPARROW) lanConfig_cursor = 1; else lanConfig_cursor = 0; } l = Q_atoi(lanConfig_portname); - if (l > 65535) + if(l > 65535) l = lanConfig_port; else lanConfig_port = l; @@ -1895,27 +1896,27 @@ void M_LanConfig_Key (int32_t key) } -void M_LanConfig_Char (int32_t key) +void M_LanConfig_Char(int32_t key) { int32_t l; - switch (lanConfig_cursor) + switch(lanConfig_cursor) { case 0: - if (key < '0' || key > '9') + if(key < '0' || key > '9') return; l = strlen(lanConfig_portname); - if (l < 5) + if(l < 5) { - lanConfig_portname[l+1] = 0; + lanConfig_portname[l + 1] = 0; lanConfig_portname[l] = key; } break; case 2: l = strlen(lanConfig_joinname); - if (l < 21) + if(l < 21) { - lanConfig_joinname[l+1] = 0; + lanConfig_joinname[l + 1] = 0; lanConfig_joinname[l] = key; } break; @@ -1923,7 +1924,7 @@ void M_LanConfig_Char (int32_t key) } -bool M_LanConfig_TextEntry (void) +bool M_LanConfig_TextEntry(void) { return (lanConfig_cursor == 0 || lanConfig_cursor == 2); } @@ -1933,15 +1934,15 @@ bool M_LanConfig_TextEntry (void) typedef struct { - const char *name; - const char *description; + const char *name; + const char *description; } level_t; -level_t levels[] = +level_t levels[] = { - {"start", "Entrance"}, // 0 + {"start", "Entrance"}, // 0 - {"e1m1", "Slipgate Complex"}, // 1 + {"e1m1", "Slipgate Complex"}, // 1 {"e1m2", "Castle of the Damned"}, {"e1m3", "The Necropolis"}, {"e1m4", "The Grisly Grotto"}, @@ -1950,7 +1951,7 @@ level_t levels[] = {"e1m7", "The House of Chthon"}, {"e1m8", "Ziggurat Vertigo"}, - {"e2m1", "The Installation"}, // 9 + {"e2m1", "The Installation"}, // 9 {"e2m2", "Ogre Citadel"}, {"e2m3", "Crypt of Decay"}, {"e2m4", "The Ebon Fortress"}, @@ -1958,7 +1959,7 @@ level_t levels[] = {"e2m6", "The Dismal Oubliette"}, {"e2m7", "Underearth"}, - {"e3m1", "Termination Central"}, // 16 + {"e3m1", "Termination Central"}, // 16 {"e3m2", "The Vaults of Zin"}, {"e3m3", "The Tomb of Terror"}, {"e3m4", "Satan's Dark Delight"}, @@ -1966,7 +1967,7 @@ level_t levels[] = {"e3m6", "Chambers of Torment"}, {"e3m7", "The Haunted Halls"}, - {"e4m1", "The Sewage System"}, // 23 + {"e4m1", "The Sewage System"}, // 23 {"e4m2", "The Tower of Despair"}, {"e4m3", "The Elder God Shrine"}, {"e4m4", "The Palace of Hate"}, @@ -1975,9 +1976,9 @@ level_t levels[] = {"e4m7", "Azure Agony"}, {"e4m8", "The Nameless City"}, - {"end", "Shub-Niggurath's Pit"}, // 31 + {"end", "Shub-Niggurath's Pit"}, // 31 - {"dm1", "Place of Two Deaths"}, // 32 + {"dm1", "Place of Two Deaths"}, // 32 {"dm2", "Claustrophobopolis"}, {"dm3", "The Abandoned Base"}, {"dm4", "The Bad Place"}, @@ -1988,62 +1989,62 @@ level_t levels[] = //MED 01/06/97 added hipnotic levels level_t hipnoticlevels[] = { - {"start", "Command HQ"}, // 0 + {"start", "Command HQ"}, // 0 - {"hip1m1", "The Pumping Station"}, // 1 + {"hip1m1", "The Pumping Station"}, // 1 {"hip1m2", "Storage Facility"}, {"hip1m3", "The Lost Mine"}, {"hip1m4", "Research Facility"}, {"hip1m5", "Military Complex"}, - {"hip2m1", "Ancient Realms"}, // 6 + {"hip2m1", "Ancient Realms"}, // 6 {"hip2m2", "The Black Cathedral"}, {"hip2m3", "The Catacombs"}, {"hip2m4", "The Crypt"}, {"hip2m5", "Mortum's Keep"}, {"hip2m6", "The Gremlin's Domain"}, - {"hip3m1", "Tur Torment"}, // 12 + {"hip3m1", "Tur Torment"}, // 12 {"hip3m2", "Pandemonium"}, {"hip3m3", "Limbo"}, {"hip3m4", "The Gauntlet"}, - {"hipend", "Armagon's Lair"}, // 16 + {"hipend", "Armagon's Lair"}, // 16 - {"hipdm1", "The Edge of Oblivion"} // 17 + {"hipdm1", "The Edge of Oblivion"} // 17 }; //PGM 01/07/97 added rogue levels //PGM 03/02/97 added dmatch level -level_t roguelevels[] = +level_t roguelevels[] = { - {"start", "Split Decision"}, - {"r1m1", "Deviant's Domain"}, - {"r1m2", "Dread Portal"}, - {"r1m3", "Judgement Call"}, - {"r1m4", "Cave of Death"}, - {"r1m5", "Towers of Wrath"}, - {"r1m6", "Temple of Pain"}, - {"r1m7", "Tomb of the Overlord"}, - {"r2m1", "Tempus Fugit"}, - {"r2m2", "Elemental Fury I"}, - {"r2m3", "Elemental Fury II"}, - {"r2m4", "Curse of Osiris"}, - {"r2m5", "Wizard's Keep"}, - {"r2m6", "Blood Sacrifice"}, - {"r2m7", "Last Bastion"}, - {"r2m8", "Source of Evil"}, + {"start", "Split Decision"}, + {"r1m1", "Deviant's Domain"}, + {"r1m2", "Dread Portal"}, + {"r1m3", "Judgement Call"}, + {"r1m4", "Cave of Death"}, + {"r1m5", "Towers of Wrath"}, + {"r1m6", "Temple of Pain"}, + {"r1m7", "Tomb of the Overlord"}, + {"r2m1", "Tempus Fugit"}, + {"r2m2", "Elemental Fury I"}, + {"r2m3", "Elemental Fury II"}, + {"r2m4", "Curse of Osiris"}, + {"r2m5", "Wizard's Keep"}, + {"r2m6", "Blood Sacrifice"}, + {"r2m7", "Last Bastion"}, + {"r2m8", "Source of Evil"}, {"ctf1", "Division of Change"} }; typedef struct { - const char *description; - int32_t firstLevel; - int32_t levels; + const char *description; + int32_t firstLevel; + int32_t levels; } episode_t; -episode_t episodes[] = +episode_t episodes[] = { {"Welcome to Quake", 0, 1}, {"Doomed Dimension", 1, 8}, @@ -2067,7 +2068,7 @@ episode_t hipnoticepisodes[] = //PGM 01/07/97 added rogue episodes //PGM 03/02/97 added dmatch episode -episode_t rogueepisodes[] = +episode_t rogueepisodes[] = { {"Introduction", 0, 1}, {"Hell's Fortress", 1, 7}, @@ -2075,66 +2076,80 @@ episode_t rogueepisodes[] = {"Deathmatch Arena", 16, 1} }; -int32_t startepisode; -int32_t startlevel; +int32_t startepisode; +int32_t startlevel; int32_t maxplayers; bool m_serverInfoMessage = false; double m_serverInfoMessageTime; -void M_Menu_GameOptions_f (void) +void M_Menu_GameOptions_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; m_state = m_gameoptions; m_entersound = true; - if (maxplayers == 0) + if(maxplayers == 0) maxplayers = svs.maxclients; - if (maxplayers < 2) + if(maxplayers < 2) maxplayers = svs.maxclientslimit; } int32_t gameoptions_cursor_table[] = {40, 56, 64, 72, 80, 88, 96, 112, 120}; -#define NUM_GAMEOPTIONS 9 -int32_t gameoptions_cursor; +#define NUM_GAMEOPTIONS 9 +int32_t gameoptions_cursor; -void M_GameOptions_Draw (void) +void M_GameOptions_Draw(void) { - qpic_t *p; - int32_t x; + qpic_t *p; + int32_t x; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawTransPic(16, 4, Draw_CachePic("gfx/qplaque.lmp")); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); - M_DrawTextBox (152, 32, 10, 1); - M_Print (160, 40, "begin game"); + M_DrawTextBox(152, 32, 10, 1); + M_Print(160, 40, "begin game"); - M_Print (0, 56, " Max players"); - M_Print (160, 56, va("%" PRIi32 "", maxplayers) ); + M_Print(0, 56, " Max players"); + M_Print(160, 56, va("%" PRIi32 "", maxplayers)); - M_Print (0, 64, " Game Type"); - if (coop.value) - M_Print (160, 64, "Cooperative"); + M_Print(0, 64, " Game Type"); + if(coop.value) + M_Print(160, 64, "Cooperative"); else - M_Print (160, 64, "Deathmatch"); + M_Print(160, 64, "Deathmatch"); - M_Print (0, 72, " Teamplay"); - if (rogue) + M_Print(0, 72, " Teamplay"); + if(rogue) { const char *msg; switch((int32_t)teamplay.value) { - case 1: msg = "No Friendly Fire"; break; - case 2: msg = "Friendly Fire"; break; - case 3: msg = "Tag"; break; - case 4: msg = "Capture the Flag"; break; - case 5: msg = "One Flag CTF"; break; - case 6: msg = "Three Team CTF"; break; - default: msg = "Off"; break; + case 1: + msg = "No Friendly Fire"; + break; + case 2: + msg = "Friendly Fire"; + break; + case 3: + msg = "Tag"; + break; + case 4: + msg = "Capture the Flag"; + break; + case 5: + msg = "One Flag CTF"; + break; + case 6: + msg = "Three Team CTF"; + break; + default: + msg = "Off"; + break; } - M_Print (160, 72, msg); + M_Print(160, 72, msg); } else { @@ -2142,78 +2157,84 @@ void M_GameOptions_Draw (void) switch((int32_t)teamplay.value) { - case 1: msg = "No Friendly Fire"; break; - case 2: msg = "Friendly Fire"; break; - default: msg = "Off"; break; + case 1: + msg = "No Friendly Fire"; + break; + case 2: + msg = "Friendly Fire"; + break; + default: + msg = "Off"; + break; } - M_Print (160, 72, msg); + M_Print(160, 72, msg); } - M_Print (0, 80, " Skill"); - if (skill.value == 0) - M_Print (160, 80, "Easy difficulty"); - else if (skill.value == 1) - M_Print (160, 80, "Normal difficulty"); - else if (skill.value == 2) - M_Print (160, 80, "Hard difficulty"); + M_Print(0, 80, " Skill"); + if(skill.value == 0) + M_Print(160, 80, "Easy difficulty"); + else if(skill.value == 1) + M_Print(160, 80, "Normal difficulty"); + else if(skill.value == 2) + M_Print(160, 80, "Hard difficulty"); else - M_Print (160, 80, "Nightmare difficulty"); + M_Print(160, 80, "Nightmare difficulty"); - M_Print (0, 88, " Frag Limit"); - if (fraglimit.value == 0) - M_Print (160, 88, "none"); + M_Print(0, 88, " Frag Limit"); + if(fraglimit.value == 0) + M_Print(160, 88, "none"); else - M_Print (160, 88, va("%" PRIi32 " frags", (int32_t)fraglimit.value)); + M_Print(160, 88, va("%" PRIi32 " frags", (int32_t)fraglimit.value)); - M_Print (0, 96, " Time Limit"); - if (timelimit.value == 0) - M_Print (160, 96, "none"); + M_Print(0, 96, " Time Limit"); + if(timelimit.value == 0) + M_Print(160, 96, "none"); else - M_Print (160, 96, va("%" PRIi32 " minutes", (int32_t)timelimit.value)); + M_Print(160, 96, va("%" PRIi32 " minutes", (int32_t)timelimit.value)); - M_Print (0, 112, " Episode"); + M_Print(0, 112, " Episode"); // MED 01/06/97 added hipnotic episodes - if (hipnotic) - M_Print (160, 112, hipnoticepisodes[startepisode].description); + if(hipnotic) + M_Print(160, 112, hipnoticepisodes[startepisode].description); // PGM 01/07/97 added rogue episodes - else if (rogue) - M_Print (160, 112, rogueepisodes[startepisode].description); + else if(rogue) + M_Print(160, 112, rogueepisodes[startepisode].description); else - M_Print (160, 112, episodes[startepisode].description); + M_Print(160, 112, episodes[startepisode].description); - M_Print (0, 120, " Level"); + M_Print(0, 120, " Level"); // MED 01/06/97 added hipnotic episodes - if (hipnotic) + if(hipnotic) { - M_Print (160, 120, hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].description); - M_Print (160, 128, hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name); + M_Print(160, 120, hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].description); + M_Print(160, 128, hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name); } // PGM 01/07/97 added rogue episodes - else if (rogue) + else if(rogue) { - M_Print (160, 120, roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].description); - M_Print (160, 128, roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name); + M_Print(160, 120, roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].description); + M_Print(160, 128, roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name); } else { - M_Print (160, 120, levels[episodes[startepisode].firstLevel + startlevel].description); - M_Print (160, 128, levels[episodes[startepisode].firstLevel + startlevel].name); + M_Print(160, 120, levels[episodes[startepisode].firstLevel + startlevel].description); + M_Print(160, 128, levels[episodes[startepisode].firstLevel + startlevel].name); } // line cursor - M_DrawCharacter (144, gameoptions_cursor_table[gameoptions_cursor], 12+((int32_t)(realtime*4)&1)); + M_DrawCharacter(144, gameoptions_cursor_table[gameoptions_cursor], 12 + ((int32_t)(realtime * 4) & 1)); - if (m_serverInfoMessage) + if(m_serverInfoMessage) { - if ((realtime - m_serverInfoMessageTime) < 5.0) + if((realtime - m_serverInfoMessageTime) < 5.0) { - x = (320-26*8)/2; - M_DrawTextBox (x, 138, 24, 4); + x = (320 - 26 * 8) / 2; + M_DrawTextBox(x, 138, 24, 4); x += 8; - M_Print (x, 146, " More than 4 players "); - M_Print (x, 154, " requires using command "); - M_Print (x, 162, "line parameters; please "); - M_Print (x, 170, " see techinfo.txt. "); + M_Print(x, 146, " More than 4 players "); + M_Print(x, 154, " requires using command "); + M_Print(x, 162, "line parameters; please "); + M_Print(x, 170, " see techinfo.txt. "); } else { @@ -2223,76 +2244,76 @@ void M_GameOptions_Draw (void) } -void M_NetStart_Change (int32_t dir) +void M_NetStart_Change(int32_t dir) { int32_t count; - float f; + float f; - switch (gameoptions_cursor) + switch(gameoptions_cursor) { case 1: maxplayers += dir; - if (maxplayers > svs.maxclientslimit) + if(maxplayers > svs.maxclientslimit) { maxplayers = svs.maxclientslimit; m_serverInfoMessage = true; m_serverInfoMessageTime = realtime; } - if (maxplayers < 2) + if(maxplayers < 2) maxplayers = 2; break; case 2: - Cvar_Set ("coop", coop.value ? "0" : "1"); + Cvar_Set("coop", coop.value ? "0" : "1"); break; case 3: count = (rogue) ? 6 : 2; f = teamplay.value + dir; - if (f > count) f = 0; - else if (f < 0) f = count; - Cvar_SetValue ("teamplay", f); + if(f > count) f = 0; + else if(f < 0) f = count; + Cvar_SetValue("teamplay", f); break; case 4: f = skill.value + dir; - if (f > 3) f = 0; - else if (f < 0) f = 3; - Cvar_SetValue ("skill", f); + if(f > 3) f = 0; + else if(f < 0) f = 3; + Cvar_SetValue("skill", f); break; case 5: f = fraglimit.value + dir * 10; - if (f > 100) f = 0; - else if (f < 0) f = 100; - Cvar_SetValue ("fraglimit", f); + if(f > 100) f = 0; + else if(f < 0) f = 100; + Cvar_SetValue("fraglimit", f); break; case 6: f = timelimit.value + dir * 5; - if (f > 60) f = 0; - else if (f < 0) f = 60; - Cvar_SetValue ("timelimit", f); + if(f > 60) f = 0; + else if(f < 0) f = 60; + Cvar_SetValue("timelimit", f); break; case 7: startepisode += dir; - //MED 01/06/97 added hipnotic count - if (hipnotic) + //MED 01/06/97 added hipnotic count + if(hipnotic) count = 6; - //PGM 01/07/97 added rogue count - //PGM 03/02/97 added 1 for dmatch episode - else if (rogue) + //PGM 01/07/97 added rogue count + //PGM 03/02/97 added 1 for dmatch episode + else if(rogue) count = 4; - else if (registered.value) + else if(registered.value) count = 7; else count = 2; - if (startepisode < 0) + if(startepisode < 0) startepisode = count - 1; - if (startepisode >= count) + if(startepisode >= count) startepisode = 0; startlevel = 0; @@ -2300,84 +2321,84 @@ void M_NetStart_Change (int32_t dir) case 8: startlevel += dir; - //MED 01/06/97 added hipnotic episodes - if (hipnotic) + //MED 01/06/97 added hipnotic episodes + if(hipnotic) count = hipnoticepisodes[startepisode].levels; - //PGM 01/06/97 added hipnotic episodes - else if (rogue) + //PGM 01/06/97 added hipnotic episodes + else if(rogue) count = rogueepisodes[startepisode].levels; else count = episodes[startepisode].levels; - if (startlevel < 0) + if(startlevel < 0) startlevel = count - 1; - if (startlevel >= count) + if(startlevel >= count) startlevel = 0; break; } } -void M_GameOptions_Key (int32_t key) +void M_GameOptions_Key(int32_t key) { - switch (key) + switch(key) { case K_ESCAPE: case K_BBUTTON: - M_Menu_Net_f (); + M_Menu_Net_f(); break; case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); gameoptions_cursor--; - if (gameoptions_cursor < 0) - gameoptions_cursor = NUM_GAMEOPTIONS-1; + if(gameoptions_cursor < 0) + gameoptions_cursor = NUM_GAMEOPTIONS - 1; break; case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); gameoptions_cursor++; - if (gameoptions_cursor >= NUM_GAMEOPTIONS) + if(gameoptions_cursor >= NUM_GAMEOPTIONS) gameoptions_cursor = 0; break; case K_LEFTARROW: - if (gameoptions_cursor == 0) + if(gameoptions_cursor == 0) break; - S_LocalSound ("misc/menu3.wav"); - M_NetStart_Change (-1); + S_LocalSound("misc/menu3.wav"); + M_NetStart_Change(-1); break; case K_RIGHTARROW: - if (gameoptions_cursor == 0) + if(gameoptions_cursor == 0) break; - S_LocalSound ("misc/menu3.wav"); - M_NetStart_Change (1); + S_LocalSound("misc/menu3.wav"); + M_NetStart_Change(1); break; case K_ENTER: case K_KP_ENTER: case K_ABUTTON: - S_LocalSound ("misc/menu2.wav"); - if (gameoptions_cursor == 0) + S_LocalSound("misc/menu2.wav"); + if(gameoptions_cursor == 0) { - if (sv.active) - Cbuf_AddText ("disconnect\n"); - Cbuf_AddText ("listen 0\n"); // so host_netport will be re-examined - Cbuf_AddText ( va ("maxplayers %" PRIu32 "\n", maxplayers) ); - SCR_BeginLoadingPlaque (); + if(sv.active) + Cbuf_AddText("disconnect\n"); + Cbuf_AddText("listen 0\n"); // so host_netport will be re-examined + Cbuf_AddText(va("maxplayers %" PRIu32 "\n", maxplayers)); + SCR_BeginLoadingPlaque(); - if (hipnotic) - Cbuf_AddText ( va ("map %s\n", hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name) ); - else if (rogue) - Cbuf_AddText ( va ("map %s\n", roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name) ); + if(hipnotic) + Cbuf_AddText(va("map %s\n", hipnoticlevels[hipnoticepisodes[startepisode].firstLevel + startlevel].name)); + else if(rogue) + Cbuf_AddText(va("map %s\n", roguelevels[rogueepisodes[startepisode].firstLevel + startlevel].name)); else - Cbuf_AddText ( va ("map %s\n", levels[episodes[startepisode].firstLevel + startlevel].name) ); + Cbuf_AddText(va("map %s\n", levels[episodes[startepisode].firstLevel + startlevel].name)); return; } - M_NetStart_Change (1); + M_NetStart_Change(1); break; } } @@ -2385,10 +2406,10 @@ void M_GameOptions_Key (int32_t key) //============================================================================= /* SEARCH MENU */ -bool searchComplete = false; -double searchCompleteTime; +bool searchComplete = false; +double searchCompleteTime; -void M_Menu_Search_f (void) +void M_Menu_Search_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -2402,16 +2423,16 @@ void M_Menu_Search_f (void) } -void M_Search_Draw (void) +void M_Search_Draw(void) { - qpic_t *p; + qpic_t *p; int32_t x; - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - x = (320/2) - ((12*8)/2) + 4; - M_DrawTextBox (x-8, 32, 12, 1); - M_Print (x, 40, "Searching..."); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + x = (320 / 2) - ((12 * 8) / 2) + 4; + M_DrawTextBox(x - 8, 32, 12, 1); + M_Print(x, 40, "Searching..."); if(slistInProgress) { @@ -2419,27 +2440,27 @@ void M_Search_Draw (void) return; } - if (! searchComplete) + if(! searchComplete) { searchComplete = true; searchCompleteTime = realtime; } - if (hostCacheCount) + if(hostCacheCount) { - M_Menu_ServerList_f (); + M_Menu_ServerList_f(); return; } - M_PrintWhite ((320/2) - ((22*8)/2), 64, "No Quake servers found"); - if ((realtime - searchCompleteTime) < 3.0) + M_PrintWhite((320 / 2) - ((22 * 8) / 2), 64, "No Quake servers found"); + if((realtime - searchCompleteTime) < 3.0) return; - M_Menu_LanConfig_f (); + M_Menu_LanConfig_f(); } -void M_Search_Key (int32_t key) +void M_Search_Key(int32_t key) { (void)key; } @@ -2447,10 +2468,10 @@ void M_Search_Key (int32_t key) //============================================================================= /* SLIST MENU */ -int32_t slist_cursor; +int32_t slist_cursor; bool slist_sorted; -void M_Menu_ServerList_f (void) +void M_Menu_ServerList_f(void) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -2463,68 +2484,68 @@ void M_Menu_ServerList_f (void) } -void M_ServerList_Draw (void) +void M_ServerList_Draw(void) { - int32_t n; - qpic_t *p; + int32_t n; + qpic_t *p; - if (!slist_sorted) + if(!slist_sorted) { slist_sorted = true; - NET_SlistSort (); + NET_SlistSort(); } - p = Draw_CachePic ("gfx/p_multi.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - for (n = 0; n < hostCacheCount; n++) - M_Print (16, 32 + 8*n, NET_SlistPrintServer (n)); - M_DrawCharacter (0, 32 + slist_cursor*8, 12+((int32_t)(realtime*4)&1)); + p = Draw_CachePic("gfx/p_multi.lmp"); + M_DrawPic((320 - p->width) / 2, 4, p); + for(n = 0; n < hostCacheCount; n++) + M_Print(16, 32 + 8 * n, NET_SlistPrintServer(n)); + M_DrawCharacter(0, 32 + slist_cursor * 8, 12 + ((int32_t)(realtime * 4) & 1)); - if (*m_return_reason) - M_PrintWhite (16, 148, m_return_reason); + if(*m_return_reason) + M_PrintWhite(16, 148, m_return_reason); } -void M_ServerList_Key (int32_t k) +void M_ServerList_Key(int32_t k) { - switch (k) + switch(k) { case K_ESCAPE: case K_BBUTTON: - M_Menu_LanConfig_f (); + M_Menu_LanConfig_f(); break; case K_SPACE: - M_Menu_Search_f (); + M_Menu_Search_f(); break; case K_UPARROW: case K_LEFTARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); slist_cursor--; - if (slist_cursor < 0) + if(slist_cursor < 0) slist_cursor = hostCacheCount - 1; break; case K_DOWNARROW: case K_RIGHTARROW: - S_LocalSound ("misc/menu1.wav"); + S_LocalSound("misc/menu1.wav"); slist_cursor++; - if (slist_cursor >= hostCacheCount) + if(slist_cursor >= hostCacheCount) slist_cursor = 0; break; case K_ENTER: case K_KP_ENTER: case K_ABUTTON: - S_LocalSound ("misc/menu2.wav"); + S_LocalSound("misc/menu2.wav"); m_return_state = m_state; m_return_onerror = true; slist_sorted = false; IN_Activate(); key_dest = key_game; m_state = m_none; - Cbuf_AddText ( va ("connect \"%s\"\n", NET_SlistPrintServerName(slist_cursor)) ); + Cbuf_AddText(va("connect \"%s\"\n", NET_SlistPrintServerName(slist_cursor))); break; default: @@ -2537,218 +2558,219 @@ void M_ServerList_Key (int32_t k) /* Menu Subsystem */ -void M_Init (void) +void M_Init(void) { - Cmd_AddCommand ("togglemenu", M_ToggleMenu_f); + Cmd_AddCommand("togglemenu", M_ToggleMenu_f); - Cmd_AddCommand ("menu_main", M_Menu_Main_f); - Cmd_AddCommand ("menu_singleplayer", M_Menu_SinglePlayer_f); - Cmd_AddCommand ("menu_load", M_Menu_Load_f); - Cmd_AddCommand ("menu_save", M_Menu_Save_f); - Cmd_AddCommand ("menu_multiplayer", M_Menu_MultiPlayer_f); - Cmd_AddCommand ("menu_setup", M_Menu_Setup_f); - Cmd_AddCommand ("menu_options", M_Menu_Options_f); - Cmd_AddCommand ("menu_keys", M_Menu_Keys_f); - Cmd_AddCommand ("menu_video", M_Menu_Video_f); - Cmd_AddCommand ("help", M_Menu_Help_f); - Cmd_AddCommand ("menu_quit", M_Menu_Quit_f); + Cmd_AddCommand("menu_main", M_Menu_Main_f); + Cmd_AddCommand("menu_singleplayer", M_Menu_SinglePlayer_f); + Cmd_AddCommand("menu_load", M_Menu_Load_f); + Cmd_AddCommand("menu_save", M_Menu_Save_f); + Cmd_AddCommand("menu_multiplayer", M_Menu_MultiPlayer_f); + Cmd_AddCommand("menu_setup", M_Menu_Setup_f); + Cmd_AddCommand("menu_options", M_Menu_Options_f); + Cmd_AddCommand("menu_keys", M_Menu_Keys_f); + Cmd_AddCommand("menu_video", M_Menu_Video_f); + Cmd_AddCommand("help", M_Menu_Help_f); + Cmd_AddCommand("menu_quit", M_Menu_Quit_f); } -void M_Draw (void) +void M_Draw(void) { - if (m_state == m_none || key_dest != key_menu) + if(m_state == m_none || key_dest != key_menu) return; - if (!m_recursiveDraw) + if(!m_recursiveDraw) { - if (scr_con_current) + if(scr_con_current) { - Draw_ConsoleBackground (); - S_ExtraUpdate (); + Draw_ConsoleBackground(); + S_ExtraUpdate(); } - Draw_FadeScreen (); //johnfitz -- fade even if console fills screen + Draw_FadeScreen(); //johnfitz -- fade even if console fills screen } else { m_recursiveDraw = false; } - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - switch (m_state) + switch(m_state) { case m_none: break; case m_main: - M_Main_Draw (); + M_Main_Draw(); break; case m_singleplayer: - M_SinglePlayer_Draw (); + M_SinglePlayer_Draw(); break; case m_load: - M_Load_Draw (); + M_Load_Draw(); break; case m_save: - M_Save_Draw (); + M_Save_Draw(); break; case m_multiplayer: - M_MultiPlayer_Draw (); + M_MultiPlayer_Draw(); break; case m_setup: - M_Setup_Draw (); + M_Setup_Draw(); break; case m_net: - M_Net_Draw (); + M_Net_Draw(); break; case m_options: - M_Options_Draw (); + M_Options_Draw(); break; case m_keys: - M_Keys_Draw (); + M_Keys_Draw(); break; case m_video: - M_Video_Draw (); + M_Video_Draw(); break; case m_help: - M_Help_Draw (); + M_Help_Draw(); break; case m_quit: - if (!fitzmode) - { /* QuakeSpasm customization: */ + if(!fitzmode) + { + /* QuakeSpasm customization: */ /* Quit now! S.A. */ key_dest = key_console; - Host_Quit_f (); + Host_Quit_f(); } - M_Quit_Draw (); + M_Quit_Draw(); break; case m_lanconfig: - M_LanConfig_Draw (); + M_LanConfig_Draw(); break; case m_gameoptions: - M_GameOptions_Draw (); + M_GameOptions_Draw(); break; case m_search: - M_Search_Draw (); + M_Search_Draw(); break; case m_slist: - M_ServerList_Draw (); + M_ServerList_Draw(); break; } - if (m_entersound) + if(m_entersound) { - S_LocalSound ("misc/menu2.wav"); + S_LocalSound("misc/menu2.wav"); m_entersound = false; } - S_ExtraUpdate (); + S_ExtraUpdate(); } -void M_Keydown (int32_t key) +void M_Keydown(int32_t key) { - switch (m_state) + switch(m_state) { case m_none: return; case m_main: - M_Main_Key (key); + M_Main_Key(key); return; case m_singleplayer: - M_SinglePlayer_Key (key); + M_SinglePlayer_Key(key); return; case m_load: - M_Load_Key (key); + M_Load_Key(key); return; case m_save: - M_Save_Key (key); + M_Save_Key(key); return; case m_multiplayer: - M_MultiPlayer_Key (key); + M_MultiPlayer_Key(key); return; case m_setup: - M_Setup_Key (key); + M_Setup_Key(key); return; case m_net: - M_Net_Key (key); + M_Net_Key(key); return; case m_options: - M_Options_Key (key); + M_Options_Key(key); return; case m_keys: - M_Keys_Key (key); + M_Keys_Key(key); return; case m_video: - M_Video_Key (key); + M_Video_Key(key); return; case m_help: - M_Help_Key (key); + M_Help_Key(key); return; case m_quit: - M_Quit_Key (key); + M_Quit_Key(key); return; case m_lanconfig: - M_LanConfig_Key (key); + M_LanConfig_Key(key); return; case m_gameoptions: - M_GameOptions_Key (key); + M_GameOptions_Key(key); return; case m_search: - M_Search_Key (key); + M_Search_Key(key); break; case m_slist: - M_ServerList_Key (key); + M_ServerList_Key(key); return; } } -void M_Charinput (int32_t key) +void M_Charinput(int32_t key) { - switch (m_state) + switch(m_state) { case m_setup: - M_Setup_Char (key); + M_Setup_Char(key); return; case m_quit: - M_Quit_Char (key); + M_Quit_Char(key); return; case m_lanconfig: - M_LanConfig_Char (key); + M_LanConfig_Char(key); return; default: return; @@ -2756,16 +2778,16 @@ void M_Charinput (int32_t key) } -bool M_TextEntry (void) +bool M_TextEntry(void) { - switch (m_state) + switch(m_state) { case m_setup: - return M_Setup_TextEntry (); + return M_Setup_TextEntry(); case m_quit: - return M_Quit_TextEntry (); + return M_Quit_TextEntry(); case m_lanconfig: - return M_LanConfig_TextEntry (); + return M_LanConfig_TextEntry(); default: return false; } @@ -2775,9 +2797,9 @@ bool M_TextEntry (void) void M_ConfigureNetSubsystem(void) { // enable/disable net systems to match desired config - Cbuf_AddText ("stopdemo\n"); + Cbuf_AddText("stopdemo\n"); - if (IPXConfig || TCPIPConfig) + if(IPXConfig || TCPIPConfig) net_hostport = lanConfig_port; } diff --git a/source/menu.h b/source/menu.h index b0c68c4..cacadfa 100644 --- a/source/menu.h +++ b/source/menu.h @@ -23,7 +23,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef _QUAKE_MENU_H #define _QUAKE_MENU_H -enum m_state_e { +enum m_state_e +{ m_none, m_main, m_singleplayer, @@ -51,25 +52,25 @@ extern bool m_entersound; // // menus // -void M_Init (void); -void M_Keydown (int32_t key); -void M_Charinput (int32_t key); -bool M_TextEntry (void); -void M_ToggleMenu_f (void); +void M_Init(void); +void M_Keydown(int32_t key); +void M_Charinput(int32_t key); +bool M_TextEntry(void); +void M_ToggleMenu_f(void); -void M_Menu_Main_f (void); -void M_Menu_Options_f (void); -void M_Menu_Quit_f (void); +void M_Menu_Main_f(void); +void M_Menu_Options_f(void); +void M_Menu_Quit_f(void); -void M_Print (int32_t cx, int32_t cy, const char *str); -void M_PrintWhite (int32_t cx, int32_t cy, const char *str); +void M_Print(int32_t cx, int32_t cy, const char *str); +void M_PrintWhite(int32_t cx, int32_t cy, const char *str); -void M_Draw (void); -void M_DrawCharacter (int32_t cx, int32_t line, int32_t num); +void M_Draw(void); +void M_DrawCharacter(int32_t cx, int32_t line, int32_t num); -void M_DrawPic (int32_t x, int32_t y, qpic_t *pic); -void M_DrawTransPic (int32_t x, int32_t y, qpic_t *pic); -void M_DrawCheckbox (int32_t x, int32_t y, int32_t on); +void M_DrawPic(int32_t x, int32_t y, qpic_t *pic); +void M_DrawTransPic(int32_t x, int32_t y, qpic_t *pic); +void M_DrawCheckbox(int32_t x, int32_t y, int32_t on); -#endif /* _QUAKE_MENU_H */ +#endif /* _QUAKE_MENU_H */ diff --git a/source/modelgen.h b/source/modelgen.h index 5cb89ce..269a4db 100644 --- a/source/modelgen.h +++ b/source/modelgen.h @@ -47,95 +47,106 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #endif -#define ALIAS_VERSION 6 +#define ALIAS_VERSION 6 -#define ALIAS_ONSEAM 0x0020 +#define ALIAS_ONSEAM 0x0020 // must match definition in spritegn.h #ifndef SYNCTYPE_T #define SYNCTYPE_T -typedef enum {ST_SYNC=0, ST_RAND } synctype_t; +typedef enum {ST_SYNC = 0, ST_RAND } synctype_t; #endif -typedef enum { ALIAS_SINGLE=0, ALIAS_GROUP } aliasframetype_t; +typedef enum { ALIAS_SINGLE = 0, ALIAS_GROUP } aliasframetype_t; -typedef enum { ALIAS_SKIN_SINGLE=0, ALIAS_SKIN_GROUP } aliasskintype_t; +typedef enum { ALIAS_SKIN_SINGLE = 0, ALIAS_SKIN_GROUP } aliasskintype_t; -typedef struct { - int32_t ident; - int32_t version; - vec3_t scale; - vec3_t scale_origin; - float boundingradius; - vec3_t eyeposition; - int32_t numskins; - int32_t skinwidth; - int32_t skinheight; - int32_t numverts; - int32_t numtris; - int32_t numframes; - synctype_t synctype; - int32_t flags; - float size; +typedef struct +{ + int32_t ident; + int32_t version; + vec3_t scale; + vec3_t scale_origin; + float boundingradius; + vec3_t eyeposition; + int32_t numskins; + int32_t skinwidth; + int32_t skinheight; + int32_t numverts; + int32_t numtris; + int32_t numframes; + synctype_t synctype; + int32_t flags; + float size; } mdl_t; // TODO: could be shorts -typedef struct { - int32_t onseam; - int32_t s; - int32_t t; +typedef struct +{ + int32_t onseam; + int32_t s; + int32_t t; } stvert_t; -typedef struct dtriangle_s { - int32_t facesfront; - int32_t vertindex[3]; +typedef struct dtriangle_s +{ + int32_t facesfront; + int32_t vertindex[3]; } dtriangle_t; -#define DT_FACES_FRONT 0x0010 +#define DT_FACES_FRONT 0x0010 // This mirrors trivert_t in trilib.h, is present so Quake knows how to // load this data -typedef struct { - byte v[3]; - byte lightnormalindex; +typedef struct +{ + byte v[3]; + byte lightnormalindex; } trivertx_t; -typedef struct { - trivertx_t bboxmin; // lightnormal isn't used - trivertx_t bboxmax; // lightnormal isn't used - char name[16]; // frame name from grabbing +typedef struct +{ + trivertx_t bboxmin; // lightnormal isn't used + trivertx_t bboxmax; // lightnormal isn't used + char name[16]; // frame name from grabbing } daliasframe_t; -typedef struct { - int32_t numframes; - trivertx_t bboxmin; // lightnormal isn't used - trivertx_t bboxmax; // lightnormal isn't used +typedef struct +{ + int32_t numframes; + trivertx_t bboxmin; // lightnormal isn't used + trivertx_t bboxmax; // lightnormal isn't used } daliasgroup_t; -typedef struct { - int32_t numskins; +typedef struct +{ + int32_t numskins; } daliasskingroup_t; -typedef struct { - float interval; +typedef struct +{ + float interval; } daliasinterval_t; -typedef struct { - float interval; +typedef struct +{ + float interval; } daliasskininterval_t; -typedef struct { - aliasframetype_t type; +typedef struct +{ + aliasframetype_t type; } daliasframetype_t; -typedef struct { - aliasskintype_t type; +typedef struct +{ + aliasskintype_t type; } daliasskintype_t; -#define IDPOLYHEADER (('O'<<24)+('P'<<16)+('D'<<8)+'I') - // little-endian "IDPO" +#define IDPOLYHEADER (('O'<<24)+('P'<<16)+('D'<<8)+'I') +// little-endian "IDPO" -#endif /* _MODELGEN_H */ +#endif /* _MODELGEN_H */ diff --git a/source/net.h b/source/net.h index 8580355..0ed947c 100644 --- a/source/net.h +++ b/source/net.h @@ -22,64 +22,64 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* - net.h - quake's interface to the networking layer - network functions and data, common to the - whole engine + net.h + quake's interface to the networking layer + network functions and data, common to the + whole engine */ #ifndef _QUAKE_NET_H #define _QUAKE_NET_H -#define NET_NAMELEN 64 +#define NET_NAMELEN 64 -#define NET_MAXMESSAGE 64000 /* ericw -- was 32000 */ +#define NET_MAXMESSAGE 64000 /* ericw -- was 32000 */ -extern int32_t DEFAULTnet_hostport; -extern int32_t net_hostport; +extern int32_t DEFAULTnet_hostport; +extern int32_t net_hostport; -extern cvar_t hostname; +extern cvar_t hostname; -extern double net_time; -extern sizebuf_t net_message; -extern int32_t net_activeconnections; +extern double net_time; +extern sizebuf_t net_message; +extern int32_t net_activeconnections; -void NET_Init (void); -void NET_Shutdown (void); +void NET_Init(void); +void NET_Shutdown(void); -struct qsocket_s *NET_CheckNewConnections (void); +struct qsocket_s *NET_CheckNewConnections(void); // returns a new connection number if there is one pending, else -1 -struct qsocket_s *NET_Connect (const char *host); +struct qsocket_s *NET_Connect(const char *host); // called by client to connect to a host. Returns -1 if not able to -double NET_QSocketGetTime (const struct qsocket_s *sock); -const char *NET_QSocketGetAddressString (const struct qsocket_s *sock); +double NET_QSocketGetTime(const struct qsocket_s *sock); +const char *NET_QSocketGetAddressString(const struct qsocket_s *sock); -bool NET_CanSendMessage (struct qsocket_s *sock); +bool NET_CanSendMessage(struct qsocket_s *sock); // Returns true or false if the given qsocket can currently accept a // message to be transmitted. -int32_t NET_GetMessage (struct qsocket_s *sock); +int32_t NET_GetMessage(struct qsocket_s *sock); // returns data in net_message sizebuf // returns 0 if no data is waiting // returns 1 if a message was received // returns 2 if an unreliable message was received // returns -1 if the connection died -int32_t NET_SendMessage (struct qsocket_s *sock, sizebuf_t *data); -int32_t NET_SendUnreliableMessage (struct qsocket_s *sock, sizebuf_t *data); +int32_t NET_SendMessage(struct qsocket_s *sock, sizebuf_t *data); +int32_t NET_SendUnreliableMessage(struct qsocket_s *sock, sizebuf_t *data); // returns 0 if the message connot be delivered reliably, but the connection // is still considered valid // returns 1 if the message was sent properly // returns -1 if the connection died -int32_t NET_SendToAll(sizebuf_t *data, double blocktime); +int32_t NET_SendToAll(sizebuf_t *data, double blocktime); // This is a reliable *blocking* send to all attached clients. -void NET_Close (struct qsocket_s *sock); +void NET_Close(struct qsocket_s *sock); // if a dead connection is returned by a get or send function, this function // should be called when it is convenient @@ -88,28 +88,28 @@ void NET_Close (struct qsocket_s *sock); // from a server. // A netcon_t number will not be reused until this function is called for it -void NET_Poll (void); +void NET_Poll(void); // Server list related globals: -extern bool slistInProgress; -extern bool slistSilent; -extern bool slistLocal; +extern bool slistInProgress; +extern bool slistSilent; +extern bool slistLocal; -extern int32_t hostCacheCount; +extern int32_t hostCacheCount; -void NET_Slist_f (void); -void NET_SlistSort (void); -const char *NET_SlistPrintServer (int32_t n); -const char *NET_SlistPrintServerName (int32_t n); +void NET_Slist_f(void); +void NET_SlistSort(void); +const char *NET_SlistPrintServer(int32_t n); +const char *NET_SlistPrintServerName(int32_t n); /* FIXME: driver related, but public: */ -extern bool ipxAvailable; -extern bool tcpipAvailable; -extern char my_ipx_address[NET_NAMELEN]; -extern char my_tcpip_address[NET_NAMELEN]; +extern bool ipxAvailable; +extern bool tcpipAvailable; +extern char my_ipx_address[NET_NAMELEN]; +extern char my_tcpip_address[NET_NAMELEN]; -#endif /* _QUAKE_NET_H */ +#endif /* _QUAKE_NET_H */ diff --git a/source/net_defs.h b/source/net_defs.h index 7035f04..2fe7545 100644 --- a/source/net_defs.h +++ b/source/net_defs.h @@ -31,27 +31,27 @@ struct qsockaddr uint8_t qsa_family; #else int16_t qsa_family; -#endif /* BSD, sockaddr */ +#endif /* BSD, sockaddr */ uint8_t qsa_data[14]; }; -#define NET_HEADERSIZE (2 * sizeof(uint32_t)) -#define NET_DATAGRAMSIZE (MAX_DATAGRAM + NET_HEADERSIZE) +#define NET_HEADERSIZE (2 * sizeof(uint32_t)) +#define NET_DATAGRAMSIZE (MAX_DATAGRAM + NET_HEADERSIZE) // NetHeader flags -#define NETFLAG_LENGTH_MASK 0x0000ffff -#define NETFLAG_DATA 0x00010000 -#define NETFLAG_ACK 0x00020000 -#define NETFLAG_NAK 0x00040000 -#define NETFLAG_EOM 0x00080000 -#define NETFLAG_UNRELIABLE 0x00100000 -#define NETFLAG_CTL 0x80000000 +#define NETFLAG_LENGTH_MASK 0x0000ffff +#define NETFLAG_DATA 0x00010000 +#define NETFLAG_ACK 0x00020000 +#define NETFLAG_NAK 0x00040000 +#define NETFLAG_EOM 0x00080000 +#define NETFLAG_UNRELIABLE 0x00100000 +#define NETFLAG_CTL 0x80000000 #if (NETFLAG_LENGTH_MASK & NET_MAXMESSAGE) != NET_MAXMESSAGE #error "NET_MAXMESSAGE must fit within NETFLAG_LENGTH_MASK" #endif -#define NET_PROTOCOL_VERSION 3 +#define NET_PROTOCOL_VERSION 3 /** @@ -61,184 +61,184 @@ Quake game protocol (documented elsewhere) is used. General notes: - game_name is currently always "QUAKE", but is there so this same protocol - can be used for future games as well; can you say Quake2? + game_name is currently always "QUAKE", but is there so this same protocol + can be used for future games as well; can you say Quake2? CCREQ_CONNECT - string game_name "QUAKE" - byte net_protocol_version NET_PROTOCOL_VERSION + string game_name "QUAKE" + byte net_protocol_version NET_PROTOCOL_VERSION CCREQ_SERVER_INFO - string game_name "QUAKE" - byte net_protocol_version NET_PROTOCOL_VERSION + string game_name "QUAKE" + byte net_protocol_version NET_PROTOCOL_VERSION CCREQ_PLAYER_INFO - byte player_number + byte player_number CCREQ_RULE_INFO - string rule + string rule CCREP_ACCEPT - long port + long port CCREP_REJECT - string reason + string reason CCREP_SERVER_INFO - string server_address - string host_name - string level_name - byte current_players - byte max_players - byte protocol_version NET_PROTOCOL_VERSION + string server_address + string host_name + string level_name + byte current_players + byte max_players + byte protocol_version NET_PROTOCOL_VERSION CCREP_PLAYER_INFO - byte player_number - string name - long colors - long frags - long connect_time - string address + byte player_number + string name + long colors + long frags + long connect_time + string address CCREP_RULE_INFO - string rule - string value + string rule + string value - note: - There are two address forms used above. The short form is just a - port number. The address that goes along with the port is defined as - "whatever address you receive this reponse from". This lets us use - the host OS to solve the problem of multiple host addresses (possibly - with no routing between them); the host will use the right address - when we reply to the inbound connection request. The long from is - a full address and port in a string. It is used for returning the - address of a server that is not running locally. + note: + There are two address forms used above. The short form is just a + port number. The address that goes along with the port is defined as + "whatever address you receive this reponse from". This lets us use + the host OS to solve the problem of multiple host addresses (possibly + with no routing between them); the host will use the right address + when we reply to the inbound connection request. The long from is + a full address and port in a string. It is used for returning the + address of a server that is not running locally. **/ -#define CCREQ_CONNECT 0x01 -#define CCREQ_SERVER_INFO 0x02 -#define CCREQ_PLAYER_INFO 0x03 -#define CCREQ_RULE_INFO 0x04 +#define CCREQ_CONNECT 0x01 +#define CCREQ_SERVER_INFO 0x02 +#define CCREQ_PLAYER_INFO 0x03 +#define CCREQ_RULE_INFO 0x04 -#define CCREP_ACCEPT 0x81 -#define CCREP_REJECT 0x82 -#define CCREP_SERVER_INFO 0x83 -#define CCREP_PLAYER_INFO 0x84 -#define CCREP_RULE_INFO 0x85 +#define CCREP_ACCEPT 0x81 +#define CCREP_REJECT 0x82 +#define CCREP_SERVER_INFO 0x83 +#define CCREP_PLAYER_INFO 0x84 +#define CCREP_RULE_INFO 0x85 typedef struct qsocket_s { - struct qsocket_s *next; - double connecttime; - double lastMessageTime; - double lastSendTime; + struct qsocket_s *next; + double connecttime; + double lastMessageTime; + double lastSendTime; - bool disconnected; - bool canSend; - bool sendNext; + bool disconnected; + bool canSend; + bool sendNext; - int32_t driver; - int32_t landriver; - sys_socket_t socket; - void *driverdata; + int32_t driver; + int32_t landriver; + sys_socket_t socket; + void *driverdata; - uint32_t ackSequence; - uint32_t sendSequence; - uint32_t unreliableSendSequence; - int32_t sendMessageLength; - byte sendMessage [NET_MAXMESSAGE]; + uint32_t ackSequence; + uint32_t sendSequence; + uint32_t unreliableSendSequence; + int32_t sendMessageLength; + byte sendMessage [NET_MAXMESSAGE]; - uint32_t receiveSequence; - uint32_t unreliableReceiveSequence; - int32_t receiveMessageLength; - byte receiveMessage [NET_MAXMESSAGE]; + uint32_t receiveSequence; + uint32_t unreliableReceiveSequence; + int32_t receiveMessageLength; + byte receiveMessage [NET_MAXMESSAGE]; - struct qsockaddr addr; - char address[NET_NAMELEN]; + struct qsockaddr addr; + char address[NET_NAMELEN]; } qsocket_t; -extern qsocket_t *net_activeSockets; -extern qsocket_t *net_freeSockets; -extern int32_t net_numsockets; +extern qsocket_t *net_activeSockets; +extern qsocket_t *net_freeSockets; +extern int32_t net_numsockets; typedef struct { - const char *name; - bool initialized; - sys_socket_t controlSock; - sys_socket_t (*Init) (void); - void (*Shutdown) (void); - void (*Listen) (bool state); - sys_socket_t (*Open_Socket) (int32_t port); - int32_t (*Close_Socket) (sys_socket_t socketid); - int32_t (*Connect) (sys_socket_t socketid, struct qsockaddr *addr); - sys_socket_t (*CheckNewConnections) (void); - int32_t (*Read) (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); - int32_t (*Write) (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); - int32_t (*Broadcast) (sys_socket_t socketid, byte *buf, int32_t len); - const char * (*AddrToString) (struct qsockaddr *addr); - int32_t (*StringToAddr) (const char *string, struct qsockaddr *addr); - int32_t (*GetSocketAddr) (sys_socket_t socketid, struct qsockaddr *addr); - int32_t (*GetNameFromAddr) (struct qsockaddr *addr, char *name); - int32_t (*GetAddrFromName) (const char *name, struct qsockaddr *addr); - int32_t (*AddrCompare) (struct qsockaddr *addr1, struct qsockaddr *addr2); - int32_t (*GetSocketPort) (struct qsockaddr *addr); - int32_t (*SetSocketPort) (struct qsockaddr *addr, int32_t port); + const char *name; + bool initialized; + sys_socket_t controlSock; + sys_socket_t (*Init)(void); + void (*Shutdown)(void); + void (*Listen)(bool state); + sys_socket_t (*Open_Socket)(int32_t port); + int32_t (*Close_Socket)(sys_socket_t socketid); + int32_t (*Connect)(sys_socket_t socketid, struct qsockaddr *addr); + sys_socket_t (*CheckNewConnections)(void); + int32_t (*Read)(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); + int32_t (*Write)(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); + int32_t (*Broadcast)(sys_socket_t socketid, byte *buf, int32_t len); + const char * (*AddrToString)(struct qsockaddr *addr); + int32_t (*StringToAddr)(const char *string, struct qsockaddr *addr); + int32_t (*GetSocketAddr)(sys_socket_t socketid, struct qsockaddr *addr); + int32_t (*GetNameFromAddr)(struct qsockaddr *addr, char *name); + int32_t (*GetAddrFromName)(const char *name, struct qsockaddr *addr); + int32_t (*AddrCompare)(struct qsockaddr *addr1, struct qsockaddr *addr2); + int32_t (*GetSocketPort)(struct qsockaddr *addr); + int32_t (*SetSocketPort)(struct qsockaddr *addr, int32_t port); } net_landriver_t; -#define MAX_NET_DRIVERS 8 -extern net_landriver_t net_landrivers[]; -extern const int32_t net_numlandrivers; +#define MAX_NET_DRIVERS 8 +extern net_landriver_t net_landrivers[]; +extern const int32_t net_numlandrivers; typedef struct { - const char *name; - bool initialized; - int32_t (*Init) (void); - void (*Listen) (bool state); - void (*SearchForHosts) (bool xmit); - qsocket_t *(*Connect) (const char *host); - qsocket_t *(*CheckNewConnections) (void); - int32_t (*QGetMessage) (qsocket_t *sock); - int32_t (*QSendMessage) (qsocket_t *sock, sizebuf_t *data); - int32_t (*SendUnreliableMessage) (qsocket_t *sock, sizebuf_t *data); - bool (*CanSendMessage) (qsocket_t *sock); - bool (*CanSendUnreliableMessage) (qsocket_t *sock); - void (*Close) (qsocket_t *sock); - void (*Shutdown) (void); + const char *name; + bool initialized; + int32_t (*Init)(void); + void (*Listen)(bool state); + void (*SearchForHosts)(bool xmit); + qsocket_t *(*Connect)(const char *host); + qsocket_t *(*CheckNewConnections)(void); + int32_t (*QGetMessage)(qsocket_t *sock); + int32_t (*QSendMessage)(qsocket_t *sock, sizebuf_t *data); + int32_t (*SendUnreliableMessage)(qsocket_t *sock, sizebuf_t *data); + bool (*CanSendMessage)(qsocket_t *sock); + bool (*CanSendUnreliableMessage)(qsocket_t *sock); + void (*Close)(qsocket_t *sock); + void (*Shutdown)(void); } net_driver_t; -extern net_driver_t net_drivers[]; -extern const int32_t net_numdrivers; +extern net_driver_t net_drivers[]; +extern const int32_t net_numdrivers; /* Loop driver must always be registered the first */ -#define IS_LOOP_DRIVER(p) ((p) == 0) +#define IS_LOOP_DRIVER(p) ((p) == 0) -extern int32_t net_driverlevel; +extern int32_t net_driverlevel; -extern int32_t messagesSent; -extern int32_t messagesReceived; -extern int32_t unreliableMessagesSent; -extern int32_t unreliableMessagesReceived; +extern int32_t messagesSent; +extern int32_t messagesReceived; +extern int32_t unreliableMessagesSent; +extern int32_t unreliableMessagesReceived; -qsocket_t *NET_NewQSocket (void); +qsocket_t *NET_NewQSocket(void); void NET_FreeQSocket(qsocket_t *); double SetNetTime(void); -#define HOSTCACHESIZE 8 +#define HOSTCACHESIZE 8 typedef struct { - char name[16]; - char map[16]; - char cname[32]; - int32_t users; - int32_t maxusers; - int32_t driver; - int32_t ldriver; + char name[16]; + char map[16]; + char cname[32]; + int32_t users; + int32_t maxusers; + int32_t driver; + int32_t ldriver; struct qsockaddr addr; } hostcache_t; @@ -248,13 +248,13 @@ extern hostcache_t hostcache[HOSTCACHESIZE]; typedef struct _PollProcedure { - struct _PollProcedure *next; - double nextTime; - void (*procedure)(void *); - void *arg; + struct _PollProcedure *next; + double nextTime; + void (*procedure)(void *); + void *arg; } PollProcedure; void SchedulePollProcedure(PollProcedure *pp, double timeOffset); -#endif /* __NET_DEFS_H */ +#endif /* __NET_DEFS_H */ diff --git a/source/net_dgrm.c b/source/net_dgrm.c index fff85d4..a698f6a 100644 --- a/source/net_dgrm.c +++ b/source/net_dgrm.c @@ -30,8 +30,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "net_dgrm.h" // these two macros are to make the code more readable -#define sfunc net_landrivers[sock->landriver] -#define dfunc net_landrivers[net_landriverlevel] +#define sfunc net_landrivers[sock->landriver] +#define dfunc net_landrivers[net_landriverlevel] static int32_t net_landriverlevel; @@ -45,9 +45,9 @@ static int32_t droppedDatagrams; static struct { - uint32_t length; - uint32_t sequence; - byte data[MAX_DATAGRAM]; + uint32_t length; + uint32_t sequence; + byte data[MAX_DATAGRAM]; } packetBuffer; static int32_t myDriverLevel; @@ -56,49 +56,49 @@ extern bool m_return_onerror; extern char m_return_reason[32]; -static char *StrAddr (struct qsockaddr *addr) +static char *StrAddr(struct qsockaddr *addr) { static char buf[34]; byte *p = (byte *)addr; int32_t n; - for (n = 0; n < 16; n++) - sprintf (buf + n * 2, "%02x", *p++); + for(n = 0; n < 16; n++) + sprintf(buf + n * 2, "%02x", *p++); return buf; } #ifdef BAN_TEST -static struct in_addr banAddr; -static struct in_addr banMask; +static struct in_addr banAddr; +static struct in_addr banMask; -static void NET_Ban_f (void) +static void NET_Ban_f(void) { - char addrStr [32]; - char maskStr [32]; - void (*print_fn)(const char *fmt, ...) FUNCP_PRINTF(1,2); + char addrStr [32]; + char maskStr [32]; + void (*print_fn)(const char *fmt, ...) FUNCP_PRINTF(1, 2); - if (cmd_source == src_command) + if(cmd_source == src_command) { - if (!sv.active) + if(!sv.active) { - Cmd_ForwardToServer (); + Cmd_ForwardToServer(); return; } print_fn = Con_Printf; } else { - if (pr_global_struct->deathmatch) + if(pr_global_struct->deathmatch) return; print_fn = SV_ClientPrintf; } - switch (Cmd_Argc ()) + switch(Cmd_Argc()) { case 1: - if (banAddr.s_addr != INADDR_ANY) + if(banAddr.s_addr != INADDR_ANY) { Q_strcpy(addrStr, inet_ntoa(banAddr)); Q_strcpy(maskStr, inet_ntoa(banMask)); @@ -109,7 +109,7 @@ static void NET_Ban_f (void) break; case 2: - if (q_strcasecmp(Cmd_Argv(1), "off") == 0) + if(q_strcasecmp(Cmd_Argv(1), "off") == 0) banAddr.s_addr = INADDR_ANY; else banAddr.s_addr = inet_addr(Cmd_Argv(1)); @@ -126,30 +126,30 @@ static void NET_Ban_f (void) break; } } -#endif // BAN_TEST +#endif // BAN_TEST -int32_t Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data) +int32_t Datagram_SendMessage(qsocket_t *sock, sizebuf_t *data) { - uint32_t packetLen; - uint32_t dataLen; - uint32_t eom; + uint32_t packetLen; + uint32_t dataLen; + uint32_t eom; #ifdef DEBUG - if (data->cursize == 0) + if(data->cursize == 0) Sys_Error("Datagram_SendMessage: zero length message\n"); - if (data->cursize > NET_MAXMESSAGE) + if(data->cursize > NET_MAXMESSAGE) Sys_Error("Datagram_SendMessage: message too big %" PRIu32 "\n", data->cursize); - if (sock->canSend == false) + if(sock->canSend == false) Sys_Error("SendMessage: called with canSend == false\n"); #endif Q_memcpy(sock->sendMessage, data->data, data->cursize); sock->sendMessageLength = data->cursize; - if (data->cursize <= MAX_DATAGRAM) + if(data->cursize <= MAX_DATAGRAM) { dataLen = data->cursize; eom = NETFLAG_EOM; @@ -163,11 +163,11 @@ int32_t Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data) packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.sequence = BigLong(sock->sendSequence++); - Q_memcpy (packetBuffer.data, sock->sendMessage, dataLen); + Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); sock->canSend = false; - if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) + if(sfunc.Write(sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) return -1; sock->lastSendTime = net_time; @@ -176,13 +176,13 @@ int32_t Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data) } -static int32_t SendMessageNext (qsocket_t *sock) +static int32_t SendMessageNext(qsocket_t *sock) { - uint32_t packetLen; - uint32_t dataLen; - uint32_t eom; + uint32_t packetLen; + uint32_t dataLen; + uint32_t eom; - if (sock->sendMessageLength <= MAX_DATAGRAM) + if(sock->sendMessageLength <= MAX_DATAGRAM) { dataLen = sock->sendMessageLength; eom = NETFLAG_EOM; @@ -196,11 +196,11 @@ static int32_t SendMessageNext (qsocket_t *sock) packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.sequence = BigLong(sock->sendSequence++); - Q_memcpy (packetBuffer.data, sock->sendMessage, dataLen); + Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); sock->sendNext = false; - if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) + if(sfunc.Write(sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) return -1; sock->lastSendTime = net_time; @@ -209,13 +209,13 @@ static int32_t SendMessageNext (qsocket_t *sock) } -static int32_t ReSendMessage (qsocket_t *sock) +static int32_t ReSendMessage(qsocket_t *sock) { - uint32_t packetLen; - uint32_t dataLen; - uint32_t eom; + uint32_t packetLen; + uint32_t dataLen; + uint32_t eom; - if (sock->sendMessageLength <= MAX_DATAGRAM) + if(sock->sendMessageLength <= MAX_DATAGRAM) { dataLen = sock->sendMessageLength; eom = NETFLAG_EOM; @@ -229,11 +229,11 @@ static int32_t ReSendMessage (qsocket_t *sock) packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.sequence = BigLong(sock->sendSequence - 1); - Q_memcpy (packetBuffer.data, sock->sendMessage, dataLen); + Q_memcpy(packetBuffer.data, sock->sendMessage, dataLen); sock->sendNext = false; - if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) + if(sfunc.Write(sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) return -1; sock->lastSendTime = net_time; @@ -242,31 +242,31 @@ static int32_t ReSendMessage (qsocket_t *sock) } -bool Datagram_CanSendMessage (qsocket_t *sock) +bool Datagram_CanSendMessage(qsocket_t *sock) { - if (sock->sendNext) - SendMessageNext (sock); + if(sock->sendNext) + SendMessageNext(sock); return sock->canSend; } -bool Datagram_CanSendUnreliableMessage (qsocket_t *sock) +bool Datagram_CanSendUnreliableMessage(qsocket_t *sock) { (void)sock; return true; } -int32_t Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) +int32_t Datagram_SendUnreliableMessage(qsocket_t *sock, sizebuf_t *data) { - int32_t packetLen; + int32_t packetLen; #ifdef DEBUG - if (data->cursize == 0) + if(data->cursize == 0) Sys_Error("Datagram_SendUnreliableMessage: zero length message\n"); - if (data->cursize > MAX_DATAGRAM) + if(data->cursize > MAX_DATAGRAM) Sys_Error("Datagram_SendUnreliableMessage: message too big %" PRIu32 "\n", data->cursize); #endif @@ -274,9 +274,9 @@ int32_t Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) packetBuffer.length = BigLong(packetLen | NETFLAG_UNRELIABLE); packetBuffer.sequence = BigLong(sock->unreliableSendSequence++); - Q_memcpy (packetBuffer.data, data->data, data->cursize); + Q_memcpy(packetBuffer.data, data->data, data->cursize); - if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) + if(sfunc.Write(sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) return -1; packetsSent++; @@ -284,45 +284,45 @@ int32_t Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) } -int32_t Datagram_GetMessage (qsocket_t *sock) +int32_t Datagram_GetMessage(qsocket_t *sock) { - uint32_t length; - uint32_t flags; - int32_t ret = 0; + uint32_t length; + uint32_t flags; + int32_t ret = 0; struct qsockaddr readaddr; - uint32_t sequence; - uint32_t count; + uint32_t sequence; + uint32_t count; - if (!sock->canSend) - if ((net_time - sock->lastSendTime) > 1.0) - ReSendMessage (sock); + if(!sock->canSend) + if((net_time - sock->lastSendTime) > 1.0) + ReSendMessage(sock); - while (1) + while(1) { length = (uint32_t) sfunc.Read(sock->socket, (byte *)&packetBuffer, - NET_DATAGRAMSIZE, &readaddr); + NET_DATAGRAMSIZE, &readaddr); - // if ((rand() & 255) > 220) - // continue; + // if ((rand() & 255) > 220) + // continue; - if (length == 0) + if(length == 0) break; - if (length == (uint32_t)-1) + if(length == (uint32_t) -1) { Con_Printf("Read error\n"); return -1; } - if (sfunc.AddrCompare(&readaddr, &sock->addr) != 0) + if(sfunc.AddrCompare(&readaddr, &sock->addr) != 0) { Con_Printf("Forged packet received\n"); - Con_Printf("Expected: %s\n", StrAddr (&sock->addr)); - Con_Printf("Received: %s\n", StrAddr (&readaddr)); + Con_Printf("Expected: %s\n", StrAddr(&sock->addr)); + Con_Printf("Received: %s\n", StrAddr(&readaddr)); continue; } - if (length < NET_HEADERSIZE) + if(length < NET_HEADERSIZE) { shortPacketCount++; continue; @@ -332,21 +332,21 @@ int32_t Datagram_GetMessage (qsocket_t *sock) flags = length & (~NETFLAG_LENGTH_MASK); length &= NETFLAG_LENGTH_MASK; - if (flags & NETFLAG_CTL) + if(flags & NETFLAG_CTL) continue; sequence = BigLong(packetBuffer.sequence); packetsReceived++; - if (flags & NETFLAG_UNRELIABLE) + if(flags & NETFLAG_UNRELIABLE) { - if (sequence < sock->unreliableReceiveSequence) + if(sequence < sock->unreliableReceiveSequence) { Con_DPrintf("Got a stale datagram\n"); ret = 0; break; } - if (sequence != sock->unreliableReceiveSequence) + if(sequence != sock->unreliableReceiveSequence) { count = sequence - sock->unreliableReceiveSequence; droppedDatagrams += count; @@ -356,24 +356,24 @@ int32_t Datagram_GetMessage (qsocket_t *sock) length -= NET_HEADERSIZE; - SZ_Clear (&net_message); - SZ_Write (&net_message, packetBuffer.data, length); + SZ_Clear(&net_message); + SZ_Write(&net_message, packetBuffer.data, length); ret = 2; break; } - if (flags & NETFLAG_ACK) + if(flags & NETFLAG_ACK) { - if (sequence != (sock->sendSequence - 1)) + if(sequence != (sock->sendSequence - 1)) { Con_DPrintf("Stale ACK received\n"); continue; } - if (sequence == sock->ackSequence) + if(sequence == sock->ackSequence) { sock->ackSequence++; - if (sock->ackSequence != sock->sendSequence) + if(sock->ackSequence != sock->sendSequence) Con_DPrintf("ack sequencing error\n"); } else @@ -382,9 +382,9 @@ int32_t Datagram_GetMessage (qsocket_t *sock) continue; } sock->sendMessageLength -= MAX_DATAGRAM; - if (sock->sendMessageLength > 0) + if(sock->sendMessageLength > 0) { - memmove (sock->sendMessage, sock->sendMessage + MAX_DATAGRAM, sock->sendMessageLength); + memmove(sock->sendMessage, sock->sendMessage + MAX_DATAGRAM, sock->sendMessageLength); sock->sendNext = true; } else @@ -395,13 +395,13 @@ int32_t Datagram_GetMessage (qsocket_t *sock) continue; } - if (flags & NETFLAG_DATA) + if(flags & NETFLAG_DATA) { packetBuffer.length = BigLong(NET_HEADERSIZE | NETFLAG_ACK); packetBuffer.sequence = BigLong(sequence); - sfunc.Write (sock->socket, (byte *)&packetBuffer, NET_HEADERSIZE, &readaddr); + sfunc.Write(sock->socket, (byte *)&packetBuffer, NET_HEADERSIZE, &readaddr); - if (sequence != sock->receiveSequence) + if(sequence != sock->receiveSequence) { receivedDuplicateCount++; continue; @@ -410,7 +410,7 @@ int32_t Datagram_GetMessage (qsocket_t *sock) length -= NET_HEADERSIZE; - if (flags & NETFLAG_EOM) + if(flags & NETFLAG_EOM) { SZ_Clear(&net_message); SZ_Write(&net_message, sock->receiveMessage, sock->receiveMessageLength); @@ -427,8 +427,8 @@ int32_t Datagram_GetMessage (qsocket_t *sock) } } - if (sock->sendNext) - SendMessageNext (sock); + if(sock->sendNext) + SendMessageNext(sock); return ret; } @@ -442,11 +442,11 @@ static void PrintStats(qsocket_t *s) Con_Printf("\n"); } -static void NET_Stats_f (void) +static void NET_Stats_f(void) { - qsocket_t *s; + qsocket_t *s; - if (Cmd_Argc () == 1) + if(Cmd_Argc() == 1) { Con_Printf("unreliable messages sent = %" PRIi32 "\n", unreliableMessagesSent); Con_Printf("unreliable messages recv = %" PRIi32 "\n", unreliableMessagesReceived); @@ -459,31 +459,31 @@ static void NET_Stats_f (void) Con_Printf("shortPacketCount = %" PRIi32 "\n", shortPacketCount); Con_Printf("droppedDatagrams = %" PRIi32 "\n", droppedDatagrams); } - else if (Q_strcmp(Cmd_Argv(1), "*") == 0) + else if(Q_strcmp(Cmd_Argv(1), "*") == 0) { - for (s = net_activeSockets; s; s = s->next) + for(s = net_activeSockets; s; s = s->next) PrintStats(s); - for (s = net_freeSockets; s; s = s->next) + for(s = net_freeSockets; s; s = s->next) PrintStats(s); } else { - for (s = net_activeSockets; s; s = s->next) + for(s = net_activeSockets; s; s = s->next) { - if (q_strcasecmp(Cmd_Argv(1), s->address) == 0) + if(q_strcasecmp(Cmd_Argv(1), s->address) == 0) break; } - if (s == NULL) + if(s == NULL) { - for (s = net_freeSockets; s; s = s->next) + for(s = net_freeSockets; s; s = s->next) { - if (q_strcasecmp(Cmd_Argv(1), s->address) == 0) + if(q_strcasecmp(Cmd_Argv(1), s->address) == 0) break; } } - if (s == NULL) + if(s == NULL) return; PrintStats(s); @@ -492,21 +492,21 @@ static void NET_Stats_f (void) // recognize ip:port (based on ProQuake) -static const char *Strip_Port (const char *host) +static const char *Strip_Port(const char *host) { - static char noport[MAX_QPATH]; - /* array size as in Host_Connect_f() */ - char *p; - int32_t port; + static char noport[MAX_QPATH]; + /* array size as in Host_Connect_f() */ + char *p; + int32_t port; - if (!host || !*host) + if(!host || !*host) return host; - q_strlcpy (noport, host, sizeof(noport)); - if ((p = Q_strrchr(noport, ':')) == NULL) + q_strlcpy(noport, host, sizeof(noport)); + if((p = Q_strrchr(noport, ':')) == NULL) return host; *p++ = '\0'; - port = Q_atoi (p); - if (port > 0 && port < 65536 && port != net_hostport) + port = Q_atoi(p); + if(port > 0 && port < 65536 && port != net_hostport) { net_hostport = port; Con_Printf("Port set to %" PRIi32 "\n", net_hostport); @@ -516,47 +516,47 @@ static const char *Strip_Port (const char *host) static bool testInProgress = false; -static int32_t testPollCount; -static int32_t testDriver; -static sys_socket_t testSocket; +static int32_t testPollCount; +static int32_t testDriver; +static sys_socket_t testSocket; -static void Test_Poll (void *); -static PollProcedure testPollProcedure = {NULL, 0.0, Test_Poll}; +static void Test_Poll(void *); +static PollProcedure testPollProcedure = {NULL, 0.0, Test_Poll}; -static void Test_Poll (void *unused) +static void Test_Poll(void *unused) { struct qsockaddr clientaddr; - int32_t control; - int32_t len; - char name[32]; - char address[64]; - int32_t colors; - int32_t frags; - int32_t connectTime; + int32_t control; + int32_t len; + char name[32]; + char address[64]; + int32_t colors; + int32_t frags; + int32_t connectTime; (void)unused; net_landriverlevel = testDriver; - while (1) + while(1) { - len = dfunc.Read (testSocket, net_message.data, net_message.maxsize, &clientaddr); - if (len < (int32_t) sizeof(int32_t)) + len = dfunc.Read(testSocket, net_message.data, net_message.maxsize, &clientaddr); + if(len < (int32_t) sizeof(int32_t)) break; net_message.cursize = len; - MSG_BeginReading (); + MSG_BeginReading(); control = BigLong(*((int32_t *)net_message.data)); MSG_ReadLong(); - if (control == -1) + if(control == -1) break; - if ((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) + if((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) break; - if ((control & NETFLAG_LENGTH_MASK) != len) + if((control & NETFLAG_LENGTH_MASK) != len) break; - if (MSG_ReadByte() != CCREP_PLAYER_INFO) + if(MSG_ReadByte() != CCREP_PLAYER_INFO) Sys_Error("Unexpected repsonse to Player Info request\n"); MSG_ReadByte(); /* playerNumber */ @@ -570,7 +570,7 @@ static void Test_Poll (void *unused) } testPollCount--; - if (testPollCount) + if(testPollCount) { SchedulePollProcedure(&testPollProcedure, 0.1); } @@ -581,25 +581,25 @@ static void Test_Poll (void *unused) } } -static void Test_f (void) +static void Test_f(void) { - const char *host; - int32_t n; - int32_t maxusers = MAX_SCOREBOARD; + const char *host; + int32_t n; + int32_t maxusers = MAX_SCOREBOARD; struct qsockaddr sendaddr; - if (testInProgress) + if(testInProgress) return; - host = Strip_Port (Cmd_Argv(1)); + host = Strip_Port(Cmd_Argv(1)); - if (host && hostCacheCount) + if(host && hostCacheCount) { - for (n = 0; n < hostCacheCount; n++) + for(n = 0; n < hostCacheCount; n++) { - if (q_strcasecmp (host, hostcache[n].name) == 0) + if(q_strcasecmp(host, hostcache[n].name) == 0) { - if (hostcache[n].driver != myDriverLevel) + if(hostcache[n].driver != myDriverLevel) continue; net_landriverlevel = hostcache[n].ldriver; maxusers = hostcache[n].maxusers; @@ -607,21 +607,21 @@ static void Test_f (void) break; } } - if (n < hostCacheCount) + if(n < hostCacheCount) goto JustDoIt; } - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) + for(net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { - if (!net_landrivers[net_landriverlevel].initialized) + if(!net_landrivers[net_landriverlevel].initialized) continue; // see if we can resolve the host name - if (dfunc.GetAddrFromName(host, &sendaddr) != -1) + if(dfunc.GetAddrFromName(host, &sendaddr) != -1) break; } - if (net_landriverlevel == net_numlandrivers) + if(net_landriverlevel == net_numlandrivers) { Con_Printf("Could not resolve %s\n", host); return; @@ -629,14 +629,14 @@ static void Test_f (void) JustDoIt: testSocket = dfunc.Open_Socket(0); - if (testSocket == INVALID_SOCKET) + if(testSocket == INVALID_SOCKET) return; testInProgress = true; testPollCount = 20; testDriver = net_landriverlevel; - for (n = 0; n < maxusers; n++) + for(n = 0; n < maxusers; n++) { SZ_Clear(&net_message); // save space for the header, filled in later @@ -644,7 +644,7 @@ JustDoIt: MSG_WriteByte(&net_message, CCREQ_PLAYER_INFO); MSG_WriteByte(&net_message, n); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (testSocket, net_message.data, net_message.cursize, &sendaddr); + dfunc.Write(testSocket, net_message.data, net_message.cursize, &sendaddr); } SZ_Clear(&net_message); SchedulePollProcedure(&testPollProcedure, 0.1); @@ -652,46 +652,46 @@ JustDoIt: static bool test2InProgress = false; -static int32_t test2Driver; -static sys_socket_t test2Socket; +static int32_t test2Driver; +static sys_socket_t test2Socket; -static void Test2_Poll (void *); -static PollProcedure test2PollProcedure = {NULL, 0.0, Test2_Poll}; +static void Test2_Poll(void *); +static PollProcedure test2PollProcedure = {NULL, 0.0, Test2_Poll}; -static void Test2_Poll (void *unused) +static void Test2_Poll(void *unused) { struct qsockaddr clientaddr; - int32_t control; - int32_t len; - char name[256]; - char value[256]; + int32_t control; + int32_t len; + char name[256]; + char value[256]; (void)unused; net_landriverlevel = test2Driver; name[0] = 0; - len = dfunc.Read (test2Socket, net_message.data, net_message.maxsize, &clientaddr); - if (len < (int32_t) sizeof(int32_t)) + len = dfunc.Read(test2Socket, net_message.data, net_message.maxsize, &clientaddr); + if(len < (int32_t) sizeof(int32_t)) goto Reschedule; net_message.cursize = len; - MSG_BeginReading (); + MSG_BeginReading(); control = BigLong(*((int32_t *)net_message.data)); MSG_ReadLong(); - if (control == -1) + if(control == -1) goto Error; - if ((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) + if((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) goto Error; - if ((control & NETFLAG_LENGTH_MASK) != len) + if((control & NETFLAG_LENGTH_MASK) != len) goto Error; - if (MSG_ReadByte() != CCREP_RULE_INFO) + if(MSG_ReadByte() != CCREP_RULE_INFO) goto Error; Q_strcpy(name, MSG_ReadString()); - if (name[0] == 0) + if(name[0] == 0) goto Done; Q_strcpy(value, MSG_ReadString()); @@ -703,7 +703,7 @@ static void Test2_Poll (void *unused) MSG_WriteByte(&net_message, CCREQ_RULE_INFO); MSG_WriteString(&net_message, name); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (test2Socket, net_message.data, net_message.cursize, &clientaddr); + dfunc.Write(test2Socket, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); Reschedule: @@ -718,24 +718,24 @@ Done: return; } -static void Test2_f (void) +static void Test2_f(void) { - const char *host; - int32_t n; + const char *host; + int32_t n; struct qsockaddr sendaddr; - if (test2InProgress) + if(test2InProgress) return; - host = Strip_Port (Cmd_Argv(1)); + host = Strip_Port(Cmd_Argv(1)); - if (host && hostCacheCount) + if(host && hostCacheCount) { - for (n = 0; n < hostCacheCount; n++) + for(n = 0; n < hostCacheCount; n++) { - if (q_strcasecmp (host, hostcache[n].name) == 0) + if(q_strcasecmp(host, hostcache[n].name) == 0) { - if (hostcache[n].driver != myDriverLevel) + if(hostcache[n].driver != myDriverLevel) continue; net_landriverlevel = hostcache[n].ldriver; Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); @@ -743,21 +743,21 @@ static void Test2_f (void) } } - if (n < hostCacheCount) + if(n < hostCacheCount) goto JustDoIt; } - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) + for(net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { - if (!net_landrivers[net_landriverlevel].initialized) + if(!net_landrivers[net_landriverlevel].initialized) continue; // see if we can resolve the host name - if (dfunc.GetAddrFromName(host, &sendaddr) != -1) + if(dfunc.GetAddrFromName(host, &sendaddr) != -1) break; } - if (net_landriverlevel == net_numlandrivers) + if(net_landriverlevel == net_numlandrivers) { Con_Printf("Could not resolve %s\n", host); return; @@ -765,7 +765,7 @@ static void Test2_f (void) JustDoIt: test2Socket = dfunc.Open_Socket(0); - if (test2Socket == INVALID_SOCKET) + if(test2Socket == INVALID_SOCKET) return; test2InProgress = true; @@ -777,16 +777,16 @@ JustDoIt: MSG_WriteByte(&net_message, CCREQ_RULE_INFO); MSG_WriteString(&net_message, ""); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (test2Socket, net_message.data, net_message.cursize, &sendaddr); + dfunc.Write(test2Socket, net_message.data, net_message.cursize, &sendaddr); SZ_Clear(&net_message); SchedulePollProcedure(&test2PollProcedure, 0.05); } -int32_t Datagram_Init (void) +int32_t Datagram_Init(void) { - int32_t i, num_inited; - sys_socket_t csock; + int32_t i, num_inited; + sys_socket_t csock; #ifdef BAN_TEST banAddr.s_addr = INADDR_ANY; @@ -794,109 +794,109 @@ int32_t Datagram_Init (void) #endif myDriverLevel = net_driverlevel; - Cmd_AddCommand ("net_stats", NET_Stats_f); + Cmd_AddCommand("net_stats", NET_Stats_f); - if (safemode || COM_CheckParm("-nolan")) + if(safemode || COM_CheckParm("-nolan")) return -1; num_inited = 0; - for (i = 0; i < net_numlandrivers; i++) + for(i = 0; i < net_numlandrivers; i++) { - csock = net_landrivers[i].Init (); - if (csock == INVALID_SOCKET) + csock = net_landrivers[i].Init(); + if(csock == INVALID_SOCKET) continue; net_landrivers[i].initialized = true; net_landrivers[i].controlSock = csock; num_inited++; } - if (num_inited == 0) + if(num_inited == 0) return -1; #ifdef BAN_TEST - Cmd_AddCommand ("ban", NET_Ban_f); + Cmd_AddCommand("ban", NET_Ban_f); #endif - Cmd_AddCommand ("test", Test_f); - Cmd_AddCommand ("test2", Test2_f); + Cmd_AddCommand("test", Test_f); + Cmd_AddCommand("test2", Test2_f); return 0; } -void Datagram_Shutdown (void) +void Datagram_Shutdown(void) { int32_t i; // // shutdown the lan drivers // - for (i = 0; i < net_numlandrivers; i++) + for(i = 0; i < net_numlandrivers; i++) { - if (net_landrivers[i].initialized) + if(net_landrivers[i].initialized) { - net_landrivers[i].Shutdown (); + net_landrivers[i].Shutdown(); net_landrivers[i].initialized = false; } } } -void Datagram_Close (qsocket_t *sock) +void Datagram_Close(qsocket_t *sock) { sfunc.Close_Socket(sock->socket); } -void Datagram_Listen (bool state) +void Datagram_Listen(bool state) { int32_t i; - for (i = 0; i < net_numlandrivers; i++) + for(i = 0; i < net_numlandrivers; i++) { - if (net_landrivers[i].initialized) - net_landrivers[i].Listen (state); + if(net_landrivers[i].initialized) + net_landrivers[i].Listen(state); } } -static qsocket_t *_Datagram_CheckNewConnections (void) +static qsocket_t *_Datagram_CheckNewConnections(void) { struct qsockaddr clientaddr; struct qsockaddr newaddr; - sys_socket_t newsock; - sys_socket_t acceptsock; - qsocket_t *sock; - qsocket_t *s; - int32_t len; - int32_t command; - int32_t control; - int32_t ret; + sys_socket_t newsock; + sys_socket_t acceptsock; + qsocket_t *sock; + qsocket_t *s; + int32_t len; + int32_t command; + int32_t control; + int32_t ret; acceptsock = dfunc.CheckNewConnections(); - if (acceptsock == INVALID_SOCKET) + if(acceptsock == INVALID_SOCKET) return NULL; SZ_Clear(&net_message); - len = dfunc.Read (acceptsock, net_message.data, net_message.maxsize, &clientaddr); - if (len < (int32_t) sizeof(int32_t)) + len = dfunc.Read(acceptsock, net_message.data, net_message.maxsize, &clientaddr); + if(len < (int32_t) sizeof(int32_t)) return NULL; net_message.cursize = len; - MSG_BeginReading (); + MSG_BeginReading(); control = BigLong(*((int32_t *)net_message.data)); MSG_ReadLong(); - if (control == -1) + if(control == -1) return NULL; - if ((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) + if((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) return NULL; - if ((control & NETFLAG_LENGTH_MASK) != len) + if((control & NETFLAG_LENGTH_MASK) != len) return NULL; command = MSG_ReadByte(); - if (command == CCREQ_SERVER_INFO) + if(command == CCREQ_SERVER_INFO) { - if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) + if(Q_strcmp(MSG_ReadString(), "QUAKE") != 0) return NULL; SZ_Clear(&net_message); @@ -911,32 +911,32 @@ static qsocket_t *_Datagram_CheckNewConnections (void) MSG_WriteByte(&net_message, svs.maxclients); MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } - if (command == CCREQ_PLAYER_INFO) + if(command == CCREQ_PLAYER_INFO) { - int32_t playerNumber; - int32_t activeNumber; - int32_t clientNumber; - client_t *client; + int32_t playerNumber; + int32_t activeNumber; + int32_t clientNumber; + client_t *client; playerNumber = MSG_ReadByte(); activeNumber = -1; - for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++) + for(clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++) { - if (client->active) + if(client->active) { activeNumber++; - if (activeNumber == playerNumber) + if(activeNumber == playerNumber) break; } } - if (clientNumber == svs.maxclients) + if(clientNumber == svs.maxclients) return NULL; SZ_Clear(&net_message); @@ -950,45 +950,45 @@ static qsocket_t *_Datagram_CheckNewConnections (void) MSG_WriteLong(&net_message, (int32_t)(net_time - client->netconnection->connecttime)); MSG_WriteString(&net_message, client->netconnection->address); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } - if (command == CCREQ_RULE_INFO) + if(command == CCREQ_RULE_INFO) { - const char *prevCvarName; - cvar_t *var; + const char *prevCvarName; + cvar_t *var; // find the search start location prevCvarName = MSG_ReadString(); - var = Cvar_FindVarAfter (prevCvarName, CVAR_SERVERINFO); + var = Cvar_FindVarAfter(prevCvarName, CVAR_SERVERINFO); // send the response SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREP_RULE_INFO); - if (var) + if(var) { MSG_WriteString(&net_message, var->name); MSG_WriteString(&net_message, var->string); } *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } - if (command != CCREQ_CONNECT) + if(command != CCREQ_CONNECT) return NULL; - if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) + if(Q_strcmp(MSG_ReadString(), "QUAKE") != 0) return NULL; - if (MSG_ReadByte() != NET_PROTOCOL_VERSION) + if(MSG_ReadByte() != NET_PROTOCOL_VERSION) { SZ_Clear(&net_message); // save space for the header, filled in later @@ -996,18 +996,18 @@ static qsocket_t *_Datagram_CheckNewConnections (void) MSG_WriteByte(&net_message, CCREP_REJECT); MSG_WriteString(&net_message, "Incompatible version.\n"); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } #ifdef BAN_TEST // check for a ban - if (clientaddr.qsa_family == AF_INET) + if(clientaddr.qsa_family == AF_INET) { - in_addr_t testAddr; + in_addr_t testAddr; testAddr = ((struct sockaddr_in *)&clientaddr)->sin_addr.s_addr; - if ((testAddr & banMask.s_addr) == banAddr.s_addr) + if((testAddr & banMask.s_addr) == banAddr.s_addr) { SZ_Clear(&net_message); // save space for the header, filled in later @@ -1015,7 +1015,7 @@ static qsocket_t *_Datagram_CheckNewConnections (void) MSG_WriteByte(&net_message, CCREP_REJECT); MSG_WriteString(&net_message, "You have been banned.\n"); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } @@ -1023,15 +1023,15 @@ static qsocket_t *_Datagram_CheckNewConnections (void) #endif // see if this guy is already connected - for (s = net_activeSockets; s; s = s->next) + for(s = net_activeSockets; s; s = s->next) { - if (s->driver != net_driverlevel) + if(s->driver != net_driverlevel) continue; ret = dfunc.AddrCompare(&clientaddr, &s->addr); - if (ret >= 0) + if(ret >= 0) { // is this a duplicate connection reqeust? - if (ret == 0 && net_time - s->connecttime < 2.0) + if(ret == 0 && net_time - s->connecttime < 2.0) { // yes, so send a duplicate reply SZ_Clear(&net_message); @@ -1041,7 +1041,7 @@ static qsocket_t *_Datagram_CheckNewConnections (void) dfunc.GetSocketAddr(s->socket, &newaddr); MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr)); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } @@ -1053,8 +1053,8 @@ static qsocket_t *_Datagram_CheckNewConnections (void) } // allocate a QSocket - sock = NET_NewQSocket (); - if (sock == NULL) + sock = NET_NewQSocket(); + if(sock == NULL) { // no room; try to let him know SZ_Clear(&net_message); @@ -1063,21 +1063,21 @@ static qsocket_t *_Datagram_CheckNewConnections (void) MSG_WriteByte(&net_message, CCREP_REJECT); MSG_WriteString(&net_message, "Server is full.\n"); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } // allocate a network socket newsock = dfunc.Open_Socket(0); - if (newsock == INVALID_SOCKET) + if(newsock == INVALID_SOCKET) { NET_FreeQSocket(sock); return NULL; } // connect to the client - if (dfunc.Connect (newsock, &clientaddr) == -1) + if(dfunc.Connect(newsock, &clientaddr) == -1) { dfunc.Close_Socket(newsock); NET_FreeQSocket(sock); @@ -1099,21 +1099,21 @@ static qsocket_t *_Datagram_CheckNewConnections (void) MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr)); // MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr)); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); + dfunc.Write(acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return sock; } -qsocket_t *Datagram_CheckNewConnections (void) +qsocket_t *Datagram_CheckNewConnections(void) { qsocket_t *ret = NULL; - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) + for(net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { - if (net_landrivers[net_landriverlevel].initialized) + if(net_landrivers[net_landriverlevel].initialized) { - if ((ret = _Datagram_CheckNewConnections ()) != NULL) + if((ret = _Datagram_CheckNewConnections()) != NULL) break; } } @@ -1121,17 +1121,17 @@ qsocket_t *Datagram_CheckNewConnections (void) } -static void _Datagram_SearchForHosts (bool xmit) +static void _Datagram_SearchForHosts(bool xmit) { - int32_t ret; - int32_t n; - int32_t i; + int32_t ret; + int32_t n; + int32_t i; struct qsockaddr readaddr; struct qsockaddr myaddr; - int32_t control; + int32_t control; - dfunc.GetSocketAddr (dfunc.controlSock, &myaddr); - if (xmit) + dfunc.GetSocketAddr(dfunc.controlSock, &myaddr); + if(xmit) { SZ_Clear(&net_message); // save space for the header, filled in later @@ -1144,43 +1144,43 @@ static void _Datagram_SearchForHosts (bool xmit) SZ_Clear(&net_message); } - while ((ret = dfunc.Read (dfunc.controlSock, net_message.data, net_message.maxsize, &readaddr)) > 0) + while((ret = dfunc.Read(dfunc.controlSock, net_message.data, net_message.maxsize, &readaddr)) > 0) { - if (ret < (int32_t) sizeof(int32_t)) + if(ret < (int32_t) sizeof(int32_t)) continue; net_message.cursize = ret; // don't answer our own query - if (dfunc.AddrCompare(&readaddr, &myaddr) >= 0) + if(dfunc.AddrCompare(&readaddr, &myaddr) >= 0) continue; // is the cache full? - if (hostCacheCount == HOSTCACHESIZE) + if(hostCacheCount == HOSTCACHESIZE) continue; - MSG_BeginReading (); + MSG_BeginReading(); control = BigLong(*((int32_t *)net_message.data)); MSG_ReadLong(); - if (control == -1) + if(control == -1) continue; - if ((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) + if((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) continue; - if ((control & NETFLAG_LENGTH_MASK) != ret) + if((control & NETFLAG_LENGTH_MASK) != ret) continue; - if (MSG_ReadByte() != CCREP_SERVER_INFO) + if(MSG_ReadByte() != CCREP_SERVER_INFO) continue; dfunc.GetAddrFromName(MSG_ReadString(), &readaddr); // search the cache for this server - for (n = 0; n < hostCacheCount; n++) + for(n = 0; n < hostCacheCount; n++) { - if (dfunc.AddrCompare(&readaddr, &hostcache[n].addr) == 0) + if(dfunc.AddrCompare(&readaddr, &hostcache[n].addr) == 0) break; } // is it already there? - if (n < hostCacheCount) + if(n < hostCacheCount) continue; // add it @@ -1189,7 +1189,7 @@ static void _Datagram_SearchForHosts (bool xmit) Q_strcpy(hostcache[n].map, MSG_ReadString()); hostcache[n].users = MSG_ReadByte(); hostcache[n].maxusers = MSG_ReadByte(); - if (MSG_ReadByte() != NET_PROTOCOL_VERSION) + if(MSG_ReadByte() != NET_PROTOCOL_VERSION) { Q_strcpy(hostcache[n].cname, hostcache[n].name); hostcache[n].cname[14] = 0; @@ -1202,20 +1202,20 @@ static void _Datagram_SearchForHosts (bool xmit) Q_strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr)); // check for a name conflict - for (i = 0; i < hostCacheCount; i++) + for(i = 0; i < hostCacheCount; i++) { - if (i == n) + if(i == n) continue; - if (q_strcasecmp (hostcache[n].name, hostcache[i].name) == 0) + if(q_strcasecmp(hostcache[n].name, hostcache[i].name) == 0) { i = Q_strlen(hostcache[n].name); - if (i < 15 && hostcache[n].name[i-1] > '8') + if(i < 15 && hostcache[n].name[i - 1] > '8') { hostcache[n].name[i] = '0'; - hostcache[n].name[i+1] = 0; + hostcache[n].name[i + 1] = 0; } else - hostcache[n].name[i-1]++; + hostcache[n].name[i - 1]++; i = -1; } @@ -1223,57 +1223,57 @@ static void _Datagram_SearchForHosts (bool xmit) } } -void Datagram_SearchForHosts (bool xmit) +void Datagram_SearchForHosts(bool xmit) { - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) + for(net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { - if (hostCacheCount == HOSTCACHESIZE) + if(hostCacheCount == HOSTCACHESIZE) break; - if (net_landrivers[net_landriverlevel].initialized) - _Datagram_SearchForHosts (xmit); + if(net_landrivers[net_landriverlevel].initialized) + _Datagram_SearchForHosts(xmit); } } -static qsocket_t *_Datagram_Connect (const char *host) +static qsocket_t *_Datagram_Connect(const char *host) { struct qsockaddr sendaddr; struct qsockaddr readaddr; - qsocket_t *sock; - sys_socket_t newsock; - int32_t ret; - int32_t reps; - double start_time; - int32_t control; - const char *reason; + qsocket_t *sock; + sys_socket_t newsock; + int32_t ret; + int32_t reps; + double start_time; + int32_t control; + const char *reason; // see if we can resolve the host name - if (dfunc.GetAddrFromName(host, &sendaddr) == -1) + if(dfunc.GetAddrFromName(host, &sendaddr) == -1) { Con_Printf("Could not resolve %s\n", host); return NULL; } - newsock = dfunc.Open_Socket (0); - if (newsock == INVALID_SOCKET) + newsock = dfunc.Open_Socket(0); + if(newsock == INVALID_SOCKET) return NULL; - sock = NET_NewQSocket (); - if (sock == NULL) + sock = NET_NewQSocket(); + if(sock == NULL) goto ErrorReturn2; sock->socket = newsock; sock->landriver = net_landriverlevel; // connect to the host - if (dfunc.Connect (newsock, &sendaddr) == -1) + if(dfunc.Connect(newsock, &sendaddr) == -1) goto ErrorReturn; // send the connection request Con_Printf("trying...\n"); - SCR_UpdateScreen (); + SCR_UpdateScreen(); start_time = net_time; - for (reps = 0; reps < 3; reps++) + for(reps = 0; reps < 3; reps++) { SZ_Clear(&net_message); // save space for the header, filled in later @@ -1282,64 +1282,64 @@ static qsocket_t *_Datagram_Connect (const char *host) MSG_WriteString(&net_message, "QUAKE"); MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); *((int32_t *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - dfunc.Write (newsock, net_message.data, net_message.cursize, &sendaddr); + dfunc.Write(newsock, net_message.data, net_message.cursize, &sendaddr); SZ_Clear(&net_message); do { - ret = dfunc.Read (newsock, net_message.data, net_message.maxsize, &readaddr); + ret = dfunc.Read(newsock, net_message.data, net_message.maxsize, &readaddr); // if we got something, validate it - if (ret > 0) + if(ret > 0) { // is it from the right place? - if (sfunc.AddrCompare(&readaddr, &sendaddr) != 0) + if(sfunc.AddrCompare(&readaddr, &sendaddr) != 0) { Con_Printf("wrong reply address\n"); - Con_Printf("Expected: %s | %s\n", dfunc.AddrToString (&sendaddr), StrAddr(&sendaddr)); - Con_Printf("Received: %s | %s\n", dfunc.AddrToString (&readaddr), StrAddr(&readaddr)); - SCR_UpdateScreen (); + Con_Printf("Expected: %s | %s\n", dfunc.AddrToString(&sendaddr), StrAddr(&sendaddr)); + Con_Printf("Received: %s | %s\n", dfunc.AddrToString(&readaddr), StrAddr(&readaddr)); + SCR_UpdateScreen(); ret = 0; continue; } - if (ret < (int32_t) sizeof(int32_t)) + if(ret < (int32_t) sizeof(int32_t)) { ret = 0; continue; } net_message.cursize = ret; - MSG_BeginReading (); + MSG_BeginReading(); control = BigLong(*((int32_t *)net_message.data)); MSG_ReadLong(); - if (control == -1) + if(control == -1) { ret = 0; continue; } - if ((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) + if((control & (~NETFLAG_LENGTH_MASK)) != (int32_t)NETFLAG_CTL) { ret = 0; continue; } - if ((control & NETFLAG_LENGTH_MASK) != ret) + if((control & NETFLAG_LENGTH_MASK) != ret) { ret = 0; continue; } } } - while (ret == 0 && (SetNetTime() - start_time) < 2.5); + while(ret == 0 && (SetNetTime() - start_time) < 2.5); - if (ret) + if(ret) break; Con_Printf("still trying...\n"); - SCR_UpdateScreen (); + SCR_UpdateScreen(); start_time = SetNetTime(); } - if (ret == 0) + if(ret == 0) { reason = "No Response"; Con_Printf("%s\n", reason); @@ -1347,7 +1347,7 @@ static qsocket_t *_Datagram_Connect (const char *host) goto ErrorReturn; } - if (ret == -1) + if(ret == -1) { reason = "Network Error"; Con_Printf("%s\n", reason); @@ -1356,7 +1356,7 @@ static qsocket_t *_Datagram_Connect (const char *host) } ret = MSG_ReadByte(); - if (ret == CCREP_REJECT) + if(ret == CCREP_REJECT) { reason = MSG_ReadString(); Con_Printf("%s\n", reason); @@ -1364,10 +1364,10 @@ static qsocket_t *_Datagram_Connect (const char *host) goto ErrorReturn; } - if (ret == CCREP_ACCEPT) + if(ret == CCREP_ACCEPT) { Q_memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr)); - dfunc.SetSocketPort (&sock->addr, MSG_ReadLong()); + dfunc.SetSocketPort(&sock->addr, MSG_ReadLong()); } else { @@ -1377,13 +1377,13 @@ static qsocket_t *_Datagram_Connect (const char *host) goto ErrorReturn; } - dfunc.GetNameFromAddr (&sendaddr, sock->address); + dfunc.GetNameFromAddr(&sendaddr, sock->address); - Con_Printf ("Connection accepted\n"); + Con_Printf("Connection accepted\n"); sock->lastMessageTime = SetNetTime(); // switch the connection to the specified address - if (dfunc.Connect (newsock, &sock->addr) == -1) + if(dfunc.Connect(newsock, &sock->addr) == -1) { reason = "Connect to Game failed"; Con_Printf("%s\n", reason); @@ -1398,7 +1398,7 @@ ErrorReturn: NET_FreeQSocket(sock); ErrorReturn2: dfunc.Close_Socket(newsock); - if (m_return_onerror) + if(m_return_onerror) { IN_Deactivate(modestate == MS_WINDOWED); key_dest = key_menu; @@ -1408,16 +1408,16 @@ ErrorReturn2: return NULL; } -qsocket_t *Datagram_Connect (const char *host) +qsocket_t *Datagram_Connect(const char *host) { qsocket_t *ret = NULL; - host = Strip_Port (host); - for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) + host = Strip_Port(host); + for(net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { - if (net_landrivers[net_landriverlevel].initialized) + if(net_landrivers[net_landriverlevel].initialized) { - if ((ret = _Datagram_Connect (host)) != NULL) + if((ret = _Datagram_Connect(host)) != NULL) break; } } diff --git a/source/net_dgrm.h b/source/net_dgrm.h index 32517c6..825cee2 100644 --- a/source/net_dgrm.h +++ b/source/net_dgrm.h @@ -22,18 +22,18 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef __NET_DATAGRAM_H #define __NET_DATAGRAM_H -int32_t Datagram_Init (void); -void Datagram_Listen (bool state); -void Datagram_SearchForHosts (bool xmit); -qsocket_t *Datagram_Connect (const char *host); -qsocket_t *Datagram_CheckNewConnections (void); -int32_t Datagram_GetMessage (qsocket_t *sock); -int32_t Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data); -int32_t Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data); -bool Datagram_CanSendMessage (qsocket_t *sock); -bool Datagram_CanSendUnreliableMessage (qsocket_t *sock); -void Datagram_Close (qsocket_t *sock); -void Datagram_Shutdown (void); +int32_t Datagram_Init(void); +void Datagram_Listen(bool state); +void Datagram_SearchForHosts(bool xmit); +qsocket_t *Datagram_Connect(const char *host); +qsocket_t *Datagram_CheckNewConnections(void); +int32_t Datagram_GetMessage(qsocket_t *sock); +int32_t Datagram_SendMessage(qsocket_t *sock, sizebuf_t *data); +int32_t Datagram_SendUnreliableMessage(qsocket_t *sock, sizebuf_t *data); +bool Datagram_CanSendMessage(qsocket_t *sock); +bool Datagram_CanSendUnreliableMessage(qsocket_t *sock); +void Datagram_Close(qsocket_t *sock); +void Datagram_Shutdown(void); -#endif /* __NET_DATAGRAM_H */ +#endif /* __NET_DATAGRAM_H */ diff --git a/source/net_loop.c b/source/net_loop.c index 8ca4bfb..b66c0e3 100644 --- a/source/net_loop.c +++ b/source/net_loop.c @@ -26,38 +26,38 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "net_defs.h" #include "net_loop.h" -static bool localconnectpending = false; -static qsocket_t *loop_client = NULL; -static qsocket_t *loop_server = NULL; +static bool localconnectpending = false; +static qsocket_t *loop_client = NULL; +static qsocket_t *loop_server = NULL; -int32_t Loop_Init (void) +int32_t Loop_Init(void) { - if (cls.state == ca_dedicated) + if(cls.state == ca_dedicated) return -1; return 0; } -void Loop_Shutdown (void) +void Loop_Shutdown(void) { } -void Loop_Listen (bool state) +void Loop_Listen(bool state) { (void)state; } -void Loop_SearchForHosts (bool xmit) +void Loop_SearchForHosts(bool xmit) { (void)xmit; - if (!sv.active) + if(!sv.active) return; hostCacheCount = 1; - if (Q_strcmp(hostname.string, "UNNAMED") == 0) + if(Q_strcmp(hostname.string, "UNNAMED") == 0) Q_strcpy(hostcache[0].name, "local"); else Q_strcpy(hostcache[0].name, hostname.string); @@ -69,34 +69,34 @@ void Loop_SearchForHosts (bool xmit) } -qsocket_t *Loop_Connect (const char *host) +qsocket_t *Loop_Connect(const char *host) { - if (Q_strcmp(host,"local") != 0) + if(Q_strcmp(host, "local") != 0) return NULL; localconnectpending = true; - if (!loop_client) + if(!loop_client) { - if ((loop_client = NET_NewQSocket ()) == NULL) + if((loop_client = NET_NewQSocket()) == NULL) { Con_Printf("Loop_Connect: no qsocket available\n"); return NULL; } - Q_strcpy (loop_client->address, "localhost"); + Q_strcpy(loop_client->address, "localhost"); } loop_client->receiveMessageLength = 0; loop_client->sendMessageLength = 0; loop_client->canSend = true; - if (!loop_server) + if(!loop_server) { - if ((loop_server = NET_NewQSocket ()) == NULL) + if((loop_server = NET_NewQSocket()) == NULL) { Con_Printf("Loop_Connect: no qsocket available\n"); return NULL; } - Q_strcpy (loop_server->address, "LOCAL"); + Q_strcpy(loop_server->address, "LOCAL"); } loop_server->receiveMessageLength = 0; loop_server->sendMessageLength = 0; @@ -109,9 +109,9 @@ qsocket_t *Loop_Connect (const char *host) } -qsocket_t *Loop_CheckNewConnections (void) +qsocket_t *Loop_CheckNewConnections(void) { - if (!localconnectpending) + if(!localconnectpending) return NULL; localconnectpending = false; @@ -131,44 +131,44 @@ static int32_t IntAlign(int32_t value) } -int32_t Loop_GetMessage (qsocket_t *sock) +int32_t Loop_GetMessage(qsocket_t *sock) { - int32_t ret; - int32_t length; + int32_t ret; + int32_t length; - if (sock->receiveMessageLength == 0) + if(sock->receiveMessageLength == 0) return 0; ret = sock->receiveMessage[0]; length = sock->receiveMessage[1] + (sock->receiveMessage[2] << 8); // alignment byte skipped here - SZ_Clear (&net_message); - SZ_Write (&net_message, &sock->receiveMessage[4], length); + SZ_Clear(&net_message); + SZ_Write(&net_message, &sock->receiveMessage[4], length); length = IntAlign(length + 4); sock->receiveMessageLength -= length; - if (sock->receiveMessageLength) - memmove (sock->receiveMessage, &sock->receiveMessage[length], sock->receiveMessageLength); + if(sock->receiveMessageLength) + memmove(sock->receiveMessage, &sock->receiveMessage[length], sock->receiveMessageLength); - if (sock->driverdata && ret == 1) + if(sock->driverdata && ret == 1) ((qsocket_t *)sock->driverdata)->canSend = true; return ret; } -int32_t Loop_SendMessage (qsocket_t *sock, sizebuf_t *data) +int32_t Loop_SendMessage(qsocket_t *sock, sizebuf_t *data) { byte *buffer; int32_t *bufferLength; - if (!sock->driverdata) + if(!sock->driverdata) return -1; bufferLength = &((qsocket_t *)sock->driverdata)->receiveMessageLength; - if ((*bufferLength + data->cursize + 4) > NET_MAXMESSAGE) + if((*bufferLength + data->cursize + 4) > NET_MAXMESSAGE) Sys_Error("Loop_SendMessage: overflow"); buffer = ((qsocket_t *)sock->driverdata)->receiveMessage + *bufferLength; @@ -192,17 +192,17 @@ int32_t Loop_SendMessage (qsocket_t *sock, sizebuf_t *data) } -int32_t Loop_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) +int32_t Loop_SendUnreliableMessage(qsocket_t *sock, sizebuf_t *data) { byte *buffer; int32_t *bufferLength; - if (!sock->driverdata) + if(!sock->driverdata) return -1; bufferLength = &((qsocket_t *)sock->driverdata)->receiveMessageLength; - if ((*bufferLength + data->cursize + sizeof(byte) + sizeof(int16_t)) > NET_MAXMESSAGE) + if((*bufferLength + data->cursize + sizeof(byte) + sizeof(int16_t)) > NET_MAXMESSAGE) return 0; buffer = ((qsocket_t *)sock->driverdata)->receiveMessage + *bufferLength; @@ -224,29 +224,29 @@ int32_t Loop_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) } -bool Loop_CanSendMessage (qsocket_t *sock) +bool Loop_CanSendMessage(qsocket_t *sock) { - if (!sock->driverdata) + if(!sock->driverdata) return false; return sock->canSend; } -bool Loop_CanSendUnreliableMessage (qsocket_t *sock) +bool Loop_CanSendUnreliableMessage(qsocket_t *sock) { (void)sock; return true; } -void Loop_Close (qsocket_t *sock) +void Loop_Close(qsocket_t *sock) { - if (sock->driverdata) + if(sock->driverdata) ((qsocket_t *)sock->driverdata)->driverdata = NULL; sock->receiveMessageLength = 0; sock->sendMessageLength = 0; sock->canSend = true; - if (sock == loop_client) + if(sock == loop_client) loop_client = NULL; else loop_server = NULL; diff --git a/source/net_loop.h b/source/net_loop.h index def5c93..77d60cd 100644 --- a/source/net_loop.h +++ b/source/net_loop.h @@ -23,18 +23,18 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define __NET_LOOP_H // net_loop.h -int32_t Loop_Init (void); -void Loop_Listen (bool state); -void Loop_SearchForHosts (bool xmit); -qsocket_t *Loop_Connect (const char *host); -qsocket_t *Loop_CheckNewConnections (void); -int32_t Loop_GetMessage (qsocket_t *sock); -int32_t Loop_SendMessage (qsocket_t *sock, sizebuf_t *data); -int32_t Loop_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data); -bool Loop_CanSendMessage (qsocket_t *sock); -bool Loop_CanSendUnreliableMessage (qsocket_t *sock); -void Loop_Close (qsocket_t *sock); -void Loop_Shutdown (void); +int32_t Loop_Init(void); +void Loop_Listen(bool state); +void Loop_SearchForHosts(bool xmit); +qsocket_t *Loop_Connect(const char *host); +qsocket_t *Loop_CheckNewConnections(void); +int32_t Loop_GetMessage(qsocket_t *sock); +int32_t Loop_SendMessage(qsocket_t *sock, sizebuf_t *data); +int32_t Loop_SendUnreliableMessage(qsocket_t *sock, sizebuf_t *data); +bool Loop_CanSendMessage(qsocket_t *sock); +bool Loop_CanSendUnreliableMessage(qsocket_t *sock); +void Loop_Close(qsocket_t *sock); +void Loop_Shutdown(void); -#endif /* __NET_LOOP_H */ +#endif /* __NET_LOOP_H */ diff --git a/source/net_main.c b/source/net_main.c index 2ff1579..9285c7e 100644 --- a/source/net_main.c +++ b/source/net_main.c @@ -25,53 +25,53 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" #include "net_defs.h" -qsocket_t *net_activeSockets = NULL; -qsocket_t *net_freeSockets = NULL; -int32_t net_numsockets = 0; +qsocket_t *net_activeSockets = NULL; +qsocket_t *net_freeSockets = NULL; +int32_t net_numsockets = 0; -bool ipxAvailable = false; -bool tcpipAvailable = false; +bool ipxAvailable = false; +bool tcpipAvailable = false; -int32_t net_hostport; -int32_t DEFAULTnet_hostport = 26000; +int32_t net_hostport; +int32_t DEFAULTnet_hostport = 26000; -char my_ipx_address[NET_NAMELEN]; -char my_tcpip_address[NET_NAMELEN]; +char my_ipx_address[NET_NAMELEN]; +char my_tcpip_address[NET_NAMELEN]; -static bool listening = false; +static bool listening = false; -bool slistInProgress = false; -bool slistSilent = false; -bool slistLocal = true; -static double slistStartTime; -static int32_t slistLastShown; +bool slistInProgress = false; +bool slistSilent = false; +bool slistLocal = true; +static double slistStartTime; +static int32_t slistLastShown; -static void Slist_Send (void *); -static void Slist_Poll (void *); -static PollProcedure slistSendProcedure = {NULL, 0.0, Slist_Send}; -static PollProcedure slistPollProcedure = {NULL, 0.0, Slist_Poll}; +static void Slist_Send(void *); +static void Slist_Poll(void *); +static PollProcedure slistSendProcedure = {NULL, 0.0, Slist_Send}; +static PollProcedure slistPollProcedure = {NULL, 0.0, Slist_Poll}; -sizebuf_t net_message; -int32_t net_activeconnections = 0; +sizebuf_t net_message; +int32_t net_activeconnections = 0; -int32_t messagesSent = 0; -int32_t messagesReceived = 0; -int32_t unreliableMessagesSent = 0; -int32_t unreliableMessagesReceived = 0; +int32_t messagesSent = 0; +int32_t messagesReceived = 0; +int32_t unreliableMessagesSent = 0; +int32_t unreliableMessagesReceived = 0; -static cvar_t net_messagetimeout = {"net_messagetimeout","300",CVAR_NONE}; -cvar_t hostname = {"hostname", "UNNAMED", CVAR_NONE}; +static cvar_t net_messagetimeout = {"net_messagetimeout", "300", CVAR_NONE}; +cvar_t hostname = {"hostname", "UNNAMED", CVAR_NONE}; // these two macros are to make the code more readable -#define sfunc net_drivers[sock->driver] -#define dfunc net_drivers[net_driverlevel] +#define sfunc net_drivers[sock->driver] +#define dfunc net_drivers[net_driverlevel] -int32_t net_driverlevel; +int32_t net_driverlevel; -double net_time; +double net_time; -double SetNetTime (void) +double SetNetTime(void) { net_time = Sys_DoubleTime(); return net_time; @@ -86,14 +86,14 @@ Called by drivers when a new communications endpoint is required The sequence and buffer fields will be filled in properly =================== */ -qsocket_t *NET_NewQSocket (void) +qsocket_t *NET_NewQSocket(void) { - qsocket_t *sock; + qsocket_t *sock; - if (net_freeSockets == NULL) + if(net_freeSockets == NULL) return NULL; - if (net_activeconnections >= svs.maxclients) + if(net_activeconnections >= svs.maxclients) return NULL; // get one from free list @@ -106,7 +106,7 @@ qsocket_t *NET_NewQSocket (void) sock->disconnected = false; sock->connecttime = net_time; - Q_strcpy (sock->address,"UNSET ADDRESS"); + Q_strcpy(sock->address, "UNSET ADDRESS"); sock->driver = net_driverlevel; sock->socket = 0; sock->driverdata = NULL; @@ -127,24 +127,24 @@ qsocket_t *NET_NewQSocket (void) void NET_FreeQSocket(qsocket_t *sock) { - qsocket_t *s; + qsocket_t *s; // remove it from active list - if (sock == net_activeSockets) + if(sock == net_activeSockets) net_activeSockets = net_activeSockets->next; else { - for (s = net_activeSockets; s; s = s->next) + for(s = net_activeSockets; s; s = s->next) { - if (s->next == sock) + if(s->next == sock) { s->next = sock->next; break; } } - if (!s) - Sys_Error ("NET_FreeQSocket: not active"); + if(!s) + Sys_Error("NET_FreeQSocket: not active"); } // add it to free list @@ -154,101 +154,101 @@ void NET_FreeQSocket(qsocket_t *sock) } -double NET_QSocketGetTime (const qsocket_t *s) +double NET_QSocketGetTime(const qsocket_t *s) { return s->connecttime; } -const char *NET_QSocketGetAddressString (const qsocket_t *s) +const char *NET_QSocketGetAddressString(const qsocket_t *s) { return s->address; } -static void NET_Listen_f (void) +static void NET_Listen_f(void) { - if (Cmd_Argc () != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("\"listen\" is \"%" PRIi32 "\"\n", listening ? 1 : 0); + Con_Printf("\"listen\" is \"%" PRIi32 "\"\n", listening ? 1 : 0); return; } listening = Q_atoi(Cmd_Argv(1)) ? true : false; - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) + for(net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { - if (net_drivers[net_driverlevel].initialized == false) + if(net_drivers[net_driverlevel].initialized == false) continue; - dfunc.Listen (listening); + dfunc.Listen(listening); } } -static void MaxPlayers_f (void) +static void MaxPlayers_f(void) { - int32_t n; + int32_t n; - if (Cmd_Argc () != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("\"maxplayers\" is \"%" PRIi32 "\"\n", svs.maxclients); + Con_Printf("\"maxplayers\" is \"%" PRIi32 "\"\n", svs.maxclients); return; } - if (sv.active) + if(sv.active) { - Con_Printf ("maxplayers can not be changed while a server is running.\n"); + Con_Printf("maxplayers can not be changed while a server is running.\n"); return; } n = Q_atoi(Cmd_Argv(1)); - if (n < 1) + if(n < 1) n = 1; - if (n > svs.maxclientslimit) + if(n > svs.maxclientslimit) { n = svs.maxclientslimit; - Con_Printf ("\"maxplayers\" set to \"%" PRIi32 "\"\n", n); + Con_Printf("\"maxplayers\" set to \"%" PRIi32 "\"\n", n); } - if ((n == 1) && listening) - Cbuf_AddText ("listen 0\n"); + if((n == 1) && listening) + Cbuf_AddText("listen 0\n"); - if ((n > 1) && (!listening)) - Cbuf_AddText ("listen 1\n"); + if((n > 1) && (!listening)) + Cbuf_AddText("listen 1\n"); svs.maxclients = n; - if (n == 1) - Cvar_Set ("deathmatch", "0"); + if(n == 1) + Cvar_Set("deathmatch", "0"); else - Cvar_Set ("deathmatch", "1"); + Cvar_Set("deathmatch", "1"); } -static void NET_Port_f (void) +static void NET_Port_f(void) { - int32_t n; + int32_t n; - if (Cmd_Argc () != 2) + if(Cmd_Argc() != 2) { - Con_Printf ("\"port\" is \"%" PRIi32 "\"\n", net_hostport); + Con_Printf("\"port\" is \"%" PRIi32 "\"\n", net_hostport); return; } n = Q_atoi(Cmd_Argv(1)); - if (n < 1 || n > 65534) + if(n < 1 || n > 65534) { - Con_Printf ("Bad value, must be between 1 and 65534\n"); + Con_Printf("Bad value, must be between 1 and 65534\n"); return; } DEFAULTnet_hostport = n; net_hostport = n; - if (listening) + if(listening) { // force a change to the new port - Cbuf_AddText ("listen 0\n"); - Cbuf_AddText ("listen 1\n"); + Cbuf_AddText("listen 0\n"); + Cbuf_AddText("listen 1\n"); } } @@ -263,11 +263,11 @@ static void PrintSlistHeader(void) static void PrintSlist(void) { - int32_t n; + int32_t n; - for (n = slistLastShown; n < hostCacheCount; n++) + for(n = slistLastShown; n < hostCacheCount; n++) { - if (hostcache[n].maxusers) + if(hostcache[n].maxusers) Con_Printf("%-15.15s %-15.15s %2" PRIu32 "/%2" PRIu32 "\n", hostcache[n].name, hostcache[n].map, hostcache[n].users, hostcache[n].maxusers); else Con_Printf("%-15.15s %-15.15s\n", hostcache[n].name, hostcache[n].map); @@ -278,19 +278,19 @@ static void PrintSlist(void) static void PrintSlistTrailer(void) { - if (hostCacheCount) + if(hostCacheCount) Con_Printf("== end list ==\n\n"); else Con_Printf("No Quake servers found.\n\n"); } -void NET_Slist_f (void) +void NET_Slist_f(void) { - if (slistInProgress) + if(slistInProgress) return; - if (! slistSilent) + if(! slistSilent) { Con_Printf("Looking for Quake servers...\n"); PrintSlistHeader(); @@ -306,17 +306,17 @@ void NET_Slist_f (void) } -void NET_SlistSort (void) +void NET_SlistSort(void) { - if (hostCacheCount > 1) + if(hostCacheCount > 1) { - int32_t i, j; + int32_t i, j; hostcache_t temp; - for (i = 0; i < hostCacheCount; i++) + for(i = 0; i < hostCacheCount; i++) { - for (j = i + 1; j < hostCacheCount; j++) + for(j = i + 1; j < hostCacheCount; j++) { - if (strcmp(hostcache[j].name, hostcache[i].name) < 0) + if(strcmp(hostcache[j].name, hostcache[i].name) < 0) { memcpy(&temp, &hostcache[j], sizeof(hostcache_t)); memcpy(&hostcache[j], &hostcache[i], sizeof(hostcache_t)); @@ -328,76 +328,76 @@ void NET_SlistSort (void) } -const char *NET_SlistPrintServer (int32_t idx) +const char *NET_SlistPrintServer(int32_t idx) { - static char string[64]; + static char string[64]; - if (idx < 0 || idx >= hostCacheCount) + if(idx < 0 || idx >= hostCacheCount) return ""; - if (hostcache[idx].maxusers) + if(hostcache[idx].maxusers) { q_snprintf(string, sizeof(string), "%-15.15s %-15.15s %2" PRIu32 "/%2" PRIu32 "\n", - hostcache[idx].name, hostcache[idx].map, - hostcache[idx].users, hostcache[idx].maxusers); + hostcache[idx].name, hostcache[idx].map, + hostcache[idx].users, hostcache[idx].maxusers); } else { q_snprintf(string, sizeof(string), "%-15.15s %-15.15s\n", - hostcache[idx].name, hostcache[idx].map); + hostcache[idx].name, hostcache[idx].map); } return string; } -const char *NET_SlistPrintServerName (int32_t idx) +const char *NET_SlistPrintServerName(int32_t idx) { - if (idx < 0 || idx >= hostCacheCount) + if(idx < 0 || idx >= hostCacheCount) return ""; return hostcache[idx].cname; } -static void Slist_Send (void *unused) +static void Slist_Send(void *unused) { (void)unused; - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) + for(net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { - if (!slistLocal && IS_LOOP_DRIVER(net_driverlevel)) + if(!slistLocal && IS_LOOP_DRIVER(net_driverlevel)) continue; - if (net_drivers[net_driverlevel].initialized == false) + if(net_drivers[net_driverlevel].initialized == false) continue; - dfunc.SearchForHosts (true); + dfunc.SearchForHosts(true); } - if ((Sys_DoubleTime() - slistStartTime) < 0.5) + if((Sys_DoubleTime() - slistStartTime) < 0.5) SchedulePollProcedure(&slistSendProcedure, 0.75); } -static void Slist_Poll (void *unused) +static void Slist_Poll(void *unused) { (void)unused; - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) + for(net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { - if (!slistLocal && IS_LOOP_DRIVER(net_driverlevel)) + if(!slistLocal && IS_LOOP_DRIVER(net_driverlevel)) continue; - if (net_drivers[net_driverlevel].initialized == false) + if(net_drivers[net_driverlevel].initialized == false) continue; - dfunc.SearchForHosts (false); + dfunc.SearchForHosts(false); } - if (! slistSilent) + if(! slistSilent) PrintSlist(); - if ((Sys_DoubleTime() - slistStartTime) < 1.5) + if((Sys_DoubleTime() - slistStartTime) < 1.5) { SchedulePollProcedure(&slistPollProcedure, 0.1); return; } - if (! slistSilent) + if(! slistSilent) PrintSlistTrailer(); slistInProgress = false; slistSilent = false; @@ -414,57 +414,57 @@ NET_Connect int32_t hostCacheCount = 0; hostcache_t hostcache[HOSTCACHESIZE]; -qsocket_t *NET_Connect (const char *host) +qsocket_t *NET_Connect(const char *host) { - qsocket_t *ret; - int32_t n; - int32_t numdrivers = net_numdrivers; + qsocket_t *ret; + int32_t n; + int32_t numdrivers = net_numdrivers; SetNetTime(); - if (host && *host == 0) + if(host && *host == 0) host = NULL; - if (host) + if(host) { - if (q_strcasecmp (host, "local") == 0) + if(q_strcasecmp(host, "local") == 0) { numdrivers = 1; goto JustDoIt; } - if (hostCacheCount) + if(hostCacheCount) { - for (n = 0; n < hostCacheCount; n++) - if (q_strcasecmp (host, hostcache[n].name) == 0) + for(n = 0; n < hostCacheCount; n++) + if(q_strcasecmp(host, hostcache[n].name) == 0) { host = hostcache[n].cname; break; } - if (n < hostCacheCount) + if(n < hostCacheCount) goto JustDoIt; } } slistSilent = host ? true : false; - NET_Slist_f (); + NET_Slist_f(); - while (slistInProgress) + while(slistInProgress) NET_Poll(); - if (host == NULL) + if(host == NULL) { - if (hostCacheCount != 1) + if(hostCacheCount != 1) return NULL; host = hostcache[0].cname; Con_Printf("Connecting to...\n%s @ %s\n\n", hostcache[0].name, host); } - if (hostCacheCount) + if(hostCacheCount) { - for (n = 0; n < hostCacheCount; n++) + for(n = 0; n < hostCacheCount; n++) { - if (q_strcasecmp (host, hostcache[n].name) == 0) + if(q_strcasecmp(host, hostcache[n].name) == 0) { host = hostcache[n].cname; break; @@ -473,16 +473,16 @@ qsocket_t *NET_Connect (const char *host) } JustDoIt: - for (net_driverlevel = 0; net_driverlevel < numdrivers; net_driverlevel++) + for(net_driverlevel = 0; net_driverlevel < numdrivers; net_driverlevel++) { - if (net_drivers[net_driverlevel].initialized == false) + if(net_drivers[net_driverlevel].initialized == false) continue; - ret = dfunc.Connect (host); - if (ret) + ret = dfunc.Connect(host); + if(ret) return ret; } - if (host) + if(host) { Con_Printf("\n"); PrintSlistHeader(); @@ -499,20 +499,20 @@ JustDoIt: NET_CheckNewConnections =================== */ -qsocket_t *NET_CheckNewConnections (void) +qsocket_t *NET_CheckNewConnections(void) { - qsocket_t *ret; + qsocket_t *ret; SetNetTime(); - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) + for(net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { - if (net_drivers[net_driverlevel].initialized == false) + if(net_drivers[net_driverlevel].initialized == false) continue; - if (!IS_LOOP_DRIVER(net_driverlevel) && listening == false) + if(!IS_LOOP_DRIVER(net_driverlevel) && listening == false) continue; - ret = dfunc.CheckNewConnections (); - if (ret) + ret = dfunc.CheckNewConnections(); + if(ret) { return ret; } @@ -526,18 +526,18 @@ qsocket_t *NET_CheckNewConnections (void) NET_Close =================== */ -void NET_Close (qsocket_t *sock) +void NET_Close(qsocket_t *sock) { - if (!sock) + if(!sock) return; - if (sock->disconnected) + if(sock->disconnected) return; SetNetTime(); // call the driver_Close function - sfunc.Close (sock); + sfunc.Close(sock); NET_FreeQSocket(sock); } @@ -554,14 +554,14 @@ returns 1 if a message was received returns -1 if connection is invalid ================= */ -int32_t NET_GetMessage (qsocket_t *sock) +int32_t NET_GetMessage(qsocket_t *sock) { int32_t ret; - if (!sock) + if(!sock) return -1; - if (sock->disconnected) + if(sock->disconnected) { Con_Printf("NET_GetMessage: disconnected socket\n"); return -1; @@ -572,23 +572,23 @@ int32_t NET_GetMessage (qsocket_t *sock) ret = sfunc.QGetMessage(sock); // see if this connection has timed out - if (ret == 0 && !IS_LOOP_DRIVER(sock->driver)) + if(ret == 0 && !IS_LOOP_DRIVER(sock->driver)) { - if (net_time - sock->lastMessageTime > net_messagetimeout.value) + if(net_time - sock->lastMessageTime > net_messagetimeout.value) { NET_Close(sock); return -1; } } - if (ret > 0) + if(ret > 0) { - if (!IS_LOOP_DRIVER(sock->driver)) + if(!IS_LOOP_DRIVER(sock->driver)) { sock->lastMessageTime = net_time; - if (ret == 1) + if(ret == 1) messagesReceived++; - else if (ret == 2) + else if(ret == 2) unreliableMessagesReceived++; } } @@ -603,19 +603,19 @@ NET_SendMessage Try to send a complete length+message unit over the reliable stream. returns 0 if the message cannot be delivered reliably, but the connection - is still considered valid + is still considered valid returns 1 if the message was sent properly returns -1 if the connection died ================== */ -int32_t NET_SendMessage (qsocket_t *sock, sizebuf_t *data) +int32_t NET_SendMessage(qsocket_t *sock, sizebuf_t *data) { - int32_t r; + int32_t r; - if (!sock) + if(!sock) return -1; - if (sock->disconnected) + if(sock->disconnected) { Con_Printf("NET_SendMessage: disconnected socket\n"); return -1; @@ -623,21 +623,21 @@ int32_t NET_SendMessage (qsocket_t *sock, sizebuf_t *data) SetNetTime(); r = sfunc.QSendMessage(sock, data); - if (r == 1 && !IS_LOOP_DRIVER(sock->driver)) + if(r == 1 && !IS_LOOP_DRIVER(sock->driver)) messagesSent++; return r; } -int32_t NET_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) +int32_t NET_SendUnreliableMessage(qsocket_t *sock, sizebuf_t *data) { - int32_t r; + int32_t r; - if (!sock) + if(!sock) return -1; - if (sock->disconnected) + if(sock->disconnected) { Con_Printf("NET_SendMessage: disconnected socket\n"); return -1; @@ -645,7 +645,7 @@ int32_t NET_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) SetNetTime(); r = sfunc.SendUnreliableMessage(sock, data); - if (r == 1 && !IS_LOOP_DRIVER(sock->driver)) + if(r == 1 && !IS_LOOP_DRIVER(sock->driver)) unreliableMessagesSent++; return r; @@ -660,12 +660,12 @@ Returns true or false if the given qsocket can currently accept a message to be transmitted. ================== */ -bool NET_CanSendMessage (qsocket_t *sock) +bool NET_CanSendMessage(qsocket_t *sock) { - if (!sock) + if(!sock) return false; - if (sock->disconnected) + if(sock->disconnected) return false; SetNetTime(); @@ -674,24 +674,24 @@ bool NET_CanSendMessage (qsocket_t *sock) } -int32_t NET_SendToAll (sizebuf_t *data, double blocktime) +int32_t NET_SendToAll(sizebuf_t *data, double blocktime) { - double start; - int32_t i; - int32_t count = 0; - bool msg_init[MAX_SCOREBOARD]; /* did we write the message to the client's connection */ - bool msg_sent[MAX_SCOREBOARD]; /* did the msg arrive its destination (canSend state). */ + double start; + int32_t i; + int32_t count = 0; + bool msg_init[MAX_SCOREBOARD]; /* did we write the message to the client's connection */ + bool msg_sent[MAX_SCOREBOARD]; /* did the msg arrive its destination (canSend state). */ - for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) + for(i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { /* if (!host_client->netconnection) - continue; + continue; if (host_client->active) */ - if (host_client->netconnection && host_client->active) + if(host_client->netconnection && host_client->active) { - if (IS_LOOP_DRIVER(host_client->netconnection->driver)) + if(IS_LOOP_DRIVER(host_client->netconnection->driver)) { NET_SendMessage(host_client->netconnection, data); msg_init[i] = true; @@ -710,41 +710,41 @@ int32_t NET_SendToAll (sizebuf_t *data, double blocktime) } start = Sys_DoubleTime(); - while (count) + while(count) { count = 0; - for (i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) + for(i = 0, host_client = svs.clients; i < svs.maxclients; i++, host_client++) { - if (! msg_init[i]) + if(! msg_init[i]) { - if (NET_CanSendMessage (host_client->netconnection)) + if(NET_CanSendMessage(host_client->netconnection)) { msg_init[i] = true; NET_SendMessage(host_client->netconnection, data); } else { - NET_GetMessage (host_client->netconnection); + NET_GetMessage(host_client->netconnection); } count++; continue; } - if (! msg_sent[i]) + if(! msg_sent[i]) { - if (NET_CanSendMessage (host_client->netconnection)) + if(NET_CanSendMessage(host_client->netconnection)) { msg_sent[i] = true; } else { - NET_GetMessage (host_client->netconnection); + NET_GetMessage(host_client->netconnection); } count++; continue; } } - if ((Sys_DoubleTime() - start) > blocktime) + if((Sys_DoubleTime() - start) > blocktime) break; } return count; @@ -759,35 +759,35 @@ NET_Init ==================== */ -void NET_Init (void) +void NET_Init(void) { - int32_t i; - qsocket_t *s; + int32_t i; + qsocket_t *s; - i = COM_CheckParm ("-port"); - if (!i) - i = COM_CheckParm ("-udpport"); - if (!i) - i = COM_CheckParm ("-ipxport"); + i = COM_CheckParm("-port"); + if(!i) + i = COM_CheckParm("-udpport"); + if(!i) + i = COM_CheckParm("-ipxport"); - if (i) + if(i) { - if (i < com_argc-1) - DEFAULTnet_hostport = Q_atoi (com_argv[i+1]); + if(i < com_argc - 1) + DEFAULTnet_hostport = Q_atoi(com_argv[i + 1]); else - Sys_Error ("NET_Init: you must specify a number after -port"); + Sys_Error("NET_Init: you must specify a number after -port"); } net_hostport = DEFAULTnet_hostport; net_numsockets = svs.maxclientslimit; - if (cls.state != ca_dedicated) + if(cls.state != ca_dedicated) net_numsockets++; - if (COM_CheckParm("-listen") || cls.state == ca_dedicated) + if(COM_CheckParm("-listen") || cls.state == ca_dedicated) listening = true; SetNetTime(); - for (i = 0; i < net_numsockets; i++) + for(i = 0; i < net_numsockets; i++) { s = (qsocket_t *)Hunk_AllocName(sizeof(qsocket_t), "qsocket"); s->next = net_freeSockets; @@ -796,41 +796,41 @@ void NET_Init (void) } // allocate space for network message buffer - SZ_Alloc (&net_message, NET_MAXMESSAGE); + SZ_Alloc(&net_message, NET_MAXMESSAGE); - Cvar_RegisterVariable (&net_messagetimeout); - Cvar_RegisterVariable (&hostname); + Cvar_RegisterVariable(&net_messagetimeout); + Cvar_RegisterVariable(&hostname); - Cmd_AddCommand ("slist", NET_Slist_f); - Cmd_AddCommand ("listen", NET_Listen_f); - Cmd_AddCommand ("maxplayers", MaxPlayers_f); - Cmd_AddCommand ("port", NET_Port_f); + Cmd_AddCommand("slist", NET_Slist_f); + Cmd_AddCommand("listen", NET_Listen_f); + Cmd_AddCommand("maxplayers", MaxPlayers_f); + Cmd_AddCommand("port", NET_Port_f); // initialize all the drivers - for (i = net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) + for(i = net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { - if (net_drivers[net_driverlevel].Init() == -1) + if(net_drivers[net_driverlevel].Init() == -1) continue; i++; net_drivers[net_driverlevel].initialized = true; - if (listening) - net_drivers[net_driverlevel].Listen (true); + if(listening) + net_drivers[net_driverlevel].Listen(true); } /* Loop_Init() returns -1 for dedicated server case, * therefore the i == 0 check is correct */ - if (i == 0 - && cls.state == ca_dedicated - ) + if(i == 0 + && cls.state == ca_dedicated + ) { Sys_Error("Network not available!"); } - if (*my_ipx_address) + if(*my_ipx_address) { Con_DPrintf("IPX address %s\n", my_ipx_address); } - if (*my_tcpip_address) + if(*my_tcpip_address) { Con_DPrintf("TCP/IP address %s\n", my_tcpip_address); } @@ -842,23 +842,23 @@ NET_Shutdown ==================== */ -void NET_Shutdown (void) +void NET_Shutdown(void) { - qsocket_t *sock; + qsocket_t *sock; SetNetTime(); - for (sock = net_activeSockets; sock; sock = sock->next) + for(sock = net_activeSockets; sock; sock = sock->next) NET_Close(sock); // // shutdown the drivers // - for (net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) + for(net_driverlevel = 0; net_driverlevel < net_numdrivers; net_driverlevel++) { - if (net_drivers[net_driverlevel].initialized == true) + if(net_drivers[net_driverlevel].initialized == true) { - net_drivers[net_driverlevel].Shutdown (); + net_drivers[net_driverlevel].Shutdown(); net_drivers[net_driverlevel].initialized = false; } } @@ -873,9 +873,9 @@ void NET_Poll(void) SetNetTime(); - for (pp = pollProcedureList; pp; pp = pp->next) + for(pp = pollProcedureList; pp; pp = pp->next) { - if (pp->nextTime > net_time) + if(pp->nextTime > net_time) break; pollProcedureList = pp->next; pp->procedure(pp->arg); @@ -888,14 +888,14 @@ void SchedulePollProcedure(PollProcedure *proc, double timeOffset) PollProcedure *pp, *prev; proc->nextTime = Sys_DoubleTime() + timeOffset; - for (pp = pollProcedureList, prev = NULL; pp; pp = pp->next) + for(pp = pollProcedureList, prev = NULL; pp; pp = pp->next) { - if (pp->nextTime >= proc->nextTime) + if(pp->nextTime >= proc->nextTime) break; prev = pp; } - if (prev == NULL) + if(prev == NULL) { proc->next = pollProcedureList; pollProcedureList = proc; diff --git a/source/net_sys.h b/source/net_sys.h index 9d4541d..e6fdc7e 100644 --- a/source/net_sys.h +++ b/source/net_sys.h @@ -29,8 +29,8 @@ #include #include -#if defined(PLATFORM_BSD) || defined(PLATFORM_OSX) || \ - defined(PLATFORM_AMIGA) /* bsdsocket.library */ || \ +#if defined(PLATFORM_BSD) || defined(PLATFORM_OSX) || \ + defined(PLATFORM_AMIGA) /* bsdsocket.library */ || \ defined(__GNU__) /* GNU/Hurd */ || defined(__riscos__) /* struct sockaddr has uint8_t sa_len as the first member in BSD * variants and the family member is also an uint8_t instead of an @@ -39,12 +39,12 @@ * provide a struct sockaddr doesn't hurt either (see down below for the * compile time asserts.) */ /* FIXME : GET RID OF THIS ABOMINATION !!! */ -#define HAVE_SA_LEN 1 -#define SA_FAM_OFFSET 1 +#define HAVE_SA_LEN 1 +#define SA_FAM_OFFSET 1 #else -#undef HAVE_SA_LEN -#define SA_FAM_OFFSET 0 -#endif /* BSD, sockaddr */ +#undef HAVE_SA_LEN +#define SA_FAM_OFFSET 0 +#endif /* BSD, sockaddr */ /* unix includes and compatibility macros */ #if defined(PLATFORM_UNIX) || defined(PLATFORM_RISCOS) @@ -54,32 +54,32 @@ #if defined(__sun) || defined(sun) #include #include -#endif /* __sunos__ */ +#endif /* __sunos__ */ #include #include #include #include #include -typedef int32_t sys_socket_t; -#define INVALID_SOCKET (-1) -#define SOCKET_ERROR (-1) +typedef int32_t sys_socket_t; +#define INVALID_SOCKET (-1) +#define SOCKET_ERROR (-1) -#define SOCKETERRNO errno -#define ioctlsocket ioctl -#define closesocket close -#define selectsocket select -#define IOCTLARG_P(x) /* (char *) */ x +#define SOCKETERRNO errno +#define ioctlsocket ioctl +#define closesocket close +#define selectsocket select +#define IOCTLARG_P(x) /* (char *) */ x -#define NET_EWOULDBLOCK EWOULDBLOCK -#define NET_ECONNREFUSED ECONNREFUSED +#define NET_EWOULDBLOCK EWOULDBLOCK +#define NET_ECONNREFUSED ECONNREFUSED -#define socketerror(x) strerror((x)) +#define socketerror(x) strerror((x)) _Static_assert(offsetof(struct sockaddr, sa_family) == SA_FAM_OFFSET, "HAVE_SA_LEN not defined correctly"); -#endif /* end of unix stuff */ +#endif /* end of unix stuff */ /* amiga includes and compatibility macros */ @@ -95,34 +95,34 @@ _Static_assert(offsetof(struct sockaddr, sa_family) == SA_FAM_OFFSET, #include #include -typedef int32_t sys_socket_t; -#define INVALID_SOCKET (-1) -#define SOCKET_ERROR (-1) +typedef int32_t sys_socket_t; +#define INVALID_SOCKET (-1) +#define SOCKET_ERROR (-1) typedef uint32_t in_addr_t; -#define SOCKETERRNO Errno() -#define ioctlsocket IoctlSocket -#define closesocket CloseSocket -#define selectsocket(_N,_R,_W,_E,_T) \ - WaitSelect((_N),(_R),(_W),(_E),(_T),NULL) -#define IOCTLARG_P(x) (char *) x +#define SOCKETERRNO Errno() +#define ioctlsocket IoctlSocket +#define closesocket CloseSocket +#define selectsocket(_N,_R,_W,_E,_T) \ + WaitSelect((_N),(_R),(_W),(_E),(_T),NULL) +#define IOCTLARG_P(x) (char *) x #if defined(__amigaos4__) || defined(PLATFORM_AMIGAOS3) -#define inet_ntoa(x) Inet_NtoA(x.s_addr) /* Inet_NtoA(*(ULONG*)&x) */ -#define h_errno Errno() +#define inet_ntoa(x) Inet_NtoA(x.s_addr) /* Inet_NtoA(*(ULONG*)&x) */ +#define h_errno Errno() #endif -#define NET_EWOULDBLOCK EWOULDBLOCK -#define NET_ECONNREFUSED ECONNREFUSED +#define NET_EWOULDBLOCK EWOULDBLOCK +#define NET_ECONNREFUSED ECONNREFUSED -#define socketerror(x) strerror((x)) +#define socketerror(x) strerror((x)) /* there is h_errno but no hstrerror() */ -#define hstrerror(x) strerror((x)) +#define hstrerror(x) strerror((x)) _Static_assert(offsetof(struct sockaddr, sa_family) == SA_FAM_OFFSET, "HAVE_SA_LEN not defined correctly"); -#endif /* end of amiga bsdsocket.library stuff */ +#endif /* end of amiga bsdsocket.library stuff */ /* windows includes and compatibility macros */ @@ -138,48 +138,48 @@ _Static_assert(offsetof(struct sockaddr, sa_family) == SA_FAM_OFFSET, /* there is no in_addr_t on windows: define it as the type of the S_addr of in_addr structure */ -typedef u_long in_addr_t; /* uint32_t */ +typedef u_long in_addr_t; /* uint32_t */ /* on windows, socklen_t is to be a winsock2 thing */ #if !defined(IP_MSFILTER_SIZE) -typedef int32_t socklen_t; -#endif /* socklen_t type */ +typedef int32_t socklen_t; +#endif /* socklen_t type */ -typedef SOCKET sys_socket_t; +typedef SOCKET sys_socket_t; -#define selectsocket select -#define IOCTLARG_P(x) /* (u_long *) */ x +#define selectsocket select +#define IOCTLARG_P(x) /* (u_long *) */ x -#define SOCKETERRNO WSAGetLastError() -#define NET_EWOULDBLOCK WSAEWOULDBLOCK -#define NET_ECONNREFUSED WSAECONNREFUSED +#define SOCKETERRNO WSAGetLastError() +#define NET_EWOULDBLOCK WSAEWOULDBLOCK +#define NET_ECONNREFUSED WSAECONNREFUSED /* must #include "wsaerror.h" for this : */ -#define socketerror(x) __WSAE_StrError((x)) +#define socketerror(x) __WSAE_StrError((x)) _Static_assert(offsetof(struct sockaddr, sa_family) == SA_FAM_OFFSET, "HAVE_SA_LEN not defined correctly"); -#endif /* end of windows stuff */ +#endif /* end of windows stuff */ /* macros which may still be missing */ #if !defined(INADDR_NONE) -#define INADDR_NONE ((in_addr_t) 0xffffffff) -#endif /* INADDR_NONE */ +#define INADDR_NONE ((in_addr_t) 0xffffffff) +#endif /* INADDR_NONE */ #if !defined(INADDR_LOOPBACK) -#define INADDR_LOOPBACK ((in_addr_t) 0x7f000001) /* 127.0.0.1 */ -#endif /* INADDR_LOOPBACK */ +#define INADDR_LOOPBACK ((in_addr_t) 0x7f000001) /* 127.0.0.1 */ +#endif /* INADDR_LOOPBACK */ #if !defined(MAXHOSTNAMELEN) /* SUSv2 guarantees that `Host names are limited to 255 bytes'. POSIX 1003.1-2001 guarantees that `Host names (not including the terminating NUL) are limited to HOST_NAME_MAX bytes'. */ -#define MAXHOSTNAMELEN 256 -#endif /* MAXHOSTNAMELEN */ +#define MAXHOSTNAMELEN 256 +#endif /* MAXHOSTNAMELEN */ -#endif /* __NET_SYS_H__ */ +#endif /* __NET_SYS_H__ */ diff --git a/source/platform.h b/source/platform.h index 679ecff..8123e5e 100644 --- a/source/platform.h +++ b/source/platform.h @@ -28,13 +28,13 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. void PL_SetWindowIcon(void); /* platform dependent cleanup */ -void PL_VID_Shutdown (void); +void PL_VID_Shutdown(void); /* retrieve text from the clipboard (returns Z_Malloc()'ed data) */ -char *PL_GetClipboardData (void); +char *PL_GetClipboardData(void); /* show an error dialog */ void PL_ErrorDialog(const char *text); -#endif /* _QUAKE_PLATFORM_H */ +#endif /* _QUAKE_PLATFORM_H */ diff --git a/source/pr_cmds.c b/source/pr_cmds.c index 49a813d..a41815e 100644 --- a/source/pr_cmds.c +++ b/source/pr_cmds.c @@ -22,51 +22,51 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -#define STRINGTEMP_BUFFERS 16 -#define STRINGTEMP_LENGTH 1024 -static char pr_string_temp[STRINGTEMP_BUFFERS][STRINGTEMP_LENGTH]; -static byte pr_string_tempindex = 0; +#define STRINGTEMP_BUFFERS 16 +#define STRINGTEMP_LENGTH 1024 +static char pr_string_temp[STRINGTEMP_BUFFERS][STRINGTEMP_LENGTH]; +static byte pr_string_tempindex = 0; -static char *PR_GetTempString (void) +static char *PR_GetTempString(void) { - return pr_string_temp[(STRINGTEMP_BUFFERS-1) & ++pr_string_tempindex]; + return pr_string_temp[(STRINGTEMP_BUFFERS - 1) & ++pr_string_tempindex]; } -#define RETURN_EDICT(e) (((int32_t *)pr_globals)[OFS_RETURN] = EDICT_TO_PROG(e)) +#define RETURN_EDICT(e) (((int32_t *)pr_globals)[OFS_RETURN] = EDICT_TO_PROG(e)) -#define MSG_BROADCAST 0 // unreliable to all -#define MSG_ONE 1 // reliable to one (msg_entity) -#define MSG_ALL 2 // reliable to all -#define MSG_INIT 3 // write to the init string +#define MSG_BROADCAST 0 // unreliable to all +#define MSG_ONE 1 // reliable to one (msg_entity) +#define MSG_ALL 2 // reliable to all +#define MSG_INIT 3 // write to the init string /* =============================================================================== - BUILT-IN FUNCTIONS + BUILT-IN FUNCTIONS =============================================================================== */ -static char *PF_VarString (int32_t first) +static char *PF_VarString(int32_t first) { - int32_t i; + int32_t i; static char out[1024]; size_t s; out[0] = 0; s = 0; - for (i = first; i < pr_argc; i++) + for(i = first; i < pr_argc; i++) { - s = q_strlcat(out, G_STRING((OFS_PARM0+i*3)), sizeof(out)); - if (s >= sizeof(out)) + s = q_strlcat(out, G_STRING((OFS_PARM0 + i * 3)), sizeof(out)); + if(s >= sizeof(out)) { Con_Warning("PF_VarString: overflow (string truncated)\n"); return out; } } - if (s > 255) + if(s > 255) { - if (!dev_overflows.varstring || dev_overflows.varstring + CONSOLE_RESPAM_TIME < realtime) + if(!dev_overflows.varstring || dev_overflows.varstring + CONSOLE_RESPAM_TIME < realtime) { Con_DWarning("PF_VarString: %" PRIi32 " characters exceeds standard limit of 255 (max = %" PRIi32 ").\n", (int32_t) s, (int32_t)(sizeof(out) - 1)); dev_overflows.varstring = realtime; @@ -86,18 +86,18 @@ Dumps self. error(value) ================= */ -static void PF_error (void) +static void PF_error(void) { - char *s; - edict_t *ed; + char *s; + edict_t *ed; s = PF_VarString(0); - Con_Printf ("======SERVER ERROR in %s:\n%s\n", - PR_GetString(pr_xfunction->s_name), s); + Con_Printf("======SERVER ERROR in %s:\n%s\n", + PR_GetString(pr_xfunction->s_name), s); ed = PROG_TO_EDICT(pr_global_struct->self); - ED_Print (ed); + ED_Print(ed); - Host_Error ("Program error"); + Host_Error("Program error"); } /* @@ -110,17 +110,17 @@ removed, but the level can continue. objerror(value) ================= */ -static void PF_objerror (void) +static void PF_objerror(void) { - char *s; - edict_t *ed; + char *s; + edict_t *ed; s = PF_VarString(0); - Con_Printf ("======OBJECT ERROR in %s:\n%s\n", - PR_GetString(pr_xfunction->s_name), s); + Con_Printf("======OBJECT ERROR in %s:\n%s\n", + PR_GetString(pr_xfunction->s_name), s); ed = PROG_TO_EDICT(pr_global_struct->self); - ED_Print (ed); - ED_Free (ed); + ED_Print(ed); + ED_Free(ed); //Host_Error ("Program error"); //johnfitz -- by design, this should not be fatal } @@ -135,9 +135,9 @@ Writes new values for v_forward, v_up, and v_right based on angles makevectors(vector) ============== */ -static void PF_makevectors (void) +static void PF_makevectors(void) { - AngleVectors (G_VECTOR(OFS_PARM0), pr_global_struct->v_forward, pr_global_struct->v_right, pr_global_struct->v_up); + AngleVectors(G_VECTOR(OFS_PARM0), pr_global_struct->v_forward, pr_global_struct->v_right, pr_global_struct->v_up); } /* @@ -154,77 +154,77 @@ teleported. setorigin (entity, origin) ================= */ -static void PF_setorigin (void) +static void PF_setorigin(void) { - edict_t *e; - float *org; + edict_t *e; + float *org; e = G_EDICT(OFS_PARM0); org = G_VECTOR(OFS_PARM1); - VectorCopy (org, e->v.origin); - SV_LinkEdict (e, false); + VectorCopy(org, e->v.origin); + SV_LinkEdict(e, false); } -static void SetMinMaxSize (edict_t *e, float *minvec, float *maxvec, bool rotate) +static void SetMinMaxSize(edict_t *e, float *minvec, float *maxvec, bool rotate) { - float *angles; - vec3_t rmin, rmax; - float bounds[2][3]; - float xvector[2], yvector[2]; - float a; - vec3_t base, transformed; - int32_t i, j, k, l; + float *angles; + vec3_t rmin, rmax; + float bounds[2][3]; + float xvector[2], yvector[2]; + float a; + vec3_t base, transformed; + int32_t i, j, k, l; - for (i = 0; i < 3; i++) - if (minvec[i] > maxvec[i]) - PR_RunError ("backwards mins/maxs"); + for(i = 0; i < 3; i++) + if(minvec[i] > maxvec[i]) + PR_RunError("backwards mins/maxs"); - rotate = false; // FIXME: implement rotation properly again + rotate = false; // FIXME: implement rotation properly again - if (!rotate) + if(!rotate) { - VectorCopy (minvec, rmin); - VectorCopy (maxvec, rmax); + VectorCopy(minvec, rmin); + VectorCopy(maxvec, rmax); } else { - // find min / max for rotations + // find min / max for rotations angles = e->v.angles; - a = angles[1]/180 * M_PI; + a = angles[1] / 180 * M_PI; xvector[0] = cos(a); xvector[1] = sin(a); yvector[0] = -sin(a); yvector[1] = cos(a); - VectorCopy (minvec, bounds[0]); - VectorCopy (maxvec, bounds[1]); + VectorCopy(minvec, bounds[0]); + VectorCopy(maxvec, bounds[1]); rmin[0] = rmin[1] = rmin[2] = 9999; rmax[0] = rmax[1] = rmax[2] = -9999; - for (i = 0; i <= 1; i++) + for(i = 0; i <= 1; i++) { base[0] = bounds[i][0]; - for (j = 0; j <= 1; j++) + for(j = 0; j <= 1; j++) { base[1] = bounds[j][1]; - for (k = 0; k <= 1; k++) + for(k = 0; k <= 1; k++) { base[2] = bounds[k][2]; - // transform the point - transformed[0] = xvector[0]*base[0] + yvector[0]*base[1]; - transformed[1] = xvector[1]*base[0] + yvector[1]*base[1]; + // transform the point + transformed[0] = xvector[0] * base[0] + yvector[0] * base[1]; + transformed[1] = xvector[1] * base[0] + yvector[1] * base[1]; transformed[2] = base[2]; - for (l = 0; l < 3; l++) + for(l = 0; l < 3; l++) { - if (transformed[l] < rmin[l]) + if(transformed[l] < rmin[l]) rmin[l] = transformed[l]; - if (transformed[l] > rmax[l]) + if(transformed[l] > rmax[l]) rmax[l] = transformed[l]; } } @@ -233,11 +233,11 @@ static void SetMinMaxSize (edict_t *e, float *minvec, float *maxvec, bool rotate } // set derived values - VectorCopy (rmin, e->v.mins); - VectorCopy (rmax, e->v.maxs); - VectorSubtract (maxvec, minvec, e->v.size); + VectorCopy(rmin, e->v.mins); + VectorCopy(rmax, e->v.maxs); + VectorSubtract(maxvec, minvec, e->v.size); - SV_LinkEdict (e, false); + SV_LinkEdict(e, false); } /* @@ -249,15 +249,15 @@ the size box is rotated by the current angle setsize (entity, minvector, maxvector) ================= */ -static void PF_setsize (void) +static void PF_setsize(void) { - edict_t *e; - float *minvec, *maxvec; + edict_t *e; + float *minvec, *maxvec; e = G_EDICT(OFS_PARM0); minvec = G_VECTOR(OFS_PARM1); maxvec = G_VECTOR(OFS_PARM2); - SetMinMaxSize (e, minvec, maxvec, false); + SetMinMaxSize(e, minvec, maxvec, false); } @@ -268,43 +268,43 @@ PF_setmodel setmodel(entity, model) ================= */ -static void PF_setmodel (void) +static void PF_setmodel(void) { - int32_t i; - const char *m, **check; - qmodel_t *mod; - edict_t *e; + int32_t i; + const char *m, **check; + qmodel_t *mod; + edict_t *e; e = G_EDICT(OFS_PARM0); m = G_STRING(OFS_PARM1); // check to see if model was properly precached - for (i = 0, check = sv.model_precache; *check; i++, check++) + for(i = 0, check = sv.model_precache; *check; i++, check++) { - if (!strcmp(*check, m)) + if(!strcmp(*check, m)) break; } - if (!*check) + if(!*check) { - PR_RunError ("no precache: %s", m); + PR_RunError("no precache: %s", m); } e->v.model = PR_SetEngineString(*check); e->v.modelindex = i; //SV_ModelIndex (m); - mod = sv.models[ (int32_t)e->v.modelindex]; // Mod_ForName (m, true); + mod = sv.models[(int32_t)e->v.modelindex]; // Mod_ForName (m, true); - if (mod) - //johnfitz -- correct physics cullboxes for bmodels + if(mod) + //johnfitz -- correct physics cullboxes for bmodels { - if (mod->type == mod_brush) - SetMinMaxSize (e, mod->clipmins, mod->clipmaxs, true); + if(mod->type == mod_brush) + SetMinMaxSize(e, mod->clipmins, mod->clipmaxs, true); else - SetMinMaxSize (e, mod->mins, mod->maxs, true); + SetMinMaxSize(e, mod->mins, mod->maxs, true); } //johnfitz else - SetMinMaxSize (e, vec3_origin, vec3_origin, true); + SetMinMaxSize(e, vec3_origin, vec3_origin, true); } /* @@ -316,12 +316,12 @@ broadcast print to everyone on server bprint(value) ================= */ -static void PF_bprint (void) +static void PF_bprint(void) { - char *s; + char *s; s = PF_VarString(0); - SV_BroadcastPrintf ("%s", s); + SV_BroadcastPrintf("%s", s); } /* @@ -333,25 +333,25 @@ single print to a specific client sprint(clientent, value) ================= */ -static void PF_sprint (void) +static void PF_sprint(void) { - char *s; - client_t *client; - int32_t entnum; + char *s; + client_t *client; + int32_t entnum; entnum = G_EDICTNUM(OFS_PARM0); s = PF_VarString(1); - if (entnum < 1 || entnum > svs.maxclients) + if(entnum < 1 || entnum > svs.maxclients) { - Con_Printf ("tried to sprint to a non-client\n"); + Con_Printf("tried to sprint to a non-client\n"); return; } - client = &svs.clients[entnum-1]; + client = &svs.clients[entnum - 1]; - MSG_WriteChar (&client->message,svc_print); - MSG_WriteString (&client->message, s ); + MSG_WriteChar(&client->message, svc_print); + MSG_WriteString(&client->message, s); } @@ -364,25 +364,25 @@ single print to a specific client centerprint(clientent, value) ================= */ -static void PF_centerprint (void) +static void PF_centerprint(void) { - char *s; - client_t *client; - int32_t entnum; + char *s; + client_t *client; + int32_t entnum; entnum = G_EDICTNUM(OFS_PARM0); s = PF_VarString(1); - if (entnum < 1 || entnum > svs.maxclients) + if(entnum < 1 || entnum > svs.maxclients) { - Con_Printf ("tried to sprint to a non-client\n"); + Con_Printf("tried to sprint to a non-client\n"); return; } - client = &svs.clients[entnum-1]; + client = &svs.clients[entnum - 1]; - MSG_WriteChar (&client->message,svc_centerprint); - MSG_WriteString (&client->message, s); + MSG_WriteChar(&client->message, svc_centerprint); + MSG_WriteString(&client->message, s); } @@ -393,18 +393,18 @@ PF_normalize vector normalize(vector) ================= */ -static void PF_normalize (void) +static void PF_normalize(void) { - float *value1; - vec3_t newvalue; - double new_temp; + float *value1; + vec3_t newvalue; + double new_temp; value1 = G_VECTOR(OFS_PARM0); - new_temp = (double)value1[0] * value1[0] + (double)value1[1] * value1[1] + (double)value1[2]*value1[2]; - new_temp = sqrt (new_temp); + new_temp = (double)value1[0] * value1[0] + (double)value1[1] * value1[1] + (double)value1[2] * value1[2]; + new_temp = sqrt(new_temp); - if (new_temp == 0) + if(new_temp == 0) newvalue[0] = newvalue[1] = newvalue[2] = 0; else { @@ -414,7 +414,7 @@ static void PF_normalize (void) newvalue[2] = value1[2] * new_temp; } - VectorCopy (newvalue, G_VECTOR(OFS_RETURN)); + VectorCopy(newvalue, G_VECTOR(OFS_RETURN)); } /* @@ -424,14 +424,14 @@ PF_vlen scalar vlen(vector) ================= */ -static void PF_vlen (void) +static void PF_vlen(void) { - float *value1; - double new_temp; + float *value1; + double new_temp; value1 = G_VECTOR(OFS_PARM0); - new_temp = (double)value1[0] * value1[0] + (double)value1[1] * value1[1] + (double)value1[2]*value1[2]; + new_temp = (double)value1[0] * value1[0] + (double)value1[1] * value1[1] + (double)value1[2] * value1[2]; new_temp = sqrt(new_temp); G_FLOAT(OFS_RETURN) = new_temp; @@ -444,19 +444,19 @@ PF_vectoyaw float vectoyaw(vector) ================= */ -static void PF_vectoyaw (void) +static void PF_vectoyaw(void) { - float *value1; - float yaw; + float *value1; + float yaw; value1 = G_VECTOR(OFS_PARM0); - if (value1[1] == 0 && value1[0] == 0) + if(value1[1] == 0 && value1[0] == 0) yaw = 0; else { - yaw = (int32_t) (atan2(value1[1], value1[0]) * 180 / M_PI); - if (yaw < 0) + yaw = (int32_t)(atan2(value1[1], value1[0]) * 180 / M_PI); + if(yaw < 0) yaw += 360; } @@ -471,37 +471,37 @@ PF_vectoangles vector vectoangles(vector) ================= */ -static void PF_vectoangles (void) +static void PF_vectoangles(void) { - float *value1; - float forward; - float yaw, pitch; + float *value1; + float forward; + float yaw, pitch; value1 = G_VECTOR(OFS_PARM0); - if (value1[1] == 0 && value1[0] == 0) + if(value1[1] == 0 && value1[0] == 0) { yaw = 0; - if (value1[2] > 0) + if(value1[2] > 0) pitch = 90; else pitch = 270; } else { - yaw = (int32_t) (atan2(value1[1], value1[0]) * 180 / M_PI); - if (yaw < 0) + yaw = (int32_t)(atan2(value1[1], value1[0]) * 180 / M_PI); + if(yaw < 0) yaw += 360; - forward = sqrt (value1[0]*value1[0] + value1[1]*value1[1]); - pitch = (int32_t) (atan2(value1[2], forward) * 180 / M_PI); - if (pitch < 0) + forward = sqrt(value1[0] * value1[0] + value1[1] * value1[1]); + pitch = (int32_t)(atan2(value1[2], forward) * 180 / M_PI); + if(pitch < 0) pitch += 360; } - G_FLOAT(OFS_RETURN+0) = pitch; - G_FLOAT(OFS_RETURN+1) = yaw; - G_FLOAT(OFS_RETURN+2) = 0; + G_FLOAT(OFS_RETURN + 0) = pitch; + G_FLOAT(OFS_RETURN + 1) = yaw; + G_FLOAT(OFS_RETURN + 2) = 0; } /* @@ -513,9 +513,9 @@ Returns a number from 0 <= num < 1 random() ================= */ -static void PF_random (void) +static void PF_random(void) { - float num; + float num; num = (rand() & 0x7fff) / ((float)0x7fff); @@ -529,17 +529,17 @@ PF_particle particle(origin, color, count) ================= */ -static void PF_particle (void) +static void PF_particle(void) { - float *org, *dir; - float color; - float count; + float *org, *dir; + float color; + float count; org = G_VECTOR(OFS_PARM0); dir = G_VECTOR(OFS_PARM1); color = G_FLOAT(OFS_PARM2); count = G_FLOAT(OFS_PARM3); - SV_StartParticle (org, dir, color, count); + SV_StartParticle(org, dir, color, count); } @@ -549,36 +549,36 @@ PF_ambientsound ================= */ -static void PF_ambientsound (void) +static void PF_ambientsound(void) { - const char *samp, **check; - float *pos; - float vol, attenuation; - int32_t i, soundnum; - int32_t large = false; //johnfitz -- PROTOCOL_FITZQUAKE + const char *samp, **check; + float *pos; + float vol, attenuation; + int32_t i, soundnum; + int32_t large = false; //johnfitz -- PROTOCOL_FITZQUAKE - pos = G_VECTOR (OFS_PARM0); + pos = G_VECTOR(OFS_PARM0); samp = G_STRING(OFS_PARM1); vol = G_FLOAT(OFS_PARM2); attenuation = G_FLOAT(OFS_PARM3); // check to see if samp was properly precached - for (soundnum = 0, check = sv.sound_precache; *check; check++, soundnum++) + for(soundnum = 0, check = sv.sound_precache; *check; check++, soundnum++) { - if (!strcmp(*check, samp)) + if(!strcmp(*check, samp)) break; } - if (!*check) + if(!*check) { - Con_Printf ("no precache: %s\n", samp); + Con_Printf("no precache: %s\n", samp); return; } //johnfitz -- PROTOCOL_FITZQUAKE - if (soundnum > 255) + if(soundnum > 255) { - if (sv.protocol == PROTOCOL_NETQUAKE) + if(sv.protocol == PROTOCOL_NETQUAKE) return; //don't send any info protocol can't support else large = true; @@ -588,24 +588,24 @@ static void PF_ambientsound (void) // add an svc_spawnambient command to the level signon packet //johnfitz -- PROTOCOL_FITZQUAKE - if (large) - MSG_WriteByte (&sv.signon,svc_spawnstaticsound2); + if(large) + MSG_WriteByte(&sv.signon, svc_spawnstaticsound2); else - MSG_WriteByte (&sv.signon,svc_spawnstaticsound); + MSG_WriteByte(&sv.signon, svc_spawnstaticsound); //johnfitz - for (i = 0; i < 3; i++) + for(i = 0; i < 3; i++) MSG_WriteCoord(&sv.signon, pos[i], sv.protocolflags); //johnfitz -- PROTOCOL_FITZQUAKE - if (large) + if(large) MSG_WriteShort(&sv.signon, soundnum); else - MSG_WriteByte (&sv.signon, soundnum); + MSG_WriteByte(&sv.signon, soundnum); //johnfitz - MSG_WriteByte (&sv.signon, vol*255); - MSG_WriteByte (&sv.signon, attenuation*64); + MSG_WriteByte(&sv.signon, vol * 255); + MSG_WriteByte(&sv.signon, attenuation * 64); } @@ -624,13 +624,13 @@ Larger attenuations will drop off. ================= */ -static void PF_sound (void) +static void PF_sound(void) { - const char *sample; - int32_t channel; - edict_t *entity; - int32_t volume; - float attenuation; + const char *sample; + int32_t channel; + edict_t *entity; + int32_t volume; + float attenuation; entity = G_EDICT(OFS_PARM0); channel = G_FLOAT(OFS_PARM1); @@ -638,16 +638,16 @@ static void PF_sound (void) volume = G_FLOAT(OFS_PARM3) * 255; attenuation = G_FLOAT(OFS_PARM4); - if (volume < 0 || volume > 255) - Host_Error ("SV_StartSound: volume = %" PRIi32 "", volume); + if(volume < 0 || volume > 255) + Host_Error("SV_StartSound: volume = %" PRIi32 "", volume); - if (attenuation < 0 || attenuation > 4) - Host_Error ("SV_StartSound: attenuation = %f", attenuation); + if(attenuation < 0 || attenuation > 4) + Host_Error("SV_StartSound: attenuation = %f", attenuation); - if (channel < 0 || channel > 7) - Host_Error ("SV_StartSound: channel = %" PRIi32 "", channel); + if(channel < 0 || channel > 7) + Host_Error("SV_StartSound: channel = %" PRIi32 "", channel); - SV_StartSound (entity, channel, sample, volume, attenuation); + SV_StartSound(entity, channel, sample, volume, attenuation); } /* @@ -657,10 +657,10 @@ PF_break break() ================= */ -static void PF_break (void) +static void PF_break(void) { - Con_Printf ("break statement\n"); - *(int32_t *)-4 = 0; // dump to debugger + Con_Printf("break statement\n"); + *(int32_t *) -4 = 0; // dump to debugger // PR_RunError ("break statement"); } @@ -675,12 +675,12 @@ if the tryents flag is set. traceline (vector1, vector2, tryents) ================= */ -static void PF_traceline (void) +static void PF_traceline(void) { - float *v1, *v2; - trace_t trace; - int32_t nomonsters; - edict_t *ent; + float *v1, *v2; + trace_t trace; + int32_t nomonsters; + edict_t *ent; v1 = G_VECTOR(OFS_PARM0); v2 = G_VECTOR(OFS_PARM1); @@ -688,30 +688,32 @@ static void PF_traceline (void) ent = G_EDICT(OFS_PARM3); /* FIXME FIXME FIXME: Why do we hit this with certain progs.dat ?? */ - if (developer.value) { - if (IS_NAN(v1[0]) || IS_NAN(v1[1]) || IS_NAN(v1[2]) || - IS_NAN(v2[0]) || IS_NAN(v2[1]) || IS_NAN(v2[2])) { - Con_Warning ("NAN in traceline:\nv1(%f %f %f) v2(%f %f %f)\nentity %" PRIi32 "\n", - v1[0], v1[1], v1[2], v2[0], v2[1], v2[2], NUM_FOR_EDICT(ent)); - } + if(developer.value) + { + if(IS_NAN(v1[0]) || IS_NAN(v1[1]) || IS_NAN(v1[2]) || + IS_NAN(v2[0]) || IS_NAN(v2[1]) || IS_NAN(v2[2])) + { + Con_Warning("NAN in traceline:\nv1(%f %f %f) v2(%f %f %f)\nentity %" PRIi32 "\n", + v1[0], v1[1], v1[2], v2[0], v2[1], v2[2], NUM_FOR_EDICT(ent)); + } } - if (IS_NAN(v1[0]) || IS_NAN(v1[1]) || IS_NAN(v1[2])) + if(IS_NAN(v1[0]) || IS_NAN(v1[1]) || IS_NAN(v1[2])) v1[0] = v1[1] = v1[2] = 0; - if (IS_NAN(v2[0]) || IS_NAN(v2[1]) || IS_NAN(v2[2])) + if(IS_NAN(v2[0]) || IS_NAN(v2[1]) || IS_NAN(v2[2])) v2[0] = v2[1] = v2[2] = 0; - trace = SV_Move (v1, vec3_origin, vec3_origin, v2, nomonsters, ent); + trace = SV_Move(v1, vec3_origin, vec3_origin, v2, nomonsters, ent); pr_global_struct->trace_allsolid = trace.allsolid; pr_global_struct->trace_startsolid = trace.startsolid; pr_global_struct->trace_fraction = trace.fraction; pr_global_struct->trace_inwater = trace.inwater; pr_global_struct->trace_inopen = trace.inopen; - VectorCopy (trace.endpos, pr_global_struct->trace_endpos); - VectorCopy (trace.plane.normal, pr_global_struct->trace_plane_normal); + VectorCopy(trace.endpos, pr_global_struct->trace_endpos); + VectorCopy(trace.plane.normal, pr_global_struct->trace_plane_normal); pr_global_struct->trace_plane_dist = trace.plane.dist; - if (trace.ent) + if(trace.ent) pr_global_struct->trace_ent = EDICT_TO_PROG(trace.ent); else pr_global_struct->trace_ent = EDICT_TO_PROG(sv.edicts); @@ -728,72 +730,72 @@ scalar checkpos (entity, vector) ================= */ #if 0 -static void PF_checkpos (void) +static void PF_checkpos(void) { } #endif //============================================================================ -static byte *checkpvs; //ericw -- changed to malloc -static int32_t checkpvs_capacity; +static byte *checkpvs; //ericw -- changed to malloc +static int32_t checkpvs_capacity; -static int32_t PF_newcheckclient (int32_t check) +static int32_t PF_newcheckclient(int32_t check) { - int32_t i; - byte *pvs; - edict_t *ent; - mleaf_t *leaf; - vec3_t org; - int32_t pvsbytes; + int32_t i; + byte *pvs; + edict_t *ent; + mleaf_t *leaf; + vec3_t org; + int32_t pvsbytes; // cycle to the next one - if (check < 1) + if(check < 1) check = 1; - if (check > svs.maxclients) + if(check > svs.maxclients) check = svs.maxclients; - if (check == svs.maxclients) + if(check == svs.maxclients) i = 1; else i = check + 1; - for ( ; ; i++) + for(; ; i++) { - if (i == svs.maxclients+1) + if(i == svs.maxclients + 1) i = 1; ent = EDICT_NUM(i); - if (i == check) - break; // didn't find anything else + if(i == check) + break; // didn't find anything else - if (ent->free) + if(ent->free) continue; - if (ent->v.health <= 0) + if(ent->v.health <= 0) continue; - if ((int32_t)ent->v.flags & FL_NOTARGET) + if((int32_t)ent->v.flags & FL_NOTARGET) continue; - // anything that is a client, or has a client as an enemy + // anything that is a client, or has a client as an enemy break; } // get the PVS for the entity - VectorAdd (ent->v.origin, ent->v.view_ofs, org); - leaf = Mod_PointInLeaf (org, sv.worldmodel); - pvs = Mod_LeafPVS (leaf, sv.worldmodel); - - pvsbytes = (sv.worldmodel->numleafs+7)>>3; - if (checkpvs == NULL || pvsbytes > checkpvs_capacity) + VectorAdd(ent->v.origin, ent->v.view_ofs, org); + leaf = Mod_PointInLeaf(org, sv.worldmodel); + pvs = Mod_LeafPVS(leaf, sv.worldmodel); + + pvsbytes = (sv.worldmodel->numleafs + 7) >> 3; + if(checkpvs == NULL || pvsbytes > checkpvs_capacity) { checkpvs_capacity = pvsbytes; - checkpvs = (byte *) realloc (checkpvs, checkpvs_capacity); - if (!checkpvs) - Sys_Error ("PF_newcheckclient: realloc() failed on %" PRIi32 " bytes", checkpvs_capacity); + checkpvs = (byte *) realloc(checkpvs, checkpvs_capacity); + if(!checkpvs) + Sys_Error("PF_newcheckclient: realloc() failed on %" PRIi32 " bytes", checkpvs_capacity); } - memcpy (checkpvs, pvs, pvsbytes); + memcpy(checkpvs, pvs, pvsbytes); return i; } @@ -813,25 +815,25 @@ it is not returned at all. name checkclient () ================= */ -#define MAX_CHECK 16 +#define MAX_CHECK 16 static int32_t c_invis, c_notvis; -static void PF_checkclient (void) +static void PF_checkclient(void) { - edict_t *ent, *self; - mleaf_t *leaf; - int32_t l; - vec3_t view; + edict_t *ent, *self; + mleaf_t *leaf; + int32_t l; + vec3_t view; // find a new check if on a new frame - if (sv.time - sv.lastchecktime >= 0.1) + if(sv.time - sv.lastchecktime >= 0.1) { - sv.lastcheck = PF_newcheckclient (sv.lastcheck); + sv.lastcheck = PF_newcheckclient(sv.lastcheck); sv.lastchecktime = sv.time; } // return check if it might be visible ent = EDICT_NUM(sv.lastcheck); - if (ent->free || ent->v.health <= 0) + if(ent->free || ent->v.health <= 0) { RETURN_EDICT(sv.edicts); return; @@ -839,10 +841,10 @@ static void PF_checkclient (void) // if current entity can't possibly see the check entity, return 0 self = PROG_TO_EDICT(pr_global_struct->self); - VectorAdd (self->v.origin, self->v.view_ofs, view); - leaf = Mod_PointInLeaf (view, sv.worldmodel); + VectorAdd(self->v.origin, self->v.view_ofs, view); + leaf = Mod_PointInLeaf(view, sv.worldmodel); l = (leaf - sv.worldmodel->leafs) - 1; - if ( (l < 0) || !(checkpvs[l>>3] & (1 << (l & 7))) ) + if((l < 0) || !(checkpvs[l >> 3] & (1 << (l & 7)))) { c_notvis++; RETURN_EDICT(sv.edicts); @@ -866,20 +868,20 @@ Sends text over to the client's execution buffer stuffcmd (clientent, value) ================= */ -static void PF_stuffcmd (void) +static void PF_stuffcmd(void) { - int32_t entnum; - const char *str; - client_t *old; + int32_t entnum; + const char *str; + client_t *old; entnum = G_EDICTNUM(OFS_PARM0); - if (entnum < 1 || entnum > svs.maxclients) - PR_RunError ("Parm 0 not a client"); + if(entnum < 1 || entnum > svs.maxclients) + PR_RunError("Parm 0 not a client"); str = G_STRING(OFS_PARM1); old = host_client; - host_client = &svs.clients[entnum-1]; - Host_ClientCommands ("%s", str); + host_client = &svs.clients[entnum - 1]; + Host_ClientCommands("%s", str); host_client = old; } @@ -892,12 +894,12 @@ Sends text over to the client's execution buffer localcmd (string) ================= */ -static void PF_localcmd (void) +static void PF_localcmd(void) { - const char *str; + const char *str; str = G_STRING(OFS_PARM0); - Cbuf_AddText (str); + Cbuf_AddText(str); } /* @@ -907,13 +909,13 @@ PF_cvar float cvar (string) ================= */ -static void PF_cvar (void) +static void PF_cvar(void) { - const char *str; + const char *str; str = G_STRING(OFS_PARM0); - G_FLOAT(OFS_RETURN) = Cvar_VariableValue (str); + G_FLOAT(OFS_RETURN) = Cvar_VariableValue(str); } /* @@ -923,14 +925,14 @@ PF_cvar_set float cvar (string) ================= */ -static void PF_cvar_set (void) +static void PF_cvar_set(void) { - const char *var, *val; + const char *var, *val; var = G_STRING(OFS_PARM0); val = G_STRING(OFS_PARM1); - Cvar_Set (var, val); + Cvar_Set(var, val); } /* @@ -942,13 +944,13 @@ Returns a chain of entities that have origins within a spherical area findradius (origin, radius) ================= */ -static void PF_findradius (void) +static void PF_findradius(void) { - edict_t *ent, *chain; - float rad; - float *org; - vec3_t eorg; - int32_t i, j; + edict_t *ent, *chain; + float rad; + float *org; + vec3_t eorg; + int32_t i, j; chain = (edict_t *)sv.edicts; @@ -956,15 +958,15 @@ static void PF_findradius (void) rad = G_FLOAT(OFS_PARM1); ent = NEXT_EDICT(sv.edicts); - for (i = 1; i < sv.num_edicts; i++, ent = NEXT_EDICT(ent)) + for(i = 1; i < sv.num_edicts; i++, ent = NEXT_EDICT(ent)) { - if (ent->free) + if(ent->free) continue; - if (ent->v.solid == SOLID_NOT) + if(ent->v.solid == SOLID_NOT) continue; - for (j = 0; j < 3; j++) + for(j = 0; j < 3; j++) eorg[j] = org[j] - (ent->v.origin[j] + (ent->v.mins[j] + ent->v.maxs[j]) * 0.5); - if (VectorLength(eorg) > rad) + if(VectorLength(eorg) > rad) continue; ent->v.chain = EDICT_TO_PROG(chain); @@ -979,82 +981,82 @@ static void PF_findradius (void) PF_dprint ========= */ -static void PF_dprint (void) +static void PF_dprint(void) { - Con_DPrintf ("%s",PF_VarString(0)); + Con_DPrintf("%s", PF_VarString(0)); } -static void PF_ftos (void) +static void PF_ftos(void) { - float v; - char *s; + float v; + char *s; v = G_FLOAT(OFS_PARM0); s = PR_GetTempString(); - if (v == (int32_t)v) - sprintf (s, "%" PRIi32 "",(int32_t)v); + if(v == (int32_t)v) + sprintf(s, "%" PRIi32 "", (int32_t)v); else - sprintf (s, "%5.1f",v); + sprintf(s, "%5.1f", v); G_INT(OFS_RETURN) = PR_SetEngineString(s); } -static void PF_fabs (void) +static void PF_fabs(void) { - float v; + float v; v = G_FLOAT(OFS_PARM0); G_FLOAT(OFS_RETURN) = fabs(v); } -static void PF_vtos (void) +static void PF_vtos(void) { - char *s; + char *s; s = PR_GetTempString(); - sprintf (s, "'%5.1f %5.1f %5.1f'", G_VECTOR(OFS_PARM0)[0], G_VECTOR(OFS_PARM0)[1], G_VECTOR(OFS_PARM0)[2]); + sprintf(s, "'%5.1f %5.1f %5.1f'", G_VECTOR(OFS_PARM0)[0], G_VECTOR(OFS_PARM0)[1], G_VECTOR(OFS_PARM0)[2]); G_INT(OFS_RETURN) = PR_SetEngineString(s); } -static void PF_Spawn (void) +static void PF_Spawn(void) { - edict_t *ed; + edict_t *ed; ed = ED_Alloc(); RETURN_EDICT(ed); } -static void PF_Remove (void) +static void PF_Remove(void) { - edict_t *ed; + edict_t *ed; ed = G_EDICT(OFS_PARM0); - ED_Free (ed); + ED_Free(ed); } // entity (entity start, .string field, string match) find = #5; -static void PF_Find (void) +static void PF_Find(void) { - int32_t e; - int32_t f; - const char *s, *t; - edict_t *ed; + int32_t e; + int32_t f; + const char *s, *t; + edict_t *ed; e = G_EDICTNUM(OFS_PARM0); f = G_INT(OFS_PARM1); s = G_STRING(OFS_PARM2); - if (!s) - PR_RunError ("PF_Find: bad search string"); + if(!s) + PR_RunError("PF_Find: bad search string"); - for (e++ ; e < sv.num_edicts ; e++) + for(e++ ; e < sv.num_edicts ; e++) { ed = EDICT_NUM(e); - if (ed->free) + if(ed->free) continue; - t = E_STRING(ed,f); - if (!t) + t = E_STRING(ed, f); + if(!t) continue; - if (!strcmp(t,s)) + if(!strcmp(t, s)) { RETURN_EDICT(ed); return; @@ -1064,87 +1066,88 @@ static void PF_Find (void) RETURN_EDICT(sv.edicts); } -static void PR_CheckEmptyString (const char *s) +static void PR_CheckEmptyString(const char *s) { - if (s[0] <= ' ') - PR_RunError ("Bad string"); + if(s[0] <= ' ') + PR_RunError("Bad string"); } -static void PF_precache_file (void) -{ // precache_file is only used to copy files with qcc, it does nothing +static void PF_precache_file(void) +{ + // precache_file is only used to copy files with qcc, it does nothing G_INT(OFS_RETURN) = G_INT(OFS_PARM0); } -static void PF_precache_sound (void) +static void PF_precache_sound(void) { - const char *s; - int32_t i; + const char *s; + int32_t i; - if (sv.state != ss_loading) - PR_RunError ("PF_Precache_*: Precache can only be done in spawn functions"); + if(sv.state != ss_loading) + PR_RunError("PF_Precache_*: Precache can only be done in spawn functions"); s = G_STRING(OFS_PARM0); G_INT(OFS_RETURN) = G_INT(OFS_PARM0); - PR_CheckEmptyString (s); + PR_CheckEmptyString(s); - for (i = 0; i < MAX_SOUNDS; i++) + for(i = 0; i < MAX_SOUNDS; i++) { - if (!sv.sound_precache[i]) + if(!sv.sound_precache[i]) { sv.sound_precache[i] = s; return; } - if (!strcmp(sv.sound_precache[i], s)) + if(!strcmp(sv.sound_precache[i], s)) return; } - PR_RunError ("PF_precache_sound: overflow"); + PR_RunError("PF_precache_sound: overflow"); } -static void PF_precache_model (void) +static void PF_precache_model(void) { - const char *s; - int32_t i; + const char *s; + int32_t i; - if (sv.state != ss_loading) - PR_RunError ("PF_Precache_*: Precache can only be done in spawn functions"); + if(sv.state != ss_loading) + PR_RunError("PF_Precache_*: Precache can only be done in spawn functions"); s = G_STRING(OFS_PARM0); G_INT(OFS_RETURN) = G_INT(OFS_PARM0); - PR_CheckEmptyString (s); + PR_CheckEmptyString(s); - for (i = 0; i < MAX_MODELS; i++) + for(i = 0; i < MAX_MODELS; i++) { - if (!sv.model_precache[i]) + if(!sv.model_precache[i]) { sv.model_precache[i] = s; - sv.models[i] = Mod_ForName (s, true); + sv.models[i] = Mod_ForName(s, true); return; } - if (!strcmp(sv.model_precache[i], s)) + if(!strcmp(sv.model_precache[i], s)) return; } - PR_RunError ("PF_precache_model: overflow"); + PR_RunError("PF_precache_model: overflow"); } -static void PF_coredump (void) +static void PF_coredump(void) { - ED_PrintEdicts (); + ED_PrintEdicts(); } -static void PF_traceon (void) +static void PF_traceon(void) { pr_trace = true; } -static void PF_traceoff (void) +static void PF_traceoff(void) { pr_trace = false; } -static void PF_eprint (void) +static void PF_eprint(void) { - ED_PrintNum (G_EDICTNUM(OFS_PARM0)); + ED_PrintNum(G_EDICTNUM(OFS_PARM0)); } /* @@ -1154,19 +1157,19 @@ PF_walkmove float(float yaw, float dist) walkmove =============== */ -static void PF_walkmove (void) +static void PF_walkmove(void) { - edict_t *ent; - float yaw, dist; - vec3_t move; - dfunction_t *oldf; - int32_t oldself; + edict_t *ent; + float yaw, dist; + vec3_t move; + dfunction_t *oldf; + int32_t oldself; ent = PROG_TO_EDICT(pr_global_struct->self); yaw = G_FLOAT(OFS_PARM0); dist = G_FLOAT(OFS_PARM1); - if ( !( (int32_t)ent->v.flags & (FL_ONGROUND|FL_FLY|FL_SWIM) ) ) + if(!((int32_t)ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM))) { G_FLOAT(OFS_RETURN) = 0; return; @@ -1197,25 +1200,25 @@ PF_droptofloor void() droptofloor =============== */ -static void PF_droptofloor (void) +static void PF_droptofloor(void) { - edict_t *ent; - vec3_t end; - trace_t trace; + edict_t *ent; + vec3_t end; + trace_t trace; ent = PROG_TO_EDICT(pr_global_struct->self); - VectorCopy (ent->v.origin, end); + VectorCopy(ent->v.origin, end); end[2] -= 256; - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); + trace = SV_Move(ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); - if (trace.fraction == 1 || trace.allsolid) + if(trace.fraction == 1 || trace.allsolid) G_FLOAT(OFS_RETURN) = 0; else { - VectorCopy (trace.endpos, ent->v.origin); - SV_LinkEdict (ent, false); + VectorCopy(trace.endpos, ent->v.origin); + SV_LinkEdict(ent, false); ent->v.flags = (int32_t)ent->v.flags | FL_ONGROUND; ent->v.groundentity = EDICT_TO_PROG(trace.ent); G_FLOAT(OFS_RETURN) = 1; @@ -1229,18 +1232,18 @@ PF_lightstyle void(float style, string value) lightstyle =============== */ -static void PF_lightstyle (void) +static void PF_lightstyle(void) { - int32_t style; - const char *val; - client_t *client; - int32_t j; + int32_t style; + const char *val; + client_t *client; + int32_t j; style = G_FLOAT(OFS_PARM0); val = G_STRING(OFS_PARM1); // bounds check to avoid clobbering sv struct - if (style < 0 || style >= MAX_LIGHTSTYLES) + if(style < 0 || style >= MAX_LIGHTSTYLES) { Con_DWarning("PF_lightstyle: invalid style %" PRIi32 "\n", style); return; @@ -1250,36 +1253,36 @@ static void PF_lightstyle (void) sv.lightstyles[style] = val; // send message to all clients on this server - if (sv.state != ss_active) + if(sv.state != ss_active) return; - for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) + for(j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { - if (client->active || client->spawned) + if(client->active || client->spawned) { - MSG_WriteChar (&client->message, svc_lightstyle); - MSG_WriteChar (&client->message, style); - MSG_WriteString (&client->message, val); + MSG_WriteChar(&client->message, svc_lightstyle); + MSG_WriteChar(&client->message, style); + MSG_WriteString(&client->message, val); } } } -static void PF_rint (void) +static void PF_rint(void) { - float f; + float f; f = G_FLOAT(OFS_PARM0); - if (f > 0) + if(f > 0) G_FLOAT(OFS_RETURN) = (int32_t)(f + 0.5); else G_FLOAT(OFS_RETURN) = (int32_t)(f - 0.5); } -static void PF_floor (void) +static void PF_floor(void) { G_FLOAT(OFS_RETURN) = floor(G_FLOAT(OFS_PARM0)); } -static void PF_ceil (void) +static void PF_ceil(void) { G_FLOAT(OFS_RETURN) = ceil(G_FLOAT(OFS_PARM0)); } @@ -1290,13 +1293,13 @@ static void PF_ceil (void) PF_checkbottom ============= */ -static void PF_checkbottom (void) +static void PF_checkbottom(void) { - edict_t *ent; + edict_t *ent; ent = G_EDICT(OFS_PARM0); - G_FLOAT(OFS_RETURN) = SV_CheckBottom (ent); + G_FLOAT(OFS_RETURN) = SV_CheckBottom(ent); } /* @@ -1304,13 +1307,13 @@ static void PF_checkbottom (void) PF_pointcontents ============= */ -static void PF_pointcontents (void) +static void PF_pointcontents(void) { - float *v; + float *v; v = G_VECTOR(OFS_PARM0); - G_FLOAT(OFS_RETURN) = SV_PointContents (v); + G_FLOAT(OFS_RETURN) = SV_PointContents(v); } /* @@ -1320,22 +1323,22 @@ PF_nextent entity nextent(entity) ============= */ -static void PF_nextent (void) +static void PF_nextent(void) { - int32_t i; - edict_t *ent; + int32_t i; + edict_t *ent; i = G_EDICTNUM(OFS_PARM0); - while (1) + while(1) { i++; - if (i == sv.num_edicts) + if(i == sv.num_edicts) { RETURN_EDICT(sv.edicts); return; } ent = EDICT_NUM(i); - if (!ent->free) + if(!ent->free) { RETURN_EDICT(ent); return; @@ -1351,75 +1354,76 @@ Pick a vector for the player to shoot along vector aim(entity, missilespeed) ============= */ -cvar_t sv_aim = {"sv_aim", "1", CVAR_NONE}; // ericw -- turn autoaim off by default. was 0.93 -static void PF_aim (void) +cvar_t sv_aim = {"sv_aim", "1", CVAR_NONE}; // ericw -- turn autoaim off by default. was 0.93 +static void PF_aim(void) { - edict_t *ent, *check, *bestent; - vec3_t start, dir, end, bestdir; - int32_t i, j; - trace_t tr; - float dist, bestdist; - float speed; + edict_t *ent, *check, *bestent; + vec3_t start, dir, end, bestdir; + int32_t i, j; + trace_t tr; + float dist, bestdist; + float speed; ent = G_EDICT(OFS_PARM0); speed = G_FLOAT(OFS_PARM1); (void) speed; /* variable set but not used */ - VectorCopy (ent->v.origin, start); + VectorCopy(ent->v.origin, start); start[2] += 20; // try sending a trace straight - VectorCopy (pr_global_struct->v_forward, dir); - VectorMA (start, 2048, dir, end); - tr = SV_Move (start, vec3_origin, vec3_origin, end, false, ent); - if (tr.ent && tr.ent->v.takedamage == DAMAGE_AIM - && (!teamplay.value || ent->v.team <= 0 || ent->v.team != tr.ent->v.team) ) + VectorCopy(pr_global_struct->v_forward, dir); + VectorMA(start, 2048, dir, end); + tr = SV_Move(start, vec3_origin, vec3_origin, end, false, ent); + if(tr.ent && tr.ent->v.takedamage == DAMAGE_AIM + && (!teamplay.value || ent->v.team <= 0 || ent->v.team != tr.ent->v.team)) { - VectorCopy (pr_global_struct->v_forward, G_VECTOR(OFS_RETURN)); + VectorCopy(pr_global_struct->v_forward, G_VECTOR(OFS_RETURN)); return; } // try all possible entities - VectorCopy (dir, bestdir); + VectorCopy(dir, bestdir); bestdist = sv_aim.value; bestent = NULL; check = NEXT_EDICT(sv.edicts); - for (i = 1; i < sv.num_edicts; i++, check = NEXT_EDICT(check) ) + for(i = 1; i < sv.num_edicts; i++, check = NEXT_EDICT(check)) { - if (check->v.takedamage != DAMAGE_AIM) + if(check->v.takedamage != DAMAGE_AIM) continue; - if (check == ent) + if(check == ent) continue; - if (teamplay.value && ent->v.team > 0 && ent->v.team == check->v.team) - continue; // don't aim at teammate - for (j = 0; j < 3; j++) + if(teamplay.value && ent->v.team > 0 && ent->v.team == check->v.team) + continue; // don't aim at teammate + for(j = 0; j < 3; j++) end[j] = check->v.origin[j] + 0.5 * (check->v.mins[j] + check->v.maxs[j]); - VectorSubtract (end, start, dir); - VectorNormalize (dir); - dist = DotProduct (dir, pr_global_struct->v_forward); - if (dist < bestdist) - continue; // to far to turn - tr = SV_Move (start, vec3_origin, vec3_origin, end, false, ent); - if (tr.ent == check) - { // can shoot at this one + VectorSubtract(end, start, dir); + VectorNormalize(dir); + dist = DotProduct(dir, pr_global_struct->v_forward); + if(dist < bestdist) + continue; // to far to turn + tr = SV_Move(start, vec3_origin, vec3_origin, end, false, ent); + if(tr.ent == check) + { + // can shoot at this one bestdist = dist; bestent = check; } } - if (bestent) + if(bestent) { - VectorSubtract (bestent->v.origin, ent->v.origin, dir); - dist = DotProduct (dir, pr_global_struct->v_forward); - VectorScale (pr_global_struct->v_forward, dist, end); + VectorSubtract(bestent->v.origin, ent->v.origin, dir); + dist = DotProduct(dir, pr_global_struct->v_forward); + VectorScale(pr_global_struct->v_forward, dist, end); end[2] = dir[2]; - VectorNormalize (end); - VectorCopy (end, G_VECTOR(OFS_RETURN)); + VectorNormalize(end); + VectorCopy(end, G_VECTOR(OFS_RETURN)); } else { - VectorCopy (bestdir, G_VECTOR(OFS_RETURN)); + VectorCopy(bestdir, G_VECTOR(OFS_RETURN)); } } @@ -1430,41 +1434,41 @@ PF_changeyaw This was a major timewaster in progs, so it was converted to C ============== */ -void PF_changeyaw (void) +void PF_changeyaw(void) { - edict_t *ent; - float ideal, current, move, speed; + edict_t *ent; + float ideal, current, move, speed; ent = PROG_TO_EDICT(pr_global_struct->self); - current = anglemod( ent->v.angles[1] ); + current = anglemod(ent->v.angles[1]); ideal = ent->v.ideal_yaw; speed = ent->v.yaw_speed; - if (current == ideal) + if(current == ideal) return; move = ideal - current; - if (ideal > current) + if(ideal > current) { - if (move >= 180) + if(move >= 180) move = move - 360; } else { - if (move <= -180) + if(move <= -180) move = move + 360; } - if (move > 0) + if(move > 0) { - if (move > speed) + if(move > speed) move = speed; } else { - if (move < -speed) + if(move < -speed) move = -speed; } - ent->v.angles[1] = anglemod (current + move); + ent->v.angles[1] = anglemod(current + move); } /* @@ -1475,14 +1479,14 @@ MESSAGE WRITING =============================================================================== */ -static sizebuf_t *WriteDest (void) +static sizebuf_t *WriteDest(void) { - int32_t entnum; - int32_t dest; - edict_t *ent; + int32_t entnum; + int32_t dest; + edict_t *ent; dest = G_FLOAT(OFS_PARM0); - switch (dest) + switch(dest) { case MSG_BROADCAST: return &sv.datagram; @@ -1490,9 +1494,9 @@ static sizebuf_t *WriteDest (void) case MSG_ONE: ent = PROG_TO_EDICT(pr_global_struct->msg_entity); entnum = NUM_FOR_EDICT(ent); - if (entnum < 1 || entnum > svs.maxclients) - PR_RunError ("WriteDest: not a client"); - return &svs.clients[entnum-1].message; + if(entnum < 1 || entnum > svs.maxclients) + PR_RunError("WriteDest: not a client"); + return &svs.clients[entnum - 1].message; case MSG_ALL: return &sv.reliable_datagram; @@ -1501,123 +1505,124 @@ static sizebuf_t *WriteDest (void) return &sv.signon; default: - PR_RunError ("WriteDest: bad destination"); + PR_RunError("WriteDest: bad destination"); break; } return NULL; } -static void PF_WriteByte (void) +static void PF_WriteByte(void) { - MSG_WriteByte (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteByte(WriteDest(), G_FLOAT(OFS_PARM1)); } -static void PF_WriteChar (void) +static void PF_WriteChar(void) { - MSG_WriteChar (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteChar(WriteDest(), G_FLOAT(OFS_PARM1)); } -static void PF_WriteShort (void) +static void PF_WriteShort(void) { - MSG_WriteShort (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteShort(WriteDest(), G_FLOAT(OFS_PARM1)); } -static void PF_WriteLong (void) +static void PF_WriteLong(void) { - MSG_WriteLong (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteLong(WriteDest(), G_FLOAT(OFS_PARM1)); } -static void PF_WriteAngle (void) +static void PF_WriteAngle(void) { - MSG_WriteAngle (WriteDest(), G_FLOAT(OFS_PARM1), sv.protocolflags); + MSG_WriteAngle(WriteDest(), G_FLOAT(OFS_PARM1), sv.protocolflags); } -static void PF_WriteCoord (void) +static void PF_WriteCoord(void) { - MSG_WriteCoord (WriteDest(), G_FLOAT(OFS_PARM1), sv.protocolflags); + MSG_WriteCoord(WriteDest(), G_FLOAT(OFS_PARM1), sv.protocolflags); } -static void PF_WriteString (void) +static void PF_WriteString(void) { - MSG_WriteString (WriteDest(), G_STRING(OFS_PARM1)); + MSG_WriteString(WriteDest(), G_STRING(OFS_PARM1)); } -static void PF_WriteEntity (void) +static void PF_WriteEntity(void) { - MSG_WriteShort (WriteDest(), G_EDICTNUM(OFS_PARM1)); + MSG_WriteShort(WriteDest(), G_EDICTNUM(OFS_PARM1)); } //============================================================================= -static void PF_makestatic (void) +static void PF_makestatic(void) { - edict_t *ent; - int32_t i; - int32_t bits = 0; //johnfitz -- PROTOCOL_FITZQUAKE + edict_t *ent; + int32_t i; + int32_t bits = 0; //johnfitz -- PROTOCOL_FITZQUAKE ent = G_EDICT(OFS_PARM0); //johnfitz -- don't send invisible static entities - if (ent->alpha == ENTALPHA_ZERO) { - ED_Free (ent); + if(ent->alpha == ENTALPHA_ZERO) + { + ED_Free(ent); return; } //johnfitz //johnfitz -- PROTOCOL_FITZQUAKE - if (sv.protocol == PROTOCOL_NETQUAKE) + if(sv.protocol == PROTOCOL_NETQUAKE) { - if (SV_ModelIndex(PR_GetString(ent->v.model)) & 0xFF00 || (int32_t)(ent->v.frame) & 0xFF00) + if(SV_ModelIndex(PR_GetString(ent->v.model)) & 0xFF00 || (int32_t)(ent->v.frame) & 0xFF00) { - ED_Free (ent); + ED_Free(ent); return; //can't display the correct model & frame, so don't show it at all } } else { - if (SV_ModelIndex(PR_GetString(ent->v.model)) & 0xFF00) + if(SV_ModelIndex(PR_GetString(ent->v.model)) & 0xFF00) bits |= B_LARGEMODEL; - if ((int32_t)(ent->v.frame) & 0xFF00) + if((int32_t)(ent->v.frame) & 0xFF00) bits |= B_LARGEFRAME; - if (ent->alpha != ENTALPHA_DEFAULT) + if(ent->alpha != ENTALPHA_DEFAULT) bits |= B_ALPHA; } - if (bits) + if(bits) { - MSG_WriteByte (&sv.signon, svc_spawnstatic2); - MSG_WriteByte (&sv.signon, bits); + MSG_WriteByte(&sv.signon, svc_spawnstatic2); + MSG_WriteByte(&sv.signon, bits); } else - MSG_WriteByte (&sv.signon, svc_spawnstatic); + MSG_WriteByte(&sv.signon, svc_spawnstatic); - if (bits & B_LARGEMODEL) - MSG_WriteShort (&sv.signon, SV_ModelIndex(PR_GetString(ent->v.model))); + if(bits & B_LARGEMODEL) + MSG_WriteShort(&sv.signon, SV_ModelIndex(PR_GetString(ent->v.model))); else - MSG_WriteByte (&sv.signon, SV_ModelIndex(PR_GetString(ent->v.model))); + MSG_WriteByte(&sv.signon, SV_ModelIndex(PR_GetString(ent->v.model))); - if (bits & B_LARGEFRAME) - MSG_WriteShort (&sv.signon, ent->v.frame); + if(bits & B_LARGEFRAME) + MSG_WriteShort(&sv.signon, ent->v.frame); else - MSG_WriteByte (&sv.signon, ent->v.frame); + MSG_WriteByte(&sv.signon, ent->v.frame); //johnfitz - MSG_WriteByte (&sv.signon, ent->v.colormap); - MSG_WriteByte (&sv.signon, ent->v.skin); - for (i = 0; i < 3; i++) + MSG_WriteByte(&sv.signon, ent->v.colormap); + MSG_WriteByte(&sv.signon, ent->v.skin); + for(i = 0; i < 3; i++) { MSG_WriteCoord(&sv.signon, ent->v.origin[i], sv.protocolflags); MSG_WriteAngle(&sv.signon, ent->v.angles[i], sv.protocolflags); } //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & B_ALPHA) - MSG_WriteByte (&sv.signon, ent->alpha); + if(bits & B_ALPHA) + MSG_WriteByte(&sv.signon, ent->alpha); //johnfitz // throw the entity away now - ED_Free (ent); + ED_Free(ent); } //============================================================================= @@ -1627,21 +1632,21 @@ static void PF_makestatic (void) PF_setspawnparms ============== */ -static void PF_setspawnparms (void) +static void PF_setspawnparms(void) { - edict_t *ent; - int32_t i; - client_t *client; + edict_t *ent; + int32_t i; + client_t *client; ent = G_EDICT(OFS_PARM0); i = NUM_FOR_EDICT(ent); - if (i < 1 || i > svs.maxclients) - PR_RunError ("Entity is not a client"); + if(i < 1 || i > svs.maxclients) + PR_RunError("Entity is not a client"); // copy spawn parms out of the client_t - client = svs.clients + (i-1); + client = svs.clients + (i - 1); - for (i = 0; i < NUM_SPAWN_PARMS; i++) + for(i = 0; i < NUM_SPAWN_PARMS; i++) (&pr_global_struct->parm1)[i] = client->spawn_parms[i]; } @@ -1650,61 +1655,61 @@ static void PF_setspawnparms (void) PF_changelevel ============== */ -static void PF_changelevel (void) +static void PF_changelevel(void) { - const char *s; + const char *s; // make sure we don't issue two changelevels - if (svs.changelevel_issued) + if(svs.changelevel_issued) return; svs.changelevel_issued = true; s = G_STRING(OFS_PARM0); - Cbuf_AddText (va("changelevel %s\n",s)); + Cbuf_AddText(va("changelevel %s\n", s)); } -static void PF_Fixme (void) +static void PF_Fixme(void) { - PR_RunError ("unimplemented builtin"); + PR_RunError("unimplemented builtin"); } static builtin_t pr_builtin[] = { PF_Fixme, - PF_makevectors, // void(entity e) makevectors = #1 - PF_setorigin, // void(entity e, vector o) setorigin = #2 - PF_setmodel, // void(entity e, string m) setmodel = #3 - PF_setsize, // void(entity e, vector min, vector max) setsize = #4 - PF_Fixme, // void(entity e, vector min, vector max) setabssize = #5 - PF_break, // void() break = #6 - PF_random, // float() random = #7 - PF_sound, // void(entity e, float chan, string samp) sound = #8 - PF_normalize, // vector(vector v) normalize = #9 - PF_error, // void(string e) error = #10 - PF_objerror, // void(string e) objerror = #11 - PF_vlen, // float(vector v) vlen = #12 - PF_vectoyaw, // float(vector v) vectoyaw = #13 - PF_Spawn, // entity() spawn = #14 - PF_Remove, // void(entity e) remove = #15 - PF_traceline, // float(vector v1, vector v2, float tryents) traceline = #16 - PF_checkclient, // entity() clientlist = #17 - PF_Find, // entity(entity start, .string fld, string match) find = #18 - PF_precache_sound, // void(string s) precache_sound = #19 - PF_precache_model, // void(string s) precache_model = #20 - PF_stuffcmd, // void(entity client, string s)stuffcmd = #21 - PF_findradius, // entity(vector org, float rad) findradius = #22 - PF_bprint, // void(string s) bprint = #23 - PF_sprint, // void(entity client, string s) sprint = #24 - PF_dprint, // void(string s) dprint = #25 - PF_ftos, // void(string s) ftos = #26 - PF_vtos, // void(string s) vtos = #27 + PF_makevectors, // void(entity e) makevectors = #1 + PF_setorigin, // void(entity e, vector o) setorigin = #2 + PF_setmodel, // void(entity e, string m) setmodel = #3 + PF_setsize, // void(entity e, vector min, vector max) setsize = #4 + PF_Fixme, // void(entity e, vector min, vector max) setabssize = #5 + PF_break, // void() break = #6 + PF_random, // float() random = #7 + PF_sound, // void(entity e, float chan, string samp) sound = #8 + PF_normalize, // vector(vector v) normalize = #9 + PF_error, // void(string e) error = #10 + PF_objerror, // void(string e) objerror = #11 + PF_vlen, // float(vector v) vlen = #12 + PF_vectoyaw, // float(vector v) vectoyaw = #13 + PF_Spawn, // entity() spawn = #14 + PF_Remove, // void(entity e) remove = #15 + PF_traceline, // float(vector v1, vector v2, float tryents) traceline = #16 + PF_checkclient, // entity() clientlist = #17 + PF_Find, // entity(entity start, .string fld, string match) find = #18 + PF_precache_sound, // void(string s) precache_sound = #19 + PF_precache_model, // void(string s) precache_model = #20 + PF_stuffcmd, // void(entity client, string s)stuffcmd = #21 + PF_findradius, // entity(vector org, float rad) findradius = #22 + PF_bprint, // void(string s) bprint = #23 + PF_sprint, // void(entity client, string s) sprint = #24 + PF_dprint, // void(string s) dprint = #25 + PF_ftos, // void(string s) ftos = #26 + PF_vtos, // void(string s) vtos = #27 PF_coredump, PF_traceon, PF_traceoff, - PF_eprint, // void(entity e) debug print an entire entity - PF_walkmove, // float(float yaw, float dist) walkmove - PF_Fixme, // float(float yaw, float dist) walkmove + PF_eprint, // void(entity e) debug print an entire entity + PF_walkmove, // float(float yaw, float dist) walkmove + PF_Fixme, // float(float yaw, float dist) walkmove PF_droptofloor, PF_lightstyle, PF_rint, @@ -1754,12 +1759,12 @@ static builtin_t pr_builtin[] = PF_ambientsound, PF_precache_model, - PF_precache_sound, // precache_sound2 is different only for qcc + PF_precache_sound, // precache_sound2 is different only for qcc PF_precache_file, PF_setspawnparms }; builtin_t *pr_builtins = pr_builtin; -int32_t pr_numbuiltins = sizeof(pr_builtin)/sizeof(pr_builtin[0]); +int32_t pr_numbuiltins = sizeof(pr_builtin) / sizeof(pr_builtin[0]); diff --git a/source/pr_comp.h b/source/pr_comp.h index bcdbacc..2a2fe3b 100644 --- a/source/pr_comp.h +++ b/source/pr_comp.h @@ -24,8 +24,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // this file is shared by quake and qcc -typedef int32_t func_t; -typedef int32_t string_t; +typedef int32_t func_t; +typedef int32_t string_t; typedef enum { @@ -40,17 +40,17 @@ typedef enum ev_pointer } etype_t; -#define OFS_NULL 0 -#define OFS_RETURN 1 -#define OFS_PARM0 4 // leave 3 ofs for each parm to hold vectors -#define OFS_PARM1 7 -#define OFS_PARM2 10 -#define OFS_PARM3 13 -#define OFS_PARM4 16 -#define OFS_PARM5 19 -#define OFS_PARM6 22 -#define OFS_PARM7 25 -#define RESERVED_OFS 28 +#define OFS_NULL 0 +#define OFS_RETURN 1 +#define OFS_PARM0 4 // leave 3 ofs for each parm to hold vectors +#define OFS_PARM1 7 +#define OFS_PARM2 10 +#define OFS_PARM3 13 +#define OFS_PARM4 16 +#define OFS_PARM5 19 +#define OFS_PARM6 22 +#define OFS_PARM7 25 +#define RESERVED_OFS 28 enum @@ -134,64 +134,64 @@ enum typedef struct statement_s { - uint16_t op; - int16_t a, b, c; + uint16_t op; + int16_t a, b, c; } dstatement_t; typedef struct { - uint16_t type; // if DEF_SAVEGLOBAL bit is set - // the variable needs to be saved in savegames - uint16_t ofs; - int32_t s_name; + uint16_t type; // if DEF_SAVEGLOBAL bit is set + // the variable needs to be saved in savegames + uint16_t ofs; + int32_t s_name; } ddef_t; -#define DEF_SAVEGLOBAL (1<<15) +#define DEF_SAVEGLOBAL (1<<15) -#define MAX_PARMS 8 +#define MAX_PARMS 8 typedef struct { - int32_t first_statement; // negative numbers are builtins - int32_t parm_start; - int32_t locals; // total ints of parms + locals + int32_t first_statement; // negative numbers are builtins + int32_t parm_start; + int32_t locals; // total ints of parms + locals - int32_t profile; // runtime + int32_t profile; // runtime - int32_t s_name; - int32_t s_file; // source file defined in + int32_t s_name; + int32_t s_file; // source file defined in - int32_t numparms; - byte parm_size[MAX_PARMS]; + int32_t numparms; + byte parm_size[MAX_PARMS]; } dfunction_t; -#define PROG_VERSION 6 +#define PROG_VERSION 6 typedef struct { - int32_t version; - int32_t crc; // check of header file + int32_t version; + int32_t crc; // check of header file - int32_t ofs_statements; - int32_t numstatements; // statement 0 is an error + int32_t ofs_statements; + int32_t numstatements; // statement 0 is an error - int32_t ofs_globaldefs; - int32_t numglobaldefs; + int32_t ofs_globaldefs; + int32_t numglobaldefs; - int32_t ofs_fielddefs; - int32_t numfielddefs; + int32_t ofs_fielddefs; + int32_t numfielddefs; - int32_t ofs_functions; - int32_t numfunctions; // function 0 is an empty + int32_t ofs_functions; + int32_t numfunctions; // function 0 is an empty - int32_t ofs_strings; - int32_t numstrings; // first string is a null string + int32_t ofs_strings; + int32_t numstrings; // first string is a null string - int32_t ofs_globals; - int32_t numglobals; + int32_t ofs_globals; + int32_t numglobals; - int32_t entityfields; + int32_t entityfields; } dprograms_t; -#endif /* __PR_COMP_H */ +#endif /* __PR_COMP_H */ diff --git a/source/pr_edict.c b/source/pr_edict.c index 1219ba2..0e9a0de 100644 --- a/source/pr_edict.c +++ b/source/pr_edict.c @@ -23,65 +23,67 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -dprograms_t *progs; -dfunction_t *pr_functions; +dprograms_t *progs; +dfunction_t *pr_functions; -static char *pr_strings; -static int32_t pr_stringssize; -static const char **pr_knownstrings; -static int32_t pr_maxknownstrings; -static int32_t pr_numknownstrings; -static ddef_t *pr_fielddefs; -static ddef_t *pr_globaldefs; +static char *pr_strings; +static int32_t pr_stringssize; +static const char **pr_knownstrings; +static int32_t pr_maxknownstrings; +static int32_t pr_numknownstrings; +static ddef_t *pr_fielddefs; +static ddef_t *pr_globaldefs; -bool pr_alpha_supported; //johnfitz +bool pr_alpha_supported; //johnfitz -dstatement_t *pr_statements; -globalvars_t *pr_global_struct; -float *pr_globals; // same as pr_global_struct -int32_t pr_edict_size; // in bytes +dstatement_t *pr_statements; +globalvars_t *pr_global_struct; +float *pr_globals; // same as pr_global_struct +int32_t pr_edict_size; // in bytes -uint16_t pr_crc; +uint16_t pr_crc; -int32_t type_size[8] = { - 1, // ev_void - 1, // sizeof(string_t) / 4 // ev_string - 1, // ev_float - 3, // ev_vector - 1, // ev_entity - 1, // ev_field - 1, // sizeof(func_t) / 4 // ev_function - 1 // sizeof(void *) / 4 // ev_pointer +int32_t type_size[8] = +{ + 1, // ev_void + 1, // sizeof(string_t) / 4 // ev_string + 1, // ev_float + 3, // ev_vector + 1, // ev_entity + 1, // ev_field + 1, // sizeof(func_t) / 4 // ev_function + 1 // sizeof(void *) / 4 // ev_pointer }; -static ddef_t *ED_FieldAtOfs (int32_t ofs); -static bool ED_ParseEpair (void *base, ddef_t *key, const char *s); +static ddef_t *ED_FieldAtOfs(int32_t ofs); +static bool ED_ParseEpair(void *base, ddef_t *key, const char *s); -#define MAX_FIELD_LEN 64 -#define GEFV_CACHESIZE 2 +#define MAX_FIELD_LEN 64 +#define GEFV_CACHESIZE 2 -typedef struct { - ddef_t *pcache; - char field[MAX_FIELD_LEN]; +typedef struct +{ + ddef_t *pcache; + char field[MAX_FIELD_LEN]; } gefv_cache; -static gefv_cache gefvCache[GEFV_CACHESIZE] = +static gefv_cache gefvCache[GEFV_CACHESIZE] = { - { NULL, "" }, - { NULL, "" } + { NULL, "" }, + { NULL, "" } }; -cvar_t nomonsters = {"nomonsters", "0", CVAR_NONE}; -cvar_t gamecfg = {"gamecfg", "0", CVAR_NONE}; -cvar_t scratch1 = {"scratch1", "0", CVAR_NONE}; -cvar_t scratch2 = {"scratch2", "0", CVAR_NONE}; -cvar_t scratch3 = {"scratch3", "0", CVAR_NONE}; -cvar_t scratch4 = {"scratch4", "0", CVAR_NONE}; -cvar_t savedgamecfg = {"savedgamecfg", "0", CVAR_ARCHIVE}; -cvar_t saved1 = {"saved1", "0", CVAR_ARCHIVE}; -cvar_t saved2 = {"saved2", "0", CVAR_ARCHIVE}; -cvar_t saved3 = {"saved3", "0", CVAR_ARCHIVE}; -cvar_t saved4 = {"saved4", "0", CVAR_ARCHIVE}; +cvar_t nomonsters = {"nomonsters", "0", CVAR_NONE}; +cvar_t gamecfg = {"gamecfg", "0", CVAR_NONE}; +cvar_t scratch1 = {"scratch1", "0", CVAR_NONE}; +cvar_t scratch2 = {"scratch2", "0", CVAR_NONE}; +cvar_t scratch3 = {"scratch3", "0", CVAR_NONE}; +cvar_t scratch4 = {"scratch4", "0", CVAR_NONE}; +cvar_t savedgamecfg = {"savedgamecfg", "0", CVAR_ARCHIVE}; +cvar_t saved1 = {"saved1", "0", CVAR_ARCHIVE}; +cvar_t saved2 = {"saved2", "0", CVAR_ARCHIVE}; +cvar_t saved3 = {"saved3", "0", CVAR_ARCHIVE}; +cvar_t saved4 = {"saved4", "0", CVAR_ARCHIVE}; /* ================= @@ -90,9 +92,9 @@ ED_ClearEdict Sets everything to NULL ================= */ -void ED_ClearEdict (edict_t *e) +void ED_ClearEdict(edict_t *e) { - memset (&e->v, 0, progs->entityfields * 4); + memset(&e->v, 0, progs->entityfields * 4); e->free = false; } @@ -107,25 +109,25 @@ instead of being removed and recreated, which can cause interpolated angles and bad trails. ================= */ -edict_t *ED_Alloc (void) +edict_t *ED_Alloc(void) { - int32_t i; - edict_t *e; + int32_t i; + edict_t *e; - for (i = svs.maxclients + 1; i < sv.num_edicts; i++) + for(i = svs.maxclients + 1; i < sv.num_edicts; i++) { e = EDICT_NUM(i); // the first couple seconds of server time can involve a lot of // freeing and allocating, so relax the replacement policy - if (e->free && ( e->freetime < 2 || sv.time - e->freetime > 0.5 ) ) + if(e->free && (e->freetime < 2 || sv.time - e->freetime > 0.5)) { - ED_ClearEdict (e); + ED_ClearEdict(e); return e; } } - if (i == sv.max_edicts) //johnfitz -- use sv.max_edicts instead of MAX_EDICTS - Host_Error ("ED_Alloc: no free edicts (max_edicts is %" PRIi32 ")", sv.max_edicts); + if(i == sv.max_edicts) //johnfitz -- use sv.max_edicts instead of MAX_EDICTS + Host_Error("ED_Alloc: no free edicts (max_edicts is %" PRIi32 ")", sv.max_edicts); sv.num_edicts++; e = EDICT_NUM(i); @@ -142,9 +144,9 @@ Marks the edict as free FIXME: walk all entities and NULL out references to this entity ================= */ -void ED_Free (edict_t *ed) +void ED_Free(edict_t *ed) { - SV_UnlinkEdict (ed); // unlink from world bsp + SV_UnlinkEdict(ed); // unlink from world bsp ed->free = true; ed->v.model = 0; @@ -153,8 +155,8 @@ void ED_Free (edict_t *ed) ed->v.colormap = 0; ed->v.skin = 0; ed->v.frame = 0; - VectorCopy (vec3_origin, ed->v.origin); - VectorCopy (vec3_origin, ed->v.angles); + VectorCopy(vec3_origin, ed->v.origin); + VectorCopy(vec3_origin, ed->v.angles); ed->v.nextthink = -1; ed->v.solid = 0; ed->alpha = ENTALPHA_DEFAULT; //johnfitz -- reset alpha for next entity @@ -169,15 +171,15 @@ void ED_Free (edict_t *ed) ED_GlobalAtOfs ============ */ -static ddef_t *ED_GlobalAtOfs (int32_t ofs) +static ddef_t *ED_GlobalAtOfs(int32_t ofs) { - ddef_t *def; - int32_t i; + ddef_t *def; + int32_t i; - for (i = 0; i < progs->numglobaldefs; i++) + for(i = 0; i < progs->numglobaldefs; i++) { def = &pr_globaldefs[i]; - if (def->ofs == ofs) + if(def->ofs == ofs) return def; } return NULL; @@ -188,15 +190,15 @@ static ddef_t *ED_GlobalAtOfs (int32_t ofs) ED_FieldAtOfs ============ */ -static ddef_t *ED_FieldAtOfs (int32_t ofs) +static ddef_t *ED_FieldAtOfs(int32_t ofs) { - ddef_t *def; - int32_t i; + ddef_t *def; + int32_t i; - for (i = 0; i < progs->numfielddefs; i++) + for(i = 0; i < progs->numfielddefs; i++) { def = &pr_fielddefs[i]; - if (def->ofs == ofs) + if(def->ofs == ofs) return def; } return NULL; @@ -207,15 +209,15 @@ static ddef_t *ED_FieldAtOfs (int32_t ofs) ED_FindField ============ */ -static ddef_t *ED_FindField (const char *name) +static ddef_t *ED_FindField(const char *name) { - ddef_t *def; - int32_t i; + ddef_t *def; + int32_t i; - for (i = 0; i < progs->numfielddefs; i++) + for(i = 0; i < progs->numfielddefs; i++) { def = &pr_fielddefs[i]; - if ( !strcmp(PR_GetString(def->s_name), name) ) + if(!strcmp(PR_GetString(def->s_name), name)) return def; } return NULL; @@ -227,15 +229,15 @@ static ddef_t *ED_FindField (const char *name) ED_FindGlobal ============ */ -static ddef_t *ED_FindGlobal (const char *name) +static ddef_t *ED_FindGlobal(const char *name) { - ddef_t *def; - int32_t i; + ddef_t *def; + int32_t i; - for (i = 0; i < progs->numglobaldefs; i++) + for(i = 0; i < progs->numglobaldefs; i++) { def = &pr_globaldefs[i]; - if ( !strcmp(PR_GetString(def->s_name), name) ) + if(!strcmp(PR_GetString(def->s_name), name)) return def; } return NULL; @@ -247,15 +249,15 @@ static ddef_t *ED_FindGlobal (const char *name) ED_FindFunction ============ */ -static dfunction_t *ED_FindFunction (const char *fn_name) +static dfunction_t *ED_FindFunction(const char *fn_name) { - dfunction_t *func; - int32_t i; + dfunction_t *func; + int32_t i; - for (i = 0; i < progs->numfunctions; i++) + for(i = 0; i < progs->numfunctions; i++) { func = &pr_functions[i]; - if ( !strcmp(PR_GetString(func->s_name), fn_name) ) + if(!strcmp(PR_GetString(func->s_name), fn_name)) return func; } return NULL; @@ -268,33 +270,33 @@ GetEdictFieldValue */ eval_t *GetEdictFieldValue(edict_t *ed, const char *field) { - ddef_t *def = NULL; - int32_t i; - static int32_t rep = 0; + ddef_t *def = NULL; + int32_t i; + static int32_t rep = 0; - for (i = 0; i < GEFV_CACHESIZE; i++) + for(i = 0; i < GEFV_CACHESIZE; i++) { - if (!strcmp(field, gefvCache[i].field)) + if(!strcmp(field, gefvCache[i].field)) { def = gefvCache[i].pcache; goto Done; } } - def = ED_FindField (field); + def = ED_FindField(field); - if (strlen(field) < MAX_FIELD_LEN) + if(strlen(field) < MAX_FIELD_LEN) { gefvCache[rep].pcache = def; - strcpy (gefvCache[rep].field, field); + strcpy(gefvCache[rep].field, field); rep ^= 1; } Done: - if (!def) + if(!def) return NULL; - return (eval_t *)((char *)&ed->v + def->ofs*4); + return (eval_t *)((char *)&ed->v + def->ofs * 4); } @@ -306,44 +308,44 @@ PR_ValueString Returns a string describing *data in a type specific manner ============= */ -static const char *PR_ValueString (int32_t type, eval_t *val) +static const char *PR_ValueString(int32_t type, eval_t *val) { - static char line[512]; - ddef_t *def; - dfunction_t *f; + static char line[512]; + ddef_t *def; + dfunction_t *f; type &= ~DEF_SAVEGLOBAL; - switch (type) + switch(type) { case ev_string: - sprintf (line, "%s", PR_GetString(val->string)); + sprintf(line, "%s", PR_GetString(val->string)); break; case ev_entity: - sprintf (line, "entity %" PRIi32 "", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict)) ); + sprintf(line, "entity %" PRIi32 "", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict))); break; case ev_function: f = pr_functions + val->function; - sprintf (line, "%s()", PR_GetString(f->s_name)); + sprintf(line, "%s()", PR_GetString(f->s_name)); break; case ev_field: - def = ED_FieldAtOfs ( val->_int ); - sprintf (line, ".%s", PR_GetString(def->s_name)); + def = ED_FieldAtOfs(val->_int); + sprintf(line, ".%s", PR_GetString(def->s_name)); break; case ev_void: - sprintf (line, "void"); + sprintf(line, "void"); break; case ev_float: - sprintf (line, "%5.1f", val->_float); + sprintf(line, "%5.1f", val->_float); break; case ev_vector: - sprintf (line, "'%5.1f %5.1f %5.1f'", val->vector[0], val->vector[1], val->vector[2]); + sprintf(line, "'%5.1f %5.1f %5.1f'", val->vector[0], val->vector[1], val->vector[2]); break; case ev_pointer: - sprintf (line, "pointer"); + sprintf(line, "pointer"); break; default: - sprintf (line, "bad type %" PRIi32 "", type); + sprintf(line, "bad type %" PRIi32 "", type); break; } @@ -359,41 +361,41 @@ Returns a string describing *data in a type specific manner Easier to parse than PR_ValueString ============= */ -static const char *PR_UglyValueString (int32_t type, eval_t *val) +static const char *PR_UglyValueString(int32_t type, eval_t *val) { - static char line[512]; - ddef_t *def; - dfunction_t *f; + static char line[512]; + ddef_t *def; + dfunction_t *f; type &= ~DEF_SAVEGLOBAL; - switch (type) + switch(type) { case ev_string: - sprintf (line, "%s", PR_GetString(val->string)); + sprintf(line, "%s", PR_GetString(val->string)); break; case ev_entity: - sprintf (line, "%" PRIi32 "", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict))); + sprintf(line, "%" PRIi32 "", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict))); break; case ev_function: f = pr_functions + val->function; - sprintf (line, "%s", PR_GetString(f->s_name)); + sprintf(line, "%s", PR_GetString(f->s_name)); break; case ev_field: - def = ED_FieldAtOfs ( val->_int ); - sprintf (line, "%s", PR_GetString(def->s_name)); + def = ED_FieldAtOfs(val->_int); + sprintf(line, "%s", PR_GetString(def->s_name)); break; case ev_void: - sprintf (line, "void"); + sprintf(line, "void"); break; case ev_float: - sprintf (line, "%f", val->_float); + sprintf(line, "%f", val->_float); break; case ev_vector: - sprintf (line, "%f %f %f", val->vector[0], val->vector[1], val->vector[2]); + sprintf(line, "%f %f %f", val->vector[0], val->vector[1], val->vector[2]); break; default: - sprintf (line, "bad type %" PRIi32 "", type); + sprintf(line, "bad type %" PRIi32 "", type); break; } @@ -408,48 +410,48 @@ Returns a string with a description and the contents of a global, padded to 20 field width ============ */ -const char *PR_GlobalString (int32_t ofs) +const char *PR_GlobalString(int32_t ofs) { - static char line[512]; - const char *s; - int32_t i; - ddef_t *def; - void *val; + static char line[512]; + const char *s; + int32_t i; + ddef_t *def; + void *val; val = (void *)&pr_globals[ofs]; def = ED_GlobalAtOfs(ofs); - if (!def) - sprintf (line,"%" PRIi32 "(?)", ofs); + if(!def) + sprintf(line, "%" PRIi32 "(?)", ofs); else { - s = PR_ValueString (def->type, (eval_t *)val); - sprintf (line,"%" PRIi32 "(%s)%s", ofs, PR_GetString(def->s_name), s); + s = PR_ValueString(def->type, (eval_t *)val); + sprintf(line, "%" PRIi32 "(%s)%s", ofs, PR_GetString(def->s_name), s); } i = strlen(line); - for ( ; i < 20; i++) - strcat (line, " "); - strcat (line, " "); + for(; i < 20; i++) + strcat(line, " "); + strcat(line, " "); return line; } -const char *PR_GlobalStringNoContents (int32_t ofs) +const char *PR_GlobalStringNoContents(int32_t ofs) { - static char line[512]; - int32_t i; - ddef_t *def; + static char line[512]; + int32_t i; + ddef_t *def; def = ED_GlobalAtOfs(ofs); - if (!def) - sprintf (line,"%" PRIi32 "(?)", ofs); + if(!def) + sprintf(line, "%" PRIi32 "(?)", ofs); else - sprintf (line,"%" PRIi32 "(%s)", ofs, PR_GetString(def->s_name)); + sprintf(line, "%" PRIi32 "(%s)", ofs, PR_GetString(def->s_name)); i = strlen(line); - for ( ; i < 20; i++) - strcat (line, " "); - strcat (line, " "); + for(; i < 20; i++) + strcat(line, " "); + strcat(line, " "); return line; } @@ -462,47 +464,47 @@ ED_Print For debugging ============= */ -void ED_Print (edict_t *ed) +void ED_Print(edict_t *ed) { - ddef_t *d; - int32_t *v; - int32_t i, j, l; - const char *name; - int32_t type; + ddef_t *d; + int32_t *v; + int32_t i, j, l; + const char *name; + int32_t type; - if (ed->free) + if(ed->free) { - Con_Printf ("FREE\n"); + Con_Printf("FREE\n"); return; } Con_SafePrintf("\nEDICT %" PRIi32 ":\n", NUM_FOR_EDICT(ed)); //johnfitz -- was Con_Printf - for (i = 1; i < progs->numfielddefs; i++) + for(i = 1; i < progs->numfielddefs; i++) { d = &pr_fielddefs[i]; name = PR_GetString(d->s_name); - l = strlen (name); - if (l > 1 && name[l - 2] == '_') - continue; // skip _x, _y, _z vars + l = strlen(name); + if(l > 1 && name[l - 2] == '_') + continue; // skip _x, _y, _z vars - v = (int32_t *)((char *)&ed->v + d->ofs*4); + v = (int32_t *)((char *)&ed->v + d->ofs * 4); - // if the value is still all 0, skip the field + // if the value is still all 0, skip the field type = d->type & ~DEF_SAVEGLOBAL; - for (j = 0; j < type_size[type]; j++) + for(j = 0; j < type_size[type]; j++) { - if (v[j]) + if(v[j]) break; } - if (j == type_size[type]) + if(j == type_size[type]) continue; - Con_SafePrintf ("%s", name); //johnfitz -- was Con_Printf - while (l++ < 15) - Con_SafePrintf (" "); //johnfitz -- was Con_Printf + Con_SafePrintf("%s", name); //johnfitz -- was Con_Printf + while(l++ < 15) + Con_SafePrintf(" "); //johnfitz -- was Con_Printf - Con_SafePrintf ("%s\n", PR_ValueString(d->type, (eval_t *)v)); //johnfitz -- was Con_Printf + Con_SafePrintf("%s\n", PR_ValueString(d->type, (eval_t *)v)); //johnfitz -- was Con_Printf } } @@ -513,57 +515,57 @@ ED_Write For savegames ============= */ -void ED_Write (FILE *f, edict_t *ed) +void ED_Write(FILE *f, edict_t *ed) { - ddef_t *d; - int32_t *v; - int32_t i, j; - const char *name; - int32_t type; + ddef_t *d; + int32_t *v; + int32_t i, j; + const char *name; + int32_t type; - fprintf (f, "{\n"); + fprintf(f, "{\n"); - if (ed->free) + if(ed->free) { - fprintf (f, "}\n"); + fprintf(f, "}\n"); return; } - for (i = 1; i < progs->numfielddefs; i++) + for(i = 1; i < progs->numfielddefs; i++) { d = &pr_fielddefs[i]; name = PR_GetString(d->s_name); - j = strlen (name); - if (j > 1 && name[j - 2] == '_') - continue; // skip _x, _y, _z vars + j = strlen(name); + if(j > 1 && name[j - 2] == '_') + continue; // skip _x, _y, _z vars - v = (int32_t *)((char *)&ed->v + d->ofs*4); + v = (int32_t *)((char *)&ed->v + d->ofs * 4); - // if the value is still all 0, skip the field + // if the value is still all 0, skip the field type = d->type & ~DEF_SAVEGLOBAL; - for (j = 0; j < type_size[type]; j++) + for(j = 0; j < type_size[type]; j++) { - if (v[j]) + if(v[j]) break; } - if (j == type_size[type]) + if(j == type_size[type]) continue; - fprintf (f, "\"%s\" ", name); - fprintf (f, "\"%s\"\n", PR_UglyValueString(d->type, (eval_t *)v)); + fprintf(f, "\"%s\" ", name); + fprintf(f, "\"%s\"\n", PR_UglyValueString(d->type, (eval_t *)v)); } //johnfitz -- save entity alpha manually when progs.dat doesn't know about alpha - if (!pr_alpha_supported && ed->alpha != ENTALPHA_DEFAULT) - fprintf (f, "\"alpha\" \"%f\"\n", ENTALPHA_TOSAVE(ed->alpha)); + if(!pr_alpha_supported && ed->alpha != ENTALPHA_DEFAULT) + fprintf(f, "\"alpha\" \"%f\"\n", ENTALPHA_TOSAVE(ed->alpha)); //johnfitz - fprintf (f, "}\n"); + fprintf(f, "}\n"); } -void ED_PrintNum (int32_t ent) +void ED_PrintNum(int32_t ent) { - ED_Print (EDICT_NUM(ent)); + ED_Print(EDICT_NUM(ent)); } /* @@ -573,16 +575,16 @@ ED_PrintEdicts For debugging, prints all the entities in the current server ============= */ -void ED_PrintEdicts (void) +void ED_PrintEdicts(void) { - int32_t i; + int32_t i; - if (!sv.active) + if(!sv.active) return; - Con_Printf ("%" PRIi32 " entities\n", sv.num_edicts); - for (i = 0; i < sv.num_edicts; i++) - ED_PrintNum (i); + Con_Printf("%" PRIi32 " entities\n", sv.num_edicts); + for(i = 0; i < sv.num_edicts; i++) + ED_PrintNum(i); } /* @@ -592,20 +594,20 @@ ED_PrintEdict_f For debugging, prints a single edicy ============= */ -static void ED_PrintEdict_f (void) +static void ED_PrintEdict_f(void) { - int32_t i; + int32_t i; - if (!sv.active) + if(!sv.active) return; - i = Q_atoi (Cmd_Argv(1)); - if (i < 0 || i >= sv.num_edicts) + i = Q_atoi(Cmd_Argv(1)); + if(i < 0 || i >= sv.num_edicts) { Con_Printf("Bad edict number\n"); return; } - ED_PrintNum (i); + ED_PrintNum(i); } /* @@ -615,34 +617,34 @@ ED_Count For debugging ============= */ -static void ED_Count (void) +static void ED_Count(void) { - edict_t *ent; - int32_t i, active, models, solid, step; + edict_t *ent; + int32_t i, active, models, solid, step; - if (!sv.active) + if(!sv.active) return; active = models = solid = step = 0; - for (i = 0; i < sv.num_edicts; i++) + for(i = 0; i < sv.num_edicts; i++) { ent = EDICT_NUM(i); - if (ent->free) + if(ent->free) continue; active++; - if (ent->v.solid) + if(ent->v.solid) solid++; - if (ent->v.model) + if(ent->v.model) models++; - if (ent->v.movetype == MOVETYPE_STEP) + if(ent->v.movetype == MOVETYPE_STEP) step++; } - Con_Printf ("num_edicts:%3" PRIi32 "\n", sv.num_edicts); - Con_Printf ("active :%3" PRIi32 "\n", active); - Con_Printf ("view :%3" PRIi32 "\n", models); - Con_Printf ("touch :%3" PRIi32 "\n", solid); - Con_Printf ("step :%3" PRIi32 "\n", step); + Con_Printf("num_edicts:%3" PRIi32 "\n", sv.num_edicts); + Con_Printf("active :%3" PRIi32 "\n", active); + Con_Printf("view :%3" PRIi32 "\n", models); + Con_Printf("touch :%3" PRIi32 "\n", solid); + Con_Printf("step :%3" PRIi32 "\n", step); } @@ -660,30 +662,30 @@ FIXME: need to tag constants, doesn't really work ED_WriteGlobals ============= */ -void ED_WriteGlobals (FILE *f) +void ED_WriteGlobals(FILE *f) { - ddef_t *def; - int32_t i; - const char *name; - int32_t type; + ddef_t *def; + int32_t i; + const char *name; + int32_t type; - fprintf (f, "{\n"); - for (i = 0; i < progs->numglobaldefs; i++) + fprintf(f, "{\n"); + for(i = 0; i < progs->numglobaldefs; i++) { def = &pr_globaldefs[i]; type = def->type; - if ( !(def->type & DEF_SAVEGLOBAL) ) + if(!(def->type & DEF_SAVEGLOBAL)) continue; type &= ~DEF_SAVEGLOBAL; - if (type != ev_string && type != ev_float && type != ev_entity) + if(type != ev_string && type != ev_float && type != ev_entity) continue; name = PR_GetString(def->s_name); - fprintf (f, "\"%s\" ", name); - fprintf (f, "\"%s\"\n", PR_UglyValueString(type, (eval_t *)&pr_globals[def->ofs])); + fprintf(f, "\"%s\" ", name); + fprintf(f, "\"%s\"\n", PR_UglyValueString(type, (eval_t *)&pr_globals[def->ofs])); } - fprintf (f, "}\n"); + fprintf(f, "}\n"); } /* @@ -691,39 +693,39 @@ void ED_WriteGlobals (FILE *f) ED_ParseGlobals ============= */ -const char *ED_ParseGlobals (const char *data) +const char *ED_ParseGlobals(const char *data) { - char keyname[64]; - ddef_t *key; + char keyname[64]; + ddef_t *key; - while (1) + while(1) { - // parse key - data = COM_Parse (data); - if (com_token[0] == '}') + // parse key + data = COM_Parse(data); + if(com_token[0] == '}') break; - if (!data) - Host_Error ("ED_ParseEntity: EOF without closing brace"); + if(!data) + Host_Error("ED_ParseEntity: EOF without closing brace"); - q_strlcpy (keyname, com_token, sizeof(keyname)); + q_strlcpy(keyname, com_token, sizeof(keyname)); - // parse value - data = COM_Parse (data); - if (!data) - Host_Error ("ED_ParseEntity: EOF without closing brace"); + // parse value + data = COM_Parse(data); + if(!data) + Host_Error("ED_ParseEntity: EOF without closing brace"); - if (com_token[0] == '}') - Host_Error ("ED_ParseEntity: closing brace without data"); + if(com_token[0] == '}') + Host_Error("ED_ParseEntity: closing brace without data"); - key = ED_FindGlobal (keyname); - if (!key) + key = ED_FindGlobal(keyname); + if(!key) { - Con_Printf ("'%s' is not a global\n", keyname); + Con_Printf("'%s' is not a global\n", keyname); continue; } - if (!ED_ParseEpair ((void *)pr_globals, key, com_token)) - Host_Error ("ED_ParseGlobals: parse error"); + if(!ED_ParseEpair((void *)pr_globals, key, com_token)) + Host_Error("ED_ParseGlobals: parse error"); } return data; } @@ -736,21 +738,21 @@ const char *ED_ParseGlobals (const char *data) ED_NewString ============= */ -static string_t ED_NewString (const char *string) +static string_t ED_NewString(const char *string) { - char *new_p; - int32_t i, l; - string_t num; + char *new_p; + int32_t i, l; + string_t num; l = strlen(string) + 1; - num = PR_AllocString (l, &new_p); + num = PR_AllocString(l, &new_p); - for (i = 0; i < l; i++) + for(i = 0; i < l; i++) { - if (string[i] == '\\' && i < l-1) + if(string[i] == '\\' && i < l - 1) { i++; - if (string[i] == 'n') + if(string[i] == 'n') *new_p++ = '\n'; else *new_p++ = '\\'; @@ -771,74 +773,74 @@ Can parse either fields or globals returns false if error ============= */ -static bool ED_ParseEpair (void *base, ddef_t *key, const char *s) +static bool ED_ParseEpair(void *base, ddef_t *key, const char *s) { - int32_t i; - char string[128]; - ddef_t *def; - char *v, *w; - char *end; - void *d; - dfunction_t *func; + int32_t i; + char string[128]; + ddef_t *def; + char *v, *w; + char *end; + void *d; + dfunction_t *func; d = (void *)((int32_t *)base + key->ofs); - switch (key->type & ~DEF_SAVEGLOBAL) + switch(key->type & ~DEF_SAVEGLOBAL) { case ev_string: *(string_t *)d = ED_NewString(s); break; case ev_float: - *(float *)d = atof (s); + *(float *)d = atof(s); break; case ev_vector: - q_strlcpy (string, s, sizeof(string)); + q_strlcpy(string, s, sizeof(string)); end = (char *)string + strlen(string); v = string; w = string; - for (i = 0; i < 3 && (w <= end); i++) // ericw -- added (w <= end) check + for(i = 0; i < 3 && (w <= end); i++) // ericw -- added (w <= end) check { - // set v to the next space (or 0 byte), and change that char to a 0 byte - while (*v && *v != ' ') + // set v to the next space (or 0 byte), and change that char to a 0 byte + while(*v && *v != ' ') v++; *v = 0; - ((float *)d)[i] = atof (w); - w = v = v+1; + ((float *)d)[i] = atof(w); + w = v = v + 1; } // ericw -- fill remaining elements to 0 in case we hit the end of string // before reading 3 floats. - if (i < 3) + if(i < 3) { - Con_DWarning ("Avoided reading garbage for \"%s\" \"%s\"\n", PR_GetString(key->s_name), s); - for (; i < 3; i++) + Con_DWarning("Avoided reading garbage for \"%s\" \"%s\"\n", PR_GetString(key->s_name), s); + for(; i < 3; i++) ((float *)d)[i] = 0.0f; } break; case ev_entity: - *(int32_t *)d = EDICT_TO_PROG(EDICT_NUM(atoi (s))); + *(int32_t *)d = EDICT_TO_PROG(EDICT_NUM(atoi(s))); break; case ev_field: - def = ED_FindField (s); - if (!def) + def = ED_FindField(s); + if(!def) { //johnfitz -- HACK -- suppress error becuase fog/sky fields might not be mentioned in defs.qc - if (strncmp(s, "sky", 3) && strcmp(s, "fog")) - Con_DPrintf ("Can't find field %s\n", s); + if(strncmp(s, "sky", 3) && strcmp(s, "fog")) + Con_DPrintf("Can't find field %s\n", s); return false; } *(int32_t *)d = G_INT(def->ofs); break; case ev_function: - func = ED_FindFunction (s); - if (!func) + func = ED_FindFunction(s); + if(!func) { - Con_Printf ("Can't find function %s\n", s); + Con_Printf("Can't find function %s\n", s); return false; } *(func_t *)d = func - pr_functions; @@ -859,94 +861,94 @@ ed should be a properly initialized empty edict. Used for initial level load and for savegames. ==================== */ -const char *ED_ParseEdict (const char *data, edict_t *ent) +const char *ED_ParseEdict(const char *data, edict_t *ent) { - ddef_t *key; - char keyname[256]; - bool anglehack, init; - int32_t n; + ddef_t *key; + char keyname[256]; + bool anglehack, init; + int32_t n; init = false; // clear it - if (ent != sv.edicts) // hack - memset (&ent->v, 0, progs->entityfields * 4); + if(ent != sv.edicts) // hack + memset(&ent->v, 0, progs->entityfields * 4); // go through all the dictionary pairs - while (1) + while(1) { // parse key - data = COM_Parse (data); - if (com_token[0] == '}') + data = COM_Parse(data); + if(com_token[0] == '}') break; - if (!data) - Host_Error ("ED_ParseEntity: EOF without closing brace"); + if(!data) + Host_Error("ED_ParseEntity: EOF without closing brace"); // anglehack is to allow QuakeEd to write single scalar angles // and allow them to be turned into vectors. (FIXME...) - if (!strcmp(com_token, "angle")) + if(!strcmp(com_token, "angle")) { - strcpy (com_token, "angles"); + strcpy(com_token, "angles"); anglehack = true; } else anglehack = false; // FIXME: change light to _light to get rid of this hack - if (!strcmp(com_token, "light")) - strcpy (com_token, "light_lev"); // hack for single light def + if(!strcmp(com_token, "light")) + strcpy(com_token, "light_lev"); // hack for single light def - q_strlcpy (keyname, com_token, sizeof(keyname)); + q_strlcpy(keyname, com_token, sizeof(keyname)); // another hack to fix keynames with trailing spaces n = strlen(keyname); - while (n && keyname[n-1] == ' ') + while(n && keyname[n - 1] == ' ') { - keyname[n-1] = 0; + keyname[n - 1] = 0; n--; } // parse value - data = COM_Parse (data); - if (!data) - Host_Error ("ED_ParseEntity: EOF without closing brace"); + data = COM_Parse(data); + if(!data) + Host_Error("ED_ParseEntity: EOF without closing brace"); - if (com_token[0] == '}') - Host_Error ("ED_ParseEntity: closing brace without data"); + if(com_token[0] == '}') + Host_Error("ED_ParseEntity: closing brace without data"); init = true; // keynames with a leading underscore are used for utility comments, // and are immediately discarded by quake - if (keyname[0] == '_') + if(keyname[0] == '_') continue; //johnfitz -- hack to support .alpha even when progs.dat doesn't know about it - if (!strcmp(keyname, "alpha")) + if(!strcmp(keyname, "alpha")) ent->alpha = ENTALPHA_ENCODE(atof(com_token)); //johnfitz - key = ED_FindField (keyname); - if (!key) + key = ED_FindField(keyname); + if(!key) { //johnfitz -- HACK -- suppress error becuase fog/sky/alpha fields might not be mentioned in defs.qc - if (strncmp(keyname, "sky", 3) && strcmp(keyname, "fog") && strcmp(keyname, "alpha")) - Con_DPrintf ("\"%s\" is not a field\n", keyname); //johnfitz -- was Con_Printf + if(strncmp(keyname, "sky", 3) && strcmp(keyname, "fog") && strcmp(keyname, "alpha")) + Con_DPrintf("\"%s\" is not a field\n", keyname); //johnfitz -- was Con_Printf continue; } - if (anglehack) + if(anglehack) { - char temp[32]; - strcpy (temp, com_token); - sprintf (com_token, "0 %s 0", temp); + char temp[32]; + strcpy(temp, com_token); + sprintf(com_token, "0 %s 0", temp); } - if (!ED_ParseEpair ((void *)&ent->v, key, com_token)) - Host_Error ("ED_ParseEdict: parse error"); + if(!ED_ParseEpair((void *)&ent->v, key, com_token)) + Host_Error("ED_ParseEdict: parse error"); } - if (!init) + if(!init) ent->free = true; return data; @@ -968,45 +970,45 @@ Used for both fresh maps and savegame loads. A fresh map would also need to call ED_CallSpawnFunctions () to let the objects initialize themselves. ================ */ -void ED_LoadFromFile (const char *data) +void ED_LoadFromFile(const char *data) { - dfunction_t *func; - edict_t *ent = NULL; - int32_t inhibit = 0; + dfunction_t *func; + edict_t *ent = NULL; + int32_t inhibit = 0; pr_global_struct->time = sv.time; // parse ents - while (1) + while(1) { // parse the opening brace - data = COM_Parse (data); - if (!data) + data = COM_Parse(data); + if(!data) break; - if (com_token[0] != '{') - Host_Error ("ED_LoadFromFile: found %s when expecting {",com_token); + if(com_token[0] != '{') + Host_Error("ED_LoadFromFile: found %s when expecting {", com_token); - if (!ent) + if(!ent) ent = EDICT_NUM(0); else - ent = ED_Alloc (); - data = ED_ParseEdict (data, ent); + ent = ED_Alloc(); + data = ED_ParseEdict(data, ent); // remove things from different skill levels or deathmatch - if (deathmatch.value) + if(deathmatch.value) { - if (((int32_t)ent->v.spawnflags & SPAWNFLAG_NOT_DEATHMATCH)) + if(((int32_t)ent->v.spawnflags & SPAWNFLAG_NOT_DEATHMATCH)) { - ED_Free (ent); + ED_Free(ent); inhibit++; continue; } } - else if ((current_skill == 0 && ((int32_t)ent->v.spawnflags & SPAWNFLAG_NOT_EASY)) - || (current_skill == 1 && ((int32_t)ent->v.spawnflags & SPAWNFLAG_NOT_MEDIUM)) - || (current_skill >= 2 && ((int32_t)ent->v.spawnflags & SPAWNFLAG_NOT_HARD)) ) + else if((current_skill == 0 && ((int32_t)ent->v.spawnflags & SPAWNFLAG_NOT_EASY)) + || (current_skill == 1 && ((int32_t)ent->v.spawnflags & SPAWNFLAG_NOT_MEDIUM)) + || (current_skill >= 2 && ((int32_t)ent->v.spawnflags & SPAWNFLAG_NOT_HARD))) { - ED_Free (ent); + ED_Free(ent); inhibit++; continue; } @@ -1014,30 +1016,30 @@ void ED_LoadFromFile (const char *data) // // immediately call spawn function // - if (!ent->v.classname) + if(!ent->v.classname) { - Con_SafePrintf ("No classname for:\n"); //johnfitz -- was Con_Printf - ED_Print (ent); - ED_Free (ent); + Con_SafePrintf("No classname for:\n"); //johnfitz -- was Con_Printf + ED_Print(ent); + ED_Free(ent); continue; } - // look for the spawn function - func = ED_FindFunction ( PR_GetString(ent->v.classname) ); + // look for the spawn function + func = ED_FindFunction(PR_GetString(ent->v.classname)); - if (!func) + if(!func) { - Con_SafePrintf ("No spawn function for:\n"); //johnfitz -- was Con_Printf - ED_Print (ent); - ED_Free (ent); + Con_SafePrintf("No spawn function for:\n"); //johnfitz -- was Con_Printf + ED_Print(ent); + ED_Free(ent); continue; } pr_global_struct->self = EDICT_TO_PROG(ent); - PR_ExecuteProgram (func - pr_functions); + PR_ExecuteProgram(func - pr_functions); } - Con_DPrintf ("%" PRIi32 " entities inhibited\n", inhibit); + Con_DPrintf("%" PRIi32 " entities inhibited\n", inhibit); } @@ -1046,44 +1048,44 @@ void ED_LoadFromFile (const char *data) PR_LoadProgs =============== */ -void PR_LoadProgs (void) +void PR_LoadProgs(void) { - int32_t i; + int32_t i; // flush the non-C variable lookup cache - for (i = 0; i < GEFV_CACHESIZE; i++) + for(i = 0; i < GEFV_CACHESIZE; i++) gefvCache[i].field[0] = 0; - CRC_Init (&pr_crc); + CRC_Init(&pr_crc); - progs = (dprograms_t *)COM_LoadHunkFile ("progs.dat", NULL); - if (!progs) - Host_Error ("PR_LoadProgs: couldn't load progs.dat"); - Con_DPrintf ("Programs occupy %" PRIi32 "K.\n", com_filesize/1024); + progs = (dprograms_t *)COM_LoadHunkFile("progs.dat", NULL); + if(!progs) + Host_Error("PR_LoadProgs: couldn't load progs.dat"); + Con_DPrintf("Programs occupy %" PRIi32 "K.\n", com_filesize / 1024); - for (i = 0; i < com_filesize; i++) - CRC_ProcessByte (&pr_crc, ((byte *)progs)[i]); + for(i = 0; i < com_filesize; i++) + CRC_ProcessByte(&pr_crc, ((byte *)progs)[i]); // byte swap the header - for (i = 0; i < (int32_t) sizeof(*progs) / 4; i++) - ((int32_t *)progs)[i] = LittleLong ( ((int32_t *)progs)[i] ); + for(i = 0; i < (int32_t) sizeof(*progs) / 4; i++) + ((int32_t *)progs)[i] = LittleLong(((int32_t *)progs)[i]); - if (progs->version != PROG_VERSION) - Host_Error ("progs.dat has wrong version number (%" PRIi32 " should be %" PRIi32 ")", progs->version, PROG_VERSION); - if (progs->crc != PROGHEADER_CRC) - Host_Error ("progs.dat system vars have been modified, progdefs.h is out of date"); + if(progs->version != PROG_VERSION) + Host_Error("progs.dat has wrong version number (%" PRIi32 " should be %" PRIi32 ")", progs->version, PROG_VERSION); + if(progs->crc != PROGHEADER_CRC) + Host_Error("progs.dat system vars have been modified, progdefs.h is out of date"); pr_functions = (dfunction_t *)((byte *)progs + progs->ofs_functions); pr_strings = (char *)progs + progs->ofs_strings; - if (progs->ofs_strings + progs->numstrings >= com_filesize) - Host_Error ("progs.dat strings go past end of file\n"); + if(progs->ofs_strings + progs->numstrings >= com_filesize) + Host_Error("progs.dat strings go past end of file\n"); // initialize the strings pr_numknownstrings = 0; pr_maxknownstrings = 0; pr_stringssize = progs->numstrings; - if (pr_knownstrings) - Z_Free ((void *)pr_knownstrings); + if(pr_knownstrings) + Z_Free((void *)pr_knownstrings); pr_knownstrings = NULL; PR_SetEngineString(""); @@ -1095,7 +1097,7 @@ void PR_LoadProgs (void) pr_globals = (float *)pr_global_struct; // byte swap the lumps - for (i = 0; i < progs->numstatements; i++) + for(i = 0; i < progs->numstatements; i++) { pr_statements[i].op = LittleShort(pr_statements[i].op); pr_statements[i].a = LittleShort(pr_statements[i].a); @@ -1103,41 +1105,41 @@ void PR_LoadProgs (void) pr_statements[i].c = LittleShort(pr_statements[i].c); } - for (i = 0; i < progs->numfunctions; i++) + for(i = 0; i < progs->numfunctions; i++) { - pr_functions[i].first_statement = LittleLong (pr_functions[i].first_statement); - pr_functions[i].parm_start = LittleLong (pr_functions[i].parm_start); - pr_functions[i].s_name = LittleLong (pr_functions[i].s_name); - pr_functions[i].s_file = LittleLong (pr_functions[i].s_file); - pr_functions[i].numparms = LittleLong (pr_functions[i].numparms); - pr_functions[i].locals = LittleLong (pr_functions[i].locals); + pr_functions[i].first_statement = LittleLong(pr_functions[i].first_statement); + pr_functions[i].parm_start = LittleLong(pr_functions[i].parm_start); + pr_functions[i].s_name = LittleLong(pr_functions[i].s_name); + pr_functions[i].s_file = LittleLong(pr_functions[i].s_file); + pr_functions[i].numparms = LittleLong(pr_functions[i].numparms); + pr_functions[i].locals = LittleLong(pr_functions[i].locals); } - for (i = 0; i < progs->numglobaldefs; i++) + for(i = 0; i < progs->numglobaldefs; i++) { - pr_globaldefs[i].type = LittleShort (pr_globaldefs[i].type); - pr_globaldefs[i].ofs = LittleShort (pr_globaldefs[i].ofs); - pr_globaldefs[i].s_name = LittleLong (pr_globaldefs[i].s_name); + pr_globaldefs[i].type = LittleShort(pr_globaldefs[i].type); + pr_globaldefs[i].ofs = LittleShort(pr_globaldefs[i].ofs); + pr_globaldefs[i].s_name = LittleLong(pr_globaldefs[i].s_name); } pr_alpha_supported = false; //johnfitz - for (i = 0; i < progs->numfielddefs; i++) + for(i = 0; i < progs->numfielddefs; i++) { - pr_fielddefs[i].type = LittleShort (pr_fielddefs[i].type); - if (pr_fielddefs[i].type & DEF_SAVEGLOBAL) - Host_Error ("PR_LoadProgs: pr_fielddefs[i].type & DEF_SAVEGLOBAL"); - pr_fielddefs[i].ofs = LittleShort (pr_fielddefs[i].ofs); - pr_fielddefs[i].s_name = LittleLong (pr_fielddefs[i].s_name); + pr_fielddefs[i].type = LittleShort(pr_fielddefs[i].type); + if(pr_fielddefs[i].type & DEF_SAVEGLOBAL) + Host_Error("PR_LoadProgs: pr_fielddefs[i].type & DEF_SAVEGLOBAL"); + pr_fielddefs[i].ofs = LittleShort(pr_fielddefs[i].ofs); + pr_fielddefs[i].s_name = LittleLong(pr_fielddefs[i].s_name); //johnfitz -- detect alpha support in progs.dat - if (!strcmp(pr_strings + pr_fielddefs[i].s_name,"alpha")) + if(!strcmp(pr_strings + pr_fielddefs[i].s_name, "alpha")) pr_alpha_supported = true; //johnfitz } - for (i = 0; i < progs->numglobals; i++) - ((int32_t *)pr_globals)[i] = LittleLong (((int32_t *)pr_globals)[i]); + for(i = 0; i < progs->numglobals; i++) + ((int32_t *)pr_globals)[i] = LittleLong(((int32_t *)pr_globals)[i]); pr_edict_size = progs->entityfields * 4 + sizeof(edict_t) - sizeof(entvars_t); // round off to next highest whole word address (esp for Alpha) @@ -1153,66 +1155,66 @@ void PR_LoadProgs (void) PR_Init =============== */ -void PR_Init (void) +void PR_Init(void) { - Cmd_AddCommand ("edict", ED_PrintEdict_f); - Cmd_AddCommand ("edicts", ED_PrintEdicts); - Cmd_AddCommand ("edictcount", ED_Count); - Cmd_AddCommand ("profile", PR_Profile_f); - Cvar_RegisterVariable (&nomonsters); - Cvar_RegisterVariable (&gamecfg); - Cvar_RegisterVariable (&scratch1); - Cvar_RegisterVariable (&scratch2); - Cvar_RegisterVariable (&scratch3); - Cvar_RegisterVariable (&scratch4); - Cvar_RegisterVariable (&savedgamecfg); - Cvar_RegisterVariable (&saved1); - Cvar_RegisterVariable (&saved2); - Cvar_RegisterVariable (&saved3); - Cvar_RegisterVariable (&saved4); + Cmd_AddCommand("edict", ED_PrintEdict_f); + Cmd_AddCommand("edicts", ED_PrintEdicts); + Cmd_AddCommand("edictcount", ED_Count); + Cmd_AddCommand("profile", PR_Profile_f); + Cvar_RegisterVariable(&nomonsters); + Cvar_RegisterVariable(&gamecfg); + Cvar_RegisterVariable(&scratch1); + Cvar_RegisterVariable(&scratch2); + Cvar_RegisterVariable(&scratch3); + Cvar_RegisterVariable(&scratch4); + Cvar_RegisterVariable(&savedgamecfg); + Cvar_RegisterVariable(&saved1); + Cvar_RegisterVariable(&saved2); + Cvar_RegisterVariable(&saved3); + Cvar_RegisterVariable(&saved4); } edict_t *EDICT_NUM(int32_t n) { - if (n < 0 || n >= sv.max_edicts) - Host_Error ("EDICT_NUM: bad number %" PRIi32 "", n); - return (edict_t *)((byte *)sv.edicts + (n)*pr_edict_size); + if(n < 0 || n >= sv.max_edicts) + Host_Error("EDICT_NUM: bad number %" PRIi32 "", n); + return (edict_t *)((byte *)sv.edicts + (n) * pr_edict_size); } int32_t NUM_FOR_EDICT(edict_t *e) { - int32_t b; + int32_t b; b = (byte *)e - (byte *)sv.edicts; b = b / pr_edict_size; - if (b < 0 || b >= sv.num_edicts) - Host_Error ("NUM_FOR_EDICT: bad pointer"); + if(b < 0 || b >= sv.num_edicts) + Host_Error("NUM_FOR_EDICT: bad pointer"); return b; } //=========================================================================== -#define PR_STRING_ALLOCSLOTS 256 +#define PR_STRING_ALLOCSLOTS 256 -static void PR_AllocStringSlots (void) +static void PR_AllocStringSlots(void) { pr_maxknownstrings += PR_STRING_ALLOCSLOTS; Con_DPrintf2("PR_AllocStringSlots: realloc'ing for %" PRIi32 " slots\n", pr_maxknownstrings); - pr_knownstrings = (const char **) Z_Realloc ((void *)pr_knownstrings, pr_maxknownstrings * sizeof(char *)); + pr_knownstrings = (const char **) Z_Realloc((void *)pr_knownstrings, pr_maxknownstrings * sizeof(char *)); } -const char *PR_GetString (int32_t num) +const char *PR_GetString(int32_t num) { - if (num >= 0 && num < pr_stringssize) + if(num >= 0 && num < pr_stringssize) return pr_strings + num; - else if (num < 0 && num >= -pr_numknownstrings) + else if(num < 0 && num >= -pr_numknownstrings) { - if (!pr_knownstrings[-1 - num]) + if(!pr_knownstrings[-1 - num]) { - Host_Error ("PR_GetString: attempt to get a non-existant string %" PRIi32 "\n", num); + Host_Error("PR_GetString: attempt to get a non-existant string %" PRIi32 "\n", num); return ""; } return pr_knownstrings[-1 - num]; @@ -1224,62 +1226,62 @@ const char *PR_GetString (int32_t num) } } -int32_t PR_SetEngineString (const char *s) +int32_t PR_SetEngineString(const char *s) { - int32_t i; + int32_t i; - if (!s) + if(!s) return 0; -#if 0 /* can't: sv.model_precache & sv.sound_precache points to pr_strings */ - if (s >= pr_strings && s <= pr_strings + pr_stringssize) +#if 0 /* can't: sv.model_precache & sv.sound_precache points to pr_strings */ + if(s >= pr_strings && s <= pr_strings + pr_stringssize) Host_Error("PR_SetEngineString: \"%s\" in pr_strings area\n", s); #else - if (s >= pr_strings && s <= pr_strings + pr_stringssize - 2) + if(s >= pr_strings && s <= pr_strings + pr_stringssize - 2) return (int32_t)(s - pr_strings); #endif - for (i = 0; i < pr_numknownstrings; i++) + for(i = 0; i < pr_numknownstrings; i++) { - if (pr_knownstrings[i] == s) + if(pr_knownstrings[i] == s) return -1 - i; } // new unknown engine string //Con_DPrintf ("PR_SetEngineString: new engine string %p\n", s); #if 0 - for (i = 0; i < pr_numknownstrings; i++) + for(i = 0; i < pr_numknownstrings; i++) { - if (!pr_knownstrings[i]) + if(!pr_knownstrings[i]) break; } #endif // if (i >= pr_numknownstrings) // { - if (i >= pr_maxknownstrings) - PR_AllocStringSlots(); - pr_numknownstrings++; + if(i >= pr_maxknownstrings) + PR_AllocStringSlots(); + pr_numknownstrings++; // } pr_knownstrings[i] = s; return -1 - i; } -int32_t PR_AllocString (int32_t size, char **ptr) +int32_t PR_AllocString(int32_t size, char **ptr) { - int32_t i; + int32_t i; - if (!size) + if(!size) return 0; - for (i = 0; i < pr_numknownstrings; i++) + for(i = 0; i < pr_numknownstrings; i++) { - if (!pr_knownstrings[i]) + if(!pr_knownstrings[i]) break; } // if (i >= pr_numknownstrings) // { - if (i >= pr_maxknownstrings) - PR_AllocStringSlots(); - pr_numknownstrings++; + if(i >= pr_maxknownstrings) + PR_AllocStringSlots(); + pr_numknownstrings++; // } pr_knownstrings[i] = (char *)Hunk_AllocName(size, "string"); - if (ptr) + if(ptr) *ptr = (char *) pr_knownstrings[i]; return -1 - i; } diff --git a/source/pr_exec.c b/source/pr_exec.c index 605f017..bb8bdae 100644 --- a/source/pr_exec.c +++ b/source/pr_exec.c @@ -23,22 +23,22 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. typedef struct { - int32_t s; - dfunction_t *f; + int32_t s; + dfunction_t *f; } prstack_t; -#define MAX_STACK_DEPTH 64 /* was 32 */ -static prstack_t pr_stack[MAX_STACK_DEPTH]; -static int32_t pr_depth; +#define MAX_STACK_DEPTH 64 /* was 32 */ +static prstack_t pr_stack[MAX_STACK_DEPTH]; +static int32_t pr_depth; -#define LOCALSTACK_SIZE 2048 -static int32_t localstack[LOCALSTACK_SIZE]; -static int32_t localstack_used; +#define LOCALSTACK_SIZE 2048 +static int32_t localstack[LOCALSTACK_SIZE]; +static int32_t localstack_used; -bool pr_trace; -dfunction_t *pr_xfunction; -int32_t pr_xstatement; -int32_t pr_argc; +bool pr_trace; +dfunction_t *pr_xfunction; +int32_t pr_xstatement; +int32_t pr_argc; static const char *pr_opnames[] = { @@ -129,8 +129,8 @@ static const char *pr_opnames[] = "BITOR" }; -const char *PR_GlobalString (int32_t ofs); -const char *PR_GlobalStringNoContents (int32_t ofs); +const char *PR_GlobalString(int32_t ofs); +const char *PR_GlobalStringNoContents(int32_t ofs); //============================================================================= @@ -140,36 +140,36 @@ const char *PR_GlobalStringNoContents (int32_t ofs); PR_PrintStatement ================= */ -static void PR_PrintStatement (dstatement_t *s) +static void PR_PrintStatement(dstatement_t *s) { - int32_t i; + int32_t i; - if ((uint32_t)s->op < sizeof(pr_opnames)/sizeof(pr_opnames[0])) + if((uint32_t)s->op < sizeof(pr_opnames) / sizeof(pr_opnames[0])) { Con_Printf("%s ", pr_opnames[s->op]); i = strlen(pr_opnames[s->op]); - for ( ; i < 10; i++) + for(; i < 10; i++) Con_Printf(" "); } - if (s->op == OP_IF || s->op == OP_IFNOT) + if(s->op == OP_IF || s->op == OP_IFNOT) Con_Printf("%sbranch %" PRIi32 "", PR_GlobalString(s->a), s->b); - else if (s->op == OP_GOTO) + else if(s->op == OP_GOTO) { Con_Printf("branch %" PRIi32 "", s->a); } - else if ((uint32_t)(s->op-OP_STORE_F) < 6) + else if((uint32_t)(s->op - OP_STORE_F) < 6) { Con_Printf("%s", PR_GlobalString(s->a)); Con_Printf("%s", PR_GlobalStringNoContents(s->b)); } else { - if (s->a) + if(s->a) Con_Printf("%s", PR_GlobalString(s->a)); - if (s->b) + if(s->b) Con_Printf("%s", PR_GlobalString(s->b)); - if (s->c) + if(s->c) Con_Printf("%s", PR_GlobalStringNoContents(s->c)); } Con_Printf("\n"); @@ -180,22 +180,22 @@ static void PR_PrintStatement (dstatement_t *s) PR_StackTrace ============ */ -static void PR_StackTrace (void) +static void PR_StackTrace(void) { - int32_t i; - dfunction_t *f; + int32_t i; + dfunction_t *f; - if (pr_depth == 0) + if(pr_depth == 0) { Con_Printf("\n"); return; } pr_stack[pr_depth].f = pr_xfunction; - for (i = pr_depth; i >= 0; i--) + for(i = pr_depth; i >= 0; i--) { f = pr_stack[i].f; - if (!f) + if(!f) { Con_Printf("\n"); } @@ -213,13 +213,13 @@ PR_Profile_f ============ */ -void PR_Profile_f (void) +void PR_Profile_f(void) { - int32_t i, num; - int32_t pmax; - dfunction_t *f, *best; + int32_t i, num; + int32_t pmax; + dfunction_t *f, *best; - if (!sv.active) + if(!sv.active) return; num = 0; @@ -227,23 +227,24 @@ void PR_Profile_f (void) { pmax = 0; best = NULL; - for (i = 0; i < progs->numfunctions; i++) + for(i = 0; i < progs->numfunctions; i++) { f = &pr_functions[i]; - if (f->profile > pmax) + if(f->profile > pmax) { pmax = f->profile; best = f; } } - if (best) + if(best) { - if (num < 10) + if(num < 10) Con_Printf("%7" PRIi32 " %s\n", best->profile, PR_GetString(best->s_name)); num++; best->profile = 0; } - } while (best); + } + while(best); } @@ -254,21 +255,21 @@ PR_RunError Aborts the currently executing function ============ */ -void PR_RunError (const char *error, ...) +void PR_RunError(const char *error, ...) { - va_list argptr; - char string[1024]; + va_list argptr; + char string[1024]; - va_start (argptr, error); - q_vsnprintf (string, sizeof(string), error, argptr); - va_end (argptr); + va_start(argptr, error); + q_vsnprintf(string, sizeof(string), error, argptr); + va_end(argptr); PR_PrintStatement(pr_statements + pr_xstatement); PR_StackTrace(); Con_Printf("%s\n", string); - pr_depth = 0; // dump the stack so host_error can shutdown functions + pr_depth = 0; // dump the stack so host_error can shutdown functions Host_Error("Program error"); } @@ -280,38 +281,38 @@ PR_EnterFunction Returns the new program statement counter ==================== */ -static int32_t PR_EnterFunction (dfunction_t *f) +static int32_t PR_EnterFunction(dfunction_t *f) { - int32_t i, j, c, o; + int32_t i, j, c, o; pr_stack[pr_depth].s = pr_xstatement; pr_stack[pr_depth].f = pr_xfunction; pr_depth++; - if (pr_depth >= MAX_STACK_DEPTH) + if(pr_depth >= MAX_STACK_DEPTH) PR_RunError("stack overflow"); // save off any locals that the new function steps on c = f->locals; - if (localstack_used + c > LOCALSTACK_SIZE) + if(localstack_used + c > LOCALSTACK_SIZE) PR_RunError("PR_ExecuteProgram: locals stack overflow\n"); - for (i = 0; i < c ; i++) + for(i = 0; i < c ; i++) localstack[localstack_used + i] = ((int32_t *)pr_globals)[f->parm_start + i]; localstack_used += c; // copy parameters o = f->parm_start; - for (i = 0; i < f->numparms; i++) + for(i = 0; i < f->numparms; i++) { - for (j = 0; j < f->parm_size[i]; j++) + for(j = 0; j < f->parm_size[i]; j++) { - ((int32_t *)pr_globals)[o] = ((int32_t *)pr_globals)[OFS_PARM0 + i*3 + j]; + ((int32_t *)pr_globals)[o] = ((int32_t *)pr_globals)[OFS_PARM0 + i * 3 + j]; o++; } } pr_xfunction = f; - return f->first_statement - 1; // offset the s++ + return f->first_statement - 1; // offset the s++ } /* @@ -319,20 +320,20 @@ static int32_t PR_EnterFunction (dfunction_t *f) PR_LeaveFunction ==================== */ -static int32_t PR_LeaveFunction (void) +static int32_t PR_LeaveFunction(void) { - int32_t i, c; + int32_t i, c; - if (pr_depth <= 0) + if(pr_depth <= 0) Host_Error("prog stack underflow"); // Restore locals from the stack c = pr_xfunction->locals; localstack_used -= c; - if (localstack_used < 0) + if(localstack_used < 0) PR_RunError("PR_ExecuteProgram: locals stack underflow"); - for (i = 0; i < c; i++) + for(i = 0; i < c; i++) ((int32_t *)pr_globals)[pr_xfunction->parm_start + i] = localstack[localstack_used + i]; // up stack @@ -353,20 +354,20 @@ The interpretation main loop #define OPB ((eval_t *)&pr_globals[(uint16_t)st->b]) #define OPC ((eval_t *)&pr_globals[(uint16_t)st->c]) -void PR_ExecuteProgram (func_t fnum) +void PR_ExecuteProgram(func_t fnum) { - eval_t *ptr; - dstatement_t *st; - dfunction_t *f, *newf; + eval_t *ptr; + dstatement_t *st; + dfunction_t *f, *newf; int32_t profile, startprofile; - edict_t *ed; - int32_t exitdepth; + edict_t *ed; + int32_t exitdepth; - if (!fnum || fnum >= progs->numfunctions) + if(!fnum || fnum >= progs->numfunctions) { - if (pr_global_struct->self) - ED_Print (PROG_TO_EDICT(pr_global_struct->self)); - Host_Error ("PR_ExecuteProgram: NULL function"); + if(pr_global_struct->self) + ED_Print(PROG_TO_EDICT(pr_global_struct->self)); + Host_Error("PR_ExecuteProgram: NULL function"); } f = &pr_functions[fnum]; @@ -379,274 +380,276 @@ void PR_ExecuteProgram (func_t fnum) st = &pr_statements[PR_EnterFunction(f)]; startprofile = profile = 0; - while (1) - { - st++; /* next statement */ - - if (++profile > 100000) + while(1) { - pr_xstatement = st - pr_statements; - PR_RunError("runaway loop error"); - } + st++; /* next statement */ - if (pr_trace) - PR_PrintStatement(st); - - switch (st->op) - { - case OP_ADD_F: - OPC->_float = OPA->_float + OPB->_float; - break; - case OP_ADD_V: - OPC->vector[0] = OPA->vector[0] + OPB->vector[0]; - OPC->vector[1] = OPA->vector[1] + OPB->vector[1]; - OPC->vector[2] = OPA->vector[2] + OPB->vector[2]; - break; - - case OP_SUB_F: - OPC->_float = OPA->_float - OPB->_float; - break; - case OP_SUB_V: - OPC->vector[0] = OPA->vector[0] - OPB->vector[0]; - OPC->vector[1] = OPA->vector[1] - OPB->vector[1]; - OPC->vector[2] = OPA->vector[2] - OPB->vector[2]; - break; - - case OP_MUL_F: - OPC->_float = OPA->_float * OPB->_float; - break; - case OP_MUL_V: - OPC->_float = OPA->vector[0] * OPB->vector[0] + - OPA->vector[1] * OPB->vector[1] + - OPA->vector[2] * OPB->vector[2]; - break; - case OP_MUL_FV: - OPC->vector[0] = OPA->_float * OPB->vector[0]; - OPC->vector[1] = OPA->_float * OPB->vector[1]; - OPC->vector[2] = OPA->_float * OPB->vector[2]; - break; - case OP_MUL_VF: - OPC->vector[0] = OPB->_float * OPA->vector[0]; - OPC->vector[1] = OPB->_float * OPA->vector[1]; - OPC->vector[2] = OPB->_float * OPA->vector[2]; - break; - - case OP_DIV_F: - OPC->_float = OPA->_float / OPB->_float; - break; - - case OP_BITAND: - OPC->_float = (int32_t)OPA->_float & (int32_t)OPB->_float; - break; - - case OP_BITOR: - OPC->_float = (int32_t)OPA->_float | (int32_t)OPB->_float; - break; - - case OP_GE: - OPC->_float = OPA->_float >= OPB->_float; - break; - case OP_LE: - OPC->_float = OPA->_float <= OPB->_float; - break; - case OP_GT: - OPC->_float = OPA->_float > OPB->_float; - break; - case OP_LT: - OPC->_float = OPA->_float < OPB->_float; - break; - case OP_AND: - OPC->_float = OPA->_float && OPB->_float; - break; - case OP_OR: - OPC->_float = OPA->_float || OPB->_float; - break; - - case OP_NOT_F: - OPC->_float = !OPA->_float; - break; - case OP_NOT_V: - OPC->_float = !OPA->vector[0] && !OPA->vector[1] && !OPA->vector[2]; - break; - case OP_NOT_S: - OPC->_float = !OPA->string || !*PR_GetString(OPA->string); - break; - case OP_NOT_FNC: - OPC->_float = !OPA->function; - break; - case OP_NOT_ENT: - OPC->_float = (PROG_TO_EDICT(OPA->edict) == sv.edicts); - break; - - case OP_EQ_F: - OPC->_float = OPA->_float == OPB->_float; - break; - case OP_EQ_V: - OPC->_float = (OPA->vector[0] == OPB->vector[0]) && - (OPA->vector[1] == OPB->vector[1]) && - (OPA->vector[2] == OPB->vector[2]); - break; - case OP_EQ_S: - OPC->_float = !strcmp(PR_GetString(OPA->string), PR_GetString(OPB->string)); - break; - case OP_EQ_E: - OPC->_float = OPA->_int == OPB->_int; - break; - case OP_EQ_FNC: - OPC->_float = OPA->function == OPB->function; - break; - - case OP_NE_F: - OPC->_float = OPA->_float != OPB->_float; - break; - case OP_NE_V: - OPC->_float = (OPA->vector[0] != OPB->vector[0]) || - (OPA->vector[1] != OPB->vector[1]) || - (OPA->vector[2] != OPB->vector[2]); - break; - case OP_NE_S: - OPC->_float = strcmp(PR_GetString(OPA->string), PR_GetString(OPB->string)); - break; - case OP_NE_E: - OPC->_float = OPA->_int != OPB->_int; - break; - case OP_NE_FNC: - OPC->_float = OPA->function != OPB->function; - break; - - case OP_STORE_F: - case OP_STORE_ENT: - case OP_STORE_FLD: // integers - case OP_STORE_S: - case OP_STORE_FNC: // pointers - OPB->_int = OPA->_int; - break; - case OP_STORE_V: - OPB->vector[0] = OPA->vector[0]; - OPB->vector[1] = OPA->vector[1]; - OPB->vector[2] = OPA->vector[2]; - break; - - case OP_STOREP_F: - case OP_STOREP_ENT: - case OP_STOREP_FLD: // integers - case OP_STOREP_S: - case OP_STOREP_FNC: // pointers - ptr = (eval_t *)((byte *)sv.edicts + OPB->_int); - ptr->_int = OPA->_int; - break; - case OP_STOREP_V: - ptr = (eval_t *)((byte *)sv.edicts + OPB->_int); - ptr->vector[0] = OPA->vector[0]; - ptr->vector[1] = OPA->vector[1]; - ptr->vector[2] = OPA->vector[2]; - break; - - case OP_ADDRESS: - ed = PROG_TO_EDICT(OPA->edict); -#ifdef PARANOID - NUM_FOR_EDICT(ed); // Make sure it's in range -#endif - if (ed == (edict_t *)sv.edicts && sv.state == ss_active) + if(++profile > 100000) { pr_xstatement = st - pr_statements; - PR_RunError("assignment to world entity"); + PR_RunError("runaway loop error"); } - OPC->_int = (byte *)((int32_t *)&ed->v + OPB->_int) - (byte *)sv.edicts; - break; - case OP_LOAD_F: - case OP_LOAD_FLD: - case OP_LOAD_ENT: - case OP_LOAD_S: - case OP_LOAD_FNC: - ed = PROG_TO_EDICT(OPA->edict); -#ifdef PARANOID - NUM_FOR_EDICT(ed); // Make sure it's in range -#endif - OPC->_int = ((eval_t *)((int32_t *)&ed->v + OPB->_int))->_int; - break; + if(pr_trace) + PR_PrintStatement(st); - case OP_LOAD_V: - ed = PROG_TO_EDICT(OPA->edict); -#ifdef PARANOID - NUM_FOR_EDICT(ed); // Make sure it's in range -#endif - ptr = (eval_t *)((int32_t *)&ed->v + OPB->_int); - OPC->vector[0] = ptr->vector[0]; - OPC->vector[1] = ptr->vector[1]; - OPC->vector[2] = ptr->vector[2]; - break; - - case OP_IFNOT: - if (!OPA->_int) - st += st->b - 1; /* -1 to offset the st++ */ - break; - - case OP_IF: - if (OPA->_int) - st += st->b - 1; /* -1 to offset the st++ */ - break; - - case OP_GOTO: - st += st->a - 1; /* -1 to offset the st++ */ - break; - - case OP_CALL0: - case OP_CALL1: - case OP_CALL2: - case OP_CALL3: - case OP_CALL4: - case OP_CALL5: - case OP_CALL6: - case OP_CALL7: - case OP_CALL8: - pr_xfunction->profile += profile - startprofile; - startprofile = profile; - pr_xstatement = st - pr_statements; - pr_argc = st->op - OP_CALL0; - if (!OPA->function) - PR_RunError("NULL function"); - newf = &pr_functions[OPA->function]; - if (newf->first_statement < 0) - { // Built-in function - int32_t i = -newf->first_statement; - if (i >= pr_numbuiltins) - PR_RunError("Bad builtin call number %" PRIi32 "", i); - pr_builtins[i](); + switch(st->op) + { + case OP_ADD_F: + OPC->_float = OPA->_float + OPB->_float; break; + case OP_ADD_V: + OPC->vector[0] = OPA->vector[0] + OPB->vector[0]; + OPC->vector[1] = OPA->vector[1] + OPB->vector[1]; + OPC->vector[2] = OPA->vector[2] + OPB->vector[2]; + break; + + case OP_SUB_F: + OPC->_float = OPA->_float - OPB->_float; + break; + case OP_SUB_V: + OPC->vector[0] = OPA->vector[0] - OPB->vector[0]; + OPC->vector[1] = OPA->vector[1] - OPB->vector[1]; + OPC->vector[2] = OPA->vector[2] - OPB->vector[2]; + break; + + case OP_MUL_F: + OPC->_float = OPA->_float * OPB->_float; + break; + case OP_MUL_V: + OPC->_float = OPA->vector[0] * OPB->vector[0] + + OPA->vector[1] * OPB->vector[1] + + OPA->vector[2] * OPB->vector[2]; + break; + case OP_MUL_FV: + OPC->vector[0] = OPA->_float * OPB->vector[0]; + OPC->vector[1] = OPA->_float * OPB->vector[1]; + OPC->vector[2] = OPA->_float * OPB->vector[2]; + break; + case OP_MUL_VF: + OPC->vector[0] = OPB->_float * OPA->vector[0]; + OPC->vector[1] = OPB->_float * OPA->vector[1]; + OPC->vector[2] = OPB->_float * OPA->vector[2]; + break; + + case OP_DIV_F: + OPC->_float = OPA->_float / OPB->_float; + break; + + case OP_BITAND: + OPC->_float = (int32_t)OPA->_float & (int32_t)OPB->_float; + break; + + case OP_BITOR: + OPC->_float = (int32_t)OPA->_float | (int32_t)OPB->_float; + break; + + case OP_GE: + OPC->_float = OPA->_float >= OPB->_float; + break; + case OP_LE: + OPC->_float = OPA->_float <= OPB->_float; + break; + case OP_GT: + OPC->_float = OPA->_float > OPB->_float; + break; + case OP_LT: + OPC->_float = OPA->_float < OPB->_float; + break; + case OP_AND: + OPC->_float = OPA->_float && OPB->_float; + break; + case OP_OR: + OPC->_float = OPA->_float || OPB->_float; + break; + + case OP_NOT_F: + OPC->_float = !OPA->_float; + break; + case OP_NOT_V: + OPC->_float = !OPA->vector[0] && !OPA->vector[1] && !OPA->vector[2]; + break; + case OP_NOT_S: + OPC->_float = !OPA->string || !*PR_GetString(OPA->string); + break; + case OP_NOT_FNC: + OPC->_float = !OPA->function; + break; + case OP_NOT_ENT: + OPC->_float = (PROG_TO_EDICT(OPA->edict) == sv.edicts); + break; + + case OP_EQ_F: + OPC->_float = OPA->_float == OPB->_float; + break; + case OP_EQ_V: + OPC->_float = (OPA->vector[0] == OPB->vector[0]) && + (OPA->vector[1] == OPB->vector[1]) && + (OPA->vector[2] == OPB->vector[2]); + break; + case OP_EQ_S: + OPC->_float = !strcmp(PR_GetString(OPA->string), PR_GetString(OPB->string)); + break; + case OP_EQ_E: + OPC->_float = OPA->_int == OPB->_int; + break; + case OP_EQ_FNC: + OPC->_float = OPA->function == OPB->function; + break; + + case OP_NE_F: + OPC->_float = OPA->_float != OPB->_float; + break; + case OP_NE_V: + OPC->_float = (OPA->vector[0] != OPB->vector[0]) || + (OPA->vector[1] != OPB->vector[1]) || + (OPA->vector[2] != OPB->vector[2]); + break; + case OP_NE_S: + OPC->_float = strcmp(PR_GetString(OPA->string), PR_GetString(OPB->string)); + break; + case OP_NE_E: + OPC->_float = OPA->_int != OPB->_int; + break; + case OP_NE_FNC: + OPC->_float = OPA->function != OPB->function; + break; + + case OP_STORE_F: + case OP_STORE_ENT: + case OP_STORE_FLD: // integers + case OP_STORE_S: + case OP_STORE_FNC: // pointers + OPB->_int = OPA->_int; + break; + case OP_STORE_V: + OPB->vector[0] = OPA->vector[0]; + OPB->vector[1] = OPA->vector[1]; + OPB->vector[2] = OPA->vector[2]; + break; + + case OP_STOREP_F: + case OP_STOREP_ENT: + case OP_STOREP_FLD: // integers + case OP_STOREP_S: + case OP_STOREP_FNC: // pointers + ptr = (eval_t *)((byte *)sv.edicts + OPB->_int); + ptr->_int = OPA->_int; + break; + case OP_STOREP_V: + ptr = (eval_t *)((byte *)sv.edicts + OPB->_int); + ptr->vector[0] = OPA->vector[0]; + ptr->vector[1] = OPA->vector[1]; + ptr->vector[2] = OPA->vector[2]; + break; + + case OP_ADDRESS: + ed = PROG_TO_EDICT(OPA->edict); +#ifdef PARANOID + NUM_FOR_EDICT(ed); // Make sure it's in range +#endif + if(ed == (edict_t *)sv.edicts && sv.state == ss_active) + { + pr_xstatement = st - pr_statements; + PR_RunError("assignment to world entity"); + } + OPC->_int = (byte *)((int32_t *)&ed->v + OPB->_int) - (byte *)sv.edicts; + break; + + case OP_LOAD_F: + case OP_LOAD_FLD: + case OP_LOAD_ENT: + case OP_LOAD_S: + case OP_LOAD_FNC: + ed = PROG_TO_EDICT(OPA->edict); +#ifdef PARANOID + NUM_FOR_EDICT(ed); // Make sure it's in range +#endif + OPC->_int = ((eval_t *)((int32_t *)&ed->v + OPB->_int))->_int; + break; + + case OP_LOAD_V: + ed = PROG_TO_EDICT(OPA->edict); +#ifdef PARANOID + NUM_FOR_EDICT(ed); // Make sure it's in range +#endif + ptr = (eval_t *)((int32_t *)&ed->v + OPB->_int); + OPC->vector[0] = ptr->vector[0]; + OPC->vector[1] = ptr->vector[1]; + OPC->vector[2] = ptr->vector[2]; + break; + + case OP_IFNOT: + if(!OPA->_int) + st += st->b - 1; /* -1 to offset the st++ */ + break; + + case OP_IF: + if(OPA->_int) + st += st->b - 1; /* -1 to offset the st++ */ + break; + + case OP_GOTO: + st += st->a - 1; /* -1 to offset the st++ */ + break; + + case OP_CALL0: + case OP_CALL1: + case OP_CALL2: + case OP_CALL3: + case OP_CALL4: + case OP_CALL5: + case OP_CALL6: + case OP_CALL7: + case OP_CALL8: + pr_xfunction->profile += profile - startprofile; + startprofile = profile; + pr_xstatement = st - pr_statements; + pr_argc = st->op - OP_CALL0; + if(!OPA->function) + PR_RunError("NULL function"); + newf = &pr_functions[OPA->function]; + if(newf->first_statement < 0) + { + // Built-in function + int32_t i = -newf->first_statement; + if(i >= pr_numbuiltins) + PR_RunError("Bad builtin call number %" PRIi32 "", i); + pr_builtins[i](); + break; + } + // Normal function + st = &pr_statements[PR_EnterFunction(newf)]; + break; + + case OP_DONE: + case OP_RETURN: + pr_xfunction->profile += profile - startprofile; + startprofile = profile; + pr_xstatement = st - pr_statements; + pr_globals[OFS_RETURN] = pr_globals[(uint16_t)st->a]; + pr_globals[OFS_RETURN + 1] = pr_globals[(uint16_t)st->a + 1]; + pr_globals[OFS_RETURN + 2] = pr_globals[(uint16_t)st->a + 2]; + st = &pr_statements[PR_LeaveFunction()]; + if(pr_depth == exitdepth) + { + // Done + return; + } + break; + + case OP_STATE: + ed = PROG_TO_EDICT(pr_global_struct->self); + ed->v.nextthink = pr_global_struct->time + 0.1; + ed->v.frame = OPA->_float; + ed->v.think = OPB->function; + break; + + default: + pr_xstatement = st - pr_statements; + PR_RunError("Bad opcode %" PRIi32 "", st->op); } - // Normal function - st = &pr_statements[PR_EnterFunction(newf)]; - break; - - case OP_DONE: - case OP_RETURN: - pr_xfunction->profile += profile - startprofile; - startprofile = profile; - pr_xstatement = st - pr_statements; - pr_globals[OFS_RETURN] = pr_globals[(uint16_t)st->a]; - pr_globals[OFS_RETURN + 1] = pr_globals[(uint16_t)st->a + 1]; - pr_globals[OFS_RETURN + 2] = pr_globals[(uint16_t)st->a + 2]; - st = &pr_statements[PR_LeaveFunction()]; - if (pr_depth == exitdepth) - { // Done - return; - } - break; - - case OP_STATE: - ed = PROG_TO_EDICT(pr_global_struct->self); - ed->v.nextthink = pr_global_struct->time + 0.1; - ed->v.frame = OPA->_float; - ed->v.think = OPB->function; - break; - - default: - pr_xstatement = st - pr_statements; - PR_RunError("Bad opcode %" PRIi32 "", st->op); - } - } /* end of while(1) loop */ + } /* end of while(1) loop */ } #undef OPA #undef OPB diff --git a/source/progdefs.h b/source/progdefs.h index 5a806f5..d2364dc 100644 --- a/source/progdefs.h +++ b/source/progdefs.h @@ -24,5 +24,5 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "progdefs.q1" -#endif /* __PROGDEFS_H */ +#endif /* __PROGDEFS_H */ diff --git a/source/progs.h b/source/progs.h index 854467e..750e341 100644 --- a/source/progs.h +++ b/source/progs.h @@ -23,122 +23,122 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef _QUAKE_PROGS_H #define _QUAKE_PROGS_H -#include "pr_comp.h" /* defs shared with qcc */ -#include "progdefs.h" /* generated by program cdefs */ +#include "pr_comp.h" /* defs shared with qcc */ +#include "progdefs.h" /* generated by program cdefs */ typedef union eval_s { - string_t string; - float _float; - float vector[3]; - func_t function; - int32_t _int; - int32_t edict; + string_t string; + float _float; + float vector[3]; + func_t function; + int32_t _int; + int32_t edict; } eval_t; -#define MAX_ENT_LEAFS 32 +#define MAX_ENT_LEAFS 32 typedef struct edict_s { - bool free; - link_t area; /* linked to a division node or leaf */ + bool free; + link_t area; /* linked to a division node or leaf */ - int32_t num_leafs; - int32_t leafnums[MAX_ENT_LEAFS]; + int32_t num_leafs; + int32_t leafnums[MAX_ENT_LEAFS]; - entity_state_t baseline; - uint8_t alpha; /* johnfitz -- hack to support alpha since it's not part of entvars_t */ - bool sendinterval; /* johnfitz -- send time until nextthink to client for better lerp timing */ + entity_state_t baseline; + uint8_t alpha; /* johnfitz -- hack to support alpha since it's not part of entvars_t */ + bool sendinterval; /* johnfitz -- send time until nextthink to client for better lerp timing */ - float freetime; /* sv.time when the object was freed */ - entvars_t v; /* C exported fields from progs */ + float freetime; /* sv.time when the object was freed */ + entvars_t v; /* C exported fields from progs */ /* other fields from progs come immediately after */ } edict_t; -#define EDICT_FROM_AREA(l) STRUCT_FROM_LINK(l,edict_t,area) +#define EDICT_FROM_AREA(l) STRUCT_FROM_LINK(l,edict_t,area) //============================================================================ -extern dprograms_t *progs; -extern dfunction_t *pr_functions; -extern dstatement_t *pr_statements; -extern globalvars_t *pr_global_struct; -extern float *pr_globals; /* same as pr_global_struct */ +extern dprograms_t *progs; +extern dfunction_t *pr_functions; +extern dstatement_t *pr_statements; +extern globalvars_t *pr_global_struct; +extern float *pr_globals; /* same as pr_global_struct */ -extern int32_t pr_edict_size; /* in bytes */ +extern int32_t pr_edict_size; /* in bytes */ -void PR_Init (void); +void PR_Init(void); -void PR_ExecuteProgram (func_t fnum); -void PR_LoadProgs (void); +void PR_ExecuteProgram(func_t fnum); +void PR_LoadProgs(void); -const char *PR_GetString (int32_t num); -int32_t PR_SetEngineString (const char *s); -int32_t PR_AllocString (int32_t bufferlength, char **ptr); +const char *PR_GetString(int32_t num); +int32_t PR_SetEngineString(const char *s); +int32_t PR_AllocString(int32_t bufferlength, char **ptr); -void PR_Profile_f (void); +void PR_Profile_f(void); -edict_t *ED_Alloc (void); -void ED_Free (edict_t *ed); +edict_t *ED_Alloc(void); +void ED_Free(edict_t *ed); -void ED_Print (edict_t *ed); -void ED_Write (FILE *f, edict_t *ed); -const char *ED_ParseEdict (const char *data, edict_t *ent); +void ED_Print(edict_t *ed); +void ED_Write(FILE *f, edict_t *ed); +const char *ED_ParseEdict(const char *data, edict_t *ent); -void ED_WriteGlobals (FILE *f); -const char *ED_ParseGlobals (const char *data); +void ED_WriteGlobals(FILE *f); +const char *ED_ParseGlobals(const char *data); -void ED_LoadFromFile (const char *data); +void ED_LoadFromFile(const char *data); /* -#define EDICT_NUM(n) ((edict_t *)(sv.edicts+ (n)*pr_edict_size)) -#define NUM_FOR_EDICT(e) (((byte *)(e) - sv.edicts) / pr_edict_size) +#define EDICT_NUM(n) ((edict_t *)(sv.edicts+ (n)*pr_edict_size)) +#define NUM_FOR_EDICT(e) (((byte *)(e) - sv.edicts) / pr_edict_size) */ edict_t *EDICT_NUM(int32_t n); int32_t NUM_FOR_EDICT(edict_t *e); -#define NEXT_EDICT(e) ((edict_t *)( (byte *)e + pr_edict_size)) +#define NEXT_EDICT(e) ((edict_t *)( (byte *)e + pr_edict_size)) -#define EDICT_TO_PROG(e) ((byte *)e - (byte *)sv.edicts) -#define PROG_TO_EDICT(e) ((edict_t *)((byte *)sv.edicts + e)) +#define EDICT_TO_PROG(e) ((byte *)e - (byte *)sv.edicts) +#define PROG_TO_EDICT(e) ((edict_t *)((byte *)sv.edicts + e)) -#define G_FLOAT(o) (pr_globals[o]) -#define G_INT(o) (*(int32_t *)&pr_globals[o]) -#define G_EDICT(o) ((edict_t *)((byte *)sv.edicts+ *(int32_t *)&pr_globals[o])) -#define G_EDICTNUM(o) NUM_FOR_EDICT(G_EDICT(o)) -#define G_VECTOR(o) (&pr_globals[o]) -#define G_STRING(o) (PR_GetString(*(string_t *)&pr_globals[o])) -#define G_FUNCTION(o) (*(func_t *)&pr_globals[o]) +#define G_FLOAT(o) (pr_globals[o]) +#define G_INT(o) (*(int32_t *)&pr_globals[o]) +#define G_EDICT(o) ((edict_t *)((byte *)sv.edicts+ *(int32_t *)&pr_globals[o])) +#define G_EDICTNUM(o) NUM_FOR_EDICT(G_EDICT(o)) +#define G_VECTOR(o) (&pr_globals[o]) +#define G_STRING(o) (PR_GetString(*(string_t *)&pr_globals[o])) +#define G_FUNCTION(o) (*(func_t *)&pr_globals[o]) -#define E_FLOAT(e,o) (((float*)&e->v)[o]) -#define E_INT(e,o) (*(int32_t *)&((float*)&e->v)[o]) -#define E_VECTOR(e,o) (&((float*)&e->v)[o]) -#define E_STRING(e,o) (PR_GetString(*(string_t *)&((float*)&e->v)[o])) +#define E_FLOAT(e,o) (((float*)&e->v)[o]) +#define E_INT(e,o) (*(int32_t *)&((float*)&e->v)[o]) +#define E_VECTOR(e,o) (&((float*)&e->v)[o]) +#define E_STRING(e,o) (PR_GetString(*(string_t *)&((float*)&e->v)[o])) -extern int32_t type_size[8]; +extern int32_t type_size[8]; -typedef void (*builtin_t) (void); -extern builtin_t *pr_builtins; -extern int32_t pr_numbuiltins; +typedef void (*builtin_t)(void); +extern builtin_t *pr_builtins; +extern int32_t pr_numbuiltins; -extern int32_t pr_argc; +extern int32_t pr_argc; -extern bool pr_trace; -extern dfunction_t *pr_xfunction; -extern int32_t pr_xstatement; +extern bool pr_trace; +extern dfunction_t *pr_xfunction; +extern int32_t pr_xstatement; -extern uint16_t pr_crc; +extern uint16_t pr_crc; -noreturn void PR_RunError (const char *error, ...) FUNC_PRINTF(1,2); +noreturn void PR_RunError(const char *error, ...) FUNC_PRINTF(1, 2); #ifdef __WATCOMC__ #pragma aux PR_RunError aborts; #endif -void ED_PrintEdicts (void); -void ED_PrintNum (int32_t ent); +void ED_PrintEdicts(void); +void ED_PrintNum(int32_t ent); eval_t *GetEdictFieldValue(edict_t *ed, const char *field); -#endif /* _QUAKE_PROGS_H */ +#endif /* _QUAKE_PROGS_H */ diff --git a/source/protocol.h b/source/protocol.h index 9c7191f..1a07024 100644 --- a/source/protocol.h +++ b/source/protocol.h @@ -25,124 +25,124 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // protocol.h -- communications protocols -#define PROTOCOL_NETQUAKE 15 //johnfitz -- standard quake protocol -#define PROTOCOL_FITZQUAKE 666 //johnfitz -- added new protocol for fitzquake 0.85 -#define PROTOCOL_RMQ 999 +#define PROTOCOL_NETQUAKE 15 //johnfitz -- standard quake protocol +#define PROTOCOL_FITZQUAKE 666 //johnfitz -- added new protocol for fitzquake 0.85 +#define PROTOCOL_RMQ 999 // PROTOCOL_RMQ protocol flags -#define PRFL_SHORTANGLE (1 << 1) -#define PRFL_FLOATANGLE (1 << 2) -#define PRFL_24BITCOORD (1 << 3) -#define PRFL_FLOATCOORD (1 << 4) -#define PRFL_EDICTSCALE (1 << 5) -#define PRFL_ALPHASANITY (1 << 6) // cleanup insanity with alpha -#define PRFL_INT32COORD (1 << 7) -#define PRFL_MOREFLAGS (1 << 31) // not supported +#define PRFL_SHORTANGLE (1 << 1) +#define PRFL_FLOATANGLE (1 << 2) +#define PRFL_24BITCOORD (1 << 3) +#define PRFL_FLOATCOORD (1 << 4) +#define PRFL_EDICTSCALE (1 << 5) +#define PRFL_ALPHASANITY (1 << 6) // cleanup insanity with alpha +#define PRFL_INT32COORD (1 << 7) +#define PRFL_MOREFLAGS (1 << 31) // not supported // if the high bit of the servercmd is set, the low bits are fast update flags: -#define U_MOREBITS (1<<0) -#define U_ORIGIN1 (1<<1) -#define U_ORIGIN2 (1<<2) -#define U_ORIGIN3 (1<<3) -#define U_ANGLE2 (1<<4) -#define U_STEP (1<<5) //johnfitz -- was U_NOLERP, renamed since it's only used for MOVETYPE_STEP -#define U_FRAME (1<<6) -#define U_SIGNAL (1<<7) // just differentiates from other updates +#define U_MOREBITS (1<<0) +#define U_ORIGIN1 (1<<1) +#define U_ORIGIN2 (1<<2) +#define U_ORIGIN3 (1<<3) +#define U_ANGLE2 (1<<4) +#define U_STEP (1<<5) //johnfitz -- was U_NOLERP, renamed since it's only used for MOVETYPE_STEP +#define U_FRAME (1<<6) +#define U_SIGNAL (1<<7) // just differentiates from other updates // svc_update can pass all of the fast update bits, plus more -#define U_ANGLE1 (1<<8) -#define U_ANGLE3 (1<<9) -#define U_MODEL (1<<10) -#define U_COLORMAP (1<<11) -#define U_SKIN (1<<12) -#define U_EFFECTS (1<<13) -#define U_LONGENTITY (1<<14) +#define U_ANGLE1 (1<<8) +#define U_ANGLE3 (1<<9) +#define U_MODEL (1<<10) +#define U_COLORMAP (1<<11) +#define U_SKIN (1<<12) +#define U_EFFECTS (1<<13) +#define U_LONGENTITY (1<<14) //johnfitz -- PROTOCOL_FITZQUAKE -- new bits -#define U_EXTEND1 (1<<15) -#define U_ALPHA (1<<16) // 1 byte, uses ENTALPHA_ENCODE, not sent if equal to baseline -#define U_FRAME2 (1<<17) // 1 byte, this is .frame & 0xFF00 (second byte) -#define U_MODEL2 (1<<18) // 1 byte, this is .modelindex & 0xFF00 (second byte) -#define U_LERPFINISH (1<<19) // 1 byte, 0.0-1.0 maps to 0-255, not sent if exactly 0.1, this is ent->v.nextthink - sv.time, used for lerping -#define U_SCALE (1<<20) // 1 byte, for PROTOCOL_RMQ PRFL_EDICTSCALE, currently read but ignored -#define U_UNUSED21 (1<<21) -#define U_UNUSED22 (1<<22) -#define U_EXTEND2 (1<<23) // another byte to follow, future expansion +#define U_EXTEND1 (1<<15) +#define U_ALPHA (1<<16) // 1 byte, uses ENTALPHA_ENCODE, not sent if equal to baseline +#define U_FRAME2 (1<<17) // 1 byte, this is .frame & 0xFF00 (second byte) +#define U_MODEL2 (1<<18) // 1 byte, this is .modelindex & 0xFF00 (second byte) +#define U_LERPFINISH (1<<19) // 1 byte, 0.0-1.0 maps to 0-255, not sent if exactly 0.1, this is ent->v.nextthink - sv.time, used for lerping +#define U_SCALE (1<<20) // 1 byte, for PROTOCOL_RMQ PRFL_EDICTSCALE, currently read but ignored +#define U_UNUSED21 (1<<21) +#define U_UNUSED22 (1<<22) +#define U_EXTEND2 (1<<23) // another byte to follow, future expansion //johnfitz //johnfitz -- PROTOCOL_NEHAHRA transparency -#define U_TRANS (1<<15) +#define U_TRANS (1<<15) //johnfitz -#define SU_VIEWHEIGHT (1<<0) -#define SU_IDEALPITCH (1<<1) -#define SU_PUNCH1 (1<<2) -#define SU_PUNCH2 (1<<3) -#define SU_PUNCH3 (1<<4) -#define SU_VELOCITY1 (1<<5) -#define SU_VELOCITY2 (1<<6) -#define SU_VELOCITY3 (1<<7) -#define SU_UNUSED8 (1<<8) //AVAILABLE BIT -#define SU_ITEMS (1<<9) -#define SU_ONGROUND (1<<10) // no data follows, the bit is it -#define SU_INWATER (1<<11) // no data follows, the bit is it -#define SU_WEAPONFRAME (1<<12) -#define SU_ARMOR (1<<13) -#define SU_WEAPON (1<<14) +#define SU_VIEWHEIGHT (1<<0) +#define SU_IDEALPITCH (1<<1) +#define SU_PUNCH1 (1<<2) +#define SU_PUNCH2 (1<<3) +#define SU_PUNCH3 (1<<4) +#define SU_VELOCITY1 (1<<5) +#define SU_VELOCITY2 (1<<6) +#define SU_VELOCITY3 (1<<7) +#define SU_UNUSED8 (1<<8) //AVAILABLE BIT +#define SU_ITEMS (1<<9) +#define SU_ONGROUND (1<<10) // no data follows, the bit is it +#define SU_INWATER (1<<11) // no data follows, the bit is it +#define SU_WEAPONFRAME (1<<12) +#define SU_ARMOR (1<<13) +#define SU_WEAPON (1<<14) //johnfitz -- PROTOCOL_FITZQUAKE -- new bits -#define SU_EXTEND1 (1<<15) // another byte to follow -#define SU_WEAPON2 (1<<16) // 1 byte, this is .weaponmodel & 0xFF00 (second byte) -#define SU_ARMOR2 (1<<17) // 1 byte, this is .armorvalue & 0xFF00 (second byte) -#define SU_AMMO2 (1<<18) // 1 byte, this is .currentammo & 0xFF00 (second byte) -#define SU_SHELLS2 (1<<19) // 1 byte, this is .ammo_shells & 0xFF00 (second byte) -#define SU_NAILS2 (1<<20) // 1 byte, this is .ammo_nails & 0xFF00 (second byte) -#define SU_ROCKETS2 (1<<21) // 1 byte, this is .ammo_rockets & 0xFF00 (second byte) -#define SU_CELLS2 (1<<22) // 1 byte, this is .ammo_cells & 0xFF00 (second byte) -#define SU_EXTEND2 (1<<23) // another byte to follow -#define SU_WEAPONFRAME2 (1<<24) // 1 byte, this is .weaponframe & 0xFF00 (second byte) -#define SU_WEAPONALPHA (1<<25) // 1 byte, this is alpha for weaponmodel, uses ENTALPHA_ENCODE, not sent if ENTALPHA_DEFAULT -#define SU_UNUSED26 (1<<26) -#define SU_UNUSED27 (1<<27) -#define SU_UNUSED28 (1<<28) -#define SU_UNUSED29 (1<<29) -#define SU_UNUSED30 (1<<30) -#define SU_EXTEND3 (1<<31) // another byte to follow, future expansion +#define SU_EXTEND1 (1<<15) // another byte to follow +#define SU_WEAPON2 (1<<16) // 1 byte, this is .weaponmodel & 0xFF00 (second byte) +#define SU_ARMOR2 (1<<17) // 1 byte, this is .armorvalue & 0xFF00 (second byte) +#define SU_AMMO2 (1<<18) // 1 byte, this is .currentammo & 0xFF00 (second byte) +#define SU_SHELLS2 (1<<19) // 1 byte, this is .ammo_shells & 0xFF00 (second byte) +#define SU_NAILS2 (1<<20) // 1 byte, this is .ammo_nails & 0xFF00 (second byte) +#define SU_ROCKETS2 (1<<21) // 1 byte, this is .ammo_rockets & 0xFF00 (second byte) +#define SU_CELLS2 (1<<22) // 1 byte, this is .ammo_cells & 0xFF00 (second byte) +#define SU_EXTEND2 (1<<23) // another byte to follow +#define SU_WEAPONFRAME2 (1<<24) // 1 byte, this is .weaponframe & 0xFF00 (second byte) +#define SU_WEAPONALPHA (1<<25) // 1 byte, this is alpha for weaponmodel, uses ENTALPHA_ENCODE, not sent if ENTALPHA_DEFAULT +#define SU_UNUSED26 (1<<26) +#define SU_UNUSED27 (1<<27) +#define SU_UNUSED28 (1<<28) +#define SU_UNUSED29 (1<<29) +#define SU_UNUSED30 (1<<30) +#define SU_EXTEND3 (1<<31) // another byte to follow, future expansion //johnfitz // a sound with no channel is a local only sound -#define SND_VOLUME (1<<0) // a byte -#define SND_ATTENUATION (1<<1) // a byte -#define SND_LOOPING (1<<2) // a long +#define SND_VOLUME (1<<0) // a byte +#define SND_ATTENUATION (1<<1) // a byte +#define SND_LOOPING (1<<2) // a long -#define DEFAULT_SOUND_PACKET_VOLUME 255 -#define DEFAULT_SOUND_PACKET_ATTENUATION 1.0 +#define DEFAULT_SOUND_PACKET_VOLUME 255 +#define DEFAULT_SOUND_PACKET_ATTENUATION 1.0 //johnfitz -- PROTOCOL_FITZQUAKE -- new bits -#define SND_LARGEENTITY (1<<3) // a int16_t + byte (instead of just a int16_t) -#define SND_LARGESOUND (1<<4) // a int16_t soundindex (instead of a byte) +#define SND_LARGEENTITY (1<<3) // a int16_t + byte (instead of just a int16_t) +#define SND_LARGESOUND (1<<4) // a int16_t soundindex (instead of a byte) //johnfitz //johnfitz -- PROTOCOL_FITZQUAKE -- flags for entity baseline messages -#define B_LARGEMODEL (1<<0) // modelindex is int16_t instead of byte -#define B_LARGEFRAME (1<<1) // frame is int16_t instead of byte -#define B_ALPHA (1<<2) // 1 byte, uses ENTALPHA_ENCODE, not sent if ENTALPHA_DEFAULT +#define B_LARGEMODEL (1<<0) // modelindex is int16_t instead of byte +#define B_LARGEFRAME (1<<1) // frame is int16_t instead of byte +#define B_ALPHA (1<<2) // 1 byte, uses ENTALPHA_ENCODE, not sent if ENTALPHA_DEFAULT //johnfitz //johnfitz -- PROTOCOL_FITZQUAKE -- alpha encoding -#define ENTALPHA_DEFAULT 0 //entity's alpha is "default" (i.e. water obeys r_wateralpha) -- must be zero so zeroed out memory works -#define ENTALPHA_ZERO 1 //entity is invisible (lowest possible alpha) -#define ENTALPHA_ONE 255 //entity is fully opaque (highest possible alpha) -#define ENTALPHA_ENCODE(a) (((a)==0)?ENTALPHA_DEFAULT:Q_rint(CLAMP(1,(a)*254.0f+1,255))) //server convert to byte to send to client -#define ENTALPHA_DECODE(a) (((a)==ENTALPHA_DEFAULT)?1.0f:((float)(a)-1)/(254)) //client convert to float for rendering -#define ENTALPHA_TOSAVE(a) (((a)==ENTALPHA_DEFAULT)?0.0f:(((a)==ENTALPHA_ZERO)?-1.0f:((float)(a)-1)/(254))) //server convert to float for savegame +#define ENTALPHA_DEFAULT 0 //entity's alpha is "default" (i.e. water obeys r_wateralpha) -- must be zero so zeroed out memory works +#define ENTALPHA_ZERO 1 //entity is invisible (lowest possible alpha) +#define ENTALPHA_ONE 255 //entity is fully opaque (highest possible alpha) +#define ENTALPHA_ENCODE(a) (((a)==0)?ENTALPHA_DEFAULT:Q_rint(CLAMP(1,(a)*254.0f+1,255))) //server convert to byte to send to client +#define ENTALPHA_DECODE(a) (((a)==ENTALPHA_DEFAULT)?1.0f:((float)(a)-1)/(254)) //client convert to float for rendering +#define ENTALPHA_TOSAVE(a) (((a)==ENTALPHA_DEFAULT)?0.0f:(((a)==ENTALPHA_ZERO)?-1.0f:((float)(a)-1)/(254))) //server convert to float for savegame //johnfitz // defaults for clientinfo messages -#define DEFAULT_VIEWHEIGHT 22 +#define DEFAULT_VIEWHEIGHT 22 // game types sent by serverinfo // these determine which intermission screen plays -#define GAME_COOP 0 -#define GAME_DEATHMATCH 1 +#define GAME_COOP 0 +#define GAME_DEATHMATCH 1 //================== // note that there are some defs.qc that mirror to these numbers @@ -152,106 +152,106 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // server to client // -#define svc_bad 0 -#define svc_nop 1 -#define svc_disconnect 2 -#define svc_updatestat 3 // [byte] [long] -#define svc_version 4 // [long] server version -#define svc_setview 5 // [int16_t] entity number -#define svc_sound 6 // -#define svc_time 7 // [float] server time -#define svc_print 8 // [string] null terminated string -#define svc_stufftext 9 // [string] stuffed into client's console buffer - // the string should be \n terminated -#define svc_setangle 10 // [angle3] set the view angle to this absolute value -#define svc_serverinfo 11 // [long] version - // [string] signon string - // [string]..[0]model cache - // [string]...[0]sounds cache -#define svc_lightstyle 12 // [byte] [string] -#define svc_updatename 13 // [byte] [string] -#define svc_updatefrags 14 // [byte] [int16_t] -#define svc_clientdata 15 // -#define svc_stopsound 16 // -#define svc_updatecolors 17 // [byte] [byte] -#define svc_particle 18 // [vec3] -#define svc_damage 19 -#define svc_spawnstatic 20 -//#define svc_spawnbinary 21 -#define svc_spawnbaseline 22 -#define svc_temp_entity 23 -#define svc_setpause 24 // [byte] on / off -#define svc_signonnum 25 // [byte] used for the signon sequence -#define svc_centerprint 26 // [string] to put in center of the screen -#define svc_killedmonster 27 -#define svc_foundsecret 28 -#define svc_spawnstaticsound 29 // [coord3] [byte] samp [byte] vol [byte] aten -#define svc_intermission 30 // [string] music -#define svc_finale 31 // [string] music [string] text -#define svc_cdtrack 32 // [byte] track [byte] looptrack -#define svc_sellscreen 33 -#define svc_cutscene 34 +#define svc_bad 0 +#define svc_nop 1 +#define svc_disconnect 2 +#define svc_updatestat 3 // [byte] [long] +#define svc_version 4 // [long] server version +#define svc_setview 5 // [int16_t] entity number +#define svc_sound 6 // +#define svc_time 7 // [float] server time +#define svc_print 8 // [string] null terminated string +#define svc_stufftext 9 // [string] stuffed into client's console buffer +// the string should be \n terminated +#define svc_setangle 10 // [angle3] set the view angle to this absolute value +#define svc_serverinfo 11 // [long] version +// [string] signon string +// [string]..[0]model cache +// [string]...[0]sounds cache +#define svc_lightstyle 12 // [byte] [string] +#define svc_updatename 13 // [byte] [string] +#define svc_updatefrags 14 // [byte] [int16_t] +#define svc_clientdata 15 // +#define svc_stopsound 16 // +#define svc_updatecolors 17 // [byte] [byte] +#define svc_particle 18 // [vec3] +#define svc_damage 19 +#define svc_spawnstatic 20 +//#define svc_spawnbinary 21 +#define svc_spawnbaseline 22 +#define svc_temp_entity 23 +#define svc_setpause 24 // [byte] on / off +#define svc_signonnum 25 // [byte] used for the signon sequence +#define svc_centerprint 26 // [string] to put in center of the screen +#define svc_killedmonster 27 +#define svc_foundsecret 28 +#define svc_spawnstaticsound 29 // [coord3] [byte] samp [byte] vol [byte] aten +#define svc_intermission 30 // [string] music +#define svc_finale 31 // [string] music [string] text +#define svc_cdtrack 32 // [byte] track [byte] looptrack +#define svc_sellscreen 33 +#define svc_cutscene 34 //johnfitz -- PROTOCOL_FITZQUAKE -- new server messages -#define svc_skybox 37 // [string] name -#define svc_bf 40 -#define svc_fog 41 // [byte] density [byte] red [byte] green [byte] blue [float] time -#define svc_spawnbaseline2 42 // support for large modelindex, large framenum, alpha, using flags -#define svc_spawnstatic2 43 // support for large modelindex, large framenum, alpha, using flags -#define svc_spawnstaticsound2 44 // [coord3] [int16_t] samp [byte] vol [byte] aten +#define svc_skybox 37 // [string] name +#define svc_bf 40 +#define svc_fog 41 // [byte] density [byte] red [byte] green [byte] blue [float] time +#define svc_spawnbaseline2 42 // support for large modelindex, large framenum, alpha, using flags +#define svc_spawnstatic2 43 // support for large modelindex, large framenum, alpha, using flags +#define svc_spawnstaticsound2 44 // [coord3] [int16_t] samp [byte] vol [byte] aten //johnfitz // // client to server // -#define clc_bad 0 -#define clc_nop 1 -#define clc_disconnect 2 -#define clc_move 3 // [usercmd_t] -#define clc_stringcmd 4 // [string] message +#define clc_bad 0 +#define clc_nop 1 +#define clc_disconnect 2 +#define clc_move 3 // [usercmd_t] +#define clc_stringcmd 4 // [string] message // // temp entity events // -#define TE_SPIKE 0 -#define TE_SUPERSPIKE 1 -#define TE_GUNSHOT 2 -#define TE_EXPLOSION 3 -#define TE_TAREXPLOSION 4 -#define TE_LIGHTNING1 5 -#define TE_LIGHTNING2 6 -#define TE_WIZSPIKE 7 -#define TE_KNIGHTSPIKE 8 -#define TE_LIGHTNING3 9 -#define TE_LAVASPLASH 10 -#define TE_TELEPORT 11 -#define TE_EXPLOSION2 12 +#define TE_SPIKE 0 +#define TE_SUPERSPIKE 1 +#define TE_GUNSHOT 2 +#define TE_EXPLOSION 3 +#define TE_TAREXPLOSION 4 +#define TE_LIGHTNING1 5 +#define TE_LIGHTNING2 6 +#define TE_WIZSPIKE 7 +#define TE_KNIGHTSPIKE 8 +#define TE_LIGHTNING3 9 +#define TE_LAVASPLASH 10 +#define TE_TELEPORT 11 +#define TE_EXPLOSION2 12 // PGM 01/21/97 -#define TE_BEAM 13 +#define TE_BEAM 13 // PGM 01/21/97 typedef struct { - vec3_t origin; - vec3_t angles; - uint16_t modelindex; //johnfitz -- was int32_t - uint16_t frame; //johnfitz -- was int32_t - uint8_t colormap; //johnfitz -- was int32_t - uint8_t skin; //johnfitz -- was int32_t - uint8_t alpha; //johnfitz -- added - int32_t effects; + vec3_t origin; + vec3_t angles; + uint16_t modelindex; //johnfitz -- was int32_t + uint16_t frame; //johnfitz -- was int32_t + uint8_t colormap; //johnfitz -- was int32_t + uint8_t skin; //johnfitz -- was int32_t + uint8_t alpha; //johnfitz -- added + int32_t effects; } entity_state_t; typedef struct { - vec3_t viewangles; + vec3_t viewangles; // intended velocities - float forwardmove; - float sidemove; - float upmove; + float forwardmove; + float sidemove; + float upmove; } usercmd_t; -#endif /* _QUAKE_PROTOCOL_H */ +#endif /* _QUAKE_PROTOCOL_H */ diff --git a/source/q_ctype.h b/source/q_ctype.h index e6fce51..a6c3fce 100644 --- a/source/q_ctype.h +++ b/source/q_ctype.h @@ -48,7 +48,7 @@ static inline int32_t q_isdigit(int32_t c) static inline int32_t q_isxdigit(int32_t c) { return (q_isdigit(c) || (c >= 'a' && c <= 'f') || - (c >= 'A' && c <= 'F')); + (c >= 'A' && c <= 'F')); } static inline int32_t q_isalnum(int32_t c) @@ -63,10 +63,15 @@ static inline int32_t q_isblank(int32_t c) static inline int32_t q_isspace(int32_t c) { - switch(c) { - case ' ': case '\t': - case '\n': case '\r': - case '\f': case '\v': return 1; + switch(c) + { + case ' ': + case '\t': + case '\n': + case '\r': + case '\f': + case '\v': + return 1; } return 0; } diff --git a/source/q_sound.h b/source/q_sound.h index 9494257..90f12d4 100644 --- a/source/q_sound.h +++ b/source/q_sound.h @@ -34,92 +34,92 @@ typedef struct typedef struct sfx_s { - char name[MAX_QPATH]; - cache_user_t cache; + char name[MAX_QPATH]; + cache_user_t cache; } sfx_t; /* !!! if this is changed, it must be changed in asm_i386.h too !!! */ typedef struct { - int32_t length; - int32_t loopstart; - int32_t speed; - int32_t width; - int32_t stereo; - byte data[1]; /* variable sized */ + int32_t length; + int32_t loopstart; + int32_t speed; + int32_t width; + int32_t stereo; + byte data[1]; /* variable sized */ } sfxcache_t; typedef struct { - int32_t channels; - int32_t samples; /* mono samples in buffer */ - int32_t submission_chunk; /* don't mix less than this # */ - int32_t samplepos; /* in mono samples */ - int32_t samplebits; - int32_t signed8; /* device opened for S8 format? (e.g. Amiga AHI) */ - int32_t speed; - uint8_t *buffer; + int32_t channels; + int32_t samples; /* mono samples in buffer */ + int32_t submission_chunk; /* don't mix less than this # */ + int32_t samplepos; /* in mono samples */ + int32_t samplebits; + int32_t signed8; /* device opened for S8 format? (e.g. Amiga AHI) */ + int32_t speed; + uint8_t *buffer; } dma_t; /* !!! if this is changed, it must be changed in asm_i386.h too !!! */ typedef struct { - sfx_t *sfx; /* sfx number */ - int32_t leftvol; /* 0-255 volume */ - int32_t rightvol; /* 0-255 volume */ - int32_t end; /* end time in global paintsamples */ - int32_t pos; /* sample position in sfx */ - int32_t looping; /* where to loop, -1 = no looping */ - int32_t entnum; /* to allow overriding a specific sound */ - int32_t entchannel; - vec3_t origin; /* origin of sound effect */ - vec_t dist_mult; /* distance multiplier (attenuation/clipK) */ - int32_t master_vol; /* 0-255 master volume */ + sfx_t *sfx; /* sfx number */ + int32_t leftvol; /* 0-255 volume */ + int32_t rightvol; /* 0-255 volume */ + int32_t end; /* end time in global paintsamples */ + int32_t pos; /* sample position in sfx */ + int32_t looping; /* where to loop, -1 = no looping */ + int32_t entnum; /* to allow overriding a specific sound */ + int32_t entchannel; + vec3_t origin; /* origin of sound effect */ + vec_t dist_mult; /* distance multiplier (attenuation/clipK) */ + int32_t master_vol; /* 0-255 master volume */ } channel_t; -#define WAV_FORMAT_PCM 1 +#define WAV_FORMAT_PCM 1 typedef struct { - int32_t rate; - int32_t width; - int32_t channels; - int32_t loopstart; - int32_t samples; - int32_t dataofs; /* chunk starts this many bytes from file start */ + int32_t rate; + int32_t width; + int32_t channels; + int32_t loopstart; + int32_t samples; + int32_t dataofs; /* chunk starts this many bytes from file start */ } wavinfo_t; -void S_Init (void); -void S_Startup (void); -void S_Shutdown (void); -void S_StartSound (int32_t entnum, int32_t entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation); -void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation); -void S_StopSound (int32_t entnum, int32_t entchannel); +void S_Init(void); +void S_Startup(void); +void S_Shutdown(void); +void S_StartSound(int32_t entnum, int32_t entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation); +void S_StaticSound(sfx_t *sfx, vec3_t origin, float vol, float attenuation); +void S_StopSound(int32_t entnum, int32_t entchannel); void S_StopAllSounds(bool clear); -void S_ClearBuffer (void); -void S_Update (vec3_t origin, vec3_t forward, vec3_t right, vec3_t up); -void S_ExtraUpdate (void); +void S_ClearBuffer(void); +void S_Update(vec3_t origin, vec3_t forward, vec3_t right, vec3_t up); +void S_ExtraUpdate(void); -void S_BlockSound (void); -void S_UnblockSound (void); +void S_BlockSound(void); +void S_UnblockSound(void); -sfx_t *S_PrecacheSound (const char *sample); -void S_TouchSound (const char *sample); -void S_ClearPrecache (void); -void S_BeginPrecaching (void); -void S_EndPrecaching (void); -void S_PaintChannels (int32_t endtime); -void S_InitPaintChannels (void); +sfx_t *S_PrecacheSound(const char *sample); +void S_TouchSound(const char *sample); +void S_ClearPrecache(void); +void S_BeginPrecaching(void); +void S_EndPrecaching(void); +void S_PaintChannels(int32_t endtime); +void S_InitPaintChannels(void); /* picks a channel based on priorities, empty slots, number of channels */ -channel_t *SND_PickChannel (int32_t entnum, int32_t entchannel); +channel_t *SND_PickChannel(int32_t entnum, int32_t entchannel); /* spatializes a channel */ -void SND_Spatialize (channel_t *ch); +void SND_Spatialize(channel_t *ch); /* music stream support */ void S_RawSamples(int32_t samples, int32_t rate, int32_t width, int32_t channels, byte * data, float volume); - /* Expects data in signed 16 bit, or unsigned 8 bit format. */ +/* Expects data in signed 16 bit, or unsigned 8 bit format. */ /* initializes cycling through a DMA buffer and returns information on it */ bool SNDDMA_Init(dma_t *dma); @@ -147,44 +147,44 @@ void SNDDMA_UnblockSound(void); * ==================================================================== */ -#define MAX_CHANNELS 1024 // ericw -- was 512 /* johnfitz -- was 128 */ -#define MAX_DYNAMIC_CHANNELS 128 /* johnfitz -- was 8 */ +#define MAX_CHANNELS 1024 // ericw -- was 512 /* johnfitz -- was 128 */ +#define MAX_DYNAMIC_CHANNELS 128 /* johnfitz -- was 8 */ -extern channel_t snd_channels[MAX_CHANNELS]; -/* 0 to MAX_DYNAMIC_CHANNELS-1 = normal entity sounds +extern channel_t snd_channels[MAX_CHANNELS]; +/* 0 to MAX_DYNAMIC_CHANNELS-1 = normal entity sounds * MAX_DYNAMIC_CHANNELS to MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS -1 = water, etc * MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS to total_channels = static sounds */ -extern volatile dma_t *shm; +extern volatile dma_t *shm; -extern int32_t total_channels; -extern int32_t soundtime; -extern int32_t paintedtime; -extern int32_t s_rawend; +extern int32_t total_channels; +extern int32_t soundtime; +extern int32_t paintedtime; +extern int32_t s_rawend; -extern vec3_t listener_origin; -extern vec3_t listener_forward; -extern vec3_t listener_right; -extern vec3_t listener_up; +extern vec3_t listener_origin; +extern vec3_t listener_forward; +extern vec3_t listener_right; +extern vec3_t listener_up; -extern cvar_t sndspeed; -extern cvar_t snd_mixspeed; -extern cvar_t snd_filterquality; -extern cvar_t sfxvolume; -extern cvar_t loadas8bit; +extern cvar_t sndspeed; +extern cvar_t snd_mixspeed; +extern cvar_t snd_filterquality; +extern cvar_t sfxvolume; +extern cvar_t loadas8bit; -#define MAX_RAW_SAMPLES 8192 -extern portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; +#define MAX_RAW_SAMPLES 8192 +extern portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; -extern cvar_t bgmvolume; +extern cvar_t bgmvolume; -void S_LocalSound (const char *name); -sfxcache_t *S_LoadSound (sfx_t *s); +void S_LocalSound(const char *name); +sfxcache_t *S_LoadSound(sfx_t *s); -wavinfo_t GetWavinfo (const char *name, byte *wav, int32_t wavlength); +wavinfo_t GetWavinfo(const char *name, byte *wav, int32_t wavlength); -void SND_InitScaletable (void); +void SND_InitScaletable(void); -#endif /* __QUAKE_SOUND__ */ +#endif /* __QUAKE_SOUND__ */ diff --git a/source/q_stdinc.h b/source/q_stdinc.h index abf607b..5d31859 100644 --- a/source/q_stdinc.h +++ b/source/q_stdinc.h @@ -1,11 +1,11 @@ /* * q_stdinc.h - includes the minimum necessary stdc headers, - * defines common and / or missing types. + * defines common and / or missing types. * - * NOTE: for net stuff use net_sys.h, - * for byte order use q_endian.h, - * for math stuff use mathlib.h, - * for locale-insensitive ctype.h functions use q_ctype.h. + * NOTE: for net stuff use net_sys.h, + * for byte order use q_endian.h, + * for math stuff use mathlib.h, + * for locale-insensitive ctype.h functions use q_ctype.h. * * Copyright (C) 1996-1997 Id Software, Inc. * Copyright (C) 2007-2011 O.Sezer @@ -54,7 +54,8 @@ _Static_assert(sizeof(float) == 4, "float not correct size"); _Static_assert(sizeof(int32_t) == 4, "int32_t not correct size"); /* make sure enums are the size of ints for structure packing */ -enum dummy_enum { +enum dummy_enum +{ dummy_value }; _Static_assert(sizeof(enum dummy_enum) == sizeof(int32_t), "enum not sizeof(int32_t)"); @@ -62,10 +63,10 @@ _Static_assert(sizeof(enum dummy_enum) == sizeof(int32_t), "enum not sizeof(int3 typedef uint8_t byte; /* math */ -typedef float vec_t; -typedef vec_t vec3_t[3]; -typedef vec_t vec4_t[4]; -typedef vec_t vec5_t[5]; +typedef float vec_t; +typedef vec_t vec3_t[3]; +typedef vec_t vec4_t[4]; +typedef vec_t vec5_t[5]; /* MAX_OSPATH (max length of a filesystem pathname, i.e. PATH_MAX) * Note: See GNU Hurd and others' notes about brokenness of this: @@ -75,30 +76,30 @@ typedef vec_t vec5_t[5]; #if !defined(PATH_MAX) /* equivalent values? */ #if defined(MAXPATHLEN) -#define PATH_MAX MAXPATHLEN +#define PATH_MAX MAXPATHLEN #elif defined(_WIN32) && defined(_MAX_PATH) -#define PATH_MAX _MAX_PATH +#define PATH_MAX _MAX_PATH #elif defined(_WIN32) && defined(MAX_PATH) -#define PATH_MAX MAX_PATH +#define PATH_MAX MAX_PATH #else /* fallback */ -#define PATH_MAX 1024 +#define PATH_MAX 1024 #endif -#endif /* PATH_MAX */ +#endif /* PATH_MAX */ -#define MAX_OSPATH PATH_MAX +#define MAX_OSPATH PATH_MAX /* function attributes, etc */ #if defined(__GNUC__) -#define FUNC_PRINTF(x,y) __attribute__((__format__(__printf__,x,y))) +#define FUNC_PRINTF(x,y) __attribute__((__format__(__printf__,x,y))) #else #define FUNC_PRINTF(x,y) #endif /* argument format attributes for function pointers are supported for gcc >= 3.1 */ #if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 0)) -#define FUNCP_PRINTF FUNC_PRINTF +#define FUNCP_PRINTF FUNC_PRINTF #else #define FUNCP_PRINTF(x,y) #endif -#endif /* __QSTDINC_H */ +#endif /* __QSTDINC_H */ diff --git a/source/qs_bmp.h b/source/qs_bmp.h index fd2b2b5..b5d25b7 100644 --- a/source/qs_bmp.h +++ b/source/qs_bmp.h @@ -1,189 +1,189 @@ 0x42, 0x4d, 0xc6, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc6, 0x02, 0x00, 0x00, 0x28, 0x00, -0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0xa4, 0x00, -0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x00, 0x05, 0x06, 0x07, 0x00, 0x06, 0x06, -0x07, 0x00, 0x07, 0x06, 0x07, 0x00, 0x06, 0x07, 0x06, 0x00, 0x06, 0x07, 0x07, 0x00, 0x07, 0x07, -0x07, 0x00, 0x07, 0x08, 0x07, 0x00, 0x08, 0x08, 0x08, 0x00, 0x07, 0x08, 0x09, 0x00, 0x08, 0x08, -0x09, 0x00, 0x07, 0x09, 0x08, 0x00, 0x08, 0x09, 0x08, 0x00, 0x09, 0x09, 0x08, 0x00, 0x08, 0x09, -0x09, 0x00, 0x09, 0x09, 0x09, 0x00, 0x08, 0x09, 0x0a, 0x00, 0x09, 0x09, 0x0a, 0x00, 0x09, 0x09, -0x0b, 0x00, 0x09, 0x0a, 0x09, 0x00, 0x08, 0x0a, 0x0a, 0x00, 0x09, 0x0a, 0x0a, 0x00, 0x0a, 0x0a, -0x0a, 0x00, 0x09, 0x0a, 0x0b, 0x00, 0x0a, 0x0a, 0x0b, 0x00, 0x09, 0x0a, 0x0c, 0x00, 0x09, 0x0b, -0x0b, 0x00, 0x0a, 0x0b, 0x0b, 0x00, 0x0a, 0x0b, 0x0c, 0x00, 0x0b, 0x0b, 0x0c, 0x00, 0x0a, 0x0b, -0x0d, 0x00, 0x0b, 0x0c, 0x0c, 0x00, 0x0b, 0x0c, 0x0d, 0x00, 0x0a, 0x0c, 0x0e, 0x00, 0x0b, 0x0c, -0x0e, 0x00, 0x0c, 0x0c, 0x0f, 0x00, 0x0b, 0x0d, 0x0d, 0x00, 0x0b, 0x0d, 0x0e, 0x00, 0x0c, 0x0d, -0x0e, 0x00, 0x0c, 0x0d, 0x0f, 0x00, 0x0d, 0x0d, 0x0f, 0x00, 0x0b, 0x0d, 0x10, 0x00, 0x0c, 0x0d, -0x10, 0x00, 0x0c, 0x0e, 0x0f, 0x00, 0x0d, 0x0e, 0x0f, 0x00, 0x0c, 0x0e, 0x10, 0x00, 0x0d, 0x0e, -0x10, 0x00, 0x0b, 0x0e, 0x11, 0x00, 0x0c, 0x0e, 0x11, 0x00, 0x0d, 0x0e, 0x11, 0x00, 0x0d, 0x0f, -0x10, 0x00, 0x0d, 0x0f, 0x11, 0x00, 0x0e, 0x0f, 0x11, 0x00, 0x0d, 0x0f, 0x12, 0x00, 0x0e, 0x0f, -0x12, 0x00, 0x0d, 0x0f, 0x13, 0x00, 0x0e, 0x10, 0x11, 0x00, 0x0d, 0x10, 0x12, 0x00, 0x0b, 0x10, -0x13, 0x00, 0x0e, 0x10, 0x12, 0x00, 0x0e, 0x10, 0x13, 0x00, 0x0d, 0x10, 0x14, 0x00, 0x0e, 0x10, -0x14, 0x00, 0x0d, 0x11, 0x13, 0x00, 0x0e, 0x11, 0x13, 0x00, 0x0f, 0x11, 0x13, 0x00, 0x0e, 0x11, -0x14, 0x00, 0x0f, 0x11, 0x14, 0x00, 0x0f, 0x11, 0x15, 0x00, 0x0f, 0x12, 0x14, 0x00, 0x0f, 0x12, -0x15, 0x00, 0x10, 0x12, 0x15, 0x00, 0x0f, 0x12, 0x16, 0x00, 0x10, 0x12, 0x16, 0x00, 0x0f, 0x12, -0x17, 0x00, 0x0f, 0x13, 0x16, 0x00, 0x10, 0x13, 0x16, 0x00, 0x10, 0x13, 0x17, 0x00, 0x11, 0x13, -0x17, 0x00, 0x11, 0x13, 0x18, 0x00, 0x10, 0x14, 0x17, 0x00, 0x11, 0x14, 0x17, 0x00, 0x10, 0x14, -0x18, 0x00, 0x12, 0x15, 0x18, 0x00, 0x10, 0x15, 0x19, 0x00, 0x12, 0x15, 0x19, 0x00, 0x10, 0x15, -0x1a, 0x00, 0x11, 0x15, 0x1a, 0x00, 0x12, 0x15, 0x1a, 0x00, 0x12, 0x15, 0x1b, 0x00, 0x11, 0x16, -0x1a, 0x00, 0x12, 0x16, 0x1a, 0x00, 0x13, 0x16, 0x1a, 0x00, 0x12, 0x16, 0x1b, 0x00, 0x13, 0x16, -0x1b, 0x00, 0x12, 0x17, 0x1b, 0x00, 0x13, 0x17, 0x1b, 0x00, 0x13, 0x17, 0x1c, 0x00, 0x14, 0x17, -0x1c, 0x00, 0x14, 0x17, 0x1d, 0x00, 0x13, 0x18, 0x1d, 0x00, 0x14, 0x18, 0x1d, 0x00, 0x15, 0x18, -0x1f, 0x00, 0x14, 0x19, 0x1d, 0x00, 0x15, 0x19, 0x1d, 0x00, 0x15, 0x19, 0x1e, 0x00, 0x15, 0x19, -0x1f, 0x00, 0x16, 0x19, 0x1f, 0x00, 0x15, 0x19, 0x20, 0x00, 0x16, 0x1a, 0x1e, 0x00, 0x14, 0x1a, -0x1f, 0x00, 0x15, 0x1a, 0x1f, 0x00, 0x16, 0x1a, 0x1f, 0x00, 0x15, 0x1a, 0x20, 0x00, 0x16, 0x1a, -0x21, 0x00, 0x15, 0x1b, 0x21, 0x00, 0x17, 0x1b, 0x22, 0x00, 0x17, 0x1b, 0x23, 0x00, 0x16, 0x1c, -0x22, 0x00, 0x17, 0x1d, 0x22, 0x00, 0x17, 0x1d, 0x23, 0x00, 0x18, 0x1d, 0x23, 0x00, 0x19, 0x1d, -0x23, 0x00, 0x17, 0x1d, 0x24, 0x00, 0x18, 0x1e, 0x23, 0x00, 0x18, 0x1e, 0x24, 0x00, 0x18, 0x1e, -0x25, 0x00, 0x19, 0x1e, 0x25, 0x00, 0x18, 0x1e, 0x26, 0x00, 0x19, 0x1f, 0x26, 0x00, 0x1a, 0x1f, -0x26, 0x00, 0x1a, 0x1f, 0x27, 0x00, 0x1a, 0x1f, 0x28, 0x00, 0x1a, 0x20, 0x26, 0x00, 0x19, 0x20, -0x27, 0x00, 0x1a, 0x20, 0x27, 0x00, 0x1a, 0x20, 0x28, 0x00, 0x1b, 0x20, 0x29, 0x00, 0x1b, 0x21, -0x28, 0x00, 0x1b, 0x21, 0x29, 0x00, 0x1c, 0x21, 0x2a, 0x00, 0x1d, 0x22, 0x29, 0x00, 0x1c, 0x22, -0x2a, 0x00, 0x1d, 0x22, 0x2a, 0x00, 0x1e, 0x23, 0x2c, 0x00, 0x1d, 0x24, 0x2b, 0x00, 0x1d, 0x24, -0x2c, 0x00, 0x1c, 0x24, 0x2d, 0x00, 0x1e, 0x25, 0x2d, 0x00, 0x1f, 0x25, 0x2e, 0x00, 0x1e, 0x26, -0x2e, 0x00, 0x1f, 0x26, 0x2e, 0x00, 0x1f, 0x26, 0x30, 0x00, 0x21, 0x27, 0x2e, 0x00, 0x20, 0x27, -0x2f, 0x00, 0x20, 0x27, 0x31, 0x00, 0x20, 0x29, 0x32, 0x00, 0x20, 0x29, 0x33, 0x00, 0x21, 0x2a, -0x33, 0x00, 0x24, 0x2c, 0x35, 0x00, 0x24, 0x2c, 0x38, 0x00, 0x26, 0x31, 0x3b, 0x00, 0x27, 0x31, -0x3b, 0x00, 0xff, 0x00, 0xff, 0x00, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x05, 0x1a, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x25, 0x48, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x4a, 0x54, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x8a, 0x8c, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x41, 0x5e, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x0d, 0x27, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x1b, 0x1f, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x00, 0x32, 0x69, 0x29, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x21, 0x38, 0x63, 0x2b, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x3d, 0x2b, 0x1c, 0x0e, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x5d, 0x7e, 0x2b, 0x08, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x5d, 0x80, 0x4d, 0x4c, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x24, 0x4a, 0x9c, 0xa1, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x10, 0x39, 0x76, 0x46, 0x6d, 0x9a, -0x60, 0x3f, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x01, 0x78, 0x8e, 0x32, 0x37, 0x81, 0x6c, 0x2a, 0x3c, -0x55, 0x2c, 0x1d, 0x2d, 0x17, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x06, 0x27, 0x55, 0x82, 0x9b, 0x45, 0x0e, 0x47, 0x61, 0x0f, 0x1a, -0x0f, 0x20, 0x62, 0x28, 0x0f, 0x18, 0x08, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0x35, 0x1b, 0x40, 0x98, 0x4d, 0x18, 0x15, 0x1c, 0x26, 0x1b, 0x3b, 0x49, -0x20, 0x46, 0x67, 0x1b, 0x13, 0x0c, 0x15, 0x20, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0x25, 0x4d, 0x3c, 0x34, 0x2b, 0x1c, 0x08, 0x0b, 0x0f, 0x1b, 0x32, 0x9e, 0x8a, -0x08, 0x27, 0x22, 0x0f, 0x36, 0x6f, 0x75, 0x3b, 0x39, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0x7d, 0x7a, 0x56, 0x48, 0x68, 0x32, 0x06, 0xa3, 0xa3, 0xa3, 0x14, 0x40, 0x86, 0x6e, -0xa3, 0xa3, 0xa3, 0x06, 0x2d, 0x85, 0x92, 0x5b, 0x32, 0x6a, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0x1c, 0x58, 0x8a, 0x65, 0x18, 0x21, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x07, 0x43, 0x83, 0x43, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x73, 0x91, 0x7f, 0x62, 0x20, 0x15, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0x1e, 0x31, 0x0f, 0x2e, 0x1c, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x1b, 0x1b, 0x32, 0x16, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x43, 0x3b, 0x22, 0x55, 0x47, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0x72, 0x9d, 0x60, 0x33, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2d, 0x0f, 0x1b, 0x0f, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x11, 0x2d, 0x93, 0x55, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x50, -0x44, 0x90, 0x8a, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x3a, 0x77, 0x88, 0x47, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x25, 0x45, 0x25, 0x25, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x8a, -0x51, 0x23, 0x43, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x57, 0x5a, 0xa0, 0x84, 0x87, -0x74, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x02, 0x08, 0x8f, 0x8b, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa2, 0x96, -0x6a, 0x41, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x4e, 0x95, 0x68, 0x5a, 0x4b, 0x7b, -0x70, 0x4c, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x04, 0x53, 0x8d, 0x79, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x79, 0x80, -0x5b, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x0e, 0x7c, 0x94, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x4f, 0x6a, -0x47, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x5f, 0x40, 0x1b, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x46, 0x2d, -0x08, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x97, 0x82, 0x18, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x58, 0x43, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x69, 0x5c, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x71, 0x40, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x65, 0x60, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x52, 0x2d, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x66, 0x5e, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2d, 0x20, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x6f, 0x6b, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2b, 0x5b, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2e, 0x44, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x25, 0x41, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x40, 0x1e, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x10, 0x38, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x69, 0x42, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x3b, -0x19, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x03, 0x20, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x53, -0x1d, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x4f, 0x15, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0x1d, 0x09, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x48, 0x89, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0x1e, 0x33, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x5b, 0x39, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0x3b, 0x2a, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x59, 0x9f, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0x33, 0x0a, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2f, 0x64, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0x1d, 0x2b, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x12, 0x99, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0x49, 0x3e, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x1c, 0x36, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x30, 0x5e, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x8a, 0x48, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, -0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3 + 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0xa4, 0x00, + 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x00, 0x05, 0x06, 0x07, 0x00, 0x06, 0x06, + 0x07, 0x00, 0x07, 0x06, 0x07, 0x00, 0x06, 0x07, 0x06, 0x00, 0x06, 0x07, 0x07, 0x00, 0x07, 0x07, + 0x07, 0x00, 0x07, 0x08, 0x07, 0x00, 0x08, 0x08, 0x08, 0x00, 0x07, 0x08, 0x09, 0x00, 0x08, 0x08, + 0x09, 0x00, 0x07, 0x09, 0x08, 0x00, 0x08, 0x09, 0x08, 0x00, 0x09, 0x09, 0x08, 0x00, 0x08, 0x09, + 0x09, 0x00, 0x09, 0x09, 0x09, 0x00, 0x08, 0x09, 0x0a, 0x00, 0x09, 0x09, 0x0a, 0x00, 0x09, 0x09, + 0x0b, 0x00, 0x09, 0x0a, 0x09, 0x00, 0x08, 0x0a, 0x0a, 0x00, 0x09, 0x0a, 0x0a, 0x00, 0x0a, 0x0a, + 0x0a, 0x00, 0x09, 0x0a, 0x0b, 0x00, 0x0a, 0x0a, 0x0b, 0x00, 0x09, 0x0a, 0x0c, 0x00, 0x09, 0x0b, + 0x0b, 0x00, 0x0a, 0x0b, 0x0b, 0x00, 0x0a, 0x0b, 0x0c, 0x00, 0x0b, 0x0b, 0x0c, 0x00, 0x0a, 0x0b, + 0x0d, 0x00, 0x0b, 0x0c, 0x0c, 0x00, 0x0b, 0x0c, 0x0d, 0x00, 0x0a, 0x0c, 0x0e, 0x00, 0x0b, 0x0c, + 0x0e, 0x00, 0x0c, 0x0c, 0x0f, 0x00, 0x0b, 0x0d, 0x0d, 0x00, 0x0b, 0x0d, 0x0e, 0x00, 0x0c, 0x0d, + 0x0e, 0x00, 0x0c, 0x0d, 0x0f, 0x00, 0x0d, 0x0d, 0x0f, 0x00, 0x0b, 0x0d, 0x10, 0x00, 0x0c, 0x0d, + 0x10, 0x00, 0x0c, 0x0e, 0x0f, 0x00, 0x0d, 0x0e, 0x0f, 0x00, 0x0c, 0x0e, 0x10, 0x00, 0x0d, 0x0e, + 0x10, 0x00, 0x0b, 0x0e, 0x11, 0x00, 0x0c, 0x0e, 0x11, 0x00, 0x0d, 0x0e, 0x11, 0x00, 0x0d, 0x0f, + 0x10, 0x00, 0x0d, 0x0f, 0x11, 0x00, 0x0e, 0x0f, 0x11, 0x00, 0x0d, 0x0f, 0x12, 0x00, 0x0e, 0x0f, + 0x12, 0x00, 0x0d, 0x0f, 0x13, 0x00, 0x0e, 0x10, 0x11, 0x00, 0x0d, 0x10, 0x12, 0x00, 0x0b, 0x10, + 0x13, 0x00, 0x0e, 0x10, 0x12, 0x00, 0x0e, 0x10, 0x13, 0x00, 0x0d, 0x10, 0x14, 0x00, 0x0e, 0x10, + 0x14, 0x00, 0x0d, 0x11, 0x13, 0x00, 0x0e, 0x11, 0x13, 0x00, 0x0f, 0x11, 0x13, 0x00, 0x0e, 0x11, + 0x14, 0x00, 0x0f, 0x11, 0x14, 0x00, 0x0f, 0x11, 0x15, 0x00, 0x0f, 0x12, 0x14, 0x00, 0x0f, 0x12, + 0x15, 0x00, 0x10, 0x12, 0x15, 0x00, 0x0f, 0x12, 0x16, 0x00, 0x10, 0x12, 0x16, 0x00, 0x0f, 0x12, + 0x17, 0x00, 0x0f, 0x13, 0x16, 0x00, 0x10, 0x13, 0x16, 0x00, 0x10, 0x13, 0x17, 0x00, 0x11, 0x13, + 0x17, 0x00, 0x11, 0x13, 0x18, 0x00, 0x10, 0x14, 0x17, 0x00, 0x11, 0x14, 0x17, 0x00, 0x10, 0x14, + 0x18, 0x00, 0x12, 0x15, 0x18, 0x00, 0x10, 0x15, 0x19, 0x00, 0x12, 0x15, 0x19, 0x00, 0x10, 0x15, + 0x1a, 0x00, 0x11, 0x15, 0x1a, 0x00, 0x12, 0x15, 0x1a, 0x00, 0x12, 0x15, 0x1b, 0x00, 0x11, 0x16, + 0x1a, 0x00, 0x12, 0x16, 0x1a, 0x00, 0x13, 0x16, 0x1a, 0x00, 0x12, 0x16, 0x1b, 0x00, 0x13, 0x16, + 0x1b, 0x00, 0x12, 0x17, 0x1b, 0x00, 0x13, 0x17, 0x1b, 0x00, 0x13, 0x17, 0x1c, 0x00, 0x14, 0x17, + 0x1c, 0x00, 0x14, 0x17, 0x1d, 0x00, 0x13, 0x18, 0x1d, 0x00, 0x14, 0x18, 0x1d, 0x00, 0x15, 0x18, + 0x1f, 0x00, 0x14, 0x19, 0x1d, 0x00, 0x15, 0x19, 0x1d, 0x00, 0x15, 0x19, 0x1e, 0x00, 0x15, 0x19, + 0x1f, 0x00, 0x16, 0x19, 0x1f, 0x00, 0x15, 0x19, 0x20, 0x00, 0x16, 0x1a, 0x1e, 0x00, 0x14, 0x1a, + 0x1f, 0x00, 0x15, 0x1a, 0x1f, 0x00, 0x16, 0x1a, 0x1f, 0x00, 0x15, 0x1a, 0x20, 0x00, 0x16, 0x1a, + 0x21, 0x00, 0x15, 0x1b, 0x21, 0x00, 0x17, 0x1b, 0x22, 0x00, 0x17, 0x1b, 0x23, 0x00, 0x16, 0x1c, + 0x22, 0x00, 0x17, 0x1d, 0x22, 0x00, 0x17, 0x1d, 0x23, 0x00, 0x18, 0x1d, 0x23, 0x00, 0x19, 0x1d, + 0x23, 0x00, 0x17, 0x1d, 0x24, 0x00, 0x18, 0x1e, 0x23, 0x00, 0x18, 0x1e, 0x24, 0x00, 0x18, 0x1e, + 0x25, 0x00, 0x19, 0x1e, 0x25, 0x00, 0x18, 0x1e, 0x26, 0x00, 0x19, 0x1f, 0x26, 0x00, 0x1a, 0x1f, + 0x26, 0x00, 0x1a, 0x1f, 0x27, 0x00, 0x1a, 0x1f, 0x28, 0x00, 0x1a, 0x20, 0x26, 0x00, 0x19, 0x20, + 0x27, 0x00, 0x1a, 0x20, 0x27, 0x00, 0x1a, 0x20, 0x28, 0x00, 0x1b, 0x20, 0x29, 0x00, 0x1b, 0x21, + 0x28, 0x00, 0x1b, 0x21, 0x29, 0x00, 0x1c, 0x21, 0x2a, 0x00, 0x1d, 0x22, 0x29, 0x00, 0x1c, 0x22, + 0x2a, 0x00, 0x1d, 0x22, 0x2a, 0x00, 0x1e, 0x23, 0x2c, 0x00, 0x1d, 0x24, 0x2b, 0x00, 0x1d, 0x24, + 0x2c, 0x00, 0x1c, 0x24, 0x2d, 0x00, 0x1e, 0x25, 0x2d, 0x00, 0x1f, 0x25, 0x2e, 0x00, 0x1e, 0x26, + 0x2e, 0x00, 0x1f, 0x26, 0x2e, 0x00, 0x1f, 0x26, 0x30, 0x00, 0x21, 0x27, 0x2e, 0x00, 0x20, 0x27, + 0x2f, 0x00, 0x20, 0x27, 0x31, 0x00, 0x20, 0x29, 0x32, 0x00, 0x20, 0x29, 0x33, 0x00, 0x21, 0x2a, + 0x33, 0x00, 0x24, 0x2c, 0x35, 0x00, 0x24, 0x2c, 0x38, 0x00, 0x26, 0x31, 0x3b, 0x00, 0x27, 0x31, + 0x3b, 0x00, 0xff, 0x00, 0xff, 0x00, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x05, 0x1a, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x25, 0x48, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x4a, 0x54, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x8a, 0x8c, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x41, 0x5e, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x0d, 0x27, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x1b, 0x1f, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x00, 0x32, 0x69, 0x29, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x21, 0x38, 0x63, 0x2b, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x3d, 0x2b, 0x1c, 0x0e, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x5d, 0x7e, 0x2b, 0x08, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x5d, 0x80, 0x4d, 0x4c, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x24, 0x4a, 0x9c, 0xa1, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x10, 0x39, 0x76, 0x46, 0x6d, 0x9a, + 0x60, 0x3f, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x01, 0x78, 0x8e, 0x32, 0x37, 0x81, 0x6c, 0x2a, 0x3c, + 0x55, 0x2c, 0x1d, 0x2d, 0x17, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x06, 0x27, 0x55, 0x82, 0x9b, 0x45, 0x0e, 0x47, 0x61, 0x0f, 0x1a, + 0x0f, 0x20, 0x62, 0x28, 0x0f, 0x18, 0x08, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0x35, 0x1b, 0x40, 0x98, 0x4d, 0x18, 0x15, 0x1c, 0x26, 0x1b, 0x3b, 0x49, + 0x20, 0x46, 0x67, 0x1b, 0x13, 0x0c, 0x15, 0x20, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0x25, 0x4d, 0x3c, 0x34, 0x2b, 0x1c, 0x08, 0x0b, 0x0f, 0x1b, 0x32, 0x9e, 0x8a, + 0x08, 0x27, 0x22, 0x0f, 0x36, 0x6f, 0x75, 0x3b, 0x39, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0x7d, 0x7a, 0x56, 0x48, 0x68, 0x32, 0x06, 0xa3, 0xa3, 0xa3, 0x14, 0x40, 0x86, 0x6e, + 0xa3, 0xa3, 0xa3, 0x06, 0x2d, 0x85, 0x92, 0x5b, 0x32, 0x6a, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0x1c, 0x58, 0x8a, 0x65, 0x18, 0x21, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x07, 0x43, 0x83, 0x43, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x73, 0x91, 0x7f, 0x62, 0x20, 0x15, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0x1e, 0x31, 0x0f, 0x2e, 0x1c, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x1b, 0x1b, 0x32, 0x16, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x43, 0x3b, 0x22, 0x55, 0x47, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0x72, 0x9d, 0x60, 0x33, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2d, 0x0f, 0x1b, 0x0f, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x11, 0x2d, 0x93, 0x55, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x50, + 0x44, 0x90, 0x8a, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x3a, 0x77, 0x88, 0x47, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x25, 0x45, 0x25, 0x25, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x8a, + 0x51, 0x23, 0x43, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x57, 0x5a, 0xa0, 0x84, 0x87, + 0x74, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x02, 0x08, 0x8f, 0x8b, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa2, 0x96, + 0x6a, 0x41, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x4e, 0x95, 0x68, 0x5a, 0x4b, 0x7b, + 0x70, 0x4c, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x04, 0x53, 0x8d, 0x79, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x79, 0x80, + 0x5b, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x0e, 0x7c, 0x94, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x4f, 0x6a, + 0x47, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x5f, 0x40, 0x1b, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x46, 0x2d, + 0x08, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x97, 0x82, 0x18, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x58, 0x43, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x69, 0x5c, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x71, 0x40, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x65, 0x60, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x52, 0x2d, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x66, 0x5e, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2d, 0x20, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x6f, 0x6b, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2b, 0x5b, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2e, 0x44, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x25, 0x41, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x40, 0x1e, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x10, 0x38, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x69, 0x42, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x3b, + 0x19, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x03, 0x20, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x53, + 0x1d, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x4f, 0x15, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0x1d, 0x09, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x48, 0x89, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0x1e, 0x33, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x5b, 0x39, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0x3b, 0x2a, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x59, 0x9f, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0x33, 0x0a, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x2f, 0x64, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0x1d, 0x2b, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x12, 0x99, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0x49, 0x3e, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x1c, 0x36, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x30, 0x5e, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0x8a, 0x48, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, + 0xa3, 0xa3, 0xa3, 0xa3, 0xa3, 0xa3 diff --git a/source/quakedef.h b/source/quakedef.h index 94e8282..5409cc5 100644 --- a/source/quakedef.h +++ b/source/quakedef.h @@ -30,157 +30,157 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define FITZQUAKE_VERSION "0.85" //johnfitz #define QUAKESPASM_VERSION "0.93.1" -//define PARANOID // speed sapping error checking +//define PARANOID // speed sapping error checking -#define GAMENAME "id1" // directory to look in by default +#define GAMENAME "id1" // directory to look in by default #include "q_stdinc.h" -#define MINIMUM_MEMORY 0x550000 -#define MINIMUM_MEMORY_LEVELPAK (MINIMUM_MEMORY + 0x100000) +#define MINIMUM_MEMORY 0x550000 +#define MINIMUM_MEMORY_LEVELPAK (MINIMUM_MEMORY + 0x100000) -#define MAX_NUM_ARGVS 50 +#define MAX_NUM_ARGVS 50 // up / down -#define PITCH 0 +#define PITCH 0 // left / right -#define YAW 1 +#define YAW 1 // fall over -#define ROLL 2 +#define ROLL 2 -#define MAX_QPATH 64 // max length of a quake game pathname +#define MAX_QPATH 64 // max length of a quake game pathname -#define ON_EPSILON 0.1 // point on plane side epsilon +#define ON_EPSILON 0.1 // point on plane side epsilon -#define DIST_EPSILON 0.03125 // 1/32 epsilon to keep floating point happy (moved from world.c) +#define DIST_EPSILON 0.03125 // 1/32 epsilon to keep floating point happy (moved from world.c) -#define MAX_MSGLEN 64000 // max length of a reliable message //ericw -- was 32000 -#define MAX_DATAGRAM 32000 // max length of unreliable message //johnfitz -- was 1024 +#define MAX_MSGLEN 64000 // max length of a reliable message //ericw -- was 32000 +#define MAX_DATAGRAM 32000 // max length of unreliable message //johnfitz -- was 1024 -#define DATAGRAM_MTU 1400 // johnfitz -- actual limit for unreliable messages to nonlocal clients +#define DATAGRAM_MTU 1400 // johnfitz -- actual limit for unreliable messages to nonlocal clients // // per-level limits // -#define MIN_EDICTS 256 // johnfitz -- lowest allowed value for max_edicts cvar -#define MAX_EDICTS 32000 // johnfitz -- highest allowed value for max_edicts cvar - // ents past 8192 can't play sounds in the standard protocol -#define MAX_LIGHTSTYLES 64 -#define MAX_MODELS 2048 // johnfitz -- was 256 -#define MAX_SOUNDS 2048 // johnfitz -- was 256 +#define MIN_EDICTS 256 // johnfitz -- lowest allowed value for max_edicts cvar +#define MAX_EDICTS 32000 // johnfitz -- highest allowed value for max_edicts cvar +// ents past 8192 can't play sounds in the standard protocol +#define MAX_LIGHTSTYLES 64 +#define MAX_MODELS 2048 // johnfitz -- was 256 +#define MAX_SOUNDS 2048 // johnfitz -- was 256 -#define SAVEGAME_COMMENT_LENGTH 39 +#define SAVEGAME_COMMENT_LENGTH 39 -#define MAX_STYLESTRING 64 +#define MAX_STYLESTRING 64 // // stats are integers communicated to the client by the server // -#define MAX_CL_STATS 32 -#define STAT_HEALTH 0 -#define STAT_FRAGS 1 -#define STAT_WEAPON 2 -#define STAT_AMMO 3 -#define STAT_ARMOR 4 -#define STAT_WEAPONFRAME 5 -#define STAT_SHELLS 6 -#define STAT_NAILS 7 -#define STAT_ROCKETS 8 -#define STAT_CELLS 9 -#define STAT_ACTIVEWEAPON 10 -#define STAT_TOTALSECRETS 11 -#define STAT_TOTALMONSTERS 12 -#define STAT_SECRETS 13 // bumped on client side by svc_foundsecret -#define STAT_MONSTERS 14 // bumped by svc_killedmonster +#define MAX_CL_STATS 32 +#define STAT_HEALTH 0 +#define STAT_FRAGS 1 +#define STAT_WEAPON 2 +#define STAT_AMMO 3 +#define STAT_ARMOR 4 +#define STAT_WEAPONFRAME 5 +#define STAT_SHELLS 6 +#define STAT_NAILS 7 +#define STAT_ROCKETS 8 +#define STAT_CELLS 9 +#define STAT_ACTIVEWEAPON 10 +#define STAT_TOTALSECRETS 11 +#define STAT_TOTALMONSTERS 12 +#define STAT_SECRETS 13 // bumped on client side by svc_foundsecret +#define STAT_MONSTERS 14 // bumped by svc_killedmonster // stock defines // -#define IT_SHOTGUN 1 -#define IT_SUPER_SHOTGUN 2 -#define IT_NAILGUN 4 -#define IT_SUPER_NAILGUN 8 -#define IT_GRENADE_LAUNCHER 16 -#define IT_ROCKET_LAUNCHER 32 -#define IT_LIGHTNING 64 -#define IT_SUPER_LIGHTNING 128 -#define IT_SHELLS 256 -#define IT_NAILS 512 -#define IT_ROCKETS 1024 -#define IT_CELLS 2048 -#define IT_AXE 4096 -#define IT_ARMOR1 8192 -#define IT_ARMOR2 16384 -#define IT_ARMOR3 32768 -#define IT_SUPERHEALTH 65536 -#define IT_KEY1 131072 -#define IT_KEY2 262144 -#define IT_INVISIBILITY 524288 -#define IT_INVULNERABILITY 1048576 -#define IT_SUIT 2097152 -#define IT_QUAD 4194304 -#define IT_SIGIL1 (1<<28) -#define IT_SIGIL2 (1<<29) -#define IT_SIGIL3 (1<<30) -#define IT_SIGIL4 (1<<31) +#define IT_SHOTGUN 1 +#define IT_SUPER_SHOTGUN 2 +#define IT_NAILGUN 4 +#define IT_SUPER_NAILGUN 8 +#define IT_GRENADE_LAUNCHER 16 +#define IT_ROCKET_LAUNCHER 32 +#define IT_LIGHTNING 64 +#define IT_SUPER_LIGHTNING 128 +#define IT_SHELLS 256 +#define IT_NAILS 512 +#define IT_ROCKETS 1024 +#define IT_CELLS 2048 +#define IT_AXE 4096 +#define IT_ARMOR1 8192 +#define IT_ARMOR2 16384 +#define IT_ARMOR3 32768 +#define IT_SUPERHEALTH 65536 +#define IT_KEY1 131072 +#define IT_KEY2 262144 +#define IT_INVISIBILITY 524288 +#define IT_INVULNERABILITY 1048576 +#define IT_SUIT 2097152 +#define IT_QUAD 4194304 +#define IT_SIGIL1 (1<<28) +#define IT_SIGIL2 (1<<29) +#define IT_SIGIL3 (1<<30) +#define IT_SIGIL4 (1<<31) //=========================================== //rogue changed and added defines -#define RIT_SHELLS 128 -#define RIT_NAILS 256 -#define RIT_ROCKETS 512 -#define RIT_CELLS 1024 -#define RIT_AXE 2048 -#define RIT_LAVA_NAILGUN 4096 -#define RIT_LAVA_SUPER_NAILGUN 8192 -#define RIT_MULTI_GRENADE 16384 -#define RIT_MULTI_ROCKET 32768 -#define RIT_PLASMA_GUN 65536 -#define RIT_ARMOR1 8388608 -#define RIT_ARMOR2 16777216 -#define RIT_ARMOR3 33554432 -#define RIT_LAVA_NAILS 67108864 -#define RIT_PLASMA_AMMO 134217728 -#define RIT_MULTI_ROCKETS 268435456 -#define RIT_SHIELD 536870912 -#define RIT_ANTIGRAV 1073741824 -#define RIT_SUPERHEALTH 2147483648 +#define RIT_SHELLS 128 +#define RIT_NAILS 256 +#define RIT_ROCKETS 512 +#define RIT_CELLS 1024 +#define RIT_AXE 2048 +#define RIT_LAVA_NAILGUN 4096 +#define RIT_LAVA_SUPER_NAILGUN 8192 +#define RIT_MULTI_GRENADE 16384 +#define RIT_MULTI_ROCKET 32768 +#define RIT_PLASMA_GUN 65536 +#define RIT_ARMOR1 8388608 +#define RIT_ARMOR2 16777216 +#define RIT_ARMOR3 33554432 +#define RIT_LAVA_NAILS 67108864 +#define RIT_PLASMA_AMMO 134217728 +#define RIT_MULTI_ROCKETS 268435456 +#define RIT_SHIELD 536870912 +#define RIT_ANTIGRAV 1073741824 +#define RIT_SUPERHEALTH 2147483648 //MED 01/04/97 added hipnotic defines //=========================================== //hipnotic added defines -#define HIT_PROXIMITY_GUN_BIT 16 -#define HIT_MJOLNIR_BIT 7 -#define HIT_LASER_CANNON_BIT 23 -#define HIT_PROXIMITY_GUN (1< #include #ifndef APIENTRY -#define APIENTRY +#define APIENTRY #endif #include "console.h" @@ -220,8 +220,8 @@ typedef struct #include "gl_model.h" #include "world.h" -#include "image.h" //johnfitz -#include "gl_texmgr.h" //johnfitz +#include "image.h" //johnfitz +#include "gl_texmgr.h" //johnfitz #include "input.h" #include "keys.h" #include "menu.h" @@ -239,60 +239,60 @@ extern bool noclip_anglehack; // // host // -extern quakeparms_t *host_parms; +extern quakeparms_t *host_parms; -extern cvar_t sys_ticrate; -extern cvar_t sys_throttle; -extern cvar_t sys_nostdout; -extern cvar_t developer; -extern cvar_t max_edicts; //johnfitz +extern cvar_t sys_ticrate; +extern cvar_t sys_throttle; +extern cvar_t sys_nostdout; +extern cvar_t developer; +extern cvar_t max_edicts; //johnfitz -extern bool host_initialized; // true if into command execution -extern double host_frametime; -extern byte *host_colormap; -extern int32_t host_framecount; // incremented every frame, never reset -extern double realtime; // not bounded in any way, changed at - // start of every frame, never reset +extern bool host_initialized; // true if into command execution +extern double host_frametime; +extern byte *host_colormap; +extern int32_t host_framecount; // incremented every frame, never reset +extern double realtime; // not bounded in any way, changed at +// start of every frame, never reset typedef struct filelist_item_s { - char name[32]; - struct filelist_item_s *next; + char name[32]; + struct filelist_item_s *next; } filelist_item_t; -extern filelist_item_t *modlist; -extern filelist_item_t *extralevels; -extern filelist_item_t *demolist; +extern filelist_item_t *modlist; +extern filelist_item_t *extralevels; +extern filelist_item_t *demolist; -void Host_ClearMemory (void); -void Host_ServerFrame (void); -void Host_InitCommands (void); -void Host_Init (void); +void Host_ClearMemory(void); +void Host_ServerFrame(void); +void Host_InitCommands(void); +void Host_Init(void); void Host_Shutdown(void); -void Host_Callback_Notify (cvar_t *var); /* callback function for CVAR_NOTIFY */ -noreturn void Host_Error (const char *error, ...) FUNC_PRINTF(1,2); -noreturn void Host_EndGame (const char *message, ...) FUNC_PRINTF(1,2); +void Host_Callback_Notify(cvar_t *var); /* callback function for CVAR_NOTIFY */ +noreturn void Host_Error(const char *error, ...) FUNC_PRINTF(1, 2); +noreturn void Host_EndGame(const char *message, ...) FUNC_PRINTF(1, 2); #ifdef __WATCOMC__ #pragma aux Host_Error aborts; #pragma aux Host_EndGame aborts; #endif -void Host_Frame (float time); -void Host_Quit_f (void); -void Host_ClientCommands (const char *fmt, ...) FUNC_PRINTF(1,2); -void Host_ShutdownServer (bool crash); -void Host_WriteConfiguration (void); +void Host_Frame(float time); +void Host_Quit_f(void); +void Host_ClientCommands(const char *fmt, ...) FUNC_PRINTF(1, 2); +void Host_ShutdownServer(bool crash); +void Host_WriteConfiguration(void); -void ExtraMaps_Init (void); -void Modlist_Init (void); -void DemoList_Init (void); +void ExtraMaps_Init(void); +void Modlist_Init(void); +void DemoList_Init(void); -void DemoList_Rebuild (void); +void DemoList_Rebuild(void); -extern int32_t current_skill; // skill level for currently loaded level (in case - // the user changes the cvar while the level is - // running, this reflects the level actually in use) +extern int32_t current_skill; // skill level for currently loaded level (in case +// the user changes the cvar while the level is +// running, this reflects the level actually in use) -extern bool isDedicated; +extern bool isDedicated; -#endif /* QUAKEDEFS_H */ +#endif /* QUAKEDEFS_H */ diff --git a/source/r_alias.c b/source/r_alias.c index 7cc45c5..059a86e 100644 --- a/source/r_alias.c +++ b/source/r_alias.c @@ -29,35 +29,36 @@ extern cvar_t r_drawflat, gl_overbright_models, gl_fullbrights, r_lerpmodels, r_ //up to 16 color translated skins gltexture_t *playertextures[MAX_SCOREBOARD]; //johnfitz -- changed to an array of pointers -#define NUMVERTEXNORMALS 162 +#define NUMVERTEXNORMALS 162 -float r_avertexnormals[NUMVERTEXNORMALS][3] = +float r_avertexnormals[NUMVERTEXNORMALS][3] = { #include "anorms.h" }; -extern vec3_t lightcolor; //johnfitz -- replaces "float shadelight" for lit support +extern vec3_t lightcolor; //johnfitz -- replaces "float shadelight" for lit support // precalculated dot products for quantized angles #define SHADEDOT_QUANT 16 -float r_avertexnormal_dots[SHADEDOT_QUANT][256] = +float r_avertexnormal_dots[SHADEDOT_QUANT][256] = { #include "anorm_dots.h" }; -extern vec3_t lightspot; +extern vec3_t lightspot; -float *shadedots = r_avertexnormal_dots[0]; -vec3_t shadevector; +float *shadedots = r_avertexnormal_dots[0]; +vec3_t shadevector; -float entalpha; //johnfitz +float entalpha; //johnfitz -bool overbright; //johnfitz +bool overbright; //johnfitz bool shading = true; //johnfitz -- if false, disable vertex shading for various reasons (fullbright, r_lightmap, showtris, etc) //johnfitz -- struct for passing lerp information to drawing functions -typedef struct { +typedef struct +{ int16_t pose1; int16_t pose2; float blend; @@ -94,10 +95,10 @@ Returns the offset of the first vertex's meshxyz_t.xyz in the vbo for the given model and pose. ============= */ -static void *GLARB_GetXYZOffset (aliashdr_t *hdr, int32_t pose) +static void *GLARB_GetXYZOffset(aliashdr_t *hdr, int32_t pose) { - const int32_t xyzoffs = offsetof (meshxyz_t, xyz); - return (void *) (currententity->model->vboxyzofs + (hdr->numverts_vbo * pose * sizeof (meshxyz_t)) + xyzoffs); + const int32_t xyzoffs = offsetof(meshxyz_t, xyz); + return (void *)(currententity->model->vboxyzofs + (hdr->numverts_vbo * pose * sizeof(meshxyz_t)) + xyzoffs); } /* @@ -108,10 +109,10 @@ Returns the offset of the first vertex's meshxyz_t.normal in the vbo for the given model and pose. ============= */ -static void *GLARB_GetNormalOffset (aliashdr_t *hdr, int32_t pose) +static void *GLARB_GetNormalOffset(aliashdr_t *hdr, int32_t pose) { - const int32_t normaloffs = offsetof (meshxyz_t, normal); - return (void *)(currententity->model->vboxyzofs + (hdr->numverts_vbo * pose * sizeof (meshxyz_t)) + normaloffs); + const int32_t normaloffs = offsetof(meshxyz_t, normal); + return (void *)(currententity->model->vboxyzofs + (hdr->numverts_vbo * pose * sizeof(meshxyz_t)) + normaloffs); } /* @@ -119,9 +120,10 @@ static void *GLARB_GetNormalOffset (aliashdr_t *hdr, int32_t pose) GLAlias_CreateShaders ============= */ -void GLAlias_CreateShaders (void) +void GLAlias_CreateShaders(void) { - const glsl_attrib_binding_t bindings[] = { + const glsl_attrib_binding_t bindings[] = + { { "TexCoords", texCoordsAttrIndex }, { "Pose1Vert", pose1VertexAttrIndex }, { "Pose1Normal", pose1NormalAttrIndex }, @@ -130,84 +132,84 @@ void GLAlias_CreateShaders (void) }; const GLchar *vertSource = \ - "#version 110\n" - "\n" - "uniform float Blend;\n" - "uniform vec3 ShadeVector;\n" - "uniform vec4 LightColor;\n" - "attribute vec4 TexCoords; // only xy are used \n" - "attribute vec4 Pose1Vert;\n" - "attribute vec3 Pose1Normal;\n" - "attribute vec4 Pose2Vert;\n" - "attribute vec3 Pose2Normal;\n" - "\n" - "varying float FogFragCoord;\n" - "\n" - "float r_avertexnormal_dot(vec3 vertexnormal) // from MH \n" - "{\n" - " float dot = dot(vertexnormal, ShadeVector);\n" - " // wtf - this reproduces anorm_dots within as reasonable a degree of tolerance as the >= 0 case\n" - " if (dot < 0.0)\n" - " return 1.0 + dot * (13.0 / 44.0);\n" - " else\n" - " return 1.0 + dot;\n" - "}\n" - "void main()\n" - "{\n" - " gl_TexCoord[0] = TexCoords;\n" - " vec4 lerpedVert = mix(vec4(Pose1Vert.xyz, 1.0), vec4(Pose2Vert.xyz, 1.0), Blend);\n" - " gl_Position = gl_ModelViewProjectionMatrix * lerpedVert;\n" - " FogFragCoord = gl_Position.w;\n" - " float dot1 = r_avertexnormal_dot(Pose1Normal);\n" - " float dot2 = r_avertexnormal_dot(Pose2Normal);\n" - " gl_FrontColor = LightColor * vec4(vec3(mix(dot1, dot2, Blend)), 1.0);\n" - "}\n"; + "#version 110\n" + "\n" + "uniform float Blend;\n" + "uniform vec3 ShadeVector;\n" + "uniform vec4 LightColor;\n" + "attribute vec4 TexCoords; // only xy are used \n" + "attribute vec4 Pose1Vert;\n" + "attribute vec3 Pose1Normal;\n" + "attribute vec4 Pose2Vert;\n" + "attribute vec3 Pose2Normal;\n" + "\n" + "varying float FogFragCoord;\n" + "\n" + "float r_avertexnormal_dot(vec3 vertexnormal) // from MH \n" + "{\n" + " float dot = dot(vertexnormal, ShadeVector);\n" + " // wtf - this reproduces anorm_dots within as reasonable a degree of tolerance as the >= 0 case\n" + " if (dot < 0.0)\n" + " return 1.0 + dot * (13.0 / 44.0);\n" + " else\n" + " return 1.0 + dot;\n" + "}\n" + "void main()\n" + "{\n" + " gl_TexCoord[0] = TexCoords;\n" + " vec4 lerpedVert = mix(vec4(Pose1Vert.xyz, 1.0), vec4(Pose2Vert.xyz, 1.0), Blend);\n" + " gl_Position = gl_ModelViewProjectionMatrix * lerpedVert;\n" + " FogFragCoord = gl_Position.w;\n" + " float dot1 = r_avertexnormal_dot(Pose1Normal);\n" + " float dot2 = r_avertexnormal_dot(Pose2Normal);\n" + " gl_FrontColor = LightColor * vec4(vec3(mix(dot1, dot2, Blend)), 1.0);\n" + "}\n"; const GLchar *fragSource = \ - "#version 110\n" - "\n" - "uniform sampler2D Tex;\n" - "uniform sampler2D FullbrightTex;\n" - "uniform bool UseFullbrightTex;\n" - "uniform bool UseOverbright;\n" - "uniform bool UseAlphaTest;\n" - "\n" - "varying float FogFragCoord;\n" - "\n" - "void main()\n" - "{\n" - " vec4 result = texture2D(Tex, gl_TexCoord[0].xy);\n" - " if (UseAlphaTest && (result.a < 0.666))\n" - " discard;\n" - " result *= gl_Color;\n" - " if (UseOverbright)\n" - " result.rgb *= 2.0;\n" - " if (UseFullbrightTex)\n" - " result += texture2D(FullbrightTex, gl_TexCoord[0].xy);\n" - " result = clamp(result, 0.0, 1.0);\n" - " float fog = exp(-gl_Fog.density * gl_Fog.density * FogFragCoord * FogFragCoord);\n" - " fog = clamp(fog, 0.0, 1.0);\n" - " result = mix(gl_Fog.color, result, fog);\n" - " result.a = gl_Color.a;\n" // FIXME: This will make almost transparent things cut holes though heavy fog - " gl_FragColor = result;\n" - "}\n"; + "#version 110\n" + "\n" + "uniform sampler2D Tex;\n" + "uniform sampler2D FullbrightTex;\n" + "uniform bool UseFullbrightTex;\n" + "uniform bool UseOverbright;\n" + "uniform bool UseAlphaTest;\n" + "\n" + "varying float FogFragCoord;\n" + "\n" + "void main()\n" + "{\n" + " vec4 result = texture2D(Tex, gl_TexCoord[0].xy);\n" + " if (UseAlphaTest && (result.a < 0.666))\n" + " discard;\n" + " result *= gl_Color;\n" + " if (UseOverbright)\n" + " result.rgb *= 2.0;\n" + " if (UseFullbrightTex)\n" + " result += texture2D(FullbrightTex, gl_TexCoord[0].xy);\n" + " result = clamp(result, 0.0, 1.0);\n" + " float fog = exp(-gl_Fog.density * gl_Fog.density * FogFragCoord * FogFragCoord);\n" + " fog = clamp(fog, 0.0, 1.0);\n" + " result = mix(gl_Fog.color, result, fog);\n" + " result.a = gl_Color.a;\n" // FIXME: This will make almost transparent things cut holes though heavy fog + " gl_FragColor = result;\n" + "}\n"; - if (!gl_glsl_alias_able) + if(!gl_glsl_alias_able) return; - r_alias_program = GL_CreateProgram (vertSource, fragSource, sizeof(bindings)/sizeof(bindings[0]), bindings); + r_alias_program = GL_CreateProgram(vertSource, fragSource, sizeof(bindings) / sizeof(bindings[0]), bindings); - if (r_alias_program != 0) + if(r_alias_program != 0) { - // get uniform locations - blendLoc = GL_GetUniformLocation (&r_alias_program, "Blend"); - shadevectorLoc = GL_GetUniformLocation (&r_alias_program, "ShadeVector"); - lightColorLoc = GL_GetUniformLocation (&r_alias_program, "LightColor"); - texLoc = GL_GetUniformLocation (&r_alias_program, "Tex"); - fullbrightTexLoc = GL_GetUniformLocation (&r_alias_program, "FullbrightTex"); - useFullbrightTexLoc = GL_GetUniformLocation (&r_alias_program, "UseFullbrightTex"); - useOverbrightLoc = GL_GetUniformLocation (&r_alias_program, "UseOverbright"); - useAlphaTestLoc = GL_GetUniformLocation (&r_alias_program, "UseAlphaTest"); + // get uniform locations + blendLoc = GL_GetUniformLocation(&r_alias_program, "Blend"); + shadevectorLoc = GL_GetUniformLocation(&r_alias_program, "ShadeVector"); + lightColorLoc = GL_GetUniformLocation(&r_alias_program, "LightColor"); + texLoc = GL_GetUniformLocation(&r_alias_program, "Tex"); + fullbrightTexLoc = GL_GetUniformLocation(&r_alias_program, "FullbrightTex"); + useFullbrightTexLoc = GL_GetUniformLocation(&r_alias_program, "UseFullbrightTex"); + useOverbrightLoc = GL_GetUniformLocation(&r_alias_program, "UseOverbright"); + useAlphaTestLoc = GL_GetUniformLocation(&r_alias_program, "UseAlphaTest"); } } @@ -225,11 +227,11 @@ Supports optional overbright, optional fullbright pixels. Based on code by MH from RMQEngine ============= */ -void GL_DrawAliasFrame_GLSL (aliashdr_t *paliashdr, lerpdata_t lerpdata, gltexture_t *tx, gltexture_t *fb) +void GL_DrawAliasFrame_GLSL(aliashdr_t *paliashdr, lerpdata_t lerpdata, gltexture_t *tx, gltexture_t *fb) { - float blend; + float blend; - if (lerpdata.pose1 != lerpdata.pose2) + if(lerpdata.pose1 != lerpdata.pose2) { blend = lerpdata.blend; } @@ -238,56 +240,56 @@ void GL_DrawAliasFrame_GLSL (aliashdr_t *paliashdr, lerpdata_t lerpdata, gltextu blend = 0; } - GL_UseProgramFunc (r_alias_program); + GL_UseProgramFunc(r_alias_program); - GL_BindBuffer (GL_ARRAY_BUFFER, currententity->model->meshvbo); - GL_BindBuffer (GL_ELEMENT_ARRAY_BUFFER, currententity->model->meshindexesvbo); + GL_BindBuffer(GL_ARRAY_BUFFER, currententity->model->meshvbo); + GL_BindBuffer(GL_ELEMENT_ARRAY_BUFFER, currententity->model->meshindexesvbo); - GL_EnableVertexAttribArrayFunc (texCoordsAttrIndex); - GL_EnableVertexAttribArrayFunc (pose1VertexAttrIndex); - GL_EnableVertexAttribArrayFunc (pose2VertexAttrIndex); - GL_EnableVertexAttribArrayFunc (pose1NormalAttrIndex); - GL_EnableVertexAttribArrayFunc (pose2NormalAttrIndex); + GL_EnableVertexAttribArrayFunc(texCoordsAttrIndex); + GL_EnableVertexAttribArrayFunc(pose1VertexAttrIndex); + GL_EnableVertexAttribArrayFunc(pose2VertexAttrIndex); + GL_EnableVertexAttribArrayFunc(pose1NormalAttrIndex); + GL_EnableVertexAttribArrayFunc(pose2NormalAttrIndex); - GL_VertexAttribPointerFunc (texCoordsAttrIndex, 2, GL_FLOAT, GL_FALSE, 0, (void *)(intptr_t)currententity->model->vbostofs); - GL_VertexAttribPointerFunc (pose1VertexAttrIndex, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof (meshxyz_t), GLARB_GetXYZOffset (paliashdr, lerpdata.pose1)); - GL_VertexAttribPointerFunc (pose2VertexAttrIndex, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof (meshxyz_t), GLARB_GetXYZOffset (paliashdr, lerpdata.pose2)); + GL_VertexAttribPointerFunc(texCoordsAttrIndex, 2, GL_FLOAT, GL_FALSE, 0, (void *)(intptr_t)currententity->model->vbostofs); + GL_VertexAttribPointerFunc(pose1VertexAttrIndex, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(meshxyz_t), GLARB_GetXYZOffset(paliashdr, lerpdata.pose1)); + GL_VertexAttribPointerFunc(pose2VertexAttrIndex, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(meshxyz_t), GLARB_GetXYZOffset(paliashdr, lerpdata.pose2)); // GL_TRUE to normalize the signed bytes to [-1 .. 1] - GL_VertexAttribPointerFunc (pose1NormalAttrIndex, 4, GL_BYTE, GL_TRUE, sizeof (meshxyz_t), GLARB_GetNormalOffset (paliashdr, lerpdata.pose1)); - GL_VertexAttribPointerFunc (pose2NormalAttrIndex, 4, GL_BYTE, GL_TRUE, sizeof (meshxyz_t), GLARB_GetNormalOffset (paliashdr, lerpdata.pose2)); + GL_VertexAttribPointerFunc(pose1NormalAttrIndex, 4, GL_BYTE, GL_TRUE, sizeof(meshxyz_t), GLARB_GetNormalOffset(paliashdr, lerpdata.pose1)); + GL_VertexAttribPointerFunc(pose2NormalAttrIndex, 4, GL_BYTE, GL_TRUE, sizeof(meshxyz_t), GLARB_GetNormalOffset(paliashdr, lerpdata.pose2)); // set uniforms - GL_Uniform1fFunc (blendLoc, blend); - GL_Uniform3fFunc (shadevectorLoc, shadevector[0], shadevector[1], shadevector[2]); - GL_Uniform4fFunc (lightColorLoc, lightcolor[0], lightcolor[1], lightcolor[2], entalpha); - GL_Uniform1iFunc (texLoc, 0); - GL_Uniform1iFunc (fullbrightTexLoc, 1); - GL_Uniform1iFunc (useFullbrightTexLoc, (fb != NULL) ? 1 : 0); - GL_Uniform1fFunc (useOverbrightLoc, overbright ? 1 : 0); - GL_Uniform1iFunc (useAlphaTestLoc, (currententity->model->flags & MF_HOLEY) ? 1 : 0); + GL_Uniform1fFunc(blendLoc, blend); + GL_Uniform3fFunc(shadevectorLoc, shadevector[0], shadevector[1], shadevector[2]); + GL_Uniform4fFunc(lightColorLoc, lightcolor[0], lightcolor[1], lightcolor[2], entalpha); + GL_Uniform1iFunc(texLoc, 0); + GL_Uniform1iFunc(fullbrightTexLoc, 1); + GL_Uniform1iFunc(useFullbrightTexLoc, (fb != NULL) ? 1 : 0); + GL_Uniform1fFunc(useOverbrightLoc, overbright ? 1 : 0); + GL_Uniform1iFunc(useAlphaTestLoc, (currententity->model->flags & MF_HOLEY) ? 1 : 0); // set textures - GL_SelectTexture (GL_TEXTURE0); - GL_Bind (tx); + GL_SelectTexture(GL_TEXTURE0); + GL_Bind(tx); - if (fb) + if(fb) { - GL_SelectTexture (GL_TEXTURE1); - GL_Bind (fb); + GL_SelectTexture(GL_TEXTURE1); + GL_Bind(fb); } // draw - glDrawElements (GL_TRIANGLES, paliashdr->numindexes, GL_UNSIGNED_SHORT, (void *)(intptr_t)currententity->model->vboindexofs); + glDrawElements(GL_TRIANGLES, paliashdr->numindexes, GL_UNSIGNED_SHORT, (void *)(intptr_t)currententity->model->vboindexofs); // clean up - GL_DisableVertexAttribArrayFunc (texCoordsAttrIndex); - GL_DisableVertexAttribArrayFunc (pose1VertexAttrIndex); - GL_DisableVertexAttribArrayFunc (pose2VertexAttrIndex); - GL_DisableVertexAttribArrayFunc (pose1NormalAttrIndex); - GL_DisableVertexAttribArrayFunc (pose2NormalAttrIndex); + GL_DisableVertexAttribArrayFunc(texCoordsAttrIndex); + GL_DisableVertexAttribArrayFunc(pose1VertexAttrIndex); + GL_DisableVertexAttribArrayFunc(pose2VertexAttrIndex); + GL_DisableVertexAttribArrayFunc(pose1NormalAttrIndex); + GL_DisableVertexAttribArrayFunc(pose2NormalAttrIndex); - GL_UseProgramFunc (0); - GL_SelectTexture (GL_TEXTURE0); + GL_UseProgramFunc(0); + GL_SelectTexture(GL_TEXTURE0); rs_aliaspasses += paliashdr->numtris; } @@ -297,17 +299,17 @@ void GL_DrawAliasFrame_GLSL (aliashdr_t *paliashdr, lerpdata_t lerpdata, gltextu GL_DrawAliasFrame -- johnfitz -- rewritten to support colored light, lerping, entalpha, multitexture, and r_drawflat ============= */ -void GL_DrawAliasFrame (aliashdr_t *paliashdr, lerpdata_t lerpdata) +void GL_DrawAliasFrame(aliashdr_t *paliashdr, lerpdata_t lerpdata) { - float vertcolor[4]; + float vertcolor[4]; trivertx_t *verts1, *verts2; - int32_t *commands; - int32_t count; - float u,v; - float blend, iblend; + int32_t *commands; + int32_t count; + float u, v; + float blend, iblend; bool lerping; - if (lerpdata.pose1 != lerpdata.pose2) + if(lerpdata.pose1 != lerpdata.pose2) { lerping = true; verts1 = (trivertx_t *)((byte *)paliashdr + paliashdr->posedata); @@ -330,74 +332,75 @@ void GL_DrawAliasFrame (aliashdr_t *paliashdr, lerpdata_t lerpdata) vertcolor[3] = entalpha; //never changes, so there's no need to put this inside the loop - while (1) + while(1) { // get the vertex count and primitive type count = *commands++; - if (!count) - break; // done + if(!count) + break; // done - if (count < 0) + if(count < 0) { count = -count; - glBegin (GL_TRIANGLE_FAN); + glBegin(GL_TRIANGLE_FAN); } else - glBegin (GL_TRIANGLE_STRIP); + glBegin(GL_TRIANGLE_STRIP); do { u = ((float *)commands)[0]; v = ((float *)commands)[1]; - if (mtexenabled) + if(mtexenabled) { - GL_MTexCoord2fFunc (GL_TEXTURE0_ARB, u, v); - GL_MTexCoord2fFunc (GL_TEXTURE1_ARB, u, v); + GL_MTexCoord2fFunc(GL_TEXTURE0_ARB, u, v); + GL_MTexCoord2fFunc(GL_TEXTURE1_ARB, u, v); } else - glTexCoord2f (u, v); + glTexCoord2f(u, v); commands += 2; - if (shading) + if(shading) { - if (r_drawflat_cheatsafe) + if(r_drawflat_cheatsafe) { srand(count * (uint32_t)(src_offset_t)commands); - glColor3f (rand()%256/255.0, rand()%256/255.0, rand()%256/255.0); + glColor3f(rand() % 256 / 255.0, rand() % 256 / 255.0, rand() % 256 / 255.0); } - else if (lerping) + else if(lerping) { - vertcolor[0] = (shadedots[verts1->lightnormalindex]*iblend + shadedots[verts2->lightnormalindex]*blend) * lightcolor[0]; - vertcolor[1] = (shadedots[verts1->lightnormalindex]*iblend + shadedots[verts2->lightnormalindex]*blend) * lightcolor[1]; - vertcolor[2] = (shadedots[verts1->lightnormalindex]*iblend + shadedots[verts2->lightnormalindex]*blend) * lightcolor[2]; - glColor4fv (vertcolor); + vertcolor[0] = (shadedots[verts1->lightnormalindex] * iblend + shadedots[verts2->lightnormalindex] * blend) * lightcolor[0]; + vertcolor[1] = (shadedots[verts1->lightnormalindex] * iblend + shadedots[verts2->lightnormalindex] * blend) * lightcolor[1]; + vertcolor[2] = (shadedots[verts1->lightnormalindex] * iblend + shadedots[verts2->lightnormalindex] * blend) * lightcolor[2]; + glColor4fv(vertcolor); } else { vertcolor[0] = shadedots[verts1->lightnormalindex] * lightcolor[0]; vertcolor[1] = shadedots[verts1->lightnormalindex] * lightcolor[1]; vertcolor[2] = shadedots[verts1->lightnormalindex] * lightcolor[2]; - glColor4fv (vertcolor); + glColor4fv(vertcolor); } } - if (lerping) + if(lerping) { - glVertex3f (verts1->v[0]*iblend + verts2->v[0]*blend, - verts1->v[1]*iblend + verts2->v[1]*blend, - verts1->v[2]*iblend + verts2->v[2]*blend); + glVertex3f(verts1->v[0]*iblend + verts2->v[0]*blend, + verts1->v[1]*iblend + verts2->v[1]*blend, + verts1->v[2]*iblend + verts2->v[2]*blend); verts1++; verts2++; } else { - glVertex3f (verts1->v[0], verts1->v[1], verts1->v[2]); + glVertex3f(verts1->v[0], verts1->v[1], verts1->v[2]); verts1++; } - } while (--count); + } + while(--count); - glEnd (); + glEnd(); } rs_aliaspasses += paliashdr->numtris; @@ -408,21 +411,21 @@ void GL_DrawAliasFrame (aliashdr_t *paliashdr, lerpdata_t lerpdata) R_SetupAliasFrame -- johnfitz -- rewritten to support lerping ================= */ -void R_SetupAliasFrame (aliashdr_t *paliashdr, int32_t frame, lerpdata_t *lerpdata) +void R_SetupAliasFrame(aliashdr_t *paliashdr, int32_t frame, lerpdata_t *lerpdata) { - entity_t *e = currententity; - int32_t posenum, numposes; + entity_t *e = currententity; + int32_t posenum, numposes; - if ((frame >= paliashdr->numframes) || (frame < 0)) + if((frame >= paliashdr->numframes) || (frame < 0)) { - Con_DPrintf ("R_AliasSetupFrame: no such frame %" PRIi32 " for '%s'\n", frame, e->model->name); + Con_DPrintf("R_AliasSetupFrame: no such frame %" PRIi32 " for '%s'\n", frame, e->model->name); frame = 0; } posenum = paliashdr->frames[frame].firstpose; numposes = paliashdr->frames[frame].numposes; - if (numposes > 1) + if(numposes > 1) { e->lerptime = paliashdr->frames[frame].interval; posenum += (int32_t)(cl.time / e->lerptime) % numposes; @@ -430,16 +433,16 @@ void R_SetupAliasFrame (aliashdr_t *paliashdr, int32_t frame, lerpdata_t *lerpda else e->lerptime = 0.1; - if (e->lerpflags & LERP_RESETANIM) //kill any lerp in progress + if(e->lerpflags & LERP_RESETANIM) //kill any lerp in progress { e->lerpstart = 0; e->previouspose = posenum; e->currentpose = posenum; e->lerpflags -= LERP_RESETANIM; } - else if (e->currentpose != posenum) // pose changed, start new lerp + else if(e->currentpose != posenum) // pose changed, start new lerp { - if (e->lerpflags & LERP_RESETANIM2) //defer lerping one more time + if(e->lerpflags & LERP_RESETANIM2) //defer lerping one more time { e->lerpstart = 0; e->previouspose = posenum; @@ -455,12 +458,12 @@ void R_SetupAliasFrame (aliashdr_t *paliashdr, int32_t frame, lerpdata_t *lerpda } //set up values - if (r_lerpmodels.value && !(e->model->flags & MOD_NOLERP && r_lerpmodels.value != 2)) + if(r_lerpmodels.value && !(e->model->flags & MOD_NOLERP && r_lerpmodels.value != 2)) { - if (e->lerpflags & LERP_FINISH && numposes == 1) - lerpdata->blend = CLAMP (0, (cl.time - e->lerpstart) / (e->lerpfinish - e->lerpstart), 1); + if(e->lerpflags & LERP_FINISH && numposes == 1) + lerpdata->blend = CLAMP(0, (cl.time - e->lerpstart) / (e->lerpfinish - e->lerpstart), 1); else - lerpdata->blend = CLAMP (0, (cl.time - e->lerpstart) / e->lerptime, 1); + lerpdata->blend = CLAMP(0, (cl.time - e->lerpstart) / e->lerptime, 1); lerpdata->pose1 = e->previouspose; lerpdata->pose2 = e->currentpose; } @@ -477,51 +480,51 @@ void R_SetupAliasFrame (aliashdr_t *paliashdr, int32_t frame, lerpdata_t *lerpda R_SetupEntityTransform -- johnfitz -- set up transform part of lerpdata ================= */ -void R_SetupEntityTransform (entity_t *e, lerpdata_t *lerpdata) +void R_SetupEntityTransform(entity_t *e, lerpdata_t *lerpdata) { float blend; vec3_t d; int32_t i; // if LERP_RESETMOVE, kill any lerps in progress - if (e->lerpflags & LERP_RESETMOVE) + if(e->lerpflags & LERP_RESETMOVE) { e->movelerpstart = 0; - VectorCopy (e->origin, e->previousorigin); - VectorCopy (e->origin, e->currentorigin); - VectorCopy (e->angles, e->previousangles); - VectorCopy (e->angles, e->currentangles); + VectorCopy(e->origin, e->previousorigin); + VectorCopy(e->origin, e->currentorigin); + VectorCopy(e->angles, e->previousangles); + VectorCopy(e->angles, e->currentangles); e->lerpflags -= LERP_RESETMOVE; } - else if (!VectorCompare (e->origin, e->currentorigin) || !VectorCompare (e->angles, e->currentangles)) // origin/angles changed, start new lerp + else if(!VectorCompare(e->origin, e->currentorigin) || !VectorCompare(e->angles, e->currentangles)) // origin/angles changed, start new lerp { e->movelerpstart = cl.time; - VectorCopy (e->currentorigin, e->previousorigin); - VectorCopy (e->origin, e->currentorigin); - VectorCopy (e->currentangles, e->previousangles); - VectorCopy (e->angles, e->currentangles); + VectorCopy(e->currentorigin, e->previousorigin); + VectorCopy(e->origin, e->currentorigin); + VectorCopy(e->currentangles, e->previousangles); + VectorCopy(e->angles, e->currentangles); } //set up values - if (r_lerpmove.value && e != &cl.viewent && e->lerpflags & LERP_MOVESTEP) + if(r_lerpmove.value && e != &cl.viewent && e->lerpflags & LERP_MOVESTEP) { - if (e->lerpflags & LERP_FINISH) - blend = CLAMP (0, (cl.time - e->movelerpstart) / (e->lerpfinish - e->movelerpstart), 1); + if(e->lerpflags & LERP_FINISH) + blend = CLAMP(0, (cl.time - e->movelerpstart) / (e->lerpfinish - e->movelerpstart), 1); else - blend = CLAMP (0, (cl.time - e->movelerpstart) / 0.1, 1); + blend = CLAMP(0, (cl.time - e->movelerpstart) / 0.1, 1); //translation - VectorSubtract (e->currentorigin, e->previousorigin, d); + VectorSubtract(e->currentorigin, e->previousorigin, d); lerpdata->origin[0] = e->previousorigin[0] + d[0] * blend; lerpdata->origin[1] = e->previousorigin[1] + d[1] * blend; lerpdata->origin[2] = e->previousorigin[2] + d[2] * blend; //rotation - VectorSubtract (e->currentangles, e->previousangles, d); - for (i = 0; i < 3; i++) + VectorSubtract(e->currentangles, e->previousangles, d); + for(i = 0; i < 3; i++) { - if (d[i] > 180) d[i] -= 360; - if (d[i] < -180) d[i] += 360; + if(d[i] > 180) d[i] -= 360; + if(d[i] < -180) d[i] += 360; } lerpdata->angles[0] = e->previousangles[0] + d[0] * blend; lerpdata->angles[1] = e->previousangles[1] + d[1] * blend; @@ -529,8 +532,8 @@ void R_SetupEntityTransform (entity_t *e, lerpdata_t *lerpdata) } else //don't lerp { - VectorCopy (e->origin, lerpdata->origin); - VectorCopy (e->angles, lerpdata->angles); + VectorCopy(e->origin, lerpdata->origin); + VectorCopy(e->angles, lerpdata->angles); } } @@ -539,33 +542,33 @@ void R_SetupEntityTransform (entity_t *e, lerpdata_t *lerpdata) R_SetupAliasLighting -- johnfitz -- broken out from R_DrawAliasModel and rewritten ================= */ -void R_SetupAliasLighting (entity_t *e) +void R_SetupAliasLighting(entity_t *e) { - vec3_t dist; - float add; - int32_t i; - int32_t quantizedangle; - float radiansangle; + vec3_t dist; + float add; + int32_t i; + int32_t quantizedangle; + float radiansangle; - R_LightPoint (e->origin); + R_LightPoint(e->origin); //add dlights - for (i=0 ; i= cl.time) + if(cl_dlights[i].die >= cl.time) { - VectorSubtract (currententity->origin, cl_dlights[i].origin, dist); + VectorSubtract(currententity->origin, cl_dlights[i].origin, dist); add = cl_dlights[i].radius - VectorLength(dist); - if (add > 0) - VectorMA (lightcolor, add, cl_dlights[i].color, lightcolor); + if(add > 0) + VectorMA(lightcolor, add, cl_dlights[i].color, lightcolor); } } // minimum light value on gun (24) - if (e == &cl.viewent) + if(e == &cl.viewent) { add = 72.0f - (lightcolor[0] + lightcolor[1] + lightcolor[2]); - if (add > 0.0f) + if(add > 0.0f) { lightcolor[0] += add / 3.0f; lightcolor[1] += add / 3.0f; @@ -574,10 +577,10 @@ void R_SetupAliasLighting (entity_t *e) } // minimum light value on players (8) - if (currententity > cl_entities && currententity <= cl_entities + cl.maxclients) + if(currententity > cl_entities && currententity <= cl_entities + cl.maxclients) { add = 24.0f - (lightcolor[0] + lightcolor[1] + lightcolor[2]); - if (add > 0.0f) + if(add > 0.0f) { lightcolor[0] += add / 3.0f; lightcolor[1] += add / 3.0f; @@ -586,16 +589,16 @@ void R_SetupAliasLighting (entity_t *e) } // clamp lighting so it doesn't overbright as much (96) - if (overbright) + if(overbright) { add = 288.0f / (lightcolor[0] + lightcolor[1] + lightcolor[2]); - if (add < 1.0f) + if(add < 1.0f) VectorScale(lightcolor, add, lightcolor); } //hack up the brightness when fullbrights but no overbrights (256) - if (gl_fullbrights.value && !gl_overbright_models.value) - if (e->model->flags & MOD_FBRIGHTHACK) + if(gl_fullbrights.value && !gl_overbright_models.value) + if(e->model->flags & MOD_FBRIGHTHACK) { lightcolor[0] = 256.0f; lightcolor[1] = 256.0f; @@ -614,7 +617,7 @@ void R_SetupAliasLighting (entity_t *e) //ericw -- shadedots = r_avertexnormal_dots[quantizedangle]; - VectorScale (lightcolor, 1.0f / 200.0f, lightcolor); + VectorScale(lightcolor, 1.0f / 200.0f, lightcolor); } /* @@ -622,220 +625,220 @@ void R_SetupAliasLighting (entity_t *e) R_DrawAliasModel -- johnfitz -- almost completely rewritten ================= */ -void R_DrawAliasModel (entity_t *e) +void R_DrawAliasModel(entity_t *e) { - aliashdr_t *paliashdr; - int32_t i, anim, skinnum; - gltexture_t *tx, *fb; - lerpdata_t lerpdata; - bool alphatest = !!(e->model->flags & MF_HOLEY); + aliashdr_t *paliashdr; + int32_t i, anim, skinnum; + gltexture_t *tx, *fb; + lerpdata_t lerpdata; + bool alphatest = !!(e->model->flags & MF_HOLEY); // // setup pose/lerp data -- do it first so we don't miss updates due to culling // - paliashdr = (aliashdr_t *)Mod_Extradata (e->model); - R_SetupAliasFrame (paliashdr, e->frame, &lerpdata); - R_SetupEntityTransform (e, &lerpdata); + paliashdr = (aliashdr_t *)Mod_Extradata(e->model); + R_SetupAliasFrame(paliashdr, e->frame, &lerpdata); + R_SetupEntityTransform(e, &lerpdata); // // cull it // - if (R_CullModelForEntity(e)) + if(R_CullModelForEntity(e)) return; // // transform it // - glPushMatrix (); - R_RotateForEntity (lerpdata.origin, lerpdata.angles); - glTranslatef (paliashdr->scale_origin[0], paliashdr->scale_origin[1], paliashdr->scale_origin[2]); - glScalef (paliashdr->scale[0], paliashdr->scale[1], paliashdr->scale[2]); + glPushMatrix(); + R_RotateForEntity(lerpdata.origin, lerpdata.angles); + glTranslatef(paliashdr->scale_origin[0], paliashdr->scale_origin[1], paliashdr->scale_origin[2]); + glScalef(paliashdr->scale[0], paliashdr->scale[1], paliashdr->scale[2]); // // random stuff // - if (gl_smoothmodels.value && !r_drawflat_cheatsafe) - glShadeModel (GL_SMOOTH); - if (gl_affinemodels.value) - glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); + if(gl_smoothmodels.value && !r_drawflat_cheatsafe) + glShadeModel(GL_SMOOTH); + if(gl_affinemodels.value) + glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); overbright = gl_overbright_models.value; shading = true; // // set up for alpha blending // - if (r_drawflat_cheatsafe || r_lightmap_cheatsafe) //no alpha in drawflat or lightmap mode + if(r_drawflat_cheatsafe || r_lightmap_cheatsafe) //no alpha in drawflat or lightmap mode entalpha = 1; else entalpha = ENTALPHA_DECODE(e->alpha); - if (entalpha == 0) + if(entalpha == 0) goto cleanup; - if (entalpha < 1) + if(entalpha < 1) { - if (!gl_texture_env_combine) overbright = false; //overbright can't be done in a single pass without combiners + if(!gl_texture_env_combine) overbright = false; //overbright can't be done in a single pass without combiners glDepthMask(GL_FALSE); glEnable(GL_BLEND); } - else if (alphatest) - glEnable (GL_ALPHA_TEST); + else if(alphatest) + glEnable(GL_ALPHA_TEST); // // set up lighting // rs_aliaspolys += paliashdr->numtris; - R_SetupAliasLighting (e); + R_SetupAliasLighting(e); // // set up textures // GL_DisableMultitexture(); - anim = (int32_t)(cl.time*10) & 3; + anim = (int32_t)(cl.time * 10) & 3; skinnum = e->skinnum; - if ((skinnum >= paliashdr->numskins) || (skinnum < 0)) + if((skinnum >= paliashdr->numskins) || (skinnum < 0)) { - Con_DPrintf ("R_DrawAliasModel: no such skin # %" PRIi32 " for '%s'\n", skinnum, e->model->name); + Con_DPrintf("R_DrawAliasModel: no such skin # %" PRIi32 " for '%s'\n", skinnum, e->model->name); // ericw -- display skin 0 for winquake compatibility skinnum = 0; } tx = paliashdr->gltextures[skinnum][anim]; fb = paliashdr->fbtextures[skinnum][anim]; - if (e->colormap != vid.colormap && !gl_nocolors.value) + if(e->colormap != vid.colormap && !gl_nocolors.value) { i = e - cl_entities; - if (i >= 1 && i<=cl.maxclients /* && !strcmp (currententity->model->name, "progs/player.mdl") */) - tx = playertextures[i - 1]; + if(i >= 1 && i <= cl.maxclients /* && !strcmp (currententity->model->name, "progs/player.mdl") */) + tx = playertextures[i - 1]; } - if (!gl_fullbrights.value) + if(!gl_fullbrights.value) fb = NULL; // // draw it // - if (r_drawflat_cheatsafe) + if(r_drawflat_cheatsafe) { - glDisable (GL_TEXTURE_2D); - GL_DrawAliasFrame (paliashdr, lerpdata); - glEnable (GL_TEXTURE_2D); - srand((int32_t) (cl.time * 1000)); //restore randomness + glDisable(GL_TEXTURE_2D); + GL_DrawAliasFrame(paliashdr, lerpdata); + glEnable(GL_TEXTURE_2D); + srand((int32_t)(cl.time * 1000)); //restore randomness } - else if (r_fullbright_cheatsafe) + else if(r_fullbright_cheatsafe) { - GL_Bind (tx); + GL_Bind(tx); shading = false; - glColor4f(1,1,1,entalpha); - GL_DrawAliasFrame (paliashdr, lerpdata); - if (fb) + glColor4f(1, 1, 1, entalpha); + GL_DrawAliasFrame(paliashdr, lerpdata); + if(fb) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); GL_Bind(fb); glEnable(GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE); + glBlendFunc(GL_ONE, GL_ONE); glDepthMask(GL_FALSE); - glColor3f(entalpha,entalpha,entalpha); - Fog_StartAdditive (); - GL_DrawAliasFrame (paliashdr, lerpdata); - Fog_StopAdditive (); + glColor3f(entalpha, entalpha, entalpha); + Fog_StartAdditive(); + GL_DrawAliasFrame(paliashdr, lerpdata); + Fog_StopAdditive(); glDepthMask(GL_TRUE); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); } } - else if (r_lightmap_cheatsafe) + else if(r_lightmap_cheatsafe) { - glDisable (GL_TEXTURE_2D); + glDisable(GL_TEXTURE_2D); shading = false; - glColor3f(1,1,1); - GL_DrawAliasFrame (paliashdr, lerpdata); - glEnable (GL_TEXTURE_2D); + glColor3f(1, 1, 1); + GL_DrawAliasFrame(paliashdr, lerpdata); + glEnable(GL_TEXTURE_2D); } // call fast path if possible. if the shader compliation failed for some reason, // r_alias_program will be 0. - else if (r_alias_program != 0) + else if(r_alias_program != 0) { - GL_DrawAliasFrame_GLSL (paliashdr, lerpdata, tx, fb); + GL_DrawAliasFrame_GLSL(paliashdr, lerpdata, tx, fb); } - else if (overbright) + else if(overbright) { - if (gl_texture_env_combine && gl_mtexable && gl_texture_env_add && fb) //case 1: everything in one pass + if(gl_texture_env_combine && gl_mtexable && gl_texture_env_add && fb) //case 1: everything in one pass { - GL_Bind (tx); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT); - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_EXT, GL_MODULATE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_PRIMARY_COLOR_EXT); - glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 2.0f); - GL_EnableMultitexture(); // selects TEXTURE1 - GL_Bind (fb); - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); - glEnable(GL_BLEND); - GL_DrawAliasFrame (paliashdr, lerpdata); - glDisable(GL_BLEND); - GL_DisableMultitexture(); - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - } - else if (gl_texture_env_combine) //case 2: overbright in one pass, then fullbright pass - { - // first pass GL_Bind(tx); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_EXT, GL_MODULATE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_PRIMARY_COLOR_EXT); glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 2.0f); - GL_DrawAliasFrame (paliashdr, lerpdata); + GL_EnableMultitexture(); // selects TEXTURE1 + GL_Bind(fb); + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); + glEnable(GL_BLEND); + GL_DrawAliasFrame(paliashdr, lerpdata); + glDisable(GL_BLEND); + GL_DisableMultitexture(); + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + } + else if(gl_texture_env_combine) //case 2: overbright in one pass, then fullbright pass + { + // first pass + GL_Bind(tx); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_EXT, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_PRIMARY_COLOR_EXT); + glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 2.0f); + GL_DrawAliasFrame(paliashdr, lerpdata); glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 1.0f); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - // second pass - if (fb) + // second pass + if(fb) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); GL_Bind(fb); glEnable(GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE); + glBlendFunc(GL_ONE, GL_ONE); glDepthMask(GL_FALSE); shading = false; - glColor3f(entalpha,entalpha,entalpha); - Fog_StartAdditive (); - GL_DrawAliasFrame (paliashdr, lerpdata); - Fog_StopAdditive (); + glColor3f(entalpha, entalpha, entalpha); + Fog_StartAdditive(); + GL_DrawAliasFrame(paliashdr, lerpdata); + Fog_StopAdditive(); glDepthMask(GL_TRUE); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } } else //case 3: overbright in two passes, then fullbright pass { - // first pass + // first pass GL_Bind(tx); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - GL_DrawAliasFrame (paliashdr, lerpdata); - // second pass -- additive with black fog, to double the object colors but not the fog color + GL_DrawAliasFrame(paliashdr, lerpdata); + // second pass -- additive with black fog, to double the object colors but not the fog color glEnable(GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE); + glBlendFunc(GL_ONE, GL_ONE); glDepthMask(GL_FALSE); - Fog_StartAdditive (); - GL_DrawAliasFrame (paliashdr, lerpdata); - Fog_StopAdditive (); + Fog_StartAdditive(); + GL_DrawAliasFrame(paliashdr, lerpdata); + Fog_StopAdditive(); glDepthMask(GL_TRUE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); - // third pass - if (fb) + // third pass + if(fb) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); GL_Bind(fb); glEnable(GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE); + glBlendFunc(GL_ONE, GL_ONE); glDepthMask(GL_FALSE); shading = false; - glColor3f(entalpha,entalpha,entalpha); - Fog_StartAdditive (); - GL_DrawAliasFrame (paliashdr, lerpdata); - Fog_StopAdditive (); + glColor3f(entalpha, entalpha, entalpha); + Fog_StartAdditive(); + GL_DrawAliasFrame(paliashdr, lerpdata); + Fog_StopAdditive(); glDepthMask(GL_TRUE); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } @@ -843,40 +846,40 @@ void R_DrawAliasModel (entity_t *e) } else { - if (gl_mtexable && gl_texture_env_add && fb) //case 4: fullbright mask using multitexture + if(gl_mtexable && gl_texture_env_add && fb) //case 4: fullbright mask using multitexture { GL_DisableMultitexture(); // selects TEXTURE0 - GL_Bind (tx); + GL_Bind(tx); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); GL_EnableMultitexture(); // selects TEXTURE1 - GL_Bind (fb); + GL_Bind(fb); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); glEnable(GL_BLEND); - GL_DrawAliasFrame (paliashdr, lerpdata); + GL_DrawAliasFrame(paliashdr, lerpdata); glDisable(GL_BLEND); GL_DisableMultitexture(); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } else //case 5: fullbright mask without multitexture { - // first pass + // first pass GL_Bind(tx); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - GL_DrawAliasFrame (paliashdr, lerpdata); - // second pass - if (fb) + GL_DrawAliasFrame(paliashdr, lerpdata); + // second pass + if(fb) { GL_Bind(fb); glEnable(GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE); + glBlendFunc(GL_ONE, GL_ONE); glDepthMask(GL_FALSE); shading = false; - glColor3f(entalpha,entalpha,entalpha); - Fog_StartAdditive (); - GL_DrawAliasFrame (paliashdr, lerpdata); - Fog_StopAdditive (); + glColor3f(entalpha, entalpha, entalpha); + Fog_StartAdditive(); + GL_DrawAliasFrame(paliashdr, lerpdata); + Fog_StopAdditive(); glDepthMask(GL_TRUE); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); } } @@ -884,14 +887,14 @@ void R_DrawAliasModel (entity_t *e) cleanup: glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); - glShadeModel (GL_FLAT); + glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); + glShadeModel(GL_FLAT); glDepthMask(GL_TRUE); glDisable(GL_BLEND); - if (alphatest) - glDisable (GL_ALPHA_TEST); - glColor3f(1,1,1); - glPopMatrix (); + if(alphatest) + glDisable(GL_ALPHA_TEST); + glColor3f(1, 1, 1); + glPopMatrix(); } //johnfitz -- values for shadow matrix @@ -908,57 +911,58 @@ GL_DrawAliasShadow -- johnfitz -- rewritten TODO: orient shadow onto "lightplane" (a global mplane_t*) ============= */ -void GL_DrawAliasShadow (entity_t *e) +void GL_DrawAliasShadow(entity_t *e) { - float shadowmatrix[16] = {1, 0, 0, 0, - 0, 1, 0, 0, - SHADOW_SKEW_X, SHADOW_SKEW_Y, SHADOW_VSCALE, 0, - 0, 0, SHADOW_HEIGHT, 1}; - float lheight; - aliashdr_t *paliashdr; - lerpdata_t lerpdata; + float shadowmatrix[16] = {1, 0, 0, 0, + 0, 1, 0, 0, + SHADOW_SKEW_X, SHADOW_SKEW_Y, SHADOW_VSCALE, 0, + 0, 0, SHADOW_HEIGHT, 1 + }; + float lheight; + aliashdr_t *paliashdr; + lerpdata_t lerpdata; - if (R_CullModelForEntity(e)) + if(R_CullModelForEntity(e)) return; - if (e == &cl.viewent || e->model->flags & MOD_NOSHADOW) + if(e == &cl.viewent || e->model->flags & MOD_NOSHADOW) return; entalpha = ENTALPHA_DECODE(e->alpha); - if (entalpha == 0) return; + if(entalpha == 0) return; - paliashdr = (aliashdr_t *)Mod_Extradata (e->model); - R_SetupAliasFrame (paliashdr, e->frame, &lerpdata); - R_SetupEntityTransform (e, &lerpdata); - R_LightPoint (e->origin); + paliashdr = (aliashdr_t *)Mod_Extradata(e->model); + R_SetupAliasFrame(paliashdr, e->frame, &lerpdata); + R_SetupEntityTransform(e, &lerpdata); + R_LightPoint(e->origin); lheight = currententity->origin[2] - lightspot[2]; // set up matrix - glPushMatrix (); - glTranslatef (lerpdata.origin[0], lerpdata.origin[1], lerpdata.origin[2]); - glTranslatef (0,0,-lheight); - glMultMatrixf (shadowmatrix); - glTranslatef (0,0,lheight); - glRotatef (lerpdata.angles[1], 0, 0, 1); - glRotatef (-lerpdata.angles[0], 0, 1, 0); - glRotatef (lerpdata.angles[2], 1, 0, 0); - glTranslatef (paliashdr->scale_origin[0], paliashdr->scale_origin[1], paliashdr->scale_origin[2]); - glScalef (paliashdr->scale[0], paliashdr->scale[1], paliashdr->scale[2]); + glPushMatrix(); + glTranslatef(lerpdata.origin[0], lerpdata.origin[1], lerpdata.origin[2]); + glTranslatef(0, 0, -lheight); + glMultMatrixf(shadowmatrix); + glTranslatef(0, 0, lheight); + glRotatef(lerpdata.angles[1], 0, 0, 1); + glRotatef(-lerpdata.angles[0], 0, 1, 0); + glRotatef(lerpdata.angles[2], 1, 0, 0); + glTranslatef(paliashdr->scale_origin[0], paliashdr->scale_origin[1], paliashdr->scale_origin[2]); + glScalef(paliashdr->scale[0], paliashdr->scale[1], paliashdr->scale[2]); // draw it glDepthMask(GL_FALSE); - glEnable (GL_BLEND); - GL_DisableMultitexture (); - glDisable (GL_TEXTURE_2D); + glEnable(GL_BLEND); + GL_DisableMultitexture(); + glDisable(GL_TEXTURE_2D); shading = false; - glColor4f(0,0,0,entalpha * 0.5); - GL_DrawAliasFrame (paliashdr, lerpdata); - glEnable (GL_TEXTURE_2D); - glDisable (GL_BLEND); + glColor4f(0, 0, 0, entalpha * 0.5); + GL_DrawAliasFrame(paliashdr, lerpdata); + glEnable(GL_TEXTURE_2D); + glDisable(GL_BLEND); glDepthMask(GL_TRUE); //clean up - glPopMatrix (); + glPopMatrix(); } /* @@ -966,27 +970,27 @@ void GL_DrawAliasShadow (entity_t *e) R_DrawAliasModel_ShowTris -- johnfitz ================= */ -void R_DrawAliasModel_ShowTris (entity_t *e) +void R_DrawAliasModel_ShowTris(entity_t *e) { - aliashdr_t *paliashdr; - lerpdata_t lerpdata; + aliashdr_t *paliashdr; + lerpdata_t lerpdata; - if (R_CullModelForEntity(e)) + if(R_CullModelForEntity(e)) return; - paliashdr = (aliashdr_t *)Mod_Extradata (e->model); - R_SetupAliasFrame (paliashdr, e->frame, &lerpdata); - R_SetupEntityTransform (e, &lerpdata); + paliashdr = (aliashdr_t *)Mod_Extradata(e->model); + R_SetupAliasFrame(paliashdr, e->frame, &lerpdata); + R_SetupEntityTransform(e, &lerpdata); - glPushMatrix (); - R_RotateForEntity (lerpdata.origin,lerpdata.angles); - glTranslatef (paliashdr->scale_origin[0], paliashdr->scale_origin[1], paliashdr->scale_origin[2]); - glScalef (paliashdr->scale[0], paliashdr->scale[1], paliashdr->scale[2]); + glPushMatrix(); + R_RotateForEntity(lerpdata.origin, lerpdata.angles); + glTranslatef(paliashdr->scale_origin[0], paliashdr->scale_origin[1], paliashdr->scale_origin[2]); + glScalef(paliashdr->scale[0], paliashdr->scale[1], paliashdr->scale[2]); shading = false; - glColor3f(1,1,1); - GL_DrawAliasFrame (paliashdr, lerpdata); + glColor3f(1, 1, 1); + GL_DrawAliasFrame(paliashdr, lerpdata); - glPopMatrix (); + glPopMatrix(); } diff --git a/source/r_brush.c b/source/r_brush.c index dde0e6f..878222f 100644 --- a/source/r_brush.c +++ b/source/r_brush.c @@ -27,30 +27,31 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. extern cvar_t gl_fullbrights, r_drawflat, gl_overbright, r_oldwater; //johnfitz extern cvar_t gl_zfix; // QuakeSpasm z-fighting fix -int32_t gl_lightmap_format; -int32_t lightmap_bytes; +int32_t gl_lightmap_format; +int32_t lightmap_bytes; -#define BLOCK_WIDTH 128 -#define BLOCK_HEIGHT 128 +#define BLOCK_WIDTH 128 +#define BLOCK_HEIGHT 128 -gltexture_t *lightmap_textures[MAX_LIGHTMAPS]; //johnfitz -- changed to an array +gltexture_t *lightmap_textures[MAX_LIGHTMAPS]; //johnfitz -- changed to an array -unsigned blocklights[BLOCK_WIDTH*BLOCK_HEIGHT*3]; //johnfitz -- was 18*18, added lit support (*3) and loosened surface extents maximum (BLOCK_WIDTH*BLOCK_HEIGHT) +unsigned blocklights[BLOCK_WIDTH * BLOCK_HEIGHT * 3]; //johnfitz -- was 18*18, added lit support (*3) and loosened surface extents maximum (BLOCK_WIDTH*BLOCK_HEIGHT) -typedef struct glRect_s { - uint8_t l,t,w,h; +typedef struct glRect_s +{ + uint8_t l, t, w, h; } glRect_t; -glpoly_t *lightmap_polys[MAX_LIGHTMAPS]; -bool lightmap_modified[MAX_LIGHTMAPS]; -glRect_t lightmap_rectchange[MAX_LIGHTMAPS]; +glpoly_t *lightmap_polys[MAX_LIGHTMAPS]; +bool lightmap_modified[MAX_LIGHTMAPS]; +glRect_t lightmap_rectchange[MAX_LIGHTMAPS]; -int32_t allocated[MAX_LIGHTMAPS][BLOCK_WIDTH]; -int32_t last_lightmap_allocated; //ericw -- optimization: remember the index of the last lightmap AllocBlock stored a surf in +int32_t allocated[MAX_LIGHTMAPS][BLOCK_WIDTH]; +int32_t last_lightmap_allocated; //ericw -- optimization: remember the index of the last lightmap AllocBlock stored a surf in // the lightmap texture data needs to be kept in // main memory so texsubimage can update properly -byte lightmaps[4*MAX_LIGHTMAPS*BLOCK_WIDTH*BLOCK_HEIGHT]; +byte lightmaps[4 * MAX_LIGHTMAPS * BLOCK_WIDTH * BLOCK_HEIGHT]; /* @@ -60,28 +61,28 @@ R_TextureAnimation -- johnfitz -- added "frame" param to eliminate use of "curre Returns the proper texture for a given time and base texture =============== */ -texture_t *R_TextureAnimation (texture_t *base, int32_t frame) +texture_t *R_TextureAnimation(texture_t *base, int32_t frame) { - int32_t relative; - int32_t count; + int32_t relative; + int32_t count; - if (frame) - if (base->alternate_anims) + if(frame) + if(base->alternate_anims) base = base->alternate_anims; - if (!base->anim_total) + if(!base->anim_total) return base; - relative = (int32_t)(cl.time*10) % base->anim_total; + relative = (int32_t)(cl.time * 10) % base->anim_total; count = 0; - while (base->anim_min > relative || base->anim_max <= relative) + while(base->anim_min > relative || base->anim_max <= relative) { base = base->anim_next; - if (!base) - Sys_Error ("R_TextureAnimation: broken cycle"); - if (++count > 100) - Sys_Error ("R_TextureAnimation: infinite cycle"); + if(!base) + Sys_Error("R_TextureAnimation: broken cycle"); + if(++count > 100) + Sys_Error("R_TextureAnimation: infinite cycle"); } return base; @@ -92,19 +93,19 @@ texture_t *R_TextureAnimation (texture_t *base, int32_t frame) DrawGLPoly ================ */ -void DrawGLPoly (glpoly_t *p) +void DrawGLPoly(glpoly_t *p) { - float *v; - int32_t i; + float *v; + int32_t i; - glBegin (GL_POLYGON); + glBegin(GL_POLYGON); v = p->verts[0]; - for (i=0 ; inumverts ; i++, v+= VERTEXSIZE) + for(i = 0 ; i < p->numverts ; i++, v += VERTEXSIZE) { - glTexCoord2f (v[3], v[4]); - glVertex3fv (v); + glTexCoord2f(v[3], v[4]); + glVertex3fv(v); } - glEnd (); + glEnd(); } /* @@ -112,24 +113,24 @@ void DrawGLPoly (glpoly_t *p) DrawGLTriangleFan -- johnfitz -- like DrawGLPoly but for r_showtris ================ */ -void DrawGLTriangleFan (glpoly_t *p) +void DrawGLTriangleFan(glpoly_t *p) { - float *v; - int32_t i; + float *v; + int32_t i; - glBegin (GL_TRIANGLE_FAN); + glBegin(GL_TRIANGLE_FAN); v = p->verts[0]; - for (i=0 ; inumverts ; i++, v+= VERTEXSIZE) + for(i = 0 ; i < p->numverts ; i++, v += VERTEXSIZE) { - glVertex3fv (v); + glVertex3fv(v); } - glEnd (); + glEnd(); } /* ============================================================= - BRUSH MODELS + BRUSH MODELS ============================================================= */ @@ -140,43 +141,43 @@ void DrawGLTriangleFan (glpoly_t *p) R_DrawSequentialPoly -- johnfitz -- rewritten ================ */ -void R_DrawSequentialPoly (msurface_t *s) +void R_DrawSequentialPoly(msurface_t *s) { - glpoly_t *p; - texture_t *t; - float *v; - float entalpha; - int32_t i; + glpoly_t *p; + texture_t *t; + float *v; + float entalpha; + int32_t i; - t = R_TextureAnimation (s->texinfo->texture, currententity->frame); + t = R_TextureAnimation(s->texinfo->texture, currententity->frame); entalpha = ENTALPHA_DECODE(currententity->alpha); // drawflat - if (r_drawflat_cheatsafe) + if(r_drawflat_cheatsafe) { - if ((s->flags & SURF_DRAWTURB) && r_oldwater.value) + if((s->flags & SURF_DRAWTURB) && r_oldwater.value) { - for (p = s->polys->next; p; p = p->next) + for(p = s->polys->next; p; p = p->next) { - srand((uint32_t) (uintptr_t) p); - glColor3f (rand()%256/255.0, rand()%256/255.0, rand()%256/255.0); - DrawGLPoly (p); + srand((uint32_t)(uintptr_t) p); + glColor3f(rand() % 256 / 255.0, rand() % 256 / 255.0, rand() % 256 / 255.0); + DrawGLPoly(p); rs_brushpasses++; } return; } - srand((uint32_t) (uintptr_t) s->polys); - glColor3f (rand()%256/255.0, rand()%256/255.0, rand()%256/255.0); - DrawGLPoly (s->polys); + srand((uint32_t)(uintptr_t) s->polys); + glColor3f(rand() % 256 / 255.0, rand() % 256 / 255.0, rand() % 256 / 255.0); + DrawGLPoly(s->polys); rs_brushpasses++; return; } // fullbright - if ((r_fullbright_cheatsafe) && !(s->flags & SURF_DRAWTILED)) + if((r_fullbright_cheatsafe) && !(s->flags & SURF_DRAWTILED)) { - if (entalpha < 1) + if(entalpha < 1) { glDepthMask(GL_FALSE); glEnable(GL_BLEND); @@ -184,17 +185,17 @@ void R_DrawSequentialPoly (msurface_t *s) glColor4f(1, 1, 1, entalpha); } - if (s->flags & SURF_DRAWFENCE) - glEnable (GL_ALPHA_TEST); // Flip on alpha test + if(s->flags & SURF_DRAWFENCE) + glEnable(GL_ALPHA_TEST); // Flip on alpha test - GL_Bind (t->gltexture); - DrawGLPoly (s->polys); + GL_Bind(t->gltexture); + DrawGLPoly(s->polys); rs_brushpasses++; - if (s->flags & SURF_DRAWFENCE) - glDisable (GL_ALPHA_TEST); // Flip alpha test back off + if(s->flags & SURF_DRAWFENCE) + glDisable(GL_ALPHA_TEST); // Flip alpha test back off - if (entalpha < 1) + if(entalpha < 1) { glDepthMask(GL_TRUE); glDisable(GL_BLEND); @@ -205,35 +206,35 @@ void R_DrawSequentialPoly (msurface_t *s) } // r_lightmap - if (r_lightmap_cheatsafe) + if(r_lightmap_cheatsafe) { - if (s->flags & SURF_DRAWTILED) + if(s->flags & SURF_DRAWTILED) { - glDisable (GL_TEXTURE_2D); - DrawGLPoly (s->polys); - glEnable (GL_TEXTURE_2D); + glDisable(GL_TEXTURE_2D); + DrawGLPoly(s->polys); + glEnable(GL_TEXTURE_2D); rs_brushpasses++; return; } - R_RenderDynamicLightmaps (s); - GL_Bind (lightmap_textures[s->lightmaptexturenum]); - if (!gl_overbright.value) + R_RenderDynamicLightmaps(s); + GL_Bind(lightmap_textures[s->lightmaptexturenum]); + if(!gl_overbright.value) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glColor3f(0.5, 0.5, 0.5); } - glBegin (GL_POLYGON); + glBegin(GL_POLYGON); v = s->polys->verts[0]; - for (i=0 ; ipolys->numverts ; i++, v+= VERTEXSIZE) + for(i = 0 ; i < s->polys->numverts ; i++, v += VERTEXSIZE) { - glTexCoord2f (v[5], v[6]); - glVertex3fv (v); + glTexCoord2f(v[5], v[6]); + glVertex3fv(v); } - glEnd (); - if (!gl_overbright.value) + glEnd(); + if(!gl_overbright.value) { - glColor3f(1,1,1); + glColor3f(1, 1, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } rs_brushpasses++; @@ -241,40 +242,40 @@ void R_DrawSequentialPoly (msurface_t *s) } // sky poly -- skip it, already handled in gl_sky.c - if (s->flags & SURF_DRAWSKY) + if(s->flags & SURF_DRAWSKY) return; // water poly - if (s->flags & SURF_DRAWTURB) + if(s->flags & SURF_DRAWTURB) { - if (currententity->alpha == ENTALPHA_DEFAULT) + if(currententity->alpha == ENTALPHA_DEFAULT) entalpha = CLAMP(0.0, GL_WaterAlphaForSurface(s), 1.0); - if (entalpha < 1) + if(entalpha < 1) { glDepthMask(GL_FALSE); glEnable(GL_BLEND); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glColor4f(1, 1, 1, entalpha); } - if (r_oldwater.value) + if(r_oldwater.value) { - GL_Bind (s->texinfo->texture->gltexture); - for (p = s->polys->next; p; p = p->next) + GL_Bind(s->texinfo->texture->gltexture); + for(p = s->polys->next; p; p = p->next) { - DrawWaterPoly (p); + DrawWaterPoly(p); rs_brushpasses++; } rs_brushpasses++; } else { - GL_Bind (s->texinfo->texture->warpimage); + GL_Bind(s->texinfo->texture->warpimage); s->texinfo->texture->update_warp = true; // FIXME: one frame too late! - DrawGLPoly (s->polys); + DrawGLPoly(s->polys); rs_brushpasses++; } - if (entalpha < 1) + if(entalpha < 1) { glDepthMask(GL_TRUE); glDisable(GL_BLEND); @@ -285,19 +286,19 @@ void R_DrawSequentialPoly (msurface_t *s) } // missing texture - if (s->flags & SURF_NOTEXTURE) + if(s->flags & SURF_NOTEXTURE) { - if (entalpha < 1) + if(entalpha < 1) { glDepthMask(GL_FALSE); glEnable(GL_BLEND); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glColor4f(1, 1, 1, entalpha); } - GL_Bind (t->gltexture); - DrawGLPoly (s->polys); + GL_Bind(t->gltexture); + DrawGLPoly(s->polys); rs_brushpasses++; - if (entalpha < 1) + if(entalpha < 1) { glDepthMask(GL_TRUE); glDisable(GL_BLEND); @@ -308,7 +309,7 @@ void R_DrawSequentialPoly (msurface_t *s) } // lightmapped poly - if (entalpha < 1) + if(entalpha < 1) { glDepthMask(GL_FALSE); glEnable(GL_BLEND); @@ -318,19 +319,19 @@ void R_DrawSequentialPoly (msurface_t *s) else glColor3f(1, 1, 1); - if (s->flags & SURF_DRAWFENCE) - glEnable (GL_ALPHA_TEST); // Flip on alpha test + if(s->flags & SURF_DRAWFENCE) + glEnable(GL_ALPHA_TEST); // Flip on alpha test - if (gl_overbright.value) + if(gl_overbright.value) { - if (gl_texture_env_combine && gl_mtexable) //case 1: texture and lightmap in one pass, overbright using texture combiners + if(gl_texture_env_combine && gl_mtexable) //case 1: texture and lightmap in one pass, overbright using texture combiners { GL_DisableMultitexture(); // selects TEXTURE0 - GL_Bind (t->gltexture); + GL_Bind(t->gltexture); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); GL_EnableMultitexture(); // selects TEXTURE1 - GL_Bind (lightmap_textures[s->lightmaptexturenum]); - R_RenderDynamicLightmaps (s); + GL_Bind(lightmap_textures[s->lightmaptexturenum]); + R_RenderDynamicLightmaps(s); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_EXT, GL_MODULATE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_PREVIOUS_EXT); @@ -338,143 +339,143 @@ void R_DrawSequentialPoly (msurface_t *s) glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 2.0f); glBegin(GL_POLYGON); v = s->polys->verts[0]; - for (i=0 ; ipolys->numverts ; i++, v+= VERTEXSIZE) + for(i = 0 ; i < s->polys->numverts ; i++, v += VERTEXSIZE) { - GL_MTexCoord2fFunc (GL_TEXTURE0_ARB, v[3], v[4]); - GL_MTexCoord2fFunc (GL_TEXTURE1_ARB, v[5], v[6]); - glVertex3fv (v); + GL_MTexCoord2fFunc(GL_TEXTURE0_ARB, v[3], v[4]); + GL_MTexCoord2fFunc(GL_TEXTURE1_ARB, v[5], v[6]); + glVertex3fv(v); } - glEnd (); + glEnd(); glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 1.0f); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - GL_DisableMultitexture (); + GL_DisableMultitexture(); rs_brushpasses++; } - else if (entalpha < 1 || (s->flags & SURF_DRAWFENCE)) //case 2: can't do multipass if entity has alpha, so just draw the texture + else if(entalpha < 1 || (s->flags & SURF_DRAWFENCE)) //case 2: can't do multipass if entity has alpha, so just draw the texture { - GL_Bind (t->gltexture); - DrawGLPoly (s->polys); + GL_Bind(t->gltexture); + DrawGLPoly(s->polys); rs_brushpasses++; } else //case 3: texture in one pass, lightmap in second pass using 2x modulation blend func, fog in third pass { //first pass -- texture with no fog - Fog_DisableGFog (); - GL_Bind (t->gltexture); - DrawGLPoly (s->polys); - Fog_EnableGFog (); + Fog_DisableGFog(); + GL_Bind(t->gltexture); + DrawGLPoly(s->polys); + Fog_EnableGFog(); rs_brushpasses++; //second pass -- lightmap with black fog, modulate blended - R_RenderDynamicLightmaps (s); - GL_Bind (lightmap_textures[s->lightmaptexturenum]); - glDepthMask (GL_FALSE); - glEnable (GL_BLEND); + R_RenderDynamicLightmaps(s); + GL_Bind(lightmap_textures[s->lightmaptexturenum]); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); //2x modulate - Fog_StartAdditive (); - glBegin (GL_POLYGON); + Fog_StartAdditive(); + glBegin(GL_POLYGON); v = s->polys->verts[0]; - for (i=0 ; ipolys->numverts ; i++, v+= VERTEXSIZE) + for(i = 0 ; i < s->polys->numverts ; i++, v += VERTEXSIZE) { - glTexCoord2f (v[5], v[6]); - glVertex3fv (v); + glTexCoord2f(v[5], v[6]); + glVertex3fv(v); } - glEnd (); - Fog_StopAdditive (); + glEnd(); + Fog_StopAdditive(); rs_brushpasses++; //third pass -- black geo with normal fog, additive blended - if (Fog_GetDensity() > 0) + if(Fog_GetDensity() > 0) { glBlendFunc(GL_ONE, GL_ONE); //add glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glColor3f(0,0,0); - DrawGLPoly (s->polys); - glColor3f(1,1,1); + glColor3f(0, 0, 0); + DrawGLPoly(s->polys); + glColor3f(1, 1, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); rs_brushpasses++; } - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable (GL_BLEND); - glDepthMask (GL_TRUE); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_BLEND); + glDepthMask(GL_TRUE); } } else { - if (gl_mtexable) //case 4: texture and lightmap in one pass, regular modulation + if(gl_mtexable) //case 4: texture and lightmap in one pass, regular modulation { GL_DisableMultitexture(); // selects TEXTURE0 - GL_Bind (t->gltexture); + GL_Bind(t->gltexture); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); GL_EnableMultitexture(); // selects TEXTURE1 - GL_Bind (lightmap_textures[s->lightmaptexturenum]); - R_RenderDynamicLightmaps (s); + GL_Bind(lightmap_textures[s->lightmaptexturenum]); + R_RenderDynamicLightmaps(s); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glBegin(GL_POLYGON); v = s->polys->verts[0]; - for (i=0 ; ipolys->numverts ; i++, v+= VERTEXSIZE) + for(i = 0 ; i < s->polys->numverts ; i++, v += VERTEXSIZE) { - GL_MTexCoord2fFunc (GL_TEXTURE0_ARB, v[3], v[4]); - GL_MTexCoord2fFunc (GL_TEXTURE1_ARB, v[5], v[6]); - glVertex3fv (v); + GL_MTexCoord2fFunc(GL_TEXTURE0_ARB, v[3], v[4]); + GL_MTexCoord2fFunc(GL_TEXTURE1_ARB, v[5], v[6]); + glVertex3fv(v); } - glEnd (); - GL_DisableMultitexture (); + glEnd(); + GL_DisableMultitexture(); rs_brushpasses++; } - else if (entalpha < 1 || (s->flags & SURF_DRAWFENCE)) //case 5: can't do multipass if entity has alpha, so just draw the texture + else if(entalpha < 1 || (s->flags & SURF_DRAWFENCE)) //case 5: can't do multipass if entity has alpha, so just draw the texture { - GL_Bind (t->gltexture); - DrawGLPoly (s->polys); + GL_Bind(t->gltexture); + DrawGLPoly(s->polys); rs_brushpasses++; } else //case 6: texture in one pass, lightmap in a second pass, fog in third pass { //first pass -- texture with no fog - Fog_DisableGFog (); - GL_Bind (t->gltexture); - DrawGLPoly (s->polys); - Fog_EnableGFog (); + Fog_DisableGFog(); + GL_Bind(t->gltexture); + DrawGLPoly(s->polys); + Fog_EnableGFog(); rs_brushpasses++; //second pass -- lightmap with black fog, modulate blended - R_RenderDynamicLightmaps (s); - GL_Bind (lightmap_textures[s->lightmaptexturenum]); - glDepthMask (GL_FALSE); - glEnable (GL_BLEND); - glBlendFunc (GL_ZERO, GL_SRC_COLOR); //modulate - Fog_StartAdditive (); - glBegin (GL_POLYGON); + R_RenderDynamicLightmaps(s); + GL_Bind(lightmap_textures[s->lightmaptexturenum]); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); + glBlendFunc(GL_ZERO, GL_SRC_COLOR); //modulate + Fog_StartAdditive(); + glBegin(GL_POLYGON); v = s->polys->verts[0]; - for (i=0 ; ipolys->numverts ; i++, v+= VERTEXSIZE) + for(i = 0 ; i < s->polys->numverts ; i++, v += VERTEXSIZE) { - glTexCoord2f (v[5], v[6]); - glVertex3fv (v); + glTexCoord2f(v[5], v[6]); + glVertex3fv(v); } - glEnd (); - Fog_StopAdditive (); + glEnd(); + Fog_StopAdditive(); rs_brushpasses++; //third pass -- black geo with normal fog, additive blended - if (Fog_GetDensity() > 0) + if(Fog_GetDensity() > 0) { glBlendFunc(GL_ONE, GL_ONE); //add glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glColor3f(0,0,0); - DrawGLPoly (s->polys); - glColor3f(1,1,1); + glColor3f(0, 0, 0); + DrawGLPoly(s->polys); + glColor3f(1, 1, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); rs_brushpasses++; } - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable (GL_BLEND); - glDepthMask (GL_TRUE); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_BLEND); + glDepthMask(GL_TRUE); } } - if (entalpha < 1) + if(entalpha < 1) { glDepthMask(GL_TRUE); glDisable(GL_BLEND); @@ -482,26 +483,26 @@ void R_DrawSequentialPoly (msurface_t *s) glColor3f(1, 1, 1); } - if (s->flags & SURF_DRAWFENCE) - glDisable (GL_ALPHA_TEST); // Flip alpha test back off + if(s->flags & SURF_DRAWFENCE) + glDisable(GL_ALPHA_TEST); // Flip alpha test back off fullbrights: - if (gl_fullbrights.value && t->fullbright) + if(gl_fullbrights.value && t->fullbright) { - glDepthMask (GL_FALSE); - glEnable (GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glColor3f (entalpha, entalpha, entalpha); - GL_Bind (t->fullbright); - Fog_StartAdditive (); - DrawGLPoly (s->polys); - Fog_StopAdditive (); + glColor3f(entalpha, entalpha, entalpha); + GL_Bind(t->fullbright); + Fog_StartAdditive(); + DrawGLPoly(s->polys); + Fog_StopAdditive(); glColor3f(1, 1, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable (GL_BLEND); - glDepthMask (GL_TRUE); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_BLEND); + glDepthMask(GL_TRUE); rs_brushpasses++; } } @@ -511,84 +512,84 @@ fullbrights: R_DrawBrushModel ================= */ -void R_DrawBrushModel (entity_t *e) +void R_DrawBrushModel(entity_t *e) { - int32_t i, k; - msurface_t *psurf; - float dot; - mplane_t *pplane; - qmodel_t *clmodel; + int32_t i, k; + msurface_t *psurf; + float dot; + mplane_t *pplane; + qmodel_t *clmodel; - if (R_CullModelForEntity(e)) + if(R_CullModelForEntity(e)) return; currententity = e; clmodel = e->model; - VectorSubtract (r_refdef.vieworg, e->origin, modelorg); - if (e->angles[0] || e->angles[1] || e->angles[2]) + VectorSubtract(r_refdef.vieworg, e->origin, modelorg); + if(e->angles[0] || e->angles[1] || e->angles[2]) { - vec3_t temp; - vec3_t forward, right, up; + vec3_t temp; + vec3_t forward, right, up; - VectorCopy (modelorg, temp); - AngleVectors (e->angles, forward, right, up); - modelorg[0] = DotProduct (temp, forward); - modelorg[1] = -DotProduct (temp, right); - modelorg[2] = DotProduct (temp, up); + VectorCopy(modelorg, temp); + AngleVectors(e->angles, forward, right, up); + modelorg[0] = DotProduct(temp, forward); + modelorg[1] = -DotProduct(temp, right); + modelorg[2] = DotProduct(temp, up); } psurf = &clmodel->surfaces[clmodel->firstmodelsurface]; // calculate dynamic lighting for bmodel if it's not an // instanced model - if (clmodel->firstmodelsurface != 0 && !gl_flashblend.value) + if(clmodel->firstmodelsurface != 0 && !gl_flashblend.value) { - for (k=0 ; knodes + clmodel->hulls[0].firstclipnode); + R_MarkLights(&cl_dlights[k], k, + clmodel->nodes + clmodel->hulls[0].firstclipnode); } } - glPushMatrix (); - e->angles[0] = -e->angles[0]; // stupid quake bug - if (gl_zfix.value) + glPushMatrix(); + e->angles[0] = -e->angles[0]; // stupid quake bug + if(gl_zfix.value) { e->origin[0] -= DIST_EPSILON; e->origin[1] -= DIST_EPSILON; e->origin[2] -= DIST_EPSILON; } - R_RotateForEntity (e->origin, e->angles); - if (gl_zfix.value) + R_RotateForEntity(e->origin, e->angles); + if(gl_zfix.value) { e->origin[0] += DIST_EPSILON; e->origin[1] += DIST_EPSILON; e->origin[2] += DIST_EPSILON; } - e->angles[0] = -e->angles[0]; // stupid quake bug + e->angles[0] = -e->angles[0]; // stupid quake bug - R_ClearTextureChains (clmodel, chain_model); - for (i=0 ; inummodelsurfaces ; i++, psurf++) + R_ClearTextureChains(clmodel, chain_model); + for(i = 0 ; i < clmodel->nummodelsurfaces ; i++, psurf++) { pplane = psurf->plane; - dot = DotProduct (modelorg, pplane->normal) - pplane->dist; - if (((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || - (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) + dot = DotProduct(modelorg, pplane->normal) - pplane->dist; + if(((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || + (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) { - R_ChainSurface (psurf, chain_model); + R_ChainSurface(psurf, chain_model); rs_brushpolys++; } } - R_DrawTextureChains (clmodel, e, chain_model); - R_DrawTextureChains_Water (clmodel, e, chain_model); + R_DrawTextureChains(clmodel, e, chain_model); + R_DrawTextureChains_Water(clmodel, e, chain_model); - glPopMatrix (); + glPopMatrix(); } /* @@ -596,66 +597,66 @@ void R_DrawBrushModel (entity_t *e) R_DrawBrushModel_ShowTris -- johnfitz ================= */ -void R_DrawBrushModel_ShowTris (entity_t *e) +void R_DrawBrushModel_ShowTris(entity_t *e) { - int32_t i; - msurface_t *psurf; - float dot; - mplane_t *pplane; - qmodel_t *clmodel; - glpoly_t *p; + int32_t i; + msurface_t *psurf; + float dot; + mplane_t *pplane; + qmodel_t *clmodel; + glpoly_t *p; - if (R_CullModelForEntity(e)) + if(R_CullModelForEntity(e)) return; currententity = e; clmodel = e->model; - VectorSubtract (r_refdef.vieworg, e->origin, modelorg); - if (e->angles[0] || e->angles[1] || e->angles[2]) + VectorSubtract(r_refdef.vieworg, e->origin, modelorg); + if(e->angles[0] || e->angles[1] || e->angles[2]) { - vec3_t temp; - vec3_t forward, right, up; + vec3_t temp; + vec3_t forward, right, up; - VectorCopy (modelorg, temp); - AngleVectors (e->angles, forward, right, up); - modelorg[0] = DotProduct (temp, forward); - modelorg[1] = -DotProduct (temp, right); - modelorg[2] = DotProduct (temp, up); + VectorCopy(modelorg, temp); + AngleVectors(e->angles, forward, right, up); + modelorg[0] = DotProduct(temp, forward); + modelorg[1] = -DotProduct(temp, right); + modelorg[2] = DotProduct(temp, up); } psurf = &clmodel->surfaces[clmodel->firstmodelsurface]; - glPushMatrix (); - e->angles[0] = -e->angles[0]; // stupid quake bug - R_RotateForEntity (e->origin, e->angles); - e->angles[0] = -e->angles[0]; // stupid quake bug + glPushMatrix(); + e->angles[0] = -e->angles[0]; // stupid quake bug + R_RotateForEntity(e->origin, e->angles); + e->angles[0] = -e->angles[0]; // stupid quake bug // // draw it // - for (i=0 ; inummodelsurfaces ; i++, psurf++) + for(i = 0 ; i < clmodel->nummodelsurfaces ; i++, psurf++) { pplane = psurf->plane; - dot = DotProduct (modelorg, pplane->normal) - pplane->dist; - if (((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || - (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) + dot = DotProduct(modelorg, pplane->normal) - pplane->dist; + if(((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || + (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) { - if ((psurf->flags & SURF_DRAWTURB) && r_oldwater.value) - for (p = psurf->polys->next; p; p = p->next) - DrawGLTriangleFan (p); + if((psurf->flags & SURF_DRAWTURB) && r_oldwater.value) + for(p = psurf->polys->next; p; p = p->next) + DrawGLTriangleFan(p); else - DrawGLTriangleFan (psurf->polys); + DrawGLTriangleFan(psurf->polys); } } - glPopMatrix (); + glPopMatrix(); } /* ============================================================= - LIGHTMAPS + LIGHTMAPS ============================================================= */ @@ -666,14 +667,14 @@ R_RenderDynamicLightmaps called during rendering ================ */ -void R_RenderDynamicLightmaps (msurface_t *fa) +void R_RenderDynamicLightmaps(msurface_t *fa) { - byte *base; - int32_t maps; + byte *base; + int32_t maps; glRect_t *theRect; int32_t smax, tmax; - if (fa->flags & SURF_DRAWTILED) //johnfitz -- not a lightmapped surface + if(fa->flags & SURF_DRAWTILED) //johnfitz -- not a lightmapped surface return; // add to lightmap chain @@ -681,37 +682,39 @@ void R_RenderDynamicLightmaps (msurface_t *fa) lightmap_polys[fa->lightmaptexturenum] = fa->polys; // check for lightmap modification - for (maps=0; maps < MAXLIGHTMAPS && fa->styles[maps] != 255; maps++) - if (d_lightstylevalue[fa->styles[maps]] != fa->cached_light[maps]) + for(maps = 0; maps < MAXLIGHTMAPS && fa->styles[maps] != 255; maps++) + if(d_lightstylevalue[fa->styles[maps]] != fa->cached_light[maps]) goto dynamic; - if (fa->dlightframe == r_framecount // dynamic this frame - || fa->cached_dlight) // dynamic previously + if(fa->dlightframe == r_framecount // dynamic this frame + || fa->cached_dlight) // dynamic previously { dynamic: - if (r_dynamic.value) + if(r_dynamic.value) { lightmap_modified[fa->lightmaptexturenum] = true; theRect = &lightmap_rectchange[fa->lightmaptexturenum]; - if (fa->light_t < theRect->t) { - if (theRect->h) + if(fa->light_t < theRect->t) + { + if(theRect->h) theRect->h += theRect->t - fa->light_t; theRect->t = fa->light_t; } - if (fa->light_s < theRect->l) { - if (theRect->w) + if(fa->light_s < theRect->l) + { + if(theRect->w) theRect->w += theRect->l - fa->light_s; theRect->l = fa->light_s; } - smax = (fa->extents[0]>>4)+1; - tmax = (fa->extents[1]>>4)+1; - if ((theRect->w + theRect->l) < (fa->light_s + smax)) - theRect->w = (fa->light_s-theRect->l)+smax; - if ((theRect->h + theRect->t) < (fa->light_t + tmax)) - theRect->h = (fa->light_t-theRect->t)+tmax; - base = lightmaps + fa->lightmaptexturenum*lightmap_bytes*BLOCK_WIDTH*BLOCK_HEIGHT; + smax = (fa->extents[0] >> 4) + 1; + tmax = (fa->extents[1] >> 4) + 1; + if((theRect->w + theRect->l) < (fa->light_s + smax)) + theRect->w = (fa->light_s - theRect->l) + smax; + if((theRect->h + theRect->t) < (fa->light_t + tmax)) + theRect->h = (fa->light_t - theRect->t) + tmax; + base = lightmaps + fa->lightmaptexturenum * lightmap_bytes * BLOCK_WIDTH * BLOCK_HEIGHT; base += fa->light_t * BLOCK_WIDTH * lightmap_bytes + fa->light_s * lightmap_bytes; - R_BuildLightMap (fa, base, BLOCK_WIDTH*lightmap_bytes); + R_BuildLightMap(fa, base, BLOCK_WIDTH * lightmap_bytes); } } } @@ -721,75 +724,76 @@ dynamic: AllocBlock -- returns a texture number and the position inside it ======================== */ -int32_t AllocBlock (int32_t w, int32_t h, int32_t *x, int32_t *y) +int32_t AllocBlock(int32_t w, int32_t h, int32_t *x, int32_t *y) { - int32_t i, j; - int32_t best, best2; - int32_t texnum; + int32_t i, j; + int32_t best, best2; + int32_t texnum; // ericw -- rather than searching starting at lightmap 0 every time, // start at the last lightmap we allocated a surface in. // This makes AllocBlock much faster on large levels (can shave off 3+ seconds // of load time on a level with 180 lightmaps), at a cost of not quite packing // lightmaps as tightly vs. not doing this (uses ~5% more lightmaps) - for (texnum=last_lightmap_allocated ; texnum= best) + if(allocated[texnum][i + j] >= best) break; - if (allocated[texnum][i+j] > best2) - best2 = allocated[texnum][i+j]; + if(allocated[texnum][i + j] > best2) + best2 = allocated[texnum][i + j]; } - if (j == w) - { // this is a valid spot + if(j == w) + { + // this is a valid spot *x = i; *y = best = best2; } } - if (best + h > BLOCK_HEIGHT) + if(best + h > BLOCK_HEIGHT) continue; - for (i=0 ; iextents[0]>>4)+1; - tmax = (surf->extents[1]>>4)+1; + smax = (surf->extents[0] >> 4) + 1; + tmax = (surf->extents[1] >> 4) + 1; - surf->lightmaptexturenum = AllocBlock (smax, tmax, &surf->light_s, &surf->light_t); - base = lightmaps + surf->lightmaptexturenum*lightmap_bytes*BLOCK_WIDTH*BLOCK_HEIGHT; + surf->lightmaptexturenum = AllocBlock(smax, tmax, &surf->light_s, &surf->light_t); + base = lightmaps + surf->lightmaptexturenum * lightmap_bytes * BLOCK_WIDTH * BLOCK_HEIGHT; base += (surf->light_t * BLOCK_WIDTH + surf->light_s) * lightmap_bytes; - R_BuildLightMap (surf, base, BLOCK_WIDTH*lightmap_bytes); + R_BuildLightMap(surf, base, BLOCK_WIDTH * lightmap_bytes); } /* @@ -797,13 +801,13 @@ void GL_CreateSurfaceLightmap (msurface_t *surf) BuildSurfaceDisplayList -- called at level load time ================ */ -void BuildSurfaceDisplayList (msurface_t *fa) +void BuildSurfaceDisplayList(msurface_t *fa) { - int32_t i, lindex, lnumverts; - medge_t *pedges, *r_pedge; - float *vec; - float s, t; - glpoly_t *poly; + int32_t i, lindex, lnumverts; + medge_t *pedges, *r_pedge; + float *vec; + float s, t; + glpoly_t *poly; // reconstruct the polygon pedges = currentmodel->edges; @@ -812,16 +816,16 @@ void BuildSurfaceDisplayList (msurface_t *fa) // // draw texture // - poly = (glpoly_t *) Hunk_Alloc (sizeof(glpoly_t) + (lnumverts-4) * VERTEXSIZE*sizeof(float)); + poly = (glpoly_t *) Hunk_Alloc(sizeof(glpoly_t) + (lnumverts - 4) * VERTEXSIZE * sizeof(float)); poly->next = fa->polys; fa->polys = poly; poly->numverts = lnumverts; - for (i=0 ; isurfedges[fa->firstedge + i]; - if (lindex > 0) + if(lindex > 0) { r_pedge = &pedges[lindex]; vec = r_pcurrentvertbase[r_pedge->v[0]].position; @@ -831,30 +835,30 @@ void BuildSurfaceDisplayList (msurface_t *fa) r_pedge = &pedges[-lindex]; vec = r_pcurrentvertbase[r_pedge->v[1]].position; } - s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3]; + s = DotProduct(vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3]; s /= fa->texinfo->texture->width; - t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3]; + t = DotProduct(vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3]; t /= fa->texinfo->texture->height; - VectorCopy (vec, poly->verts[i]); + VectorCopy(vec, poly->verts[i]); poly->verts[i][3] = s; poly->verts[i][4] = t; // // lightmap texture coordinates // - s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3]; + s = DotProduct(vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3]; s -= fa->texturemins[0]; - s += fa->light_s*16; + s += fa->light_s * 16; s += 8; - s /= BLOCK_WIDTH*16; //fa->texinfo->texture->width; + s /= BLOCK_WIDTH * 16; //fa->texinfo->texture->width; - t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3]; + t = DotProduct(vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3]; t -= fa->texturemins[1]; - t += fa->light_t*16; + t += fa->light_t * 16; t += 8; - t /= BLOCK_HEIGHT*16; //fa->texinfo->texture->height; + t /= BLOCK_HEIGHT * 16; //fa->texinfo->texture->height; poly->verts[i][5] = s; poly->verts[i][6] = t; @@ -873,26 +877,26 @@ Builds the lightmap texture with all the surfaces from all brush models ================== */ -void GL_BuildLightmaps (void) +void GL_BuildLightmaps(void) { - char name[16]; - byte *data; - int32_t i, j; - qmodel_t *m; + char name[16]; + byte *data; + int32_t i, j; + qmodel_t *m; - memset (allocated, 0, sizeof(allocated)); + memset(allocated, 0, sizeof(allocated)); last_lightmap_allocated = 0; r_framecount = 1; // no dlightcache //johnfitz -- null out array (the gltexture objects themselves were already freed by Mod_ClearAll) - for (i=0; i < MAX_LIGHTMAPS; i++) + for(i = 0; i < MAX_LIGHTMAPS; i++) lightmap_textures[i] = NULL; //johnfitz gl_lightmap_format = GL_RGBA;//FIXME: hardcoded for now! - switch (gl_lightmap_format) + switch(gl_lightmap_format) { case GL_RGBA: lightmap_bytes = 4; @@ -901,25 +905,25 @@ void GL_BuildLightmaps (void) lightmap_bytes = 4; break; default: - Sys_Error ("GL_BuildLightmaps: bad lightmap format"); + Sys_Error("GL_BuildLightmaps: bad lightmap format"); } - for (j=1 ; jname[0] == '*') + if(m->name[0] == '*') continue; r_pcurrentvertbase = m->vertexes; currentmodel = m; - for (i=0 ; inumsurfaces ; i++) + for(i = 0 ; i < m->numsurfaces ; i++) { //johnfitz -- rewritten to use SURF_DRAWTILED instead of the sky/water flags - if (m->surfaces[i].flags & SURF_DRAWTILED) + if(m->surfaces[i].flags & SURF_DRAWTILED) continue; - GL_CreateSurfaceLightmap (m->surfaces + i); - BuildSurfaceDisplayList (m->surfaces + i); + GL_CreateSurfaceLightmap(m->surfaces + i); + BuildSurfaceDisplayList(m->surfaces + i); //johnfitz } } @@ -927,10 +931,10 @@ void GL_BuildLightmaps (void) // // upload all lightmaps that were filled // - for (i=0; i= 64) - Con_DWarning ("%" PRIi32 " lightmaps exceeds standard limit of 64 (max = %" PRIi32 ").\n", i, MAX_LIGHTMAPS); + if(i >= 64) + Con_DWarning("%" PRIi32 " lightmaps exceeds standard limit of 64 (max = %" PRIi32 ").\n", i, MAX_LIGHTMAPS); //johnfitz } /* ============================================================= - VBO support + VBO support ============================================================= */ GLuint gl_bmodel_vbo = 0; -void GL_DeleteBModelVertexBuffer (void) +void GL_DeleteBModelVertexBuffer(void) { - if (!(gl_vbo_able && gl_mtexable && gl_max_texture_units >= 3)) + if(!(gl_vbo_able && gl_mtexable && gl_max_texture_units >= 3)) return; - GL_DeleteBuffersFunc (1, &gl_bmodel_vbo); + GL_DeleteBuffersFunc(1, &gl_bmodel_vbo); gl_bmodel_vbo = 0; - GL_ClearBufferBindings (); + GL_ClearBufferBindings(); } /* @@ -980,29 +984,29 @@ Deletes gl_bmodel_vbo if it already exists, then rebuilds it with all surfaces from world + all brush models ================== */ -void GL_BuildBModelVertexBuffer (void) +void GL_BuildBModelVertexBuffer(void) { - uint32_t numverts, varray_bytes, varray_index; - int32_t i, j; - qmodel_t *m; - float *varray; + uint32_t numverts, varray_bytes, varray_index; + int32_t i, j; + qmodel_t *m; + float *varray; - if (!(gl_vbo_able && gl_mtexable && gl_max_texture_units >= 3)) + if(!(gl_vbo_able && gl_mtexable && gl_max_texture_units >= 3)) return; // ask GL for a name for our VBO - GL_DeleteBuffersFunc (1, &gl_bmodel_vbo); - GL_GenBuffersFunc (1, &gl_bmodel_vbo); + GL_DeleteBuffersFunc(1, &gl_bmodel_vbo); + GL_GenBuffersFunc(1, &gl_bmodel_vbo); // count all verts in all models numverts = 0; - for (j=1 ; jname[0] == '*' || m->type != mod_brush) + if(!m || m->name[0] == '*' || m->type != mod_brush) continue; - for (i=0 ; inumsurfaces ; i++) + for(i = 0 ; i < m->numsurfaces ; i++) { numverts += m->surfaces[i].numedges; } @@ -1010,31 +1014,31 @@ void GL_BuildBModelVertexBuffer (void) // build vertex array varray_bytes = VERTEXSIZE * sizeof(float) * numverts; - varray = (float *) malloc (varray_bytes); + varray = (float *) malloc(varray_bytes); varray_index = 0; - for (j=1 ; jname[0] == '*' || m->type != mod_brush) + if(!m || m->name[0] == '*' || m->type != mod_brush) continue; - for (i=0 ; inumsurfaces ; i++) + for(i = 0 ; i < m->numsurfaces ; i++) { msurface_t *s = &m->surfaces[i]; s->vbo_firstvert = varray_index; - memcpy (&varray[VERTEXSIZE * varray_index], s->polys->verts, VERTEXSIZE * sizeof(float) * s->numedges); + memcpy(&varray[VERTEXSIZE * varray_index], s->polys->verts, VERTEXSIZE * sizeof(float) * s->numedges); varray_index += s->numedges; } } // upload to GPU - GL_BindBufferFunc (GL_ARRAY_BUFFER, gl_bmodel_vbo); - GL_BufferDataFunc (GL_ARRAY_BUFFER, varray_bytes, varray, GL_STATIC_DRAW); - free (varray); + GL_BindBufferFunc(GL_ARRAY_BUFFER, gl_bmodel_vbo); + GL_BufferDataFunc(GL_ARRAY_BUFFER, varray_bytes, varray, GL_STATIC_DRAW); + free(varray); // invalidate the cached bindings - GL_ClearBufferBindings (); + GL_ClearBufferBindings(); } /* @@ -1042,47 +1046,47 @@ void GL_BuildBModelVertexBuffer (void) R_AddDynamicLights =============== */ -void R_AddDynamicLights (msurface_t *surf) +void R_AddDynamicLights(msurface_t *surf) { - int32_t lnum; - int32_t sd, td; - float dist, rad, minlight; - vec3_t impact, local; - int32_t s, t; - int32_t i; - int32_t smax, tmax; - mtexinfo_t *tex; + int32_t lnum; + int32_t sd, td; + float dist, rad, minlight; + vec3_t impact, local; + int32_t s, t; + int32_t i; + int32_t smax, tmax; + mtexinfo_t *tex; //johnfitz -- lit support via lordhavoc - float cred, cgreen, cblue, brightness; - unsigned *bl; + float cred, cgreen, cblue, brightness; + unsigned *bl; //johnfitz - smax = (surf->extents[0]>>4)+1; - tmax = (surf->extents[1]>>4)+1; + smax = (surf->extents[0] >> 4) + 1; + tmax = (surf->extents[1] >> 4) + 1; tex = surf->texinfo; - for (lnum=0 ; lnumdlightbits[lnum >> 5] & (1U << (lnum & 31)))) - continue; // not lit by this light + if(!(surf->dlightbits[lnum >> 5] & (1U << (lnum & 31)))) + continue; // not lit by this light rad = cl_dlights[lnum].radius; - dist = DotProduct (cl_dlights[lnum].origin, surf->plane->normal) - - surf->plane->dist; + dist = DotProduct(cl_dlights[lnum].origin, surf->plane->normal) - + surf->plane->dist; rad -= fabs(dist); minlight = cl_dlights[lnum].minlight; - if (rad < minlight) + if(rad < minlight) continue; minlight = rad - minlight; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { impact[i] = cl_dlights[lnum].origin[i] - - surf->plane->normal[i]*dist; + surf->plane->normal[i] * dist; } - local[0] = DotProduct (impact, tex->vecs[0]) + tex->vecs[0][3]; - local[1] = DotProduct (impact, tex->vecs[1]) + tex->vecs[1][3]; + local[0] = DotProduct(impact, tex->vecs[0]) + tex->vecs[0][3]; + local[1] = DotProduct(impact, tex->vecs[1]) + tex->vecs[1][3]; local[0] -= surf->texturemins[0]; local[1] -= surf->texturemins[1]; @@ -1093,27 +1097,27 @@ void R_AddDynamicLights (msurface_t *surf) cgreen = cl_dlights[lnum].color[1] * 256.0f; cblue = cl_dlights[lnum].color[2] * 256.0f; //johnfitz - for (t = 0 ; t td) - dist = sd + (td>>1); + if(sd > td) + dist = sd + (td >> 1); else - dist = td + (sd>>1); - if (dist < minlight) - //johnfitz -- lit support via lordhavoc + dist = td + (sd >> 1); + if(dist < minlight) + //johnfitz -- lit support via lordhavoc { brightness = rad - dist; - bl[0] += (int32_t) (brightness * cred); - bl[1] += (int32_t) (brightness * cgreen); - bl[2] += (int32_t) (brightness * cblue); + bl[0] += (int32_t)(brightness * cred); + bl[1] += (int32_t)(brightness * cgreen); + bl[2] += (int32_t)(brightness * cblue); } bl += 3; //johnfitz @@ -1130,39 +1134,39 @@ R_BuildLightMap -- johnfitz -- revised for lit support via lordhavoc Combine and scale multiple lightmaps into the 8.8 format in blocklights =============== */ -void R_BuildLightMap (msurface_t *surf, byte *dest, int32_t stride) +void R_BuildLightMap(msurface_t *surf, byte *dest, int32_t stride) { - int32_t smax, tmax; - int32_t r,g,b; - int32_t i, j, size; - byte *lightmap; - unsigned scale; - int32_t maps; - unsigned *bl; + int32_t smax, tmax; + int32_t r, g, b; + int32_t i, j, size; + byte *lightmap; + unsigned scale; + int32_t maps; + unsigned *bl; surf->cached_dlight = (surf->dlightframe == r_framecount); - smax = (surf->extents[0]>>4)+1; - tmax = (surf->extents[1]>>4)+1; - size = smax*tmax; + smax = (surf->extents[0] >> 4) + 1; + tmax = (surf->extents[1] >> 4) + 1; + size = smax * tmax; lightmap = surf->samples; - if (cl.worldmodel->lightdata) + if(cl.worldmodel->lightdata) { - // clear to no light - memset (&blocklights[0], 0, size * 3 * sizeof (uint32_t)); //johnfitz -- lit support via lordhavoc + // clear to no light + memset(&blocklights[0], 0, size * 3 * sizeof(uint32_t)); //johnfitz -- lit support via lordhavoc - // add all the lightmaps - if (lightmap) + // add all the lightmaps + if(lightmap) { - for (maps = 0 ; maps < MAXLIGHTMAPS && surf->styles[maps] != 255 ; - maps++) + for(maps = 0 ; maps < MAXLIGHTMAPS && surf->styles[maps] != 255 ; + maps++) { scale = d_lightstylevalue[surf->styles[maps]]; - surf->cached_light[maps] = scale; // 8.8 fraction + surf->cached_light[maps] = scale; // 8.8 fraction //johnfitz -- lit support via lordhavoc bl = blocklights; - for (i=0 ; idlightframe == r_framecount) - R_AddDynamicLights (surf); + // add all the dynamic lights + if(surf->dlightframe == r_framecount) + R_AddDynamicLights(surf); } else { - // set to full bright if no light data - memset (&blocklights[0], 255, size * 3 * sizeof (uint32_t)); //johnfitz -- lit support via lordhavoc + // set to full bright if no light data + memset(&blocklights[0], 255, size * 3 * sizeof(uint32_t)); //johnfitz -- lit support via lordhavoc } // bound, invert, and shift // store: - switch (gl_lightmap_format) + switch(gl_lightmap_format) { case GL_RGBA: stride -= smax * 4; bl = blocklights; - for (i=0 ; i> 8; g = *bl++ >> 8; @@ -1205,9 +1209,9 @@ void R_BuildLightMap (msurface_t *surf, byte *dest, int32_t stride) g = *bl++ >> 7; b = *bl++ >> 7; } - *dest++ = (r > 255)? 255 : r; - *dest++ = (g > 255)? 255 : g; - *dest++ = (b > 255)? 255 : b; + *dest++ = (r > 255) ? 255 : r; + *dest++ = (g > 255) ? 255 : g; + *dest++ = (b > 255) ? 255 : b; *dest++ = 255; } } @@ -1215,11 +1219,11 @@ void R_BuildLightMap (msurface_t *surf, byte *dest, int32_t stride) case GL_BGRA: stride -= smax * 4; bl = blocklights; - for (i=0 ; i> 8; g = *bl++ >> 8; @@ -1231,15 +1235,15 @@ void R_BuildLightMap (msurface_t *surf, byte *dest, int32_t stride) g = *bl++ >> 7; b = *bl++ >> 7; } - *dest++ = (b > 255)? 255 : b; - *dest++ = (g > 255)? 255 : g; - *dest++ = (r > 255)? 255 : r; + *dest++ = (b > 255) ? 255 : b; + *dest++ = (g > 255) ? 255 : g; + *dest++ = (r > 255) ? 255 : r; *dest++ = 255; } } break; default: - Sys_Error ("R_BuildLightMap: bad lightmap format"); + Sys_Error("R_BuildLightMap: bad lightmap format"); } } @@ -1252,16 +1256,16 @@ assumes lightmap texture is already bound */ static void R_UploadLightmap(int32_t lmap) { - glRect_t *theRect; + glRect_t *theRect; - if (!lightmap_modified[lmap]) + if(!lightmap_modified[lmap]) return; lightmap_modified[lmap] = false; theRect = &lightmap_rectchange[lmap]; glTexSubImage2D(GL_TEXTURE_2D, 0, 0, theRect->t, BLOCK_WIDTH, theRect->h, gl_lightmap_format, - GL_UNSIGNED_BYTE, lightmaps+(lmap* BLOCK_HEIGHT + theRect->t) *BLOCK_WIDTH*lightmap_bytes); + GL_UNSIGNED_BYTE, lightmaps + (lmap * BLOCK_HEIGHT + theRect->t) *BLOCK_WIDTH * lightmap_bytes); theRect->l = BLOCK_WIDTH; theRect->t = BLOCK_HEIGHT; theRect->h = 0; @@ -1270,16 +1274,16 @@ static void R_UploadLightmap(int32_t lmap) rs_dynamiclightmaps++; } -void R_UploadLightmaps (void) +void R_UploadLightmaps(void) { int32_t lmap; - for (lmap = 0; lmap < MAX_LIGHTMAPS; lmap++) + for(lmap = 0; lmap < MAX_LIGHTMAPS; lmap++) { - if (!lightmap_modified[lmap]) + if(!lightmap_modified[lmap]) continue; - GL_Bind (lightmap_textures[lmap]); + GL_Bind(lightmap_textures[lmap]); R_UploadLightmap(lmap); } } @@ -1289,39 +1293,39 @@ void R_UploadLightmaps (void) R_RebuildAllLightmaps -- johnfitz -- called when gl_overbright gets toggled ================ */ -void R_RebuildAllLightmaps (void) +void R_RebuildAllLightmaps(void) { - int32_t i, j; - qmodel_t *mod; - msurface_t *fa; - byte *base; + int32_t i, j; + qmodel_t *mod; + msurface_t *fa; + byte *base; - if (!cl.worldmodel) // is this the correct test? + if(!cl.worldmodel) // is this the correct test? return; //for each surface in each model, rebuild lightmap with new scale - for (i=1; isurfaces[mod->firstmodelsurface]; - for (j=0; jnummodelsurfaces; j++, fa++) + for(j = 0; j < mod->nummodelsurfaces; j++, fa++) { - if (fa->flags & SURF_DRAWTILED) + if(fa->flags & SURF_DRAWTILED) continue; - base = lightmaps + fa->lightmaptexturenum*lightmap_bytes*BLOCK_WIDTH*BLOCK_HEIGHT; + base = lightmaps + fa->lightmaptexturenum * lightmap_bytes * BLOCK_WIDTH * BLOCK_HEIGHT; base += fa->light_t * BLOCK_WIDTH * lightmap_bytes + fa->light_s * lightmap_bytes; - R_BuildLightMap (fa, base, BLOCK_WIDTH*lightmap_bytes); + R_BuildLightMap(fa, base, BLOCK_WIDTH * lightmap_bytes); } } //for each lightmap, upload it - for (i=0; i 255 ? 255 : r; a = sharpness * (255 - r); - a = q_min(a,255); + a = q_min(a, 255); return a; } @@ -68,49 +68,49 @@ int32_t R_ParticleTextureLookup (int32_t x, int32_t y, int32_t sharpness) R_InitParticleTextures -- johnfitz -- rewritten =============== */ -void R_InitParticleTextures (void) +void R_InitParticleTextures(void) { - int32_t x,y; - static byte particle1_data[64*64*4]; - static byte particle2_data[2*2*4]; - static byte particle3_data[64*64*4]; - byte *dst; + int32_t x, y; + static byte particle1_data[64 * 64 * 4]; + static byte particle2_data[2 * 2 * 4]; + static byte particle3_data[64 * 64 * 4]; + byte *dst; // particle texture 1 -- circle dst = particle1_data; - for (x=0 ; x<64 ; x++) - for (y=0 ; y<64 ; y++) + for(x = 0 ; x < 64 ; x++) + for(y = 0 ; y < 64 ; y++) { *dst++ = 255; *dst++ = 255; *dst++ = 255; *dst++ = R_ParticleTextureLookup(x, y, 8); } - particletexture1 = TexMgr_LoadImage (NULL, "particle1", 64, 64, SRC_RGBA, particle1_data, "", (src_offset_t)particle1_data, TEXPREF_PERSIST | TEXPREF_ALPHA | TEXPREF_LINEAR); + particletexture1 = TexMgr_LoadImage(NULL, "particle1", 64, 64, SRC_RGBA, particle1_data, "", (src_offset_t)particle1_data, TEXPREF_PERSIST | TEXPREF_ALPHA | TEXPREF_LINEAR); // particle texture 2 -- square dst = particle2_data; - for (x=0 ; x<2 ; x++) - for (y=0 ; y<2 ; y++) + for(x = 0 ; x < 2 ; x++) + for(y = 0 ; y < 2 ; y++) { *dst++ = 255; *dst++ = 255; *dst++ = 255; *dst++ = x || y ? 0 : 255; } - particletexture2 = TexMgr_LoadImage (NULL, "particle2", 2, 2, SRC_RGBA, particle2_data, "", (src_offset_t)particle2_data, TEXPREF_PERSIST | TEXPREF_ALPHA | TEXPREF_NEAREST); + particletexture2 = TexMgr_LoadImage(NULL, "particle2", 2, 2, SRC_RGBA, particle2_data, "", (src_offset_t)particle2_data, TEXPREF_PERSIST | TEXPREF_ALPHA | TEXPREF_NEAREST); // particle texture 3 -- blob dst = particle3_data; - for (x=0 ; x<64 ; x++) - for (y=0 ; y<64 ; y++) + for(x = 0 ; x < 64 ; x++) + for(y = 0 ; y < 64 ; y++) { *dst++ = 255; *dst++ = 255; *dst++ = 255; *dst++ = R_ParticleTextureLookup(x, y, 2); } - particletexture3 = TexMgr_LoadImage (NULL, "particle3", 64, 64, SRC_RGBA, particle3_data, "", (src_offset_t)particle3_data, TEXPREF_PERSIST | TEXPREF_ALPHA | TEXPREF_LINEAR); + particletexture3 = TexMgr_LoadImage(NULL, "particle3", 64, 64, SRC_RGBA, particle3_data, "", (src_offset_t)particle3_data, TEXPREF_PERSIST | TEXPREF_ALPHA | TEXPREF_LINEAR); //set default particletexture = particletexture1; @@ -122,10 +122,10 @@ void R_InitParticleTextures (void) R_SetParticleTexture_f -- johnfitz =============== */ -static void R_SetParticleTexture_f (cvar_t *var) +static void R_SetParticleTexture_f(cvar_t *var) { (void)var; - switch ((int32_t)(r_particles.value)) + switch((int32_t)(r_particles.value)) { case 1: particletexture = particletexture1; @@ -147,16 +147,16 @@ static void R_SetParticleTexture_f (cvar_t *var) R_InitParticles =============== */ -void R_InitParticles (void) +void R_InitParticles(void) { - int32_t i; + int32_t i; - i = COM_CheckParm ("-particles"); + i = COM_CheckParm("-particles"); - if (i) + if(i) { - r_numparticles = (int32_t)(Q_atoi(com_argv[i+1])); - if (r_numparticles < ABSOLUTE_MIN_PARTICLES) + r_numparticles = (int32_t)(Q_atoi(com_argv[i + 1])); + if(r_numparticles < ABSOLUTE_MIN_PARTICLES) r_numparticles = ABSOLUTE_MIN_PARTICLES; } else @@ -165,13 +165,13 @@ void R_InitParticles (void) } particles = (particle_t *) - Hunk_AllocName (r_numparticles * sizeof(particle_t), "particles"); + Hunk_AllocName(r_numparticles * sizeof(particle_t), "particles"); - Cvar_RegisterVariable (&r_particles); //johnfitz - Cvar_SetCallback (&r_particles, R_SetParticleTexture_f); - Cvar_RegisterVariable (&r_quadparticles); //johnfitz + Cvar_RegisterVariable(&r_particles); //johnfitz + Cvar_SetCallback(&r_particles, R_SetParticleTexture_f); + Cvar_RegisterVariable(&r_quadparticles); //johnfitz - R_InitParticleTextures (); //johnfitz + R_InitParticleTextures(); //johnfitz } /* @@ -179,31 +179,31 @@ void R_InitParticles (void) R_EntityParticles =============== */ -#define NUMVERTEXNORMALS 162 -extern float r_avertexnormals[NUMVERTEXNORMALS][3]; -vec3_t avelocities[NUMVERTEXNORMALS]; -float beamlength = 16; -vec3_t avelocity = {23, 7, 3}; -float partstep = 0.01; -float timescale = 0.01; +#define NUMVERTEXNORMALS 162 +extern float r_avertexnormals[NUMVERTEXNORMALS][3]; +vec3_t avelocities[NUMVERTEXNORMALS]; +float beamlength = 16; +vec3_t avelocity = {23, 7, 3}; +float partstep = 0.01; +float timescale = 0.01; -void R_EntityParticles (entity_t *ent) +void R_EntityParticles(entity_t *ent) { - int32_t i; - particle_t *p; - float angle; - float sp, sy, cp, cy; -// float sr, cr; -// int32_t count; - vec3_t forward; - float dist; + int32_t i; + particle_t *p; + float angle; + float sp, sy, cp, cy; +// float sr, cr; +// int32_t count; + vec3_t forward; + float dist; dist = 64; // count = 50; - if (!avelocities[0][0]) + if(!avelocities[0][0]) { - for (i = 0; i < NUMVERTEXNORMALS; i++) + for(i = 0; i < NUMVERTEXNORMALS; i++) { avelocities[i][0] = (rand() & 255) * 0.01; avelocities[i][1] = (rand() & 255) * 0.01; @@ -211,7 +211,7 @@ void R_EntityParticles (entity_t *ent) } } - for (i = 0; i < NUMVERTEXNORMALS; i++) + for(i = 0; i < NUMVERTEXNORMALS; i++) { angle = cl.time * avelocities[i][0]; sy = sin(angle); @@ -220,14 +220,14 @@ void R_EntityParticles (entity_t *ent) sp = sin(angle); cp = cos(angle); angle = cl.time * avelocities[i][2]; - // sr = sin(angle); - // cr = cos(angle); + // sr = sin(angle); + // cr = cos(angle); - forward[0] = cp*cy; - forward[1] = cp*sy; + forward[0] = cp * cy; + forward[1] = cp * sy; forward[2] = -sp; - if (!free_particles) + if(!free_particles) return; p = free_particles; free_particles = p->next; @@ -238,9 +238,9 @@ void R_EntityParticles (entity_t *ent) p->color = 0x6f; p->type = pt_explode; - p->org[0] = ent->origin[0] + r_avertexnormals[i][0]*dist + forward[0]*beamlength; - p->org[1] = ent->origin[1] + r_avertexnormals[i][1]*dist + forward[1]*beamlength; - p->org[2] = ent->origin[2] + r_avertexnormals[i][2]*dist + forward[2]*beamlength; + p->org[0] = ent->origin[0] + r_avertexnormals[i][0] * dist + forward[0] * beamlength; + p->org[1] = ent->origin[1] + r_avertexnormals[i][1] * dist + forward[1] * beamlength; + p->org[2] = ent->origin[2] + r_avertexnormals[i][2] * dist + forward[2] * beamlength; } } @@ -249,16 +249,16 @@ void R_EntityParticles (entity_t *ent) R_ClearParticles =============== */ -void R_ClearParticles (void) +void R_ClearParticles(void) { - int32_t i; + int32_t i; free_particles = &particles[0]; active_particles = NULL; - for (i=0 ;idie = 99999; - p->color = (-c)&15; + p->color = (-c) & 15; p->type = pt_static; - VectorCopy (vec3_origin, p->vel); - VectorCopy (org, p->org); + VectorCopy(vec3_origin, p->vel); + VectorCopy(org, p->org); } - fclose (f); - Con_Printf ("%" PRIi32 " points read\n", c); + fclose(f); + Con_Printf("%" PRIi32 " points read\n", c); } /* @@ -325,24 +325,24 @@ R_ParseParticleEffect Parse an effect out of the server message =============== */ -void R_ParseParticleEffect (void) +void R_ParseParticleEffect(void) { - vec3_t org, dir; - int32_t i, count, msgcount, color; + vec3_t org, dir; + int32_t i, count, msgcount, color; - for (i=0 ; i<3 ; i++) - org[i] = MSG_ReadCoord (cl.protocolflags); - for (i=0 ; i<3 ; i++) - dir[i] = MSG_ReadChar () * (1.0/16); - msgcount = MSG_ReadByte (); - color = MSG_ReadByte (); + for(i = 0 ; i < 3 ; i++) + org[i] = MSG_ReadCoord(cl.protocolflags); + for(i = 0 ; i < 3 ; i++) + dir[i] = MSG_ReadChar() * (1.0 / 16); + msgcount = MSG_ReadByte(); + color = MSG_ReadByte(); - if (msgcount == 255) + if(msgcount == 255) count = 1024; else count = msgcount; - R_RunParticleEffect (org, dir, color, count); + R_RunParticleEffect(org, dir, color, count); } /* @@ -350,14 +350,14 @@ void R_ParseParticleEffect (void) R_ParticleExplosion =============== */ -void R_ParticleExplosion (vec3_t org) +void R_ParticleExplosion(vec3_t org) { - int32_t i, j; - particle_t *p; + int32_t i, j; + particle_t *p; - for (i=0 ; i<1024 ; i++) + for(i = 0 ; i < 1024 ; i++) { - if (!free_particles) + if(!free_particles) return; p = free_particles; free_particles = p->next; @@ -366,23 +366,23 @@ void R_ParticleExplosion (vec3_t org) p->die = cl.time + 5; p->color = ramp1[0]; - p->ramp = rand()&3; - if (i & 1) + p->ramp = rand() & 3; + if(i & 1) { p->type = pt_explode; - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + p->org[j] = org[j] + ((rand() % 32) - 16); + p->vel[j] = (rand() % 512) - 256; } } else { p->type = pt_explode2; - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + p->org[j] = org[j] + ((rand() % 32) - 16); + p->vel[j] = (rand() % 512) - 256; } } } @@ -393,15 +393,15 @@ void R_ParticleExplosion (vec3_t org) R_ParticleExplosion2 =============== */ -void R_ParticleExplosion2 (vec3_t org, int32_t colorStart, int32_t colorLength) +void R_ParticleExplosion2(vec3_t org, int32_t colorStart, int32_t colorLength) { - int32_t i, j; - particle_t *p; - int32_t colorMod = 0; + int32_t i, j; + particle_t *p; + int32_t colorMod = 0; - for (i=0; i<512; i++) + for(i = 0; i < 512; i++) { - if (!free_particles) + if(!free_particles) return; p = free_particles; free_particles = p->next; @@ -413,10 +413,10 @@ void R_ParticleExplosion2 (vec3_t org, int32_t colorStart, int32_t colorLength) colorMod++; p->type = pt_blob; - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + p->org[j] = org[j] + ((rand() % 32) - 16); + p->vel[j] = (rand() % 512) - 256; } } } @@ -426,40 +426,40 @@ void R_ParticleExplosion2 (vec3_t org, int32_t colorStart, int32_t colorLength) R_BlobExplosion =============== */ -void R_BlobExplosion (vec3_t org) +void R_BlobExplosion(vec3_t org) { - int32_t i, j; - particle_t *p; + int32_t i, j; + particle_t *p; - for (i=0 ; i<1024 ; i++) + for(i = 0 ; i < 1024 ; i++) { - if (!free_particles) + if(!free_particles) return; p = free_particles; free_particles = p->next; p->next = active_particles; active_particles = p; - p->die = cl.time + 1 + (rand()&8)*0.05; + p->die = cl.time + 1 + (rand() & 8) * 0.05; - if (i & 1) + if(i & 1) { p->type = pt_blob; - p->color = 66 + rand()%6; - for (j=0 ; j<3 ; j++) + p->color = 66 + rand() % 6; + for(j = 0 ; j < 3 ; j++) { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + p->org[j] = org[j] + ((rand() % 32) - 16); + p->vel[j] = (rand() % 512) - 256; } } else { p->type = pt_blob2; - p->color = 150 + rand()%6; - for (j=0 ; j<3 ; j++) + p->color = 150 + rand() % 6; + for(j = 0 ; j < 3 ; j++) { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + p->org[j] = org[j] + ((rand() % 32) - 16); + p->vel[j] = (rand() % 512) - 256; } } } @@ -470,53 +470,54 @@ void R_BlobExplosion (vec3_t org) R_RunParticleEffect =============== */ -void R_RunParticleEffect (vec3_t org, vec3_t dir, int32_t color, int32_t count) +void R_RunParticleEffect(vec3_t org, vec3_t dir, int32_t color, int32_t count) { - int32_t i, j; - particle_t *p; + int32_t i, j; + particle_t *p; - for (i=0 ; inext; p->next = active_particles; active_particles = p; - if (count == 1024) - { // rocket explosion + if(count == 1024) + { + // rocket explosion p->die = cl.time + 5; p->color = ramp1[0]; - p->ramp = rand()&3; - if (i & 1) + p->ramp = rand() & 3; + if(i & 1) { p->type = pt_explode; - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + p->org[j] = org[j] + ((rand() % 32) - 16); + p->vel[j] = (rand() % 512) - 256; } } else { p->type = pt_explode2; - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + p->org[j] = org[j] + ((rand() % 32) - 16); + p->vel[j] = (rand() % 512) - 256; } } } else { - p->die = cl.time + 0.1*(rand()%5); - p->color = (color&~7) + (rand()&7); + p->die = cl.time + 0.1 * (rand() % 5); + p->color = (color & ~7) + (rand() & 7); p->type = pt_slowgrav; - for (j=0 ; j<3 ; j++) + for(j = 0 ; j < 3 ; j++) { - p->org[j] = org[j] + ((rand()&15)-8); - p->vel[j] = dir[j]*15;// + (rand()%300)-150; + p->org[j] = org[j] + ((rand() & 15) - 8); + p->vel[j] = dir[j] * 15; // + (rand()%300)-150; } } } @@ -527,39 +528,39 @@ void R_RunParticleEffect (vec3_t org, vec3_t dir, int32_t color, int32_t count) R_LavaSplash =============== */ -void R_LavaSplash (vec3_t org) +void R_LavaSplash(vec3_t org) { - int32_t i, j, k; - particle_t *p; - float vel; - vec3_t dir; + int32_t i, j, k; + particle_t *p; + float vel; + vec3_t dir; - for (i=-16 ; i<16 ; i++) - for (j=-16 ; j<16 ; j++) - for (k=0 ; k<1 ; k++) + for(i = -16 ; i < 16 ; i++) + for(j = -16 ; j < 16 ; j++) + for(k = 0 ; k < 1 ; k++) { - if (!free_particles) + if(!free_particles) return; p = free_particles; free_particles = p->next; p->next = active_particles; active_particles = p; - p->die = cl.time + 2 + (rand()&31) * 0.02; - p->color = 224 + (rand()&7); + p->die = cl.time + 2 + (rand() & 31) * 0.02; + p->color = 224 + (rand() & 7); p->type = pt_slowgrav; - dir[0] = j*8 + (rand()&7); - dir[1] = i*8 + (rand()&7); + dir[0] = j * 8 + (rand() & 7); + dir[1] = i * 8 + (rand() & 7); dir[2] = 256; p->org[0] = org[0] + dir[0]; p->org[1] = org[1] + dir[1]; - p->org[2] = org[2] + (rand()&63); + p->org[2] = org[2] + (rand() & 63); - VectorNormalize (dir); - vel = 50 + (rand()&63); - VectorScale (dir, vel, p->vel); + VectorNormalize(dir); + vel = 50 + (rand() & 63); + VectorScale(dir, vel, p->vel); } } @@ -568,39 +569,39 @@ void R_LavaSplash (vec3_t org) R_TeleportSplash =============== */ -void R_TeleportSplash (vec3_t org) +void R_TeleportSplash(vec3_t org) { - int32_t i, j, k; - particle_t *p; - float vel; - vec3_t dir; + int32_t i, j, k; + particle_t *p; + float vel; + vec3_t dir; - for (i=-16 ; i<16 ; i+=4) - for (j=-16 ; j<16 ; j+=4) - for (k=-24 ; k<32 ; k+=4) + for(i = -16 ; i < 16 ; i += 4) + for(j = -16 ; j < 16 ; j += 4) + for(k = -24 ; k < 32 ; k += 4) { - if (!free_particles) + if(!free_particles) return; p = free_particles; free_particles = p->next; p->next = active_particles; active_particles = p; - p->die = cl.time + 0.2 + (rand()&7) * 0.02; - p->color = 7 + (rand()&7); + p->die = cl.time + 0.2 + (rand() & 7) * 0.02; + p->color = 7 + (rand() & 7); p->type = pt_slowgrav; - dir[0] = j*8; - dir[1] = i*8; - dir[2] = k*8; + dir[0] = j * 8; + dir[1] = i * 8; + dir[2] = k * 8; - p->org[0] = org[0] + i + (rand()&3); - p->org[1] = org[1] + j + (rand()&3); - p->org[2] = org[2] + k + (rand()&3); + p->org[0] = org[0] + i + (rand() & 3); + p->org[1] = org[1] + j + (rand() & 3); + p->org[2] = org[2] + k + (rand() & 3); - VectorNormalize (dir); - vel = 50 + (rand()&63); - VectorScale (dir, vel, p->vel); + VectorNormalize(dir); + vel = 50 + (rand() & 63); + VectorScale(dir, vel, p->vel); } } @@ -611,18 +612,18 @@ R_RocketTrail FIXME -- rename function and use #defined types instead of numbers =============== */ -void R_RocketTrail (vec3_t start, vec3_t end, int32_t type) +void R_RocketTrail(vec3_t start, vec3_t end, int32_t type) { - vec3_t vec; - float len; - int32_t j; - particle_t *p; - int32_t dec; - static int32_t tracercount; + vec3_t vec; + float len; + int32_t j; + particle_t *p; + int32_t dec; + static int32_t tracercount; - VectorSubtract (end, start, vec); - len = VectorNormalize (vec); - if (type < 128) + VectorSubtract(end, start, vec); + len = VectorNormalize(vec); + if(type < 128) dec = 3; else { @@ -630,87 +631,87 @@ void R_RocketTrail (vec3_t start, vec3_t end, int32_t type) type -= 128; } - while (len > 0) + while(len > 0) { len -= dec; - if (!free_particles) + if(!free_particles) return; p = free_particles; free_particles = p->next; p->next = active_particles; active_particles = p; - VectorCopy (vec3_origin, p->vel); + VectorCopy(vec3_origin, p->vel); p->die = cl.time + 2; - switch (type) + switch(type) { - case 0: // rocket trail - p->ramp = (rand()&3); - p->color = ramp3[(int32_t)p->ramp]; - p->type = pt_fire; - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()%6)-3); - break; + case 0: // rocket trail + p->ramp = (rand() & 3); + p->color = ramp3[(int32_t)p->ramp]; + p->type = pt_fire; + for(j = 0 ; j < 3 ; j++) + p->org[j] = start[j] + ((rand() % 6) - 3); + break; - case 1: // smoke smoke - p->ramp = (rand()&3) + 2; - p->color = ramp3[(int32_t)p->ramp]; - p->type = pt_fire; - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()%6)-3); - break; + case 1: // smoke smoke + p->ramp = (rand() & 3) + 2; + p->color = ramp3[(int32_t)p->ramp]; + p->type = pt_fire; + for(j = 0 ; j < 3 ; j++) + p->org[j] = start[j] + ((rand() % 6) - 3); + break; - case 2: // blood - p->type = pt_grav; - p->color = 67 + (rand()&3); - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()%6)-3); - break; + case 2: // blood + p->type = pt_grav; + p->color = 67 + (rand() & 3); + for(j = 0 ; j < 3 ; j++) + p->org[j] = start[j] + ((rand() % 6) - 3); + break; - case 3: - case 5: // tracer - p->die = cl.time + 0.5; - p->type = pt_static; - if (type == 3) - p->color = 52 + ((tracercount&4)<<1); - else - p->color = 230 + ((tracercount&4)<<1); + case 3: + case 5: // tracer + p->die = cl.time + 0.5; + p->type = pt_static; + if(type == 3) + p->color = 52 + ((tracercount & 4) << 1); + else + p->color = 230 + ((tracercount & 4) << 1); - tracercount++; + tracercount++; - VectorCopy (start, p->org); - if (tracercount & 1) - { - p->vel[0] = 30*vec[1]; - p->vel[1] = 30*-vec[0]; - } - else - { - p->vel[0] = 30*-vec[1]; - p->vel[1] = 30*vec[0]; - } - break; + VectorCopy(start, p->org); + if(tracercount & 1) + { + p->vel[0] = 30 * vec[1]; + p->vel[1] = 30 * -vec[0]; + } + else + { + p->vel[0] = 30 * -vec[1]; + p->vel[1] = 30 * vec[0]; + } + break; - case 4: // slight blood - p->type = pt_grav; - p->color = 67 + (rand()&3); - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()%6)-3); - len -= 3; - break; + case 4: // slight blood + p->type = pt_grav; + p->color = 67 + (rand() & 3); + for(j = 0 ; j < 3 ; j++) + p->org[j] = start[j] + ((rand() % 6) - 3); + len -= 3; + break; - case 6: // voor trail - p->color = 9*16 + 8 + (rand()&3); - p->type = pt_static; - p->die = cl.time + 0.3; - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()&15)-8); - break; + case 6: // voor trail + p->color = 9 * 16 + 8 + (rand() & 3); + p->type = pt_static; + p->die = cl.time + 0.3; + for(j = 0 ; j < 3 ; j++) + p->org[j] = start[j] + ((rand() & 15) - 8); + break; } - VectorAdd (start, vec, start); + VectorAdd(start, vec, start); } } @@ -719,24 +720,24 @@ void R_RocketTrail (vec3_t start, vec3_t end, int32_t type) CL_RunParticles -- johnfitz -- all the particle behavior, separated from R_DrawParticles =============== */ -void CL_RunParticles (void) +void CL_RunParticles(void) { - particle_t *p, *kill; - int32_t i; - float time1, time2, time3, dvel, frametime, grav; - extern cvar_t sv_gravity; + particle_t *p, *kill; + int32_t i; + float time1, time2, time3, dvel, frametime, grav; + extern cvar_t sv_gravity; frametime = cl.time - cl.oldtime; time3 = frametime * 15; time2 = frametime * 10; time1 = frametime * 5; grav = frametime * sv_gravity.value * 0.05; - dvel = 4*frametime; + dvel = 4 * frametime; - for ( ;; ) + for(;;) { kill = active_particles; - if (kill && kill->die < cl.time) + if(kill && kill->die < cl.time) { active_particles = kill->next; kill->next = free_particles; @@ -746,12 +747,12 @@ void CL_RunParticles (void) break; } - for (p=active_particles ; p ; p=p->next) + for(p = active_particles ; p ; p = p->next) { - for ( ;; ) + for(;;) { kill = p->next; - if (kill && kill->die < cl.time) + if(kill && kill->die < cl.time) { p->next = kill->next; kill->next = free_particles; @@ -761,17 +762,17 @@ void CL_RunParticles (void) break; } - p->org[0] += p->vel[0]*frametime; - p->org[1] += p->vel[1]*frametime; - p->org[2] += p->vel[2]*frametime; + p->org[0] += p->vel[0] * frametime; + p->org[1] += p->vel[1] * frametime; + p->org[2] += p->vel[2] * frametime; - switch (p->type) + switch(p->type) { case pt_static: break; case pt_fire: p->ramp += time1; - if (p->ramp >= 6) + if(p->ramp >= 6) p->die = -1; else p->color = ramp3[(int32_t)p->ramp]; @@ -780,35 +781,35 @@ void CL_RunParticles (void) case pt_explode: p->ramp += time2; - if (p->ramp >=8) + if(p->ramp >= 8) p->die = -1; else p->color = ramp1[(int32_t)p->ramp]; - for (i=0 ; i<3 ; i++) - p->vel[i] += p->vel[i]*dvel; + for(i = 0 ; i < 3 ; i++) + p->vel[i] += p->vel[i] * dvel; p->vel[2] -= grav; break; case pt_explode2: p->ramp += time3; - if (p->ramp >=8) + if(p->ramp >= 8) p->die = -1; else p->color = ramp2[(int32_t)p->ramp]; - for (i=0 ; i<3 ; i++) - p->vel[i] -= p->vel[i]*frametime; + for(i = 0 ; i < 3 ; i++) + p->vel[i] -= p->vel[i] * frametime; p->vel[2] -= grav; break; case pt_blob: - for (i=0 ; i<3 ; i++) - p->vel[i] += p->vel[i]*dvel; + for(i = 0 ; i < 3 ; i++) + p->vel[i] += p->vel[i] * dvel; p->vel[2] -= grav; break; case pt_blob2: - for (i=0 ; i<2 ; i++) - p->vel[i] -= p->vel[i]*dvel; + for(i = 0 ; i < 2 ; i++) + p->vel[i] -= p->vel[i] * dvel; p->vel[2] -= grav; break; @@ -825,40 +826,40 @@ void CL_RunParticles (void) R_DrawParticles -- johnfitz -- moved all non-drawing code to CL_RunParticles =============== */ -void R_DrawParticles (void) +void R_DrawParticles(void) { - particle_t *p; - float scale; - vec3_t up, right, p_up, p_right, p_upright; //johnfitz -- p_ vectors - GLubyte color[4], *c; //johnfitz -- particle transparency - extern cvar_t r_particles; //johnfitz - //float alpha; //johnfitz -- particle transparency + particle_t *p; + float scale; + vec3_t up, right, p_up, p_right, p_upright; //johnfitz -- p_ vectors + GLubyte color[4], *c; //johnfitz -- particle transparency + extern cvar_t r_particles; //johnfitz + //float alpha; //johnfitz -- particle transparency - if (!r_particles.value) + if(!r_particles.value) return; //ericw -- avoid empty glBegin(),glEnd() pair below; causes issues on AMD - if (!active_particles) + if(!active_particles) return; - VectorScale (vup, 1.5, up); - VectorScale (vright, 1.5, right); + VectorScale(vup, 1.5, up); + VectorScale(vright, 1.5, right); GL_Bind(particletexture); - glEnable (GL_BLEND); + glEnable(GL_BLEND); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glDepthMask (GL_FALSE); //johnfitz -- fix for particle z-buffer bug + glDepthMask(GL_FALSE); //johnfitz -- fix for particle z-buffer bug - if (r_quadparticles.value) //johnitz -- quads save fillrate + if(r_quadparticles.value) //johnitz -- quads save fillrate { - glBegin (GL_QUADS); - for (p=active_particles ; p ; p=p->next) + glBegin(GL_QUADS); + for(p = active_particles ; p ; p = p->next) { // hack a scale up to keep particles from disapearing scale = (p->org[0] - r_origin[0]) * vpn[0] - + (p->org[1] - r_origin[1]) * vpn[1] - + (p->org[2] - r_origin[2]) * vpn[2]; - if (scale < 20) + + (p->org[1] - r_origin[1]) * vpn[1] + + (p->org[2] - r_origin[2]) * vpn[2]; + if(scale < 20) scale = 1 + 0.08; //johnfitz -- added .08 to be consistent else scale = 1 + scale * 0.004; @@ -877,35 +878,35 @@ void R_DrawParticles (void) glColor4ubv(color); //johnfitz - glTexCoord2f (0,0); - glVertex3fv (p->org); + glTexCoord2f(0, 0); + glVertex3fv(p->org); - glTexCoord2f (0.5,0); - VectorMA (p->org, scale, up, p_up); - glVertex3fv (p_up); + glTexCoord2f(0.5, 0); + VectorMA(p->org, scale, up, p_up); + glVertex3fv(p_up); - glTexCoord2f (0.5,0.5); - VectorMA (p_up, scale, right, p_upright); - glVertex3fv (p_upright); + glTexCoord2f(0.5, 0.5); + VectorMA(p_up, scale, right, p_upright); + glVertex3fv(p_upright); - glTexCoord2f (0,0.5); - VectorMA (p->org, scale, right, p_right); - glVertex3fv (p_right); + glTexCoord2f(0, 0.5); + VectorMA(p->org, scale, right, p_right); + glVertex3fv(p_right); rs_particles++; //johnfitz //FIXME: just use r_numparticles } - glEnd (); + glEnd(); } else //johnitz -- triangles save verts { - glBegin (GL_TRIANGLES); - for (p=active_particles ; p ; p=p->next) + glBegin(GL_TRIANGLES); + for(p = active_particles ; p ; p = p->next) { // hack a scale up to keep particles from disapearing scale = (p->org[0] - r_origin[0]) * vpn[0] - + (p->org[1] - r_origin[1]) * vpn[1] - + (p->org[2] - r_origin[2]) * vpn[2]; - if (scale < 20) + + (p->org[1] - r_origin[1]) * vpn[1] + + (p->org[2] - r_origin[2]) * vpn[2]; + if(scale < 20) scale = 1 + 0.08; //johnfitz -- added .08 to be consistent else scale = 1 + scale * 0.004; @@ -922,26 +923,26 @@ void R_DrawParticles (void) glColor4ubv(color); //johnfitz - glTexCoord2f (0,0); - glVertex3fv (p->org); + glTexCoord2f(0, 0); + glVertex3fv(p->org); - glTexCoord2f (1,0); - VectorMA (p->org, scale, up, p_up); - glVertex3fv (p_up); + glTexCoord2f(1, 0); + VectorMA(p->org, scale, up, p_up); + glVertex3fv(p_up); - glTexCoord2f (0,1); - VectorMA (p->org, scale, right, p_right); - glVertex3fv (p_right); + glTexCoord2f(0, 1); + VectorMA(p->org, scale, right, p_right); + glVertex3fv(p_right); rs_particles++; //johnfitz //FIXME: just use r_numparticles } - glEnd (); + glEnd(); } - glDepthMask (GL_TRUE); //johnfitz -- fix for particle z-buffer bug - glDisable (GL_BLEND); + glDepthMask(GL_TRUE); //johnfitz -- fix for particle z-buffer bug + glDisable(GL_BLEND); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glColor3f(1,1,1); + glColor3f(1, 1, 1); } @@ -950,30 +951,30 @@ void R_DrawParticles (void) R_DrawParticles_ShowTris -- johnfitz =============== */ -void R_DrawParticles_ShowTris (void) +void R_DrawParticles_ShowTris(void) { - particle_t *p; - float scale; - vec3_t up, right, p_up, p_right, p_upright; - extern cvar_t r_particles; + particle_t *p; + float scale; + vec3_t up, right, p_up, p_right, p_upright; + extern cvar_t r_particles; - if (!r_particles.value) + if(!r_particles.value) return; - VectorScale (vup, 1.5, up); - VectorScale (vright, 1.5, right); + VectorScale(vup, 1.5, up); + VectorScale(vright, 1.5, right); - if (r_quadparticles.value) + if(r_quadparticles.value) { - for (p=active_particles ; p ; p=p->next) + for(p = active_particles ; p ; p = p->next) { - glBegin (GL_TRIANGLE_FAN); + glBegin(GL_TRIANGLE_FAN); // hack a scale up to keep particles from disapearing scale = (p->org[0] - r_origin[0]) * vpn[0] - + (p->org[1] - r_origin[1]) * vpn[1] - + (p->org[2] - r_origin[2]) * vpn[2]; - if (scale < 20) + + (p->org[1] - r_origin[1]) * vpn[1] + + (p->org[2] - r_origin[2]) * vpn[2]; + if(scale < 20) scale = 1 + 0.08; //johnfitz -- added .08 to be consistent else scale = 1 + scale * 0.004; @@ -982,45 +983,45 @@ void R_DrawParticles_ShowTris (void) scale *= texturescalefactor; //compensate for apparent size of different particle textures - glVertex3fv (p->org); + glVertex3fv(p->org); - VectorMA (p->org, scale, up, p_up); - glVertex3fv (p_up); + VectorMA(p->org, scale, up, p_up); + glVertex3fv(p_up); - VectorMA (p_up, scale, right, p_upright); - glVertex3fv (p_upright); + VectorMA(p_up, scale, right, p_upright); + glVertex3fv(p_upright); - VectorMA (p->org, scale, right, p_right); - glVertex3fv (p_right); + VectorMA(p->org, scale, right, p_right); + glVertex3fv(p_right); - glEnd (); + glEnd(); } } else { - glBegin (GL_TRIANGLES); - for (p=active_particles ; p ; p=p->next) + glBegin(GL_TRIANGLES); + for(p = active_particles ; p ; p = p->next) { // hack a scale up to keep particles from disapearing scale = (p->org[0] - r_origin[0]) * vpn[0] - + (p->org[1] - r_origin[1]) * vpn[1] - + (p->org[2] - r_origin[2]) * vpn[2]; - if (scale < 20) + + (p->org[1] - r_origin[1]) * vpn[1] + + (p->org[2] - r_origin[2]) * vpn[2]; + if(scale < 20) scale = 1 + 0.08; //johnfitz -- added .08 to be consistent else scale = 1 + scale * 0.004; scale *= texturescalefactor; //compensate for apparent size of different particle textures - glVertex3fv (p->org); + glVertex3fv(p->org); - VectorMA (p->org, scale, up, p_up); - glVertex3fv (p_up); + VectorMA(p->org, scale, up, p_up); + glVertex3fv(p_up); - VectorMA (p->org, scale, right, p_right); - glVertex3fv (p_right); + VectorMA(p->org, scale, right, p_right); + glVertex3fv(p_right); } - glEnd (); + glEnd(); } } diff --git a/source/r_sprite.c b/source/r_sprite.c index edb2952..40f5b0e 100644 --- a/source/r_sprite.c +++ b/source/r_sprite.c @@ -28,24 +28,24 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. R_GetSpriteFrame ================ */ -mspriteframe_t *R_GetSpriteFrame (entity_t *currentent) +mspriteframe_t *R_GetSpriteFrame(entity_t *currentent) { - msprite_t *psprite; - mspritegroup_t *pspritegroup; - mspriteframe_t *pspriteframe; - int32_t i, numframes, frame; - float *pintervals, fullinterval, targettime, time; + msprite_t *psprite; + mspritegroup_t *pspritegroup; + mspriteframe_t *pspriteframe; + int32_t i, numframes, frame; + float *pintervals, fullinterval, targettime, time; psprite = (msprite_t *) currentent->model->cache.data; frame = currentent->frame; - if ((frame >= psprite->numframes) || (frame < 0)) + if((frame >= psprite->numframes) || (frame < 0)) { - Con_DPrintf ("R_DrawSprite: no such frame %" PRIi32 " for '%s'\n", frame, currentent->model->name); + Con_DPrintf("R_DrawSprite: no such frame %" PRIi32 " for '%s'\n", frame, currentent->model->name); frame = 0; } - if (psprite->frames[frame].type == SPR_SINGLE) + if(psprite->frames[frame].type == SPR_SINGLE) { pspriteframe = psprite->frames[frame].frameptr; } @@ -54,17 +54,17 @@ mspriteframe_t *R_GetSpriteFrame (entity_t *currentent) pspritegroup = (mspritegroup_t *)psprite->frames[frame].frameptr; pintervals = pspritegroup->intervals; numframes = pspritegroup->numframes; - fullinterval = pintervals[numframes-1]; + fullinterval = pintervals[numframes - 1]; time = cl.time + currentent->syncbase; - // when loading in Mod_LoadSpriteGroup, we guaranteed all interval values - // are positive, so we don't have to worry about division by 0 + // when loading in Mod_LoadSpriteGroup, we guaranteed all interval values + // are positive, so we don't have to worry about division by 0 targettime = time - ((int32_t)(time / fullinterval)) * fullinterval; - for (i=0 ; i<(numframes-1) ; i++) + for(i = 0 ; i < (numframes - 1) ; i++) { - if (pintervals[i] > targettime) + if(pintervals[i] > targettime) break; } @@ -79,17 +79,17 @@ mspriteframe_t *R_GetSpriteFrame (entity_t *currentent) R_DrawSpriteModel -- johnfitz -- rewritten: now supports all orientations ================= */ -void R_DrawSpriteModel (entity_t *e) +void R_DrawSpriteModel(entity_t *e) { - vec3_t point, v_forward, v_right, v_up; - msprite_t *psprite; - mspriteframe_t *frame; - float *s_up, *s_right; - float angle, sr, cr; + vec3_t point, v_forward, v_right, v_up; + msprite_t *psprite; + mspriteframe_t *frame; + float *s_up, *s_right; + float angle, sr, cr; //TODO: frustum cull it? - frame = R_GetSpriteFrame (e); + frame = R_GetSpriteFrame(e); psprite = (msprite_t *) currententity->model->cache.data; switch(psprite->type) @@ -119,7 +119,7 @@ void R_DrawSpriteModel (entity_t *e) s_right = vright; break; case SPR_ORIENTED: //pitch yaw roll are independent of camera - AngleVectors (currententity->angles, v_forward, v_right, v_up); + AngleVectors(currententity->angles, v_forward, v_right, v_up); s_up = v_up; s_right = v_right; break; @@ -141,42 +141,42 @@ void R_DrawSpriteModel (entity_t *e) } //johnfitz: offset decals - if (psprite->type == SPR_ORIENTED) - GL_PolygonOffset (OFFSET_DECAL); + if(psprite->type == SPR_ORIENTED) + GL_PolygonOffset(OFFSET_DECAL); - glColor3f (1,1,1); + glColor3f(1, 1, 1); GL_DisableMultitexture(); GL_Bind(frame->gltexture); - glEnable (GL_ALPHA_TEST); - glBegin (GL_TRIANGLE_FAN); //was GL_QUADS, but changed to support r_showtris + glEnable(GL_ALPHA_TEST); + glBegin(GL_TRIANGLE_FAN); //was GL_QUADS, but changed to support r_showtris - glTexCoord2f (0, frame->tmax); - VectorMA (e->origin, frame->down, s_up, point); - VectorMA (point, frame->left, s_right, point); - glVertex3fv (point); + glTexCoord2f(0, frame->tmax); + VectorMA(e->origin, frame->down, s_up, point); + VectorMA(point, frame->left, s_right, point); + glVertex3fv(point); - glTexCoord2f (0, 0); - VectorMA (e->origin, frame->up, s_up, point); - VectorMA (point, frame->left, s_right, point); - glVertex3fv (point); + glTexCoord2f(0, 0); + VectorMA(e->origin, frame->up, s_up, point); + VectorMA(point, frame->left, s_right, point); + glVertex3fv(point); - glTexCoord2f (frame->smax, 0); - VectorMA (e->origin, frame->up, s_up, point); - VectorMA (point, frame->right, s_right, point); - glVertex3fv (point); + glTexCoord2f(frame->smax, 0); + VectorMA(e->origin, frame->up, s_up, point); + VectorMA(point, frame->right, s_right, point); + glVertex3fv(point); - glTexCoord2f (frame->smax, frame->tmax); - VectorMA (e->origin, frame->down, s_up, point); - VectorMA (point, frame->right, s_right, point); - glVertex3fv (point); + glTexCoord2f(frame->smax, frame->tmax); + VectorMA(e->origin, frame->down, s_up, point); + VectorMA(point, frame->right, s_right, point); + glVertex3fv(point); - glEnd (); - glDisable (GL_ALPHA_TEST); + glEnd(); + glDisable(GL_ALPHA_TEST); //johnfitz: offset decals - if (psprite->type == SPR_ORIENTED) - GL_PolygonOffset (OFFSET_NONE); + if(psprite->type == SPR_ORIENTED) + GL_PolygonOffset(OFFSET_NONE); } diff --git a/source/r_world.c b/source/r_world.c index b9ae330..334782b 100644 --- a/source/r_world.c +++ b/source/r_world.c @@ -26,9 +26,9 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. extern cvar_t gl_fullbrights, r_drawflat, gl_overbright, r_oldwater, r_oldskyleaf, r_showtris; //johnfitz -extern glpoly_t *lightmap_polys[MAX_LIGHTMAPS]; +extern glpoly_t *lightmap_polys[MAX_LIGHTMAPS]; -byte *SV_FatPVS (vec3_t org, qmodel_t *worldmodel); +byte *SV_FatPVS(vec3_t org, qmodel_t *worldmodel); int32_t vis_changed; //if true, force pvs to be refreshed @@ -46,17 +46,17 @@ clears texture chains for all textures used by the given model, and also clears the lightmap chains ================ */ -void R_ClearTextureChains (qmodel_t *mod, texchain_t chain) +void R_ClearTextureChains(qmodel_t *mod, texchain_t chain) { int32_t i; // set all chains to null - for (i=0 ; inumtextures ; i++) - if (mod->textures[i]) + for(i = 0 ; i < mod->numtextures ; i++) + if(mod->textures[i]) mod->textures[i]->texturechains[chain] = NULL; // clear lightmap chains - memset (lightmap_polys, 0, sizeof(lightmap_polys)); + memset(lightmap_polys, 0, sizeof(lightmap_polys)); } /* @@ -64,7 +64,7 @@ void R_ClearTextureChains (qmodel_t *mod, texchain_t chain) R_ChainSurface -- ericw -- adds the given surface to its texture chain ================ */ -void R_ChainSurface (msurface_t *surf, texchain_t chain) +void R_ChainSurface(msurface_t *surf, texchain_t chain) { surf->texturechain = surf->texinfo->texture->texturechains[chain]; surf->texinfo->texture->texturechains[chain] = surf; @@ -75,41 +75,41 @@ void R_ChainSurface (msurface_t *surf, texchain_t chain) R_MarkSurfaces -- johnfitz -- mark surfaces based on PVS and rebuild texture chains =============== */ -void R_MarkSurfaces (void) +void R_MarkSurfaces(void) { - byte *vis; - mleaf_t *leaf; - mnode_t *node; - msurface_t *surf, **mark; - int32_t i, j; - bool nearwaterportal; + byte *vis; + mleaf_t *leaf; + mnode_t *node; + msurface_t *surf, **mark; + int32_t i, j; + bool nearwaterportal; // clear lightmap chains - memset (lightmap_polys, 0, sizeof(lightmap_polys)); + memset(lightmap_polys, 0, sizeof(lightmap_polys)); // check this leaf for water portals // TODO: loop through all water surfs and use distance to leaf cullbox nearwaterportal = false; - for (i=0, mark = r_viewleaf->firstmarksurface; i < r_viewleaf->nummarksurfaces; i++, mark++) - if ((*mark)->flags & SURF_DRAWTURB) + for(i = 0, mark = r_viewleaf->firstmarksurface; i < r_viewleaf->nummarksurfaces; i++, mark++) + if((*mark)->flags & SURF_DRAWTURB) nearwaterportal = true; // choose vis data - if (r_novis.value || r_viewleaf->contents == CONTENTS_SOLID || r_viewleaf->contents == CONTENTS_SKY) - vis = Mod_NoVisPVS (cl.worldmodel); - else if (nearwaterportal) - vis = SV_FatPVS (r_origin, cl.worldmodel); + if(r_novis.value || r_viewleaf->contents == CONTENTS_SOLID || r_viewleaf->contents == CONTENTS_SKY) + vis = Mod_NoVisPVS(cl.worldmodel); + else if(nearwaterportal) + vis = SV_FatPVS(r_origin, cl.worldmodel); else - vis = Mod_LeafPVS (r_viewleaf, cl.worldmodel); + vis = Mod_LeafPVS(r_viewleaf, cl.worldmodel); // if surface chains don't need regenerating, just add static entities and return - if (r_oldviewleaf == r_viewleaf && !vis_changed && !nearwaterportal) + if(r_oldviewleaf == r_viewleaf && !vis_changed && !nearwaterportal) { leaf = &cl.worldmodel->leafs[1]; - for (i=0 ; inumleafs ; i++, leaf++) - if (vis[i>>3] & (1<<(i&7))) - if (leaf->efrags) - R_StoreEfrags (&leaf->efrags); + for(i = 0 ; i < cl.worldmodel->numleafs ; i++, leaf++) + if(vis[i >> 3] & (1 << (i & 7))) + if(leaf->efrags) + R_StoreEfrags(&leaf->efrags); return; } @@ -119,23 +119,23 @@ void R_MarkSurfaces (void) // iterate through leaves, marking surfaces leaf = &cl.worldmodel->leafs[1]; - for (i=0 ; inumleafs ; i++, leaf++) + for(i = 0 ; i < cl.worldmodel->numleafs ; i++, leaf++) { - if (vis[i>>3] & (1<<(i&7))) + if(vis[i >> 3] & (1 << (i & 7))) { - if (r_oldskyleaf.value || leaf->contents != CONTENTS_SKY) - for (j=0, mark = leaf->firstmarksurface; jnummarksurfaces; j++, mark++) + if(r_oldskyleaf.value || leaf->contents != CONTENTS_SKY) + for(j = 0, mark = leaf->firstmarksurface; j < leaf->nummarksurfaces; j++, mark++) (*mark)->visframe = r_visframecount; // add static models - if (leaf->efrags) - R_StoreEfrags (&leaf->efrags); + if(leaf->efrags) + R_StoreEfrags(&leaf->efrags); } } // set all chains to null - for (i=0 ; inumtextures ; i++) - if (cl.worldmodel->textures[i]) + for(i = 0 ; i < cl.worldmodel->numtextures ; i++) + if(cl.worldmodel->textures[i]) cl.worldmodel->textures[i]->texturechains[chain_world] = NULL; // rebuild chains @@ -145,18 +145,18 @@ void R_MarkSurfaces (void) //need to do it this way if we want to work with tyrann's skip removal tool //becuase his tool doesn't actually remove the surfaces from the bsp surfaces lump //nor does it remove references to them in each leaf's marksurfaces list - for (i=0, node = cl.worldmodel->nodes ; inumnodes ; i++, node++) - for (j=0, surf=&cl.worldmodel->surfaces[node->firstsurface] ; jnumsurfaces ; j++, surf++) - if (surf->visframe == r_visframecount) + for(i = 0, node = cl.worldmodel->nodes ; i < cl.worldmodel->numnodes ; i++, node++) + for(j = 0, surf = &cl.worldmodel->surfaces[node->firstsurface] ; j < node->numsurfaces ; j++, surf++) + if(surf->visframe == r_visframecount) { R_ChainSurface(surf, chain_world); } #else //the old way surf = &cl.worldmodel->surfaces[cl.worldmodel->firstmodelsurface]; - for (i=0 ; inummodelsurfaces ; i++, surf++) + for(i = 0 ; i < cl.worldmodel->nummodelsurfaces ; i++, surf++) { - if (surf->visframe == r_visframecount) + if(surf->visframe == r_visframecount) { R_ChainSurface(surf, chain_world); } @@ -169,11 +169,11 @@ void R_MarkSurfaces (void) R_BackFaceCull -- johnfitz -- returns true if the surface is facing away from vieworg ================ */ -bool R_BackFaceCull (msurface_t *surf) +bool R_BackFaceCull(msurface_t *surf) { double dot; - switch (surf->plane->type) + switch(surf->plane->type) { case PLANE_X: dot = r_refdef.vieworg[0] - surf->plane->dist; @@ -185,11 +185,11 @@ bool R_BackFaceCull (msurface_t *surf) dot = r_refdef.vieworg[2] - surf->plane->dist; break; default: - dot = DotProduct (r_refdef.vieworg, surf->plane->normal) - surf->plane->dist; + dot = DotProduct(r_refdef.vieworg, surf->plane->normal) - surf->plane->dist; break; } - if ((dot < 0) ^ !!(surf->flags & SURF_PLANEBACK)) + if((dot < 0) ^ !!(surf->flags & SURF_PLANEBACK)) return true; return false; @@ -200,33 +200,33 @@ bool R_BackFaceCull (msurface_t *surf) R_CullSurfaces -- johnfitz ================ */ -void R_CullSurfaces (void) +void R_CullSurfaces(void) { msurface_t *s; int32_t i; texture_t *t; - if (!r_drawworld_cheatsafe) + if(!r_drawworld_cheatsafe) return; // ericw -- instead of testing (s->visframe == r_visframecount) on all world // surfaces, use the chained surfaces, which is exactly the same set of sufaces - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < cl.worldmodel->numtextures ; i++) { t = cl.worldmodel->textures[i]; - if (!t || !t->texturechains[chain_world]) + if(!t || !t->texturechains[chain_world]) continue; - for (s = t->texturechains[chain_world]; s; s = s->texturechain) + for(s = t->texturechains[chain_world]; s; s = s->texturechain) { - if (R_CullBox(s->mins, s->maxs) || R_BackFaceCull (s)) + if(R_CullBox(s->mins, s->maxs) || R_BackFaceCull(s)) s->culled = true; else { s->culled = false; rs_brushpolys++; //count wpolys here - if (s->texinfo->texture->warpimage) + if(s->texinfo->texture->warpimage) s->texinfo->texture->update_warp = true; } } @@ -241,26 +241,26 @@ ericw -- now always used at the start of R_DrawTextureChains for the mh dynamic lighting speedup ================ */ -void R_BuildLightmapChains (qmodel_t *model, texchain_t chain) +void R_BuildLightmapChains(qmodel_t *model, texchain_t chain) { texture_t *t; msurface_t *s; int32_t i; // clear lightmap chains (already done in r_marksurfaces, but clearing them here to be safe becuase of r_stereo) - memset (lightmap_polys, 0, sizeof(lightmap_polys)); + memset(lightmap_polys, 0, sizeof(lightmap_polys)); // now rebuild them - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t || !t->texturechains[chain]) + if(!t || !t->texturechains[chain]) continue; - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) - R_RenderDynamicLightmaps (s); + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) + R_RenderDynamicLightmaps(s); } } @@ -275,14 +275,14 @@ void R_BuildLightmapChains (qmodel_t *model, texchain_t chain) R_BeginTransparentDrawing -- ericw ============= */ -static void R_BeginTransparentDrawing (float entalpha) +static void R_BeginTransparentDrawing(float entalpha) { - if (entalpha < 1.0f) + if(entalpha < 1.0f) { - glDepthMask (GL_FALSE); - glEnable (GL_BLEND); - glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glColor4f (1,1,1,entalpha); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glColor4f(1, 1, 1, entalpha); } } @@ -291,14 +291,14 @@ static void R_BeginTransparentDrawing (float entalpha) R_EndTransparentDrawing -- ericw ============= */ -static void R_EndTransparentDrawing (float entalpha) +static void R_EndTransparentDrawing(float entalpha) { - if (entalpha < 1.0f) + if(entalpha < 1.0f) { - glDepthMask (GL_TRUE); - glDisable (GL_BLEND); - glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glColor3f (1, 1, 1); + glDepthMask(GL_TRUE); + glDisable(GL_BLEND); + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + glColor3f(1, 1, 1); } } @@ -307,34 +307,34 @@ static void R_EndTransparentDrawing (float entalpha) R_DrawTextureChains_ShowTris -- johnfitz ================ */ -void R_DrawTextureChains_ShowTris (qmodel_t *model, texchain_t chain) +void R_DrawTextureChains_ShowTris(qmodel_t *model, texchain_t chain) { - int32_t i; - msurface_t *s; - texture_t *t; - glpoly_t *p; + int32_t i; + msurface_t *s; + texture_t *t; + glpoly_t *p; - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t) + if(!t) continue; - if (r_oldwater.value && t->texturechains[chain] && (t->texturechains[chain]->flags & SURF_DRAWTURB)) + if(r_oldwater.value && t->texturechains[chain] && (t->texturechains[chain]->flags & SURF_DRAWTURB)) { - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) - for (p = s->polys->next; p; p = p->next) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) + for(p = s->polys->next; p; p = p->next) { - DrawGLTriangleFan (p); + DrawGLTriangleFan(p); } } else { - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - DrawGLTriangleFan (s->polys); + DrawGLTriangleFan(s->polys); } } } @@ -345,45 +345,45 @@ void R_DrawTextureChains_ShowTris (qmodel_t *model, texchain_t chain) R_DrawTextureChains_Drawflat -- johnfitz ================ */ -void R_DrawTextureChains_Drawflat (qmodel_t *model, texchain_t chain) +void R_DrawTextureChains_Drawflat(qmodel_t *model, texchain_t chain) { - int32_t i; - msurface_t *s; - texture_t *t; - glpoly_t *p; + int32_t i; + msurface_t *s; + texture_t *t; + glpoly_t *p; - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t) + if(!t) continue; - if (r_oldwater.value && t->texturechains[chain] && (t->texturechains[chain]->flags & SURF_DRAWTURB)) + if(r_oldwater.value && t->texturechains[chain] && (t->texturechains[chain]->flags & SURF_DRAWTURB)) { - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) - for (p = s->polys->next; p; p = p->next) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) + for(p = s->polys->next; p; p = p->next) { - srand((uint32_t) (uintptr_t) p); - glColor3f (rand()%256/255.0, rand()%256/255.0, rand()%256/255.0); - DrawGLPoly (p); + srand((uint32_t)(uintptr_t) p); + glColor3f(rand() % 256 / 255.0, rand() % 256 / 255.0, rand() % 256 / 255.0); + DrawGLPoly(p); rs_brushpasses++; } } else { - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - srand((uint32_t) (uintptr_t) s->polys); - glColor3f (rand()%256/255.0, rand()%256/255.0, rand()%256/255.0); - DrawGLPoly (s->polys); + srand((uint32_t)(uintptr_t) s->polys); + glColor3f(rand() % 256 / 255.0, rand() % 256 / 255.0, rand() % 256 / 255.0); + DrawGLPoly(s->polys); rs_brushpasses++; } } } - glColor3f (1,1,1); - srand ((int32_t) (cl.time * 1000)); + glColor3f(1, 1, 1); + srand((int32_t)(cl.time * 1000)); } /* @@ -391,32 +391,32 @@ void R_DrawTextureChains_Drawflat (qmodel_t *model, texchain_t chain) R_DrawTextureChains_Glow -- johnfitz ================ */ -void R_DrawTextureChains_Glow (qmodel_t *model, entity_t *ent, texchain_t chain) +void R_DrawTextureChains_Glow(qmodel_t *model, entity_t *ent, texchain_t chain) { - int32_t i; - msurface_t *s; - texture_t *t; - gltexture_t *glt; - bool bound; + int32_t i; + msurface_t *s; + texture_t *t; + gltexture_t *glt; + bool bound; - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t || !t->texturechains[chain] || !(glt = R_TextureAnimation(t, ent != NULL ? ent->frame : 0)->fullbright)) + if(!t || !t->texturechains[chain] || !(glt = R_TextureAnimation(t, ent != NULL ? ent->frame : 0)->fullbright)) continue; bound = false; - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - if (!bound) //only bind once we are sure we need this texture + if(!bound) //only bind once we are sure we need this texture { - GL_Bind (glt); + GL_Bind(glt); bound = true; } - DrawGLPoly (s->polys); + DrawGLPoly(s->polys); rs_brushpasses++; } } @@ -428,7 +428,7 @@ void R_DrawTextureChains_Glow (qmodel_t *model, entity_t *ent, texchain_t chain) // //============================================================================== -static uint32_t R_NumTriangleIndicesForSurf (msurface_t *s) +static uint32_t R_NumTriangleIndicesForSurf(msurface_t *s) { return 3 * (s->numedges - 2); } @@ -441,10 +441,10 @@ Writes out the triangle indices needed to draw s as a triangle list. The number of indices it will write is given by R_NumTriangleIndicesForSurf. ================ */ -static void R_TriangleIndicesForSurf (msurface_t *s, uint32_t *dest) +static void R_TriangleIndicesForSurf(msurface_t *s, uint32_t *dest) { int32_t i; - for (i=2; inumedges; i++) + for(i = 2; i < s->numedges; i++) { *dest++ = s->vbo_firstvert; *dest++ = s->vbo_firstvert + i - 1; @@ -462,7 +462,7 @@ static uint32_t num_vbo_indices; R_ClearBatch ================ */ -static void R_ClearBatch () +static void R_ClearBatch() { num_vbo_indices = 0; } @@ -474,11 +474,11 @@ R_FlushBatch Draw the current batch if non-empty and clears it, ready for more R_BatchSurface calls. ================ */ -static void R_FlushBatch () +static void R_FlushBatch() { - if (num_vbo_indices > 0) + if(num_vbo_indices > 0) { - glDrawElements (GL_TRIANGLES, num_vbo_indices, GL_UNSIGNED_INT, vbo_indices); + glDrawElements(GL_TRIANGLES, num_vbo_indices, GL_UNSIGNED_INT, vbo_indices); num_vbo_indices = 0; } } @@ -491,16 +491,16 @@ Add the surface to the current batch, or just draw it immediately if we're not using VBOs. ================ */ -static void R_BatchSurface (msurface_t *s) +static void R_BatchSurface(msurface_t *s) { int32_t num_surf_indices; - num_surf_indices = R_NumTriangleIndicesForSurf (s); + num_surf_indices = R_NumTriangleIndicesForSurf(s); - if (num_vbo_indices + num_surf_indices > MAX_BATCH_SIZE) + if(num_vbo_indices + num_surf_indices > MAX_BATCH_SIZE) R_FlushBatch(); - R_TriangleIndicesForSurf (s, &vbo_indices[num_vbo_indices]); + R_TriangleIndicesForSurf(s, &vbo_indices[num_vbo_indices]); num_vbo_indices += num_surf_indices; } @@ -509,51 +509,51 @@ static void R_BatchSurface (msurface_t *s) R_DrawTextureChains_Multitexture -- johnfitz ================ */ -void R_DrawTextureChains_Multitexture (qmodel_t *model, entity_t *ent, texchain_t chain) +void R_DrawTextureChains_Multitexture(qmodel_t *model, entity_t *ent, texchain_t chain) { - int32_t i, j; - msurface_t *s; - texture_t *t; - float *v; - bool bound; + int32_t i, j; + msurface_t *s; + texture_t *t; + float *v; + bool bound; - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t || !t->texturechains[chain] || t->texturechains[chain]->flags & (SURF_DRAWTILED | SURF_NOTEXTURE)) + if(!t || !t->texturechains[chain] || t->texturechains[chain]->flags & (SURF_DRAWTILED | SURF_NOTEXTURE)) continue; bound = false; - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - if (!bound) //only bind once we are sure we need this texture + if(!bound) //only bind once we are sure we need this texture { - GL_Bind ((R_TextureAnimation(t, ent != NULL ? ent->frame : 0))->gltexture); + GL_Bind((R_TextureAnimation(t, ent != NULL ? ent->frame : 0))->gltexture); - if (t->texturechains[chain]->flags & SURF_DRAWFENCE) - glEnable (GL_ALPHA_TEST); // Flip alpha test back on + if(t->texturechains[chain]->flags & SURF_DRAWFENCE) + glEnable(GL_ALPHA_TEST); // Flip alpha test back on GL_EnableMultitexture(); // selects TEXTURE1 bound = true; } - GL_Bind (lightmap_textures[s->lightmaptexturenum]); + GL_Bind(lightmap_textures[s->lightmaptexturenum]); glBegin(GL_POLYGON); v = s->polys->verts[0]; - for (j=0 ; jpolys->numverts ; j++, v+= VERTEXSIZE) + for(j = 0 ; j < s->polys->numverts ; j++, v += VERTEXSIZE) { - GL_MTexCoord2fFunc (GL_TEXTURE0_ARB, v[3], v[4]); - GL_MTexCoord2fFunc (GL_TEXTURE1_ARB, v[5], v[6]); - glVertex3fv (v); + GL_MTexCoord2fFunc(GL_TEXTURE0_ARB, v[3], v[4]); + GL_MTexCoord2fFunc(GL_TEXTURE1_ARB, v[5], v[6]); + glVertex3fv(v); } - glEnd (); + glEnd(); rs_brushpasses++; } GL_DisableMultitexture(); // selects TEXTURE0 - if (bound && t->texturechains[chain]->flags & SURF_DRAWFENCE) - glDisable (GL_ALPHA_TEST); // Flip alpha test back off + if(bound && t->texturechains[chain]->flags & SURF_DRAWFENCE) + glDisable(GL_ALPHA_TEST); // Flip alpha test back off } } @@ -564,31 +564,31 @@ R_DrawTextureChains_NoTexture -- johnfitz draws surfs whose textures were missing from the BSP ================ */ -void R_DrawTextureChains_NoTexture (qmodel_t *model, texchain_t chain) +void R_DrawTextureChains_NoTexture(qmodel_t *model, texchain_t chain) { - int32_t i; - msurface_t *s; - texture_t *t; - bool bound; + int32_t i; + msurface_t *s; + texture_t *t; + bool bound; - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t || !t->texturechains[chain] || !(t->texturechains[chain]->flags & SURF_NOTEXTURE)) + if(!t || !t->texturechains[chain] || !(t->texturechains[chain]->flags & SURF_NOTEXTURE)) continue; bound = false; - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - if (!bound) //only bind once we are sure we need this texture + if(!bound) //only bind once we are sure we need this texture { - GL_Bind (t->gltexture); + GL_Bind(t->gltexture); bound = true; } - DrawGLPoly (s->polys); + DrawGLPoly(s->polys); rs_brushpasses++; } } @@ -599,40 +599,40 @@ void R_DrawTextureChains_NoTexture (qmodel_t *model, texchain_t chain) R_DrawTextureChains_TextureOnly -- johnfitz ================ */ -void R_DrawTextureChains_TextureOnly (qmodel_t *model, entity_t *ent, texchain_t chain) +void R_DrawTextureChains_TextureOnly(qmodel_t *model, entity_t *ent, texchain_t chain) { - int32_t i; - msurface_t *s; - texture_t *t; - bool bound; + int32_t i; + msurface_t *s; + texture_t *t; + bool bound; - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t || !t->texturechains[chain] || t->texturechains[chain]->flags & (SURF_DRAWTURB | SURF_DRAWSKY)) + if(!t || !t->texturechains[chain] || t->texturechains[chain]->flags & (SURF_DRAWTURB | SURF_DRAWSKY)) continue; bound = false; - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - if (!bound) //only bind once we are sure we need this texture + if(!bound) //only bind once we are sure we need this texture { - GL_Bind ((R_TextureAnimation(t, ent != NULL ? ent->frame : 0))->gltexture); + GL_Bind((R_TextureAnimation(t, ent != NULL ? ent->frame : 0))->gltexture); - if (t->texturechains[chain]->flags & SURF_DRAWFENCE) - glEnable (GL_ALPHA_TEST); // Flip alpha test back on + if(t->texturechains[chain]->flags & SURF_DRAWFENCE) + glEnable(GL_ALPHA_TEST); // Flip alpha test back on bound = true; } - DrawGLPoly (s->polys); + DrawGLPoly(s->polys); rs_brushpasses++; } - if (bound && t->texturechains[chain]->flags & SURF_DRAWFENCE) - glDisable (GL_ALPHA_TEST); // Flip alpha test back off + if(bound && t->texturechains[chain]->flags & SURF_DRAWFENCE) + glDisable(GL_ALPHA_TEST); // Flip alpha test back off } } @@ -643,10 +643,10 @@ GL_WaterAlphaForEntitySurface -- ericw Returns the water alpha to use for the entity and surface combination. ================ */ -float GL_WaterAlphaForEntitySurface (entity_t *ent, msurface_t *s) +float GL_WaterAlphaForEntitySurface(entity_t *ent, msurface_t *s) { float entalpha; - if (ent == NULL || ent->alpha == ENTALPHA_DEFAULT) + if(ent == NULL || ent->alpha == ENTALPHA_DEFAULT) entalpha = GL_WaterAlphaForSurface(s); else entalpha = ENTALPHA_DECODE(ent->alpha); @@ -658,65 +658,65 @@ float GL_WaterAlphaForEntitySurface (entity_t *ent, msurface_t *s) R_DrawTextureChains_Water -- johnfitz ================ */ -void R_DrawTextureChains_Water (qmodel_t *model, entity_t *ent, texchain_t chain) +void R_DrawTextureChains_Water(qmodel_t *model, entity_t *ent, texchain_t chain) { - int32_t i; - msurface_t *s; - texture_t *t; - glpoly_t *p; - bool bound; + int32_t i; + msurface_t *s; + texture_t *t; + glpoly_t *p; + bool bound; float entalpha; - if (r_drawflat_cheatsafe || r_lightmap_cheatsafe) // ericw -- !r_drawworld_cheatsafe check moved to R_DrawWorld_Water () + if(r_drawflat_cheatsafe || r_lightmap_cheatsafe) // ericw -- !r_drawworld_cheatsafe check moved to R_DrawWorld_Water () return; - if (r_oldwater.value) + if(r_oldwater.value) { - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t || !t->texturechains[chain] || !(t->texturechains[chain]->flags & SURF_DRAWTURB)) + if(!t || !t->texturechains[chain] || !(t->texturechains[chain]->flags & SURF_DRAWTURB)) continue; bound = false; entalpha = 1.0f; - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - if (!bound) //only bind once we are sure we need this texture + if(!bound) //only bind once we are sure we need this texture { - entalpha = GL_WaterAlphaForEntitySurface (ent, s); - R_BeginTransparentDrawing (entalpha); - GL_Bind (t->gltexture); + entalpha = GL_WaterAlphaForEntitySurface(ent, s); + R_BeginTransparentDrawing(entalpha); + GL_Bind(t->gltexture); bound = true; } - for (p = s->polys->next; p; p = p->next) + for(p = s->polys->next; p; p = p->next) { - DrawWaterPoly (p); + DrawWaterPoly(p); rs_brushpasses++; } } - R_EndTransparentDrawing (entalpha); + R_EndTransparentDrawing(entalpha); } } else { - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t || !t->texturechains[chain] || !(t->texturechains[chain]->flags & SURF_DRAWTURB)) + if(!t || !t->texturechains[chain] || !(t->texturechains[chain]->flags & SURF_DRAWTURB)) continue; bound = false; entalpha = 1.0f; - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - if (!bound) //only bind once we are sure we need this texture + if(!bound) //only bind once we are sure we need this texture { - entalpha = GL_WaterAlphaForEntitySurface (ent, s); - R_BeginTransparentDrawing (entalpha); - GL_Bind (t->warpimage); + entalpha = GL_WaterAlphaForEntitySurface(ent, s); + R_BeginTransparentDrawing(entalpha); + GL_Bind(t->warpimage); - if (model != cl.worldmodel) + if(model != cl.worldmodel) { // ericw -- this is copied from R_DrawSequentialPoly. // If the poly is not part of the world we have to @@ -726,10 +726,10 @@ void R_DrawTextureChains_Water (qmodel_t *model, entity_t *ent, texchain_t chain bound = true; } - DrawGLPoly (s->polys); + DrawGLPoly(s->polys); rs_brushpasses++; } - R_EndTransparentDrawing (entalpha); + R_EndTransparentDrawing(entalpha); } } } @@ -739,28 +739,28 @@ void R_DrawTextureChains_Water (qmodel_t *model, entity_t *ent, texchain_t chain R_DrawTextureChains_White -- johnfitz -- draw sky and water as white polys when r_lightmap is 1 ================ */ -void R_DrawTextureChains_White (qmodel_t *model, texchain_t chain) +void R_DrawTextureChains_White(qmodel_t *model, texchain_t chain) { - int32_t i; - msurface_t *s; - texture_t *t; + int32_t i; + msurface_t *s; + texture_t *t; - glDisable (GL_TEXTURE_2D); - for (i=0 ; inumtextures ; i++) + glDisable(GL_TEXTURE_2D); + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t || !t->texturechains[chain] || !(t->texturechains[chain]->flags & SURF_DRAWTILED)) + if(!t || !t->texturechains[chain] || !(t->texturechains[chain]->flags & SURF_DRAWTILED)) continue; - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - DrawGLPoly (s->polys); + DrawGLPoly(s->polys); rs_brushpasses++; } } - glEnable (GL_TEXTURE_2D); + glEnable(GL_TEXTURE_2D); } /* @@ -768,28 +768,28 @@ void R_DrawTextureChains_White (qmodel_t *model, texchain_t chain) R_DrawLightmapChains -- johnfitz -- R_BlendLightmaps stripped down to almost nothing ================ */ -void R_DrawLightmapChains (void) +void R_DrawLightmapChains(void) { - int32_t i, j; - glpoly_t *p; - float *v; + int32_t i, j; + glpoly_t *p; + float *v; - for (i=0 ; ichain) + GL_Bind(lightmap_textures[i]); + for(p = lightmap_polys[i]; p; p = p->chain) { - glBegin (GL_POLYGON); + glBegin(GL_POLYGON); v = p->verts[0]; - for (j=0 ; jnumverts ; j++, v+= VERTEXSIZE) + for(j = 0 ; j < p->numverts ; j++, v += VERTEXSIZE) { - glTexCoord2f (v[5], v[6]); - glVertex3fv (v); + glTexCoord2f(v[5], v[6]); + glVertex3fv(v); } - glEnd (); + glEnd(); rs_brushpasses++; } } @@ -817,77 +817,78 @@ static GLuint alphaLoc; GLWorld_CreateShaders ============= */ -void GLWorld_CreateShaders (void) +void GLWorld_CreateShaders(void) { - const glsl_attrib_binding_t bindings[] = { + const glsl_attrib_binding_t bindings[] = + { { "Vert", vertAttrIndex }, { "TexCoords", texCoordsAttrIndex }, { "LMCoords", LMCoordsAttrIndex } }; const GLchar *vertSource = \ - "#version 110\n" - "\n" - "attribute vec3 Vert;\n" - "attribute vec2 TexCoords;\n" - "attribute vec2 LMCoords;\n" - "\n" - "varying float FogFragCoord;\n" - "\n" - "void main()\n" - "{\n" - " gl_TexCoord[0] = vec4(TexCoords, 0.0, 0.0);\n" - " gl_TexCoord[1] = vec4(LMCoords, 0.0, 0.0);\n" - " gl_Position = gl_ModelViewProjectionMatrix * vec4(Vert, 1.0);\n" - " FogFragCoord = gl_Position.w;\n" - "}\n"; + "#version 110\n" + "\n" + "attribute vec3 Vert;\n" + "attribute vec2 TexCoords;\n" + "attribute vec2 LMCoords;\n" + "\n" + "varying float FogFragCoord;\n" + "\n" + "void main()\n" + "{\n" + " gl_TexCoord[0] = vec4(TexCoords, 0.0, 0.0);\n" + " gl_TexCoord[1] = vec4(LMCoords, 0.0, 0.0);\n" + " gl_Position = gl_ModelViewProjectionMatrix * vec4(Vert, 1.0);\n" + " FogFragCoord = gl_Position.w;\n" + "}\n"; const GLchar *fragSource = \ - "#version 110\n" - "\n" - "uniform sampler2D Tex;\n" - "uniform sampler2D LMTex;\n" - "uniform sampler2D FullbrightTex;\n" - "uniform bool UseFullbrightTex;\n" - "uniform bool UseOverbright;\n" - "uniform bool UseAlphaTest;\n" - "uniform float Alpha;\n" - "\n" - "varying float FogFragCoord;\n" - "\n" - "void main()\n" - "{\n" - " vec4 result = texture2D(Tex, gl_TexCoord[0].xy);\n" - " if (UseAlphaTest && (result.a < 0.666))\n" - " discard;\n" - " result *= texture2D(LMTex, gl_TexCoord[1].xy);\n" - " if (UseOverbright)\n" - " result.rgb *= 2.0;\n" - " if (UseFullbrightTex)\n" - " result += texture2D(FullbrightTex, gl_TexCoord[0].xy);\n" - " result = clamp(result, 0.0, 1.0);\n" - " float fog = exp(-gl_Fog.density * gl_Fog.density * FogFragCoord * FogFragCoord);\n" - " fog = clamp(fog, 0.0, 1.0);\n" - " result = mix(gl_Fog.color, result, fog);\n" - " result.a = Alpha;\n" // FIXME: This will make almost transparent things cut holes though heavy fog - " gl_FragColor = result;\n" - "}\n"; + "#version 110\n" + "\n" + "uniform sampler2D Tex;\n" + "uniform sampler2D LMTex;\n" + "uniform sampler2D FullbrightTex;\n" + "uniform bool UseFullbrightTex;\n" + "uniform bool UseOverbright;\n" + "uniform bool UseAlphaTest;\n" + "uniform float Alpha;\n" + "\n" + "varying float FogFragCoord;\n" + "\n" + "void main()\n" + "{\n" + " vec4 result = texture2D(Tex, gl_TexCoord[0].xy);\n" + " if (UseAlphaTest && (result.a < 0.666))\n" + " discard;\n" + " result *= texture2D(LMTex, gl_TexCoord[1].xy);\n" + " if (UseOverbright)\n" + " result.rgb *= 2.0;\n" + " if (UseFullbrightTex)\n" + " result += texture2D(FullbrightTex, gl_TexCoord[0].xy);\n" + " result = clamp(result, 0.0, 1.0);\n" + " float fog = exp(-gl_Fog.density * gl_Fog.density * FogFragCoord * FogFragCoord);\n" + " fog = clamp(fog, 0.0, 1.0);\n" + " result = mix(gl_Fog.color, result, fog);\n" + " result.a = Alpha;\n" // FIXME: This will make almost transparent things cut holes though heavy fog + " gl_FragColor = result;\n" + "}\n"; - if (!gl_glsl_alias_able) + if(!gl_glsl_alias_able) return; - r_world_program = GL_CreateProgram (vertSource, fragSource, sizeof(bindings)/sizeof(bindings[0]), bindings); + r_world_program = GL_CreateProgram(vertSource, fragSource, sizeof(bindings) / sizeof(bindings[0]), bindings); - if (r_world_program != 0) + if(r_world_program != 0) { // get uniform locations - texLoc = GL_GetUniformLocation (&r_world_program, "Tex"); - LMTexLoc = GL_GetUniformLocation (&r_world_program, "LMTex"); - fullbrightTexLoc = GL_GetUniformLocation (&r_world_program, "FullbrightTex"); - useFullbrightTexLoc = GL_GetUniformLocation (&r_world_program, "UseFullbrightTex"); - useOverbrightLoc = GL_GetUniformLocation (&r_world_program, "UseOverbright"); - useAlphaTestLoc = GL_GetUniformLocation (&r_world_program, "UseAlphaTest"); - alphaLoc = GL_GetUniformLocation (&r_world_program, "Alpha"); + texLoc = GL_GetUniformLocation(&r_world_program, "Tex"); + LMTexLoc = GL_GetUniformLocation(&r_world_program, "LMTex"); + fullbrightTexLoc = GL_GetUniformLocation(&r_world_program, "FullbrightTex"); + useFullbrightTexLoc = GL_GetUniformLocation(&r_world_program, "UseFullbrightTex"); + useOverbrightLoc = GL_GetUniformLocation(&r_world_program, "UseOverbright"); + useAlphaTestLoc = GL_GetUniformLocation(&r_world_program, "UseAlphaTest"); + alphaLoc = GL_GetUniformLocation(&r_world_program, "Alpha"); } } @@ -901,114 +902,114 @@ Draw lightmapped surfaces with fulbrights in one pass, using VBO. Requires 3 TMUs, OpenGL 2.0 ================ */ -void R_DrawTextureChains_GLSL (qmodel_t *model, entity_t *ent, texchain_t chain) +void R_DrawTextureChains_GLSL(qmodel_t *model, entity_t *ent, texchain_t chain) { - int32_t i; - msurface_t *s; - texture_t *t; - bool bound; - int32_t lastlightmap; - gltexture_t *fullbright = NULL; - float entalpha; + int32_t i; + msurface_t *s; + texture_t *t; + bool bound; + int32_t lastlightmap; + gltexture_t *fullbright = NULL; + float entalpha; entalpha = (ent != NULL) ? ENTALPHA_DECODE(ent->alpha) : 1.0f; // enable blending / disable depth writes - if (entalpha < 1) + if(entalpha < 1) { - glDepthMask (GL_FALSE); - glEnable (GL_BLEND); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); } - GL_UseProgramFunc (r_world_program); + GL_UseProgramFunc(r_world_program); // Bind the buffers - GL_BindBuffer (GL_ARRAY_BUFFER, gl_bmodel_vbo); - GL_BindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0); // indices come from client memory! + GL_BindBuffer(GL_ARRAY_BUFFER, gl_bmodel_vbo); + GL_BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // indices come from client memory! - GL_EnableVertexAttribArrayFunc (vertAttrIndex); - GL_EnableVertexAttribArrayFunc (texCoordsAttrIndex); - GL_EnableVertexAttribArrayFunc (LMCoordsAttrIndex); + GL_EnableVertexAttribArrayFunc(vertAttrIndex); + GL_EnableVertexAttribArrayFunc(texCoordsAttrIndex); + GL_EnableVertexAttribArrayFunc(LMCoordsAttrIndex); - GL_VertexAttribPointerFunc (vertAttrIndex, 3, GL_FLOAT, GL_FALSE, VERTEXSIZE * sizeof(float), &((float *)NULL)[0]); - GL_VertexAttribPointerFunc (texCoordsAttrIndex, 2, GL_FLOAT, GL_FALSE, VERTEXSIZE * sizeof(float), &((float *)NULL)[3]); - GL_VertexAttribPointerFunc (LMCoordsAttrIndex, 2, GL_FLOAT, GL_FALSE, VERTEXSIZE * sizeof(float), &((float *)NULL)[3 + 2]); + GL_VertexAttribPointerFunc(vertAttrIndex, 3, GL_FLOAT, GL_FALSE, VERTEXSIZE * sizeof(float), &((float *)NULL)[0]); + GL_VertexAttribPointerFunc(texCoordsAttrIndex, 2, GL_FLOAT, GL_FALSE, VERTEXSIZE * sizeof(float), &((float *)NULL)[3]); + GL_VertexAttribPointerFunc(LMCoordsAttrIndex, 2, GL_FLOAT, GL_FALSE, VERTEXSIZE * sizeof(float), &((float *)NULL)[3 + 2]); // set uniforms - GL_Uniform1iFunc (texLoc, 0); - GL_Uniform1iFunc (LMTexLoc, 1); - GL_Uniform1iFunc (fullbrightTexLoc, 2); - GL_Uniform1iFunc (useFullbrightTexLoc, 0); - GL_Uniform1iFunc (useOverbrightLoc, (int32_t)gl_overbright.value); - GL_Uniform1iFunc (useAlphaTestLoc, 0); - GL_Uniform1fFunc (alphaLoc, entalpha); + GL_Uniform1iFunc(texLoc, 0); + GL_Uniform1iFunc(LMTexLoc, 1); + GL_Uniform1iFunc(fullbrightTexLoc, 2); + GL_Uniform1iFunc(useFullbrightTexLoc, 0); + GL_Uniform1iFunc(useOverbrightLoc, (int32_t)gl_overbright.value); + GL_Uniform1iFunc(useAlphaTestLoc, 0); + GL_Uniform1fFunc(alphaLoc, entalpha); - for (i=0 ; inumtextures ; i++) + for(i = 0 ; i < model->numtextures ; i++) { t = model->textures[i]; - if (!t || !t->texturechains[chain] || t->texturechains[chain]->flags & (SURF_DRAWTILED | SURF_NOTEXTURE)) + if(!t || !t->texturechains[chain] || t->texturechains[chain]->flags & (SURF_DRAWTILED | SURF_NOTEXTURE)) continue; - // Enable/disable TMU 2 (fullbrights) - // FIXME: Move below to where we bind GL_TEXTURE0 - if (gl_fullbrights.value && (fullbright = R_TextureAnimation(t, ent != NULL ? ent->frame : 0)->fullbright)) + // Enable/disable TMU 2 (fullbrights) + // FIXME: Move below to where we bind GL_TEXTURE0 + if(gl_fullbrights.value && (fullbright = R_TextureAnimation(t, ent != NULL ? ent->frame : 0)->fullbright)) { - GL_SelectTexture (GL_TEXTURE2); - GL_Bind (fullbright); - GL_Uniform1iFunc (useFullbrightTexLoc, 1); + GL_SelectTexture(GL_TEXTURE2); + GL_Bind(fullbright); + GL_Uniform1iFunc(useFullbrightTexLoc, 1); } else - GL_Uniform1iFunc (useFullbrightTexLoc, 0); + GL_Uniform1iFunc(useFullbrightTexLoc, 0); - R_ClearBatch (); + R_ClearBatch(); bound = false; lastlightmap = 0; // avoid compiler warning - for (s = t->texturechains[chain]; s; s = s->texturechain) - if (!s->culled) + for(s = t->texturechains[chain]; s; s = s->texturechain) + if(!s->culled) { - if (!bound) //only bind once we are sure we need this texture + if(!bound) //only bind once we are sure we need this texture { - GL_SelectTexture (GL_TEXTURE0); - GL_Bind ((R_TextureAnimation(t, ent != NULL ? ent->frame : 0))->gltexture); + GL_SelectTexture(GL_TEXTURE0); + GL_Bind((R_TextureAnimation(t, ent != NULL ? ent->frame : 0))->gltexture); - if (t->texturechains[chain]->flags & SURF_DRAWFENCE) - GL_Uniform1iFunc (useAlphaTestLoc, 1); // Flip alpha test back on + if(t->texturechains[chain]->flags & SURF_DRAWFENCE) + GL_Uniform1iFunc(useAlphaTestLoc, 1); // Flip alpha test back on bound = true; lastlightmap = s->lightmaptexturenum; } - if (s->lightmaptexturenum != lastlightmap) - R_FlushBatch (); + if(s->lightmaptexturenum != lastlightmap) + R_FlushBatch(); - GL_SelectTexture (GL_TEXTURE1); - GL_Bind (lightmap_textures[s->lightmaptexturenum]); + GL_SelectTexture(GL_TEXTURE1); + GL_Bind(lightmap_textures[s->lightmaptexturenum]); lastlightmap = s->lightmaptexturenum; - R_BatchSurface (s); + R_BatchSurface(s); rs_brushpasses++; } - R_FlushBatch (); + R_FlushBatch(); - if (bound && t->texturechains[chain]->flags & SURF_DRAWFENCE) - GL_Uniform1iFunc (useAlphaTestLoc, 0); // Flip alpha test back off + if(bound && t->texturechains[chain]->flags & SURF_DRAWFENCE) + GL_Uniform1iFunc(useAlphaTestLoc, 0); // Flip alpha test back off } // clean up - GL_DisableVertexAttribArrayFunc (vertAttrIndex); - GL_DisableVertexAttribArrayFunc (texCoordsAttrIndex); - GL_DisableVertexAttribArrayFunc (LMCoordsAttrIndex); + GL_DisableVertexAttribArrayFunc(vertAttrIndex); + GL_DisableVertexAttribArrayFunc(texCoordsAttrIndex); + GL_DisableVertexAttribArrayFunc(LMCoordsAttrIndex); - GL_UseProgramFunc (0); - GL_SelectTexture (GL_TEXTURE0); + GL_UseProgramFunc(0); + GL_SelectTexture(GL_TEXTURE0); - if (entalpha < 1) + if(entalpha < 1) { - glDepthMask (GL_TRUE); - glDisable (GL_BLEND); + glDepthMask(GL_TRUE); + glDisable(GL_BLEND); } } @@ -1017,11 +1018,11 @@ void R_DrawTextureChains_GLSL (qmodel_t *model, entity_t *ent, texchain_t chain) R_DrawWorld -- johnfitz -- rewritten ============= */ -void R_DrawTextureChains (qmodel_t *model, entity_t *ent, texchain_t chain) +void R_DrawTextureChains(qmodel_t *model, entity_t *ent, texchain_t chain) { float entalpha; - if (ent != NULL) + if(ent != NULL) entalpha = ENTALPHA_DECODE(ent->alpha); else entalpha = 1; @@ -1031,166 +1032,166 @@ void R_DrawTextureChains (qmodel_t *model, entity_t *ent, texchain_t chain) // this also chains surfaces by lightmap which is used by r_lightmap 1. // the previous implementation of the speedup uploaded lightmaps one frame // late which was visible under some conditions, this method avoids that. - R_BuildLightmapChains (model, chain); - R_UploadLightmaps (); + R_BuildLightmapChains(model, chain); + R_UploadLightmaps(); - if (r_drawflat_cheatsafe) + if(r_drawflat_cheatsafe) { - glDisable (GL_TEXTURE_2D); - R_DrawTextureChains_Drawflat (model, chain); - glEnable (GL_TEXTURE_2D); + glDisable(GL_TEXTURE_2D); + R_DrawTextureChains_Drawflat(model, chain); + glEnable(GL_TEXTURE_2D); return; } - if (r_fullbright_cheatsafe) + if(r_fullbright_cheatsafe) { - R_BeginTransparentDrawing (entalpha); - R_DrawTextureChains_TextureOnly (model, ent, chain); - R_EndTransparentDrawing (entalpha); + R_BeginTransparentDrawing(entalpha); + R_DrawTextureChains_TextureOnly(model, ent, chain); + R_EndTransparentDrawing(entalpha); goto fullbrights; } - if (r_lightmap_cheatsafe) + if(r_lightmap_cheatsafe) { - if (!gl_overbright.value) + if(!gl_overbright.value) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glColor3f(0.5, 0.5, 0.5); } - R_DrawLightmapChains (); - if (!gl_overbright.value) + R_DrawLightmapChains(); + if(!gl_overbright.value) { - glColor3f(1,1,1); + glColor3f(1, 1, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } - R_DrawTextureChains_White (model, chain); + R_DrawTextureChains_White(model, chain); return; } - R_BeginTransparentDrawing (entalpha); + R_BeginTransparentDrawing(entalpha); - R_DrawTextureChains_NoTexture (model, chain); + R_DrawTextureChains_NoTexture(model, chain); // OpenGL 2 fast path - if (r_world_program != 0) + if(r_world_program != 0) { - R_EndTransparentDrawing (entalpha); + R_EndTransparentDrawing(entalpha); - R_DrawTextureChains_GLSL (model, ent, chain); + R_DrawTextureChains_GLSL(model, ent, chain); return; } - if (gl_overbright.value) + if(gl_overbright.value) { - if (gl_texture_env_combine && gl_mtexable) //case 1: texture and lightmap in one pass, overbright using texture combiners + if(gl_texture_env_combine && gl_mtexable) //case 1: texture and lightmap in one pass, overbright using texture combiners { - GL_EnableMultitexture (); + GL_EnableMultitexture(); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_EXT, GL_MODULATE); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_PREVIOUS_EXT); glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_TEXTURE); glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 2.0f); - GL_DisableMultitexture (); - R_DrawTextureChains_Multitexture (model, ent, chain); - GL_EnableMultitexture (); + GL_DisableMultitexture(); + R_DrawTextureChains_Multitexture(model, ent, chain); + GL_EnableMultitexture(); glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_EXT, 1.0f); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - GL_DisableMultitexture (); + GL_DisableMultitexture(); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } - else if (entalpha < 1) //case 2: can't do multipass if entity has alpha, so just draw the texture + else if(entalpha < 1) //case 2: can't do multipass if entity has alpha, so just draw the texture { - R_DrawTextureChains_TextureOnly (model, ent, chain); + R_DrawTextureChains_TextureOnly(model, ent, chain); } else //case 3: texture in one pass, lightmap in second pass using 2x modulation blend func, fog in third pass { //to make fog work with multipass lightmapping, need to do one pass //with no fog, one modulate pass with black fog, and one additive //pass with black geometry and normal fog - Fog_DisableGFog (); - R_DrawTextureChains_TextureOnly (model, ent, chain); - Fog_EnableGFog (); - glDepthMask (GL_FALSE); - glEnable (GL_BLEND); - glBlendFunc (GL_DST_COLOR, GL_SRC_COLOR); //2x modulate - Fog_StartAdditive (); - R_DrawLightmapChains (); - Fog_StopAdditive (); - if (Fog_GetDensity() > 0) + Fog_DisableGFog(); + R_DrawTextureChains_TextureOnly(model, ent, chain); + Fog_EnableGFog(); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); + glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); //2x modulate + Fog_StartAdditive(); + R_DrawLightmapChains(); + Fog_StopAdditive(); + if(Fog_GetDensity() > 0) { glBlendFunc(GL_ONE, GL_ONE); //add glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glColor3f(0,0,0); - R_DrawTextureChains_TextureOnly (model, ent, chain); - glColor3f(1,1,1); + glColor3f(0, 0, 0); + R_DrawTextureChains_TextureOnly(model, ent, chain); + glColor3f(1, 1, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable (GL_BLEND); - glDepthMask (GL_TRUE); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_BLEND); + glDepthMask(GL_TRUE); } } else { - if (gl_mtexable) //case 4: texture and lightmap in one pass, regular modulation + if(gl_mtexable) //case 4: texture and lightmap in one pass, regular modulation { - GL_EnableMultitexture (); + GL_EnableMultitexture(); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - GL_DisableMultitexture (); - R_DrawTextureChains_Multitexture (model, ent, chain); + GL_DisableMultitexture(); + R_DrawTextureChains_Multitexture(model, ent, chain); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } - else if (entalpha < 1) //case 5: can't do multipass if entity has alpha, so just draw the texture + else if(entalpha < 1) //case 5: can't do multipass if entity has alpha, so just draw the texture { - R_DrawTextureChains_TextureOnly (model, ent, chain); + R_DrawTextureChains_TextureOnly(model, ent, chain); } else //case 6: texture in one pass, lightmap in a second pass, fog in third pass { //to make fog work with multipass lightmapping, need to do one pass //with no fog, one modulate pass with black fog, and one additive //pass with black geometry and normal fog - Fog_DisableGFog (); - R_DrawTextureChains_TextureOnly (model, ent, chain); - Fog_EnableGFog (); - glDepthMask (GL_FALSE); - glEnable (GL_BLEND); + Fog_DisableGFog(); + R_DrawTextureChains_TextureOnly(model, ent, chain); + Fog_EnableGFog(); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); glBlendFunc(GL_ZERO, GL_SRC_COLOR); //modulate - Fog_StartAdditive (); - R_DrawLightmapChains (); - Fog_StopAdditive (); - if (Fog_GetDensity() > 0) + Fog_StartAdditive(); + R_DrawLightmapChains(); + Fog_StopAdditive(); + if(Fog_GetDensity() > 0) { glBlendFunc(GL_ONE, GL_ONE); //add glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glColor3f(0,0,0); - R_DrawTextureChains_TextureOnly (model, ent, chain); - glColor3f(1,1,1); + glColor3f(0, 0, 0); + R_DrawTextureChains_TextureOnly(model, ent, chain); + glColor3f(1, 1, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable (GL_BLEND); - glDepthMask (GL_TRUE); + glDisable(GL_BLEND); + glDepthMask(GL_TRUE); } } - R_EndTransparentDrawing (entalpha); + R_EndTransparentDrawing(entalpha); fullbrights: - if (gl_fullbrights.value) + if(gl_fullbrights.value) { - glDepthMask (GL_FALSE); - glEnable (GL_BLEND); - glBlendFunc (GL_ONE, GL_ONE); - glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glColor3f (entalpha, entalpha, entalpha); - Fog_StartAdditive (); - R_DrawTextureChains_Glow (model, ent, chain); - Fog_StopAdditive (); - glColor3f (1, 1, 1); - glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable (GL_BLEND); - glDepthMask (GL_TRUE); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE); + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glColor3f(entalpha, entalpha, entalpha); + Fog_StartAdditive(); + R_DrawTextureChains_Glow(model, ent, chain); + Fog_StopAdditive(); + glColor3f(1, 1, 1); + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_BLEND); + glDepthMask(GL_TRUE); } } @@ -1199,12 +1200,12 @@ fullbrights: R_DrawWorld -- ericw -- moved from R_DrawTextureChains, which is no longer specific to the world. ============= */ -void R_DrawWorld (void) +void R_DrawWorld(void) { - if (!r_drawworld_cheatsafe) + if(!r_drawworld_cheatsafe) return; - R_DrawTextureChains (cl.worldmodel, NULL, chain_world); + R_DrawTextureChains(cl.worldmodel, NULL, chain_world); } /* @@ -1212,12 +1213,12 @@ void R_DrawWorld (void) R_DrawWorld_Water -- ericw -- moved from R_DrawTextureChains_Water, which is no longer specific to the world. ============= */ -void R_DrawWorld_Water (void) +void R_DrawWorld_Water(void) { - if (!r_drawworld_cheatsafe) + if(!r_drawworld_cheatsafe) return; - R_DrawTextureChains_Water (cl.worldmodel, NULL, chain_world); + R_DrawTextureChains_Water(cl.worldmodel, NULL, chain_world); } /* @@ -1225,10 +1226,10 @@ void R_DrawWorld_Water (void) R_DrawWorld_ShowTris -- ericw -- moved from R_DrawTextureChains_ShowTris, which is no longer specific to the world. ============= */ -void R_DrawWorld_ShowTris (void) +void R_DrawWorld_ShowTris(void) { - if (!r_drawworld_cheatsafe) + if(!r_drawworld_cheatsafe) return; - R_DrawTextureChains_ShowTris (cl.worldmodel, chain_world); + R_DrawTextureChains_ShowTris(cl.worldmodel, chain_world); } diff --git a/source/render.h b/source/render.h index f11bd88..2d960ce 100644 --- a/source/render.h +++ b/source/render.h @@ -25,154 +25,154 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // refresh.h -- public interface to refresh functions -#define MAXCLIPPLANES 11 +#define MAXCLIPPLANES 11 -#define TOP_RANGE 16 // soldier uniform colors -#define BOTTOM_RANGE 96 +#define TOP_RANGE 16 // soldier uniform colors +#define BOTTOM_RANGE 96 //============================================================================= typedef struct efrag_s { - struct efrag_s *leafnext; - struct entity_s *entity; + struct efrag_s *leafnext; + struct entity_s *entity; } efrag_t; //johnfitz -- for lerping -#define LERP_MOVESTEP (1<<0) //this is a MOVETYPE_STEP entity, enable movement lerp -#define LERP_RESETANIM (1<<1) //disable anim lerping until next anim frame -#define LERP_RESETANIM2 (1<<2) //set this and previous flag to disable anim lerping for two anim frames -#define LERP_RESETMOVE (1<<3) //disable movement lerping until next origin/angles change -#define LERP_FINISH (1<<4) //use lerpfinish time from server update instead of assuming interval of 0.1 +#define LERP_MOVESTEP (1<<0) //this is a MOVETYPE_STEP entity, enable movement lerp +#define LERP_RESETANIM (1<<1) //disable anim lerping until next anim frame +#define LERP_RESETANIM2 (1<<2) //set this and previous flag to disable anim lerping for two anim frames +#define LERP_RESETMOVE (1<<3) //disable movement lerping until next origin/angles change +#define LERP_FINISH (1<<4) //use lerpfinish time from server update instead of assuming interval of 0.1 //johnfitz typedef struct entity_s { - bool forcelink; // model changed + bool forcelink; // model changed - int32_t update_type; + int32_t update_type; - entity_state_t baseline; // to fill in defaults in updates + entity_state_t baseline; // to fill in defaults in updates - double msgtime; // time of last update - vec3_t msg_origins[2]; // last two updates (0 is newest) - vec3_t origin; - vec3_t msg_angles[2]; // last two updates (0 is newest) - vec3_t angles; - struct qmodel_s *model; // NULL = no model - struct efrag_s *efrag; // linked list of efrags - int32_t frame; - float syncbase; // for client-side animations - byte *colormap; - int32_t effects; // light, particles, etc - int32_t skinnum; // for Alias models - int32_t visframe; // last frame this entity was - // found in an active leaf + double msgtime; // time of last update + vec3_t msg_origins[2]; // last two updates (0 is newest) + vec3_t origin; + vec3_t msg_angles[2]; // last two updates (0 is newest) + vec3_t angles; + struct qmodel_s *model; // NULL = no model + struct efrag_s *efrag; // linked list of efrags + int32_t frame; + float syncbase; // for client-side animations + byte *colormap; + int32_t effects; // light, particles, etc + int32_t skinnum; // for Alias models + int32_t visframe; // last frame this entity was + // found in an active leaf - int32_t dlightframe; // dynamic lighting - int32_t dlightbits; + int32_t dlightframe; // dynamic lighting + int32_t dlightbits; // FIXME: could turn these into a union - int32_t trivial_accept; - struct mnode_s *topnode; // for bmodels, first world node - // that splits bmodel, or NULL if - // not split + int32_t trivial_accept; + struct mnode_s *topnode; // for bmodels, first world node + // that splits bmodel, or NULL if + // not split - byte alpha; //johnfitz -- alpha - byte lerpflags; //johnfitz -- lerping - float lerpstart; //johnfitz -- animation lerping - float lerptime; //johnfitz -- animation lerping - float lerpfinish; //johnfitz -- lerping -- server sent us a more accurate interval, use it instead of 0.1 - int16_t previouspose; //johnfitz -- animation lerping - int16_t currentpose; //johnfitz -- animation lerping -// int16_t futurepose; //johnfitz -- animation lerping - float movelerpstart; //johnfitz -- transform lerping - vec3_t previousorigin; //johnfitz -- transform lerping - vec3_t currentorigin; //johnfitz -- transform lerping - vec3_t previousangles; //johnfitz -- transform lerping - vec3_t currentangles; //johnfitz -- transform lerping + byte alpha; //johnfitz -- alpha + byte lerpflags; //johnfitz -- lerping + float lerpstart; //johnfitz -- animation lerping + float lerptime; //johnfitz -- animation lerping + float lerpfinish; //johnfitz -- lerping -- server sent us a more accurate interval, use it instead of 0.1 + int16_t previouspose; //johnfitz -- animation lerping + int16_t currentpose; //johnfitz -- animation lerping +// int16_t futurepose; //johnfitz -- animation lerping + float movelerpstart; //johnfitz -- transform lerping + vec3_t previousorigin; //johnfitz -- transform lerping + vec3_t currentorigin; //johnfitz -- transform lerping + vec3_t previousangles; //johnfitz -- transform lerping + vec3_t currentangles; //johnfitz -- transform lerping } entity_t; // !!! if this is changed, it must be changed in asm_draw.h too !!! typedef struct { - vrect_t vrect; // subwindow in video for refresh - // FIXME: not need vrect next field here? - vrect_t aliasvrect; // scaled Alias version - int32_t vrectright, vrectbottom; // right & bottom screen coords - int32_t aliasvrectright, aliasvrectbottom; // scaled Alias versions - float vrectrightedge; // rightmost right edge we care about, - // for use in edge list - float fvrectx, fvrecty; // for floating-point compares - float fvrectx_adj, fvrecty_adj; // left and top edges, for clamping - int32_t vrect_x_adj_shift20; // (vrect.x + 0.5 - epsilon) << 20 - int32_t vrectright_adj_shift20; // (vrectright + 0.5 - epsilon) << 20 - float fvrectright_adj, fvrectbottom_adj; - // right and bottom edges, for clamping - float fvrectright; // rightmost edge, for Alias clamping - float fvrectbottom; // bottommost edge, for Alias clamping - float horizontalFieldOfView; // at Z = 1.0, this many X is visible - // 2.0 = 90 degrees - float xOrigin; // should probably allways be 0.5 - float yOrigin; // between be around 0.3 to 0.5 + vrect_t vrect; // subwindow in video for refresh + // FIXME: not need vrect next field here? + vrect_t aliasvrect; // scaled Alias version + int32_t vrectright, vrectbottom; // right & bottom screen coords + int32_t aliasvrectright, aliasvrectbottom; // scaled Alias versions + float vrectrightedge; // rightmost right edge we care about, + // for use in edge list + float fvrectx, fvrecty; // for floating-point compares + float fvrectx_adj, fvrecty_adj; // left and top edges, for clamping + int32_t vrect_x_adj_shift20; // (vrect.x + 0.5 - epsilon) << 20 + int32_t vrectright_adj_shift20; // (vrectright + 0.5 - epsilon) << 20 + float fvrectright_adj, fvrectbottom_adj; + // right and bottom edges, for clamping + float fvrectright; // rightmost edge, for Alias clamping + float fvrectbottom; // bottommost edge, for Alias clamping + float horizontalFieldOfView; // at Z = 1.0, this many X is visible + // 2.0 = 90 degrees + float xOrigin; // should probably allways be 0.5 + float yOrigin; // between be around 0.3 to 0.5 - vec3_t vieworg; - vec3_t viewangles; + vec3_t vieworg; + vec3_t viewangles; - float fov_x, fov_y; + float fov_x, fov_y; - int32_t ambientlight; + int32_t ambientlight; } refdef_t; // // refresh // -extern int32_t reinit_surfcache; +extern int32_t reinit_surfcache; -extern refdef_t r_refdef; -extern vec3_t r_origin, vpn, vright, vup; +extern refdef_t r_refdef; +extern vec3_t r_origin, vpn, vright, vup; -void R_Init (void); -void R_InitTextures (void); -void R_InitEfrags (void); -void R_RenderView (void); // must set r_refdef first -void R_ViewChanged (vrect_t *pvrect, int32_t lineadj, float aspect); - // called whenever r_refdef or vid change -//void R_InitSky (struct texture_s *mt); // called at level load +void R_Init(void); +void R_InitTextures(void); +void R_InitEfrags(void); +void R_RenderView(void); // must set r_refdef first +void R_ViewChanged(vrect_t *pvrect, int32_t lineadj, float aspect); +// called whenever r_refdef or vid change +//void R_InitSky (struct texture_s *mt); // called at level load -void R_CheckEfrags (void); //johnfitz -void R_AddEfrags (entity_t *ent); +void R_CheckEfrags(void); //johnfitz +void R_AddEfrags(entity_t *ent); -void R_NewMap (void); +void R_NewMap(void); -void R_ParseParticleEffect (void); -void R_RunParticleEffect (vec3_t org, vec3_t dir, int32_t color, int32_t count); -void R_RocketTrail (vec3_t start, vec3_t end, int32_t type); -void R_EntityParticles (entity_t *ent); -void R_BlobExplosion (vec3_t org); -void R_ParticleExplosion (vec3_t org); -void R_ParticleExplosion2 (vec3_t org, int32_t colorStart, int32_t colorLength); -void R_LavaSplash (vec3_t org); -void R_TeleportSplash (vec3_t org); +void R_ParseParticleEffect(void); +void R_RunParticleEffect(vec3_t org, vec3_t dir, int32_t color, int32_t count); +void R_RocketTrail(vec3_t start, vec3_t end, int32_t type); +void R_EntityParticles(entity_t *ent); +void R_BlobExplosion(vec3_t org); +void R_ParticleExplosion(vec3_t org); +void R_ParticleExplosion2(vec3_t org, int32_t colorStart, int32_t colorLength); +void R_LavaSplash(vec3_t org); +void R_TeleportSplash(vec3_t org); -void R_PushDlights (void); +void R_PushDlights(void); // // surface cache related // -extern int32_t reinit_surfcache; // if 1, surface cache is currently empty and -extern bool r_cache_thrash; // set if thrashing the surface cache +extern int32_t reinit_surfcache; // if 1, surface cache is currently empty and +extern bool r_cache_thrash; // set if thrashing the surface cache -int32_t D_SurfaceCacheForRes (int32_t width, int32_t height); -void D_FlushCaches (void); -void D_DeleteSurfaceCache (void); -void D_InitCaches (void *buffer, int32_t size); -void R_SetVrect (vrect_t *pvrect, vrect_t *pvrectin, int32_t lineadj); +int32_t D_SurfaceCacheForRes(int32_t width, int32_t height); +void D_FlushCaches(void); +void D_DeleteSurfaceCache(void); +void D_InitCaches(void *buffer, int32_t size); +void R_SetVrect(vrect_t *pvrect, vrect_t *pvrectin, int32_t lineadj); -#endif /* _QUAKE_RENDER_H */ +#endif /* _QUAKE_RENDER_H */ diff --git a/source/resource.h b/source/resource.h index d31f0fa..3a69b9b 100644 --- a/source/resource.h +++ b/source/resource.h @@ -12,7 +12,7 @@ #define IDC_PROGRESS 1000 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 113 @@ -22,5 +22,5 @@ #endif #endif -#endif /* _QUAKE_RESOURCE_H */ +#endif /* _QUAKE_RESOURCE_H */ diff --git a/source/sbar.c b/source/sbar.c index fb3d884..c27fa96 100644 --- a/source/sbar.c +++ b/source/sbar.c @@ -23,49 +23,49 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -int32_t sb_updates; // if >= vid.numpages, no update needed +int32_t sb_updates; // if >= vid.numpages, no update needed -#define STAT_MINUS 10 // num frame for '-' stats digit +#define STAT_MINUS 10 // num frame for '-' stats digit -qpic_t *sb_nums[2][11]; -qpic_t *sb_colon, *sb_slash; -qpic_t *sb_ibar; -qpic_t *sb_sbar; -qpic_t *sb_scorebar; +qpic_t *sb_nums[2][11]; +qpic_t *sb_colon, *sb_slash; +qpic_t *sb_ibar; +qpic_t *sb_sbar; +qpic_t *sb_scorebar; -qpic_t *sb_weapons[7][8]; // 0 is active, 1 is owned, 2-5 are flashes -qpic_t *sb_ammo[4]; -qpic_t *sb_sigil[4]; -qpic_t *sb_armor[3]; -qpic_t *sb_items[32]; +qpic_t *sb_weapons[7][8]; // 0 is active, 1 is owned, 2-5 are flashes +qpic_t *sb_ammo[4]; +qpic_t *sb_sigil[4]; +qpic_t *sb_armor[3]; +qpic_t *sb_items[32]; -qpic_t *sb_faces[7][2]; // 0 is gibbed, 1 is dead, 2-6 are alive - // 0 is static, 1 is temporary animation -qpic_t *sb_face_invis; -qpic_t *sb_face_quad; -qpic_t *sb_face_invuln; -qpic_t *sb_face_invis_invuln; +qpic_t *sb_faces[7][2]; // 0 is gibbed, 1 is dead, 2-6 are alive +// 0 is static, 1 is temporary animation +qpic_t *sb_face_invis; +qpic_t *sb_face_quad; +qpic_t *sb_face_invuln; +qpic_t *sb_face_invis_invuln; -bool sb_showscores; +bool sb_showscores; -int32_t sb_lines; // scan lines to draw +int32_t sb_lines; // scan lines to draw -qpic_t *rsb_invbar[2]; -qpic_t *rsb_weapons[5]; -qpic_t *rsb_items[2]; -qpic_t *rsb_ammo[3]; -qpic_t *rsb_teambord; // PGM 01/19/97 - team color border +qpic_t *rsb_invbar[2]; +qpic_t *rsb_weapons[5]; +qpic_t *rsb_items[2]; +qpic_t *rsb_ammo[3]; +qpic_t *rsb_teambord; // PGM 01/19/97 - team color border //MED 01/04/97 added two more weapons + 3 alternates for grenade launcher -qpic_t *hsb_weapons[7][5]; // 0 is active, 1 is owned, 2-5 are flashes +qpic_t *hsb_weapons[7][5]; // 0 is active, 1 is owned, 2-5 are flashes //MED 01/04/97 added array to simplify weapon parsing -int32_t hipweapons[4] = {HIT_LASER_CANNON_BIT,HIT_MJOLNIR_BIT,4,HIT_PROXIMITY_GUN_BIT}; +int32_t hipweapons[4] = {HIT_LASER_CANNON_BIT, HIT_MJOLNIR_BIT, 4, HIT_PROXIMITY_GUN_BIT}; //MED 01/04/97 added hipnotic items array -qpic_t *hsb_items[2]; +qpic_t *hsb_items[2]; -void Sbar_MiniDeathmatchOverlay (void); -void Sbar_DeathmatchOverlay (void); -void M_DrawPic (int32_t x, int32_t y, qpic_t *pic); +void Sbar_MiniDeathmatchOverlay(void); +void Sbar_DeathmatchOverlay(void); +void M_DrawPic(int32_t x, int32_t y, qpic_t *pic); /* =============== @@ -74,9 +74,9 @@ Sbar_ShowScores Tab key down =============== */ -void Sbar_ShowScores (void) +void Sbar_ShowScores(void) { - if (sb_showscores) + if(sb_showscores) return; sb_showscores = true; sb_updates = 0; @@ -89,7 +89,7 @@ Sbar_DontShowScores Tab key up =============== */ -void Sbar_DontShowScores (void) +void Sbar_DontShowScores(void) { sb_showscores = false; sb_updates = 0; @@ -100,9 +100,9 @@ void Sbar_DontShowScores (void) Sbar_Changed =============== */ -void Sbar_Changed (void) +void Sbar_Changed(void) { - sb_updates = 0; // update next frame + sb_updates = 0; // update next frame } /* @@ -110,139 +110,139 @@ void Sbar_Changed (void) Sbar_LoadPics -- johnfitz -- load all the sbar pics =============== */ -void Sbar_LoadPics (void) +void Sbar_LoadPics(void) { - int32_t i; + int32_t i; - for (i = 0; i < 10; i++) + for(i = 0; i < 10; i++) { - sb_nums[0][i] = Draw_PicFromWad (va("num_%" PRIi32 "",i)); - sb_nums[1][i] = Draw_PicFromWad (va("anum_%" PRIi32 "",i)); + sb_nums[0][i] = Draw_PicFromWad(va("num_%" PRIi32 "", i)); + sb_nums[1][i] = Draw_PicFromWad(va("anum_%" PRIi32 "", i)); } - sb_nums[0][10] = Draw_PicFromWad ("num_minus"); - sb_nums[1][10] = Draw_PicFromWad ("anum_minus"); + sb_nums[0][10] = Draw_PicFromWad("num_minus"); + sb_nums[1][10] = Draw_PicFromWad("anum_minus"); - sb_colon = Draw_PicFromWad ("num_colon"); - sb_slash = Draw_PicFromWad ("num_slash"); + sb_colon = Draw_PicFromWad("num_colon"); + sb_slash = Draw_PicFromWad("num_slash"); - sb_weapons[0][0] = Draw_PicFromWad ("inv_shotgun"); - sb_weapons[0][1] = Draw_PicFromWad ("inv_sshotgun"); - sb_weapons[0][2] = Draw_PicFromWad ("inv_nailgun"); - sb_weapons[0][3] = Draw_PicFromWad ("inv_snailgun"); - sb_weapons[0][4] = Draw_PicFromWad ("inv_rlaunch"); - sb_weapons[0][5] = Draw_PicFromWad ("inv_srlaunch"); - sb_weapons[0][6] = Draw_PicFromWad ("inv_lightng"); + sb_weapons[0][0] = Draw_PicFromWad("inv_shotgun"); + sb_weapons[0][1] = Draw_PicFromWad("inv_sshotgun"); + sb_weapons[0][2] = Draw_PicFromWad("inv_nailgun"); + sb_weapons[0][3] = Draw_PicFromWad("inv_snailgun"); + sb_weapons[0][4] = Draw_PicFromWad("inv_rlaunch"); + sb_weapons[0][5] = Draw_PicFromWad("inv_srlaunch"); + sb_weapons[0][6] = Draw_PicFromWad("inv_lightng"); - sb_weapons[1][0] = Draw_PicFromWad ("inv2_shotgun"); - sb_weapons[1][1] = Draw_PicFromWad ("inv2_sshotgun"); - sb_weapons[1][2] = Draw_PicFromWad ("inv2_nailgun"); - sb_weapons[1][3] = Draw_PicFromWad ("inv2_snailgun"); - sb_weapons[1][4] = Draw_PicFromWad ("inv2_rlaunch"); - sb_weapons[1][5] = Draw_PicFromWad ("inv2_srlaunch"); - sb_weapons[1][6] = Draw_PicFromWad ("inv2_lightng"); + sb_weapons[1][0] = Draw_PicFromWad("inv2_shotgun"); + sb_weapons[1][1] = Draw_PicFromWad("inv2_sshotgun"); + sb_weapons[1][2] = Draw_PicFromWad("inv2_nailgun"); + sb_weapons[1][3] = Draw_PicFromWad("inv2_snailgun"); + sb_weapons[1][4] = Draw_PicFromWad("inv2_rlaunch"); + sb_weapons[1][5] = Draw_PicFromWad("inv2_srlaunch"); + sb_weapons[1][6] = Draw_PicFromWad("inv2_lightng"); - for (i = 0; i < 5; i++) + for(i = 0; i < 5; i++) { - sb_weapons[2+i][0] = Draw_PicFromWad (va("inva%" PRIi32 "_shotgun",i+1)); - sb_weapons[2+i][1] = Draw_PicFromWad (va("inva%" PRIi32 "_sshotgun",i+1)); - sb_weapons[2+i][2] = Draw_PicFromWad (va("inva%" PRIi32 "_nailgun",i+1)); - sb_weapons[2+i][3] = Draw_PicFromWad (va("inva%" PRIi32 "_snailgun",i+1)); - sb_weapons[2+i][4] = Draw_PicFromWad (va("inva%" PRIi32 "_rlaunch",i+1)); - sb_weapons[2+i][5] = Draw_PicFromWad (va("inva%" PRIi32 "_srlaunch",i+1)); - sb_weapons[2+i][6] = Draw_PicFromWad (va("inva%" PRIi32 "_lightng",i+1)); + sb_weapons[2 + i][0] = Draw_PicFromWad(va("inva%" PRIi32 "_shotgun", i + 1)); + sb_weapons[2 + i][1] = Draw_PicFromWad(va("inva%" PRIi32 "_sshotgun", i + 1)); + sb_weapons[2 + i][2] = Draw_PicFromWad(va("inva%" PRIi32 "_nailgun", i + 1)); + sb_weapons[2 + i][3] = Draw_PicFromWad(va("inva%" PRIi32 "_snailgun", i + 1)); + sb_weapons[2 + i][4] = Draw_PicFromWad(va("inva%" PRIi32 "_rlaunch", i + 1)); + sb_weapons[2 + i][5] = Draw_PicFromWad(va("inva%" PRIi32 "_srlaunch", i + 1)); + sb_weapons[2 + i][6] = Draw_PicFromWad(va("inva%" PRIi32 "_lightng", i + 1)); } - sb_ammo[0] = Draw_PicFromWad ("sb_shells"); - sb_ammo[1] = Draw_PicFromWad ("sb_nails"); - sb_ammo[2] = Draw_PicFromWad ("sb_rocket"); - sb_ammo[3] = Draw_PicFromWad ("sb_cells"); + sb_ammo[0] = Draw_PicFromWad("sb_shells"); + sb_ammo[1] = Draw_PicFromWad("sb_nails"); + sb_ammo[2] = Draw_PicFromWad("sb_rocket"); + sb_ammo[3] = Draw_PicFromWad("sb_cells"); - sb_armor[0] = Draw_PicFromWad ("sb_armor1"); - sb_armor[1] = Draw_PicFromWad ("sb_armor2"); - sb_armor[2] = Draw_PicFromWad ("sb_armor3"); + sb_armor[0] = Draw_PicFromWad("sb_armor1"); + sb_armor[1] = Draw_PicFromWad("sb_armor2"); + sb_armor[2] = Draw_PicFromWad("sb_armor3"); - sb_items[0] = Draw_PicFromWad ("sb_key1"); - sb_items[1] = Draw_PicFromWad ("sb_key2"); - sb_items[2] = Draw_PicFromWad ("sb_invis"); - sb_items[3] = Draw_PicFromWad ("sb_invuln"); - sb_items[4] = Draw_PicFromWad ("sb_suit"); - sb_items[5] = Draw_PicFromWad ("sb_quad"); + sb_items[0] = Draw_PicFromWad("sb_key1"); + sb_items[1] = Draw_PicFromWad("sb_key2"); + sb_items[2] = Draw_PicFromWad("sb_invis"); + sb_items[3] = Draw_PicFromWad("sb_invuln"); + sb_items[4] = Draw_PicFromWad("sb_suit"); + sb_items[5] = Draw_PicFromWad("sb_quad"); - sb_sigil[0] = Draw_PicFromWad ("sb_sigil1"); - sb_sigil[1] = Draw_PicFromWad ("sb_sigil2"); - sb_sigil[2] = Draw_PicFromWad ("sb_sigil3"); - sb_sigil[3] = Draw_PicFromWad ("sb_sigil4"); + sb_sigil[0] = Draw_PicFromWad("sb_sigil1"); + sb_sigil[1] = Draw_PicFromWad("sb_sigil2"); + sb_sigil[2] = Draw_PicFromWad("sb_sigil3"); + sb_sigil[3] = Draw_PicFromWad("sb_sigil4"); - sb_faces[4][0] = Draw_PicFromWad ("face1"); - sb_faces[4][1] = Draw_PicFromWad ("face_p1"); - sb_faces[3][0] = Draw_PicFromWad ("face2"); - sb_faces[3][1] = Draw_PicFromWad ("face_p2"); - sb_faces[2][0] = Draw_PicFromWad ("face3"); - sb_faces[2][1] = Draw_PicFromWad ("face_p3"); - sb_faces[1][0] = Draw_PicFromWad ("face4"); - sb_faces[1][1] = Draw_PicFromWad ("face_p4"); - sb_faces[0][0] = Draw_PicFromWad ("face5"); - sb_faces[0][1] = Draw_PicFromWad ("face_p5"); + sb_faces[4][0] = Draw_PicFromWad("face1"); + sb_faces[4][1] = Draw_PicFromWad("face_p1"); + sb_faces[3][0] = Draw_PicFromWad("face2"); + sb_faces[3][1] = Draw_PicFromWad("face_p2"); + sb_faces[2][0] = Draw_PicFromWad("face3"); + sb_faces[2][1] = Draw_PicFromWad("face_p3"); + sb_faces[1][0] = Draw_PicFromWad("face4"); + sb_faces[1][1] = Draw_PicFromWad("face_p4"); + sb_faces[0][0] = Draw_PicFromWad("face5"); + sb_faces[0][1] = Draw_PicFromWad("face_p5"); - sb_face_invis = Draw_PicFromWad ("face_invis"); - sb_face_invuln = Draw_PicFromWad ("face_invul2"); - sb_face_invis_invuln = Draw_PicFromWad ("face_inv2"); - sb_face_quad = Draw_PicFromWad ("face_quad"); + sb_face_invis = Draw_PicFromWad("face_invis"); + sb_face_invuln = Draw_PicFromWad("face_invul2"); + sb_face_invis_invuln = Draw_PicFromWad("face_inv2"); + sb_face_quad = Draw_PicFromWad("face_quad"); - sb_sbar = Draw_PicFromWad ("sbar"); - sb_ibar = Draw_PicFromWad ("ibar"); - sb_scorebar = Draw_PicFromWad ("scorebar"); + sb_sbar = Draw_PicFromWad("sbar"); + sb_ibar = Draw_PicFromWad("ibar"); + sb_scorebar = Draw_PicFromWad("scorebar"); //MED 01/04/97 added new hipnotic weapons - if (hipnotic) + if(hipnotic) { - hsb_weapons[0][0] = Draw_PicFromWad ("inv_laser"); - hsb_weapons[0][1] = Draw_PicFromWad ("inv_mjolnir"); - hsb_weapons[0][2] = Draw_PicFromWad ("inv_gren_prox"); - hsb_weapons[0][3] = Draw_PicFromWad ("inv_prox_gren"); - hsb_weapons[0][4] = Draw_PicFromWad ("inv_prox"); + hsb_weapons[0][0] = Draw_PicFromWad("inv_laser"); + hsb_weapons[0][1] = Draw_PicFromWad("inv_mjolnir"); + hsb_weapons[0][2] = Draw_PicFromWad("inv_gren_prox"); + hsb_weapons[0][3] = Draw_PicFromWad("inv_prox_gren"); + hsb_weapons[0][4] = Draw_PicFromWad("inv_prox"); - hsb_weapons[1][0] = Draw_PicFromWad ("inv2_laser"); - hsb_weapons[1][1] = Draw_PicFromWad ("inv2_mjolnir"); - hsb_weapons[1][2] = Draw_PicFromWad ("inv2_gren_prox"); - hsb_weapons[1][3] = Draw_PicFromWad ("inv2_prox_gren"); - hsb_weapons[1][4] = Draw_PicFromWad ("inv2_prox"); + hsb_weapons[1][0] = Draw_PicFromWad("inv2_laser"); + hsb_weapons[1][1] = Draw_PicFromWad("inv2_mjolnir"); + hsb_weapons[1][2] = Draw_PicFromWad("inv2_gren_prox"); + hsb_weapons[1][3] = Draw_PicFromWad("inv2_prox_gren"); + hsb_weapons[1][4] = Draw_PicFromWad("inv2_prox"); - for (i = 0; i < 5; i++) + for(i = 0; i < 5; i++) { - hsb_weapons[2+i][0] = Draw_PicFromWad (va("inva%" PRIi32 "_laser",i+1)); - hsb_weapons[2+i][1] = Draw_PicFromWad (va("inva%" PRIi32 "_mjolnir",i+1)); - hsb_weapons[2+i][2] = Draw_PicFromWad (va("inva%" PRIi32 "_gren_prox",i+1)); - hsb_weapons[2+i][3] = Draw_PicFromWad (va("inva%" PRIi32 "_prox_gren",i+1)); - hsb_weapons[2+i][4] = Draw_PicFromWad (va("inva%" PRIi32 "_prox",i+1)); + hsb_weapons[2 + i][0] = Draw_PicFromWad(va("inva%" PRIi32 "_laser", i + 1)); + hsb_weapons[2 + i][1] = Draw_PicFromWad(va("inva%" PRIi32 "_mjolnir", i + 1)); + hsb_weapons[2 + i][2] = Draw_PicFromWad(va("inva%" PRIi32 "_gren_prox", i + 1)); + hsb_weapons[2 + i][3] = Draw_PicFromWad(va("inva%" PRIi32 "_prox_gren", i + 1)); + hsb_weapons[2 + i][4] = Draw_PicFromWad(va("inva%" PRIi32 "_prox", i + 1)); } - hsb_items[0] = Draw_PicFromWad ("sb_wsuit"); - hsb_items[1] = Draw_PicFromWad ("sb_eshld"); + hsb_items[0] = Draw_PicFromWad("sb_wsuit"); + hsb_items[1] = Draw_PicFromWad("sb_eshld"); } - if (rogue) + if(rogue) { - rsb_invbar[0] = Draw_PicFromWad ("r_invbar1"); - rsb_invbar[1] = Draw_PicFromWad ("r_invbar2"); + rsb_invbar[0] = Draw_PicFromWad("r_invbar1"); + rsb_invbar[1] = Draw_PicFromWad("r_invbar2"); - rsb_weapons[0] = Draw_PicFromWad ("r_lava"); - rsb_weapons[1] = Draw_PicFromWad ("r_superlava"); - rsb_weapons[2] = Draw_PicFromWad ("r_gren"); - rsb_weapons[3] = Draw_PicFromWad ("r_multirock"); - rsb_weapons[4] = Draw_PicFromWad ("r_plasma"); + rsb_weapons[0] = Draw_PicFromWad("r_lava"); + rsb_weapons[1] = Draw_PicFromWad("r_superlava"); + rsb_weapons[2] = Draw_PicFromWad("r_gren"); + rsb_weapons[3] = Draw_PicFromWad("r_multirock"); + rsb_weapons[4] = Draw_PicFromWad("r_plasma"); - rsb_items[0] = Draw_PicFromWad ("r_shield1"); - rsb_items[1] = Draw_PicFromWad ("r_agrav1"); + rsb_items[0] = Draw_PicFromWad("r_shield1"); + rsb_items[1] = Draw_PicFromWad("r_agrav1"); // PGM 01/19/97 - team color border - rsb_teambord = Draw_PicFromWad ("r_teambord"); + rsb_teambord = Draw_PicFromWad("r_teambord"); // PGM 01/19/97 - team color border - rsb_ammo[0] = Draw_PicFromWad ("r_ammolava"); - rsb_ammo[1] = Draw_PicFromWad ("r_ammomulti"); - rsb_ammo[2] = Draw_PicFromWad ("r_ammoplasma"); + rsb_ammo[0] = Draw_PicFromWad("r_ammolava"); + rsb_ammo[1] = Draw_PicFromWad("r_ammomulti"); + rsb_ammo[2] = Draw_PicFromWad("r_ammoplasma"); } } @@ -251,12 +251,12 @@ void Sbar_LoadPics (void) Sbar_Init -- johnfitz -- rewritten =============== */ -void Sbar_Init (void) +void Sbar_Init(void) { - Cmd_AddCommand ("+showscores", Sbar_ShowScores); - Cmd_AddCommand ("-showscores", Sbar_DontShowScores); + Cmd_AddCommand("+showscores", Sbar_ShowScores); + Cmd_AddCommand("-showscores", Sbar_DontShowScores); - Sbar_LoadPics (); + Sbar_LoadPics(); } @@ -269,9 +269,9 @@ void Sbar_Init (void) Sbar_DrawPic -- johnfitz -- rewritten now that GL_SetCanvas is doing the work ============= */ -void Sbar_DrawPic (int32_t x, int32_t y, qpic_t *pic) +void Sbar_DrawPic(int32_t x, int32_t y, qpic_t *pic) { - Draw_Pic (x, y + 24, pic); + Draw_Pic(x, y + 24, pic); } /* @@ -279,15 +279,15 @@ void Sbar_DrawPic (int32_t x, int32_t y, qpic_t *pic) Sbar_DrawPicAlpha -- johnfitz ============= */ -void Sbar_DrawPicAlpha (int32_t x, int32_t y, qpic_t *pic, float alpha) +void Sbar_DrawPicAlpha(int32_t x, int32_t y, qpic_t *pic, float alpha) { - glDisable (GL_ALPHA_TEST); - glEnable (GL_BLEND); - glColor4f(1,1,1,alpha); - Draw_Pic (x, y + 24, pic); - glColor4f(1,1,1,1); // ericw -- changed from glColor3f to work around intel 855 bug with "r_oldwater 0" and "scr_sbaralpha 0" - glDisable (GL_BLEND); - glEnable (GL_ALPHA_TEST); + glDisable(GL_ALPHA_TEST); + glEnable(GL_BLEND); + glColor4f(1, 1, 1, alpha); + Draw_Pic(x, y + 24, pic); + glColor4f(1, 1, 1, 1); // ericw -- changed from glColor3f to work around intel 855 bug with "r_oldwater 0" and "scr_sbaralpha 0" + glDisable(GL_BLEND); + glEnable(GL_ALPHA_TEST); } /* @@ -295,9 +295,9 @@ void Sbar_DrawPicAlpha (int32_t x, int32_t y, qpic_t *pic, float alpha) Sbar_DrawCharacter -- johnfitz -- rewritten now that GL_SetCanvas is doing the work ================ */ -void Sbar_DrawCharacter (int32_t x, int32_t y, int32_t num) +void Sbar_DrawCharacter(int32_t x, int32_t y, int32_t num) { - Draw_Character (x, y + 24, num); + Draw_Character(x, y + 24, num); } /* @@ -305,9 +305,9 @@ void Sbar_DrawCharacter (int32_t x, int32_t y, int32_t num) Sbar_DrawString -- johnfitz -- rewritten now that GL_SetCanvas is doing the work ================ */ -void Sbar_DrawString (int32_t x, int32_t y, const char *str) +void Sbar_DrawString(int32_t x, int32_t y, const char *str) { - Draw_String (x, y + 24, str); + Draw_String(x, y + 24, str); } /* @@ -317,28 +317,28 @@ Sbar_DrawScrollString -- johnfitz scroll the string inside a glscissor region =============== */ -void Sbar_DrawScrollString (int32_t x, int32_t y, int32_t width, const char *str) +void Sbar_DrawScrollString(int32_t x, int32_t y, int32_t width, const char *str) { float scale; int32_t len, ofs, left; - scale = CLAMP (1.0, scr_sbarscale.value, (float)glwidth / 320.0); + scale = CLAMP(1.0, scr_sbarscale.value, (float)glwidth / 320.0); left = x * scale; - if (cl.gametype != GAME_DEATHMATCH) + if(cl.gametype != GAME_DEATHMATCH) left += (((float)glwidth - 320.0 * scale) / 2); - glEnable (GL_SCISSOR_TEST); - glScissor (left, 0, width * scale, glheight); + glEnable(GL_SCISSOR_TEST); + glScissor(left, 0, width * scale, glheight); - len = strlen(str)*8 + 40; - ofs = ((int32_t)(realtime*30))%len; - Sbar_DrawString (x - ofs, y, str); - Sbar_DrawCharacter (x - ofs + len - 32, y, '/'); - Sbar_DrawCharacter (x - ofs + len - 24, y, '/'); - Sbar_DrawCharacter (x - ofs + len - 16, y, '/'); - Sbar_DrawString (x - ofs + len, y, str); + len = strlen(str) * 8 + 40; + ofs = ((int32_t)(realtime * 30)) % len; + Sbar_DrawString(x - ofs, y, str); + Sbar_DrawCharacter(x - ofs + len - 32, y, '/'); + Sbar_DrawCharacter(x - ofs + len - 24, y, '/'); + Sbar_DrawCharacter(x - ofs + len - 16, y, '/'); + Sbar_DrawString(x - ofs + len, y, str); - glDisable (GL_SCISSOR_TEST); + glDisable(GL_SCISSOR_TEST); } /* @@ -346,34 +346,35 @@ void Sbar_DrawScrollString (int32_t x, int32_t y, int32_t width, const char *str Sbar_itoa ============= */ -int32_t Sbar_itoa (int32_t num, char *buf) +int32_t Sbar_itoa(int32_t num, char *buf) { - char *str; - int32_t pow10; - int32_t dig; + char *str; + int32_t pow10; + int32_t dig; str = buf; - if (num < 0) + if(num < 0) { *str++ = '-'; num = -num; } - for (pow10 = 10 ; num >= pow10 ; pow10 *= 10) + for(pow10 = 10 ; num >= pow10 ; pow10 *= 10) ; do { pow10 /= 10; - dig = num/pow10; - *str++ = '0'+dig; - num -= dig*pow10; - } while (pow10 != 1); + dig = num / pow10; + *str++ = '0' + dig; + num -= dig * pow10; + } + while(pow10 != 1); *str = 0; - return str-buf; + return str - buf; } @@ -382,29 +383,29 @@ int32_t Sbar_itoa (int32_t num, char *buf) Sbar_DrawNum ============= */ -void Sbar_DrawNum (int32_t x, int32_t y, int32_t num, int32_t digits, int32_t color) +void Sbar_DrawNum(int32_t x, int32_t y, int32_t num, int32_t digits, int32_t color) { - char str[12]; - char *ptr; - int32_t l, frame; + char str[12]; + char *ptr; + int32_t l, frame; - num = q_min(999,num); //johnfitz -- cap high values rather than truncating number + num = q_min(999, num); //johnfitz -- cap high values rather than truncating number - l = Sbar_itoa (num, str); + l = Sbar_itoa(num, str); ptr = str; - if (l > digits) - ptr += (l-digits); - if (l < digits) - x += (digits-l)*24; + if(l > digits) + ptr += (l - digits); + if(l < digits) + x += (digits - l) * 24; - while (*ptr) + while(*ptr) { - if (*ptr == '-') + if(*ptr == '-') frame = STAT_MINUS; else - frame = *ptr -'0'; + frame = *ptr - '0'; - Sbar_DrawPic (x,y,sb_nums[color][frame]); //johnfitz -- DrawTransPic is obsolete + Sbar_DrawPic(x, y, sb_nums[color][frame]); //johnfitz -- DrawTransPic is obsolete x += 24; ptr++; } @@ -412,49 +413,49 @@ void Sbar_DrawNum (int32_t x, int32_t y, int32_t num, int32_t digits, int32_t co //============================================================================= -int32_t fragsort[MAX_SCOREBOARD]; +int32_t fragsort[MAX_SCOREBOARD]; -char scoreboardtext[MAX_SCOREBOARD][20]; -int32_t scoreboardtop[MAX_SCOREBOARD]; -int32_t scoreboardbottom[MAX_SCOREBOARD]; -int32_t scoreboardcount[MAX_SCOREBOARD]; -int32_t scoreboardlines; +char scoreboardtext[MAX_SCOREBOARD][20]; +int32_t scoreboardtop[MAX_SCOREBOARD]; +int32_t scoreboardbottom[MAX_SCOREBOARD]; +int32_t scoreboardcount[MAX_SCOREBOARD]; +int32_t scoreboardlines; /* =============== Sbar_SortFrags =============== */ -void Sbar_SortFrags (void) +void Sbar_SortFrags(void) { - int32_t i, j, k; + int32_t i, j, k; // sort by frags scoreboardlines = 0; - for (i = 0; i < cl.maxclients; i++) + for(i = 0; i < cl.maxclients; i++) { - if (cl.scores[i].name[0]) + if(cl.scores[i].name[0]) { fragsort[scoreboardlines] = i; scoreboardlines++; } } - for (i = 0; i < scoreboardlines; i++) + for(i = 0; i < scoreboardlines; i++) { - for (j = 0; j < scoreboardlines - 1 - i; j++) + for(j = 0; j < scoreboardlines - 1 - i; j++) { - if (cl.scores[fragsort[j]].frags < cl.scores[fragsort[j+1]].frags) + if(cl.scores[fragsort[j]].frags < cl.scores[fragsort[j + 1]].frags) { k = fragsort[j]; - fragsort[j] = fragsort[j+1]; - fragsort[j+1] = k; + fragsort[j] = fragsort[j + 1]; + fragsort[j + 1] = k; } } } } -int32_t Sbar_ColorForMap (int32_t m) +int32_t Sbar_ColorForMap(int32_t m) { return m < 128 ? m + 8 : m + 8; } @@ -464,27 +465,27 @@ int32_t Sbar_ColorForMap (int32_t m) Sbar_UpdateScoreboard =============== */ -void Sbar_UpdateScoreboard (void) +void Sbar_UpdateScoreboard(void) { - int32_t i, k; - int32_t top, bottom; - scoreboard_t *s; + int32_t i, k; + int32_t top, bottom; + scoreboard_t *s; - Sbar_SortFrags (); + Sbar_SortFrags(); // draw the text - memset (scoreboardtext, 0, sizeof(scoreboardtext)); + memset(scoreboardtext, 0, sizeof(scoreboardtext)); - for (i = 0; i < scoreboardlines; i++) + for(i = 0; i < scoreboardlines; i++) { k = fragsort[i]; s = &cl.scores[k]; - sprintf (&scoreboardtext[i][1], "%3" PRIi32 " %s", s->frags, s->name); + sprintf(&scoreboardtext[i][1], "%3" PRIi32 " %s", s->frags, s->name); top = s->colors & 0xf0; - bottom = (s->colors & 15) <<4; - scoreboardtop[i] = Sbar_ColorForMap (top); - scoreboardbottom[i] = Sbar_ColorForMap (bottom); + bottom = (s->colors & 15) << 4; + scoreboardtop[i] = Sbar_ColorForMap(top); + scoreboardbottom[i] = Sbar_ColorForMap(bottom); } } @@ -493,43 +494,44 @@ void Sbar_UpdateScoreboard (void) Sbar_SoloScoreboard -- johnfitz -- new layout =============== */ -void Sbar_SoloScoreboard (void) +void Sbar_SoloScoreboard(void) { - char str[256]; - int32_t minutes, seconds, tens, units; - int32_t len; + char str[256]; + int32_t minutes, seconds, tens, units; + int32_t len; - sprintf (str,"Kills: %" PRIi32 "/%" PRIi32 "", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]); - Sbar_DrawString (8, 12, str); + sprintf(str, "Kills: %" PRIi32 "/%" PRIi32 "", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]); + Sbar_DrawString(8, 12, str); - sprintf (str,"Secrets: %" PRIi32 "/%" PRIi32 "", cl.stats[STAT_SECRETS], cl.stats[STAT_TOTALSECRETS]); - Sbar_DrawString (312 - strlen(str)*8, 12, str); + sprintf(str, "Secrets: %" PRIi32 "/%" PRIi32 "", cl.stats[STAT_SECRETS], cl.stats[STAT_TOTALSECRETS]); + Sbar_DrawString(312 - strlen(str) * 8, 12, str); - if (!fitzmode) - { /* QuakeSpasm customization: */ - q_snprintf (str, sizeof(str), "skill %" PRIi32 "", (int32_t)(skill.value + 0.5)); - Sbar_DrawString (160 - strlen(str)*4, 12, str); + if(!fitzmode) + { + /* QuakeSpasm customization: */ + q_snprintf(str, sizeof(str), "skill %" PRIi32 "", (int32_t)(skill.value + 0.5)); + Sbar_DrawString(160 - strlen(str) * 4, 12, str); - q_snprintf (str, sizeof(str), "%s (%s)", cl.levelname, cl.mapname); - len = strlen (str); - if (len > 40) - Sbar_DrawScrollString (0, 4, 320, str); + q_snprintf(str, sizeof(str), "%s (%s)", cl.levelname, cl.mapname); + len = strlen(str); + if(len > 40) + Sbar_DrawScrollString(0, 4, 320, str); else - Sbar_DrawString (160 - len*4, 4, str); + Sbar_DrawString(160 - len * 4, 4, str); return; } minutes = cl.time / 60; - seconds = cl.time - 60*minutes; + seconds = cl.time - 60 * minutes; tens = seconds / 10; - units = seconds - 10*tens; - sprintf (str,"%" PRIi32 ":%" PRIi32 "%" PRIi32 "", minutes, tens, units); - Sbar_DrawString (160 - strlen(str)*4, 12, str); + units = seconds - 10 * tens; + sprintf(str, "%" PRIi32 ":%" PRIi32 "%" PRIi32 "", minutes, tens, units); + Sbar_DrawString(160 - strlen(str) * 4, 12, str); - len = strlen (cl.levelname); - if (len > 40) - Sbar_DrawScrollString (0, 4, 320, cl.levelname); + len = strlen(cl.levelname); + if(len > 40) + Sbar_DrawScrollString(0, 4, 320, cl.levelname); else - Sbar_DrawString (160 - len*4, 4, cl.levelname); + Sbar_DrawString(160 - len * 4, 4, cl.levelname); } /* @@ -537,11 +539,11 @@ void Sbar_SoloScoreboard (void) Sbar_DrawScoreboard =============== */ -void Sbar_DrawScoreboard (void) +void Sbar_DrawScoreboard(void) { - Sbar_SoloScoreboard (); - if (cl.gametype == GAME_DEATHMATCH) - Sbar_DeathmatchOverlay (); + Sbar_SoloScoreboard(); + if(cl.gametype == GAME_DEATHMATCH) + Sbar_DeathmatchOverlay(); } //============================================================================= @@ -551,218 +553,222 @@ void Sbar_DrawScoreboard (void) Sbar_DrawInventory =============== */ -void Sbar_DrawInventory (void) +void Sbar_DrawInventory(void) { - int32_t i, val; - char num[6]; - float time; - int32_t flashon; + int32_t i, val; + char num[6]; + float time; + int32_t flashon; - if (rogue) + if(rogue) { - if ( cl.stats[STAT_ACTIVEWEAPON] >= RIT_LAVA_NAILGUN ) - Sbar_DrawPicAlpha (0, -24, rsb_invbar[0], scr_sbaralpha.value); //johnfitz -- scr_sbaralpha + if(cl.stats[STAT_ACTIVEWEAPON] >= RIT_LAVA_NAILGUN) + Sbar_DrawPicAlpha(0, -24, rsb_invbar[0], scr_sbaralpha.value); //johnfitz -- scr_sbaralpha else - Sbar_DrawPicAlpha (0, -24, rsb_invbar[1], scr_sbaralpha.value); //johnfitz -- scr_sbaralpha + Sbar_DrawPicAlpha(0, -24, rsb_invbar[1], scr_sbaralpha.value); //johnfitz -- scr_sbaralpha } else { - Sbar_DrawPicAlpha (0, -24, sb_ibar, scr_sbaralpha.value); //johnfitz -- scr_sbaralpha + Sbar_DrawPicAlpha(0, -24, sb_ibar, scr_sbaralpha.value); //johnfitz -- scr_sbaralpha } // weapons - for (i = 0; i < 7; i++) + for(i = 0; i < 7; i++) { - if (cl.items & (IT_SHOTGUN<= 10) + flashon = (int32_t)((cl.time - time) * 10); + if(flashon >= 10) { - if ( cl.stats[STAT_ACTIVEWEAPON] == (IT_SHOTGUN< 1) - sb_updates = 0; // force update to remove flash + if(flashon > 1) + sb_updates = 0; // force update to remove flash } } // MED 01/04/97 // hipnotic weapons - if (hipnotic) + if(hipnotic) { int32_t grenadeflashing = 0; - for (i = 0; i < 4; i++) + for(i = 0; i < 4; i++) { - if (cl.items & (1<= 10) + flashon = (int32_t)((cl.time - time) * 10); + if(flashon >= 10) { - if (cl.stats[STAT_ACTIVEWEAPON] == (1< 1) - sb_updates = 0; // force update to remove flash + if(flashon > 1) + sb_updates = 0; // force update to remove flash } } } - if (rogue) + if(rogue) { - // check for powered up weapon. - if ( cl.stats[STAT_ACTIVEWEAPON] >= RIT_LAVA_NAILGUN ) + // check for powered up weapon. + if(cl.stats[STAT_ACTIVEWEAPON] >= RIT_LAVA_NAILGUN) { - for (i=0;i<5;i++) + for(i = 0; i < 5; i++) { - if (cl.stats[STAT_ACTIVEWEAPON] == (RIT_LAVA_NAILGUN << i)) + if(cl.stats[STAT_ACTIVEWEAPON] == (RIT_LAVA_NAILGUN << i)) { - Sbar_DrawPic ((i+2)*24, -16, rsb_weapons[i]); + Sbar_DrawPic((i + 2) * 24, -16, rsb_weapons[i]); } } } } // ammo counts - for (i = 0; i < 4; i++) + for(i = 0; i < 4; i++) { - val = cl.stats[STAT_SHELLS+i]; - val = (val < 0)? 0 : q_min(999,val);//johnfitz -- cap displayed value to 999 - sprintf (num, "%3" PRIi32 "", val); - if (num[0] != ' ') - Sbar_DrawCharacter ( (6*i+1)*8 + 2, -24, 18 + num[0] - '0'); - if (num[1] != ' ') - Sbar_DrawCharacter ( (6*i+2)*8 + 2, -24, 18 + num[1] - '0'); - if (num[2] != ' ') - Sbar_DrawCharacter ( (6*i+3)*8 + 2, -24, 18 + num[2] - '0'); + val = cl.stats[STAT_SHELLS + i]; + val = (val < 0) ? 0 : q_min(999, val); //johnfitz -- cap displayed value to 999 + sprintf(num, "%3" PRIi32 "", val); + if(num[0] != ' ') + Sbar_DrawCharacter((6 * i + 1) * 8 + 2, -24, 18 + num[0] - '0'); + if(num[1] != ' ') + Sbar_DrawCharacter((6 * i + 2) * 8 + 2, -24, 18 + num[1] - '0'); + if(num[2] != ' ') + Sbar_DrawCharacter((6 * i + 3) * 8 + 2, -24, 18 + num[2] - '0'); } flashon = 0; // items - for (i = 0; i < 6; i++) + for(i = 0; i < 6; i++) { - if (cl.items & (1<<(17+i))) + if(cl.items & (1 << (17 + i))) { - time = cl.item_gettime[17+i]; - if (time && time > cl.time - 2 && flashon) - { // flash frame + time = cl.item_gettime[17 + i]; + if(time && time > cl.time - 2 && flashon) + { + // flash frame sb_updates = 0; } else { //MED 01/04/97 changed keys - if (!hipnotic || (i > 1)) + if(!hipnotic || (i > 1)) { - Sbar_DrawPic (192 + i*16, -16, sb_items[i]); + Sbar_DrawPic(192 + i * 16, -16, sb_items[i]); } } - if (time && time > cl.time - 2) + if(time && time > cl.time - 2) sb_updates = 0; } } //MED 01/04/97 added hipnotic items // hipnotic items - if (hipnotic) + if(hipnotic) { - for (i = 0; i < 2; i++) + for(i = 0; i < 2; i++) { - if (cl.items & (1<<(24+i))) + if(cl.items & (1 << (24 + i))) { - time = cl.item_gettime[24+i]; - if (time && time > cl.time - 2 && flashon ) - { // flash frame + time = cl.item_gettime[24 + i]; + if(time && time > cl.time - 2 && flashon) + { + // flash frame sb_updates = 0; } else { - Sbar_DrawPic (288 + i*16, -16, hsb_items[i]); + Sbar_DrawPic(288 + i * 16, -16, hsb_items[i]); } - if (time && time > cl.time - 2) + if(time && time > cl.time - 2) sb_updates = 0; } } } - if (rogue) + if(rogue) { - // new rogue items - for (i = 0; i < 2; i++) + // new rogue items + for(i = 0; i < 2; i++) { - if (cl.items & (1<<(29+i))) + if(cl.items & (1 << (29 + i))) { - time = cl.item_gettime[29+i]; - if (time && time > cl.time - 2 && flashon) - { // flash frame + time = cl.item_gettime[29 + i]; + if(time && time > cl.time - 2 && flashon) + { + // flash frame sb_updates = 0; } else { - Sbar_DrawPic (288 + i*16, -16, rsb_items[i]); + Sbar_DrawPic(288 + i * 16, -16, rsb_items[i]); } - if (time && time > cl.time - 2) + if(time && time > cl.time - 2) sb_updates = 0; } } } else { - // sigils - for (i = 0; i < 4; i++) + // sigils + for(i = 0; i < 4; i++) { - if (cl.items & (1<<(28+i))) + if(cl.items & (1 << (28 + i))) { - time = cl.item_gettime[28+i]; - if (time && time > cl.time - 2 && flashon) - { // flash frame + time = cl.item_gettime[28 + i]; + if(time && time > cl.time - 2 && flashon) + { + // flash frame sb_updates = 0; } else - Sbar_DrawPic (320-32 + i*8, -16, sb_sigil[i]); - if (time && time > cl.time - 2) + Sbar_DrawPic(320 - 32 + i * 8, -16, sb_sigil[i]); + if(time && time > cl.time - 2) sb_updates = 0; } } @@ -776,44 +782,44 @@ void Sbar_DrawInventory (void) Sbar_DrawFrags -- johnfitz -- heavy revision =============== */ -void Sbar_DrawFrags (void) +void Sbar_DrawFrags(void) { - int32_t numscores, i, x, color; - char num[12]; - scoreboard_t *s; + int32_t numscores, i, x, color; + char num[12]; + scoreboard_t *s; - Sbar_SortFrags (); + Sbar_SortFrags(); // draw the text numscores = q_min(scoreboardlines, 4); - for (i = 0, x = 184; iname[0]) + if(!s->name[0]) continue; - // top color + // top color color = s->colors & 0xf0; - color = Sbar_ColorForMap (color); - Draw_Fill (x + 10, 1, 28, 4, color, 1); + color = Sbar_ColorForMap(color); + Draw_Fill(x + 10, 1, 28, 4, color, 1); - // bottom color - color = (s->colors & 15)<<4; - color = Sbar_ColorForMap (color); - Draw_Fill (x + 10, 5, 28, 3, color, 1); + // bottom color + color = (s->colors & 15) << 4; + color = Sbar_ColorForMap(color); + Draw_Fill(x + 10, 5, 28, 3, color, 1); - // number - sprintf (num, "%3" PRIi32 "", s->frags); - Sbar_DrawCharacter (x + 12, -24, num[0]); - Sbar_DrawCharacter (x + 20, -24, num[1]); - Sbar_DrawCharacter (x + 28, -24, num[2]); + // number + sprintf(num, "%3" PRIi32 "", s->frags); + Sbar_DrawCharacter(x + 12, -24, num[0]); + Sbar_DrawCharacter(x + 20, -24, num[1]); + Sbar_DrawCharacter(x + 28, -24, num[2]); - // brackets - if (fragsort[i] == cl.viewentity - 1) + // brackets + if(fragsort[i] == cl.viewentity - 1) { - Sbar_DrawCharacter (x + 6, -24, 16); - Sbar_DrawCharacter (x + 32, -24, 17); + Sbar_DrawCharacter(x + 6, -24, 16); + Sbar_DrawCharacter(x + 32, -24, 17); } } } @@ -826,96 +832,96 @@ void Sbar_DrawFrags (void) Sbar_DrawFace =============== */ -void Sbar_DrawFace (void) +void Sbar_DrawFace(void) { - int32_t f, anim; + int32_t f, anim; // PGM 01/19/97 - team color drawing // PGM 03/02/97 - fixed so color swatch only appears in CTF modes - if (rogue && (cl.maxclients != 1) && (teamplay.value>3) && (teamplay.value<7)) + if(rogue && (cl.maxclients != 1) && (teamplay.value > 3) && (teamplay.value < 7)) { - int32_t top, bottom; - int32_t xofs; - char num[12]; - scoreboard_t *s; + int32_t top, bottom; + int32_t xofs; + char num[12]; + scoreboard_t *s; s = &cl.scores[cl.viewentity - 1]; // draw background top = s->colors & 0xf0; - bottom = (s->colors & 15)<<4; - top = Sbar_ColorForMap (top); - bottom = Sbar_ColorForMap (bottom); + bottom = (s->colors & 15) << 4; + top = Sbar_ColorForMap(top); + bottom = Sbar_ColorForMap(bottom); - if (cl.gametype == GAME_DEATHMATCH) + if(cl.gametype == GAME_DEATHMATCH) xofs = 113; else - xofs = ((vid.width - 320)>>1) + 113; + xofs = ((vid.width - 320) >> 1) + 113; - Sbar_DrawPic (112, 0, rsb_teambord); - Draw_Fill (xofs, /*vid.height-*/24+3, 22, 9, top, 1); //johnfitz -- sbar coords are now relative - Draw_Fill (xofs, /*vid.height-*/24+12, 22, 9, bottom, 1); //johnfitz -- sbar coords are now relative + Sbar_DrawPic(112, 0, rsb_teambord); + Draw_Fill(xofs, /*vid.height-*/24 + 3, 22, 9, top, 1); //johnfitz -- sbar coords are now relative + Draw_Fill(xofs, /*vid.height-*/24 + 12, 22, 9, bottom, 1); //johnfitz -- sbar coords are now relative // draw number f = s->frags; - sprintf (num, "%3" PRIi32 "",f); + sprintf(num, "%3" PRIi32 "", f); - if (top == 8) + if(top == 8) { - if (num[0] != ' ') + if(num[0] != ' ') Sbar_DrawCharacter(113, 3, 18 + num[0] - '0'); - if (num[1] != ' ') + if(num[1] != ' ') Sbar_DrawCharacter(120, 3, 18 + num[1] - '0'); - if (num[2] != ' ') + if(num[2] != ' ') Sbar_DrawCharacter(127, 3, 18 + num[2] - '0'); } else { - Sbar_DrawCharacter (113, 3, num[0]); - Sbar_DrawCharacter (120, 3, num[1]); - Sbar_DrawCharacter (127, 3, num[2]); + Sbar_DrawCharacter(113, 3, num[0]); + Sbar_DrawCharacter(120, 3, num[1]); + Sbar_DrawCharacter(127, 3, num[2]); } return; } // PGM 01/19/97 - team color drawing - if ((cl.items & (IT_INVISIBILITY | IT_INVULNERABILITY)) - == (IT_INVISIBILITY | IT_INVULNERABILITY)) + if((cl.items & (IT_INVISIBILITY | IT_INVULNERABILITY)) + == (IT_INVISIBILITY | IT_INVULNERABILITY)) { - Sbar_DrawPic (112, 0, sb_face_invis_invuln); + Sbar_DrawPic(112, 0, sb_face_invis_invuln); return; } - if (cl.items & IT_QUAD) + if(cl.items & IT_QUAD) { - Sbar_DrawPic (112, 0, sb_face_quad ); + Sbar_DrawPic(112, 0, sb_face_quad); return; } - if (cl.items & IT_INVISIBILITY) + if(cl.items & IT_INVISIBILITY) { - Sbar_DrawPic (112, 0, sb_face_invis ); + Sbar_DrawPic(112, 0, sb_face_invis); return; } - if (cl.items & IT_INVULNERABILITY) + if(cl.items & IT_INVULNERABILITY) { - Sbar_DrawPic (112, 0, sb_face_invuln); + Sbar_DrawPic(112, 0, sb_face_invuln); return; } - if (cl.stats[STAT_HEALTH] >= 100) + if(cl.stats[STAT_HEALTH] >= 100) f = 4; else f = cl.stats[STAT_HEALTH] / 20; - if (f < 0) // in case we ever decide to draw when health <= 0 + if(f < 0) // in case we ever decide to draw when health <= 0 f = 0; - if (cl.time <= cl.faceanimtime) + if(cl.time <= cl.faceanimtime) { anim = 1; - sb_updates = 0; // make sure the anim gets drawn over + sb_updates = 0; // make sure the anim gets drawn over } else anim = 0; - Sbar_DrawPic (112, 0, sb_faces[f][anim]); + Sbar_DrawPic(112, 0, sb_faces[f][anim]); } /* @@ -923,144 +929,144 @@ void Sbar_DrawFace (void) Sbar_Draw =============== */ -void Sbar_Draw (void) +void Sbar_Draw(void) { float w; //johnfitz - if (scr_con_current == vid.height) - return; // console is full screen + if(scr_con_current == vid.height) + return; // console is full screen - if (cl.intermission) + if(cl.intermission) return; //johnfitz -- never draw sbar during intermission - if (sb_updates >= vid.numpages && !gl_clear.value && scr_sbaralpha.value >= 1 //johnfitz -- gl_clear, scr_sbaralpha - && !(gl_glsl_gamma_able && vid_gamma.value != 1)) //ericw -- must draw sbar every frame if doing glsl gamma + if(sb_updates >= vid.numpages && !gl_clear.value && scr_sbaralpha.value >= 1 //johnfitz -- gl_clear, scr_sbaralpha + && !(gl_glsl_gamma_able && vid_gamma.value != 1)) //ericw -- must draw sbar every frame if doing glsl gamma return; sb_updates++; - GL_SetCanvas (CANVAS_DEFAULT); //johnfitz + GL_SetCanvas(CANVAS_DEFAULT); //johnfitz //johnfitz -- don't waste fillrate by clearing the area behind the sbar - w = CLAMP (320.0f, scr_sbarscale.value * 320.0f, (float)glwidth); - if (sb_lines && glwidth > w) + w = CLAMP(320.0f, scr_sbarscale.value * 320.0f, (float)glwidth); + if(sb_lines && glwidth > w) { - if (scr_sbaralpha.value < 1) - Draw_TileClear (0, glheight - sb_lines, glwidth, sb_lines); - if (cl.gametype == GAME_DEATHMATCH) - Draw_TileClear (w, glheight - sb_lines, glwidth - w, sb_lines); + if(scr_sbaralpha.value < 1) + Draw_TileClear(0, glheight - sb_lines, glwidth, sb_lines); + if(cl.gametype == GAME_DEATHMATCH) + Draw_TileClear(w, glheight - sb_lines, glwidth - w, sb_lines); else { - Draw_TileClear (0, glheight - sb_lines, (glwidth - w) / 2.0f, sb_lines); - Draw_TileClear ((glwidth - w) / 2.0f + w, glheight - sb_lines, (glwidth - w) / 2.0f, sb_lines); + Draw_TileClear(0, glheight - sb_lines, (glwidth - w) / 2.0f, sb_lines); + Draw_TileClear((glwidth - w) / 2.0f + w, glheight - sb_lines, (glwidth - w) / 2.0f, sb_lines); } } //johnfitz - GL_SetCanvas (CANVAS_SBAR); //johnfitz + GL_SetCanvas(CANVAS_SBAR); //johnfitz - if (scr_viewsize.value < 110) //johnfitz -- check viewsize instead of sb_lines + if(scr_viewsize.value < 110) //johnfitz -- check viewsize instead of sb_lines { - Sbar_DrawInventory (); - if (cl.maxclients != 1) - Sbar_DrawFrags (); + Sbar_DrawInventory(); + if(cl.maxclients != 1) + Sbar_DrawFrags(); } - if (sb_showscores || cl.stats[STAT_HEALTH] <= 0) + if(sb_showscores || cl.stats[STAT_HEALTH] <= 0) { - Sbar_DrawPicAlpha (0, 0, sb_scorebar, scr_sbaralpha.value); //johnfitz -- scr_sbaralpha - Sbar_DrawScoreboard (); + Sbar_DrawPicAlpha(0, 0, sb_scorebar, scr_sbaralpha.value); //johnfitz -- scr_sbaralpha + Sbar_DrawScoreboard(); sb_updates = 0; } - else if (scr_viewsize.value < 120) //johnfitz -- check viewsize instead of sb_lines + else if(scr_viewsize.value < 120) //johnfitz -- check viewsize instead of sb_lines { - Sbar_DrawPicAlpha (0, 0, sb_sbar, scr_sbaralpha.value); //johnfitz -- scr_sbaralpha + Sbar_DrawPicAlpha(0, 0, sb_sbar, scr_sbaralpha.value); //johnfitz -- scr_sbaralpha - // keys (hipnotic only) + // keys (hipnotic only) //MED 01/04/97 moved keys here so they would not be overwritten - if (hipnotic) + if(hipnotic) { - if (cl.items & IT_KEY1) - Sbar_DrawPic (209, 3, sb_items[0]); - if (cl.items & IT_KEY2) - Sbar_DrawPic (209, 12, sb_items[1]); + if(cl.items & IT_KEY1) + Sbar_DrawPic(209, 3, sb_items[0]); + if(cl.items & IT_KEY2) + Sbar_DrawPic(209, 12, sb_items[1]); } - // armor - if (cl.items & IT_INVULNERABILITY) + // armor + if(cl.items & IT_INVULNERABILITY) { - Sbar_DrawNum (24, 0, 666, 3, 1); - Sbar_DrawPic (0, 0, draw_disc); + Sbar_DrawNum(24, 0, 666, 3, 1); + Sbar_DrawPic(0, 0, draw_disc); } else { - if (rogue) + if(rogue) { - Sbar_DrawNum (24, 0, cl.stats[STAT_ARMOR], 3, - cl.stats[STAT_ARMOR] <= 25); - if (cl.items & RIT_ARMOR3) - Sbar_DrawPic (0, 0, sb_armor[2]); - else if (cl.items & RIT_ARMOR2) - Sbar_DrawPic (0, 0, sb_armor[1]); - else if (cl.items & RIT_ARMOR1) - Sbar_DrawPic (0, 0, sb_armor[0]); + Sbar_DrawNum(24, 0, cl.stats[STAT_ARMOR], 3, + cl.stats[STAT_ARMOR] <= 25); + if(cl.items & RIT_ARMOR3) + Sbar_DrawPic(0, 0, sb_armor[2]); + else if(cl.items & RIT_ARMOR2) + Sbar_DrawPic(0, 0, sb_armor[1]); + else if(cl.items & RIT_ARMOR1) + Sbar_DrawPic(0, 0, sb_armor[0]); } else { - Sbar_DrawNum (24, 0, cl.stats[STAT_ARMOR], 3 - , cl.stats[STAT_ARMOR] <= 25); - if (cl.items & IT_ARMOR3) - Sbar_DrawPic (0, 0, sb_armor[2]); - else if (cl.items & IT_ARMOR2) - Sbar_DrawPic (0, 0, sb_armor[1]); - else if (cl.items & IT_ARMOR1) - Sbar_DrawPic (0, 0, sb_armor[0]); + Sbar_DrawNum(24, 0, cl.stats[STAT_ARMOR], 3 + , cl.stats[STAT_ARMOR] <= 25); + if(cl.items & IT_ARMOR3) + Sbar_DrawPic(0, 0, sb_armor[2]); + else if(cl.items & IT_ARMOR2) + Sbar_DrawPic(0, 0, sb_armor[1]); + else if(cl.items & IT_ARMOR1) + Sbar_DrawPic(0, 0, sb_armor[0]); } } - // face - Sbar_DrawFace (); + // face + Sbar_DrawFace(); - // health - Sbar_DrawNum (136, 0, cl.stats[STAT_HEALTH], 3 - , cl.stats[STAT_HEALTH] <= 25); + // health + Sbar_DrawNum(136, 0, cl.stats[STAT_HEALTH], 3 + , cl.stats[STAT_HEALTH] <= 25); - // ammo icon - if (rogue) + // ammo icon + if(rogue) { - if (cl.items & RIT_SHELLS) - Sbar_DrawPic (224, 0, sb_ammo[0]); - else if (cl.items & RIT_NAILS) - Sbar_DrawPic (224, 0, sb_ammo[1]); - else if (cl.items & RIT_ROCKETS) - Sbar_DrawPic (224, 0, sb_ammo[2]); - else if (cl.items & RIT_CELLS) - Sbar_DrawPic (224, 0, sb_ammo[3]); - else if (cl.items & RIT_LAVA_NAILS) - Sbar_DrawPic (224, 0, rsb_ammo[0]); - else if (cl.items & RIT_PLASMA_AMMO) - Sbar_DrawPic (224, 0, rsb_ammo[1]); - else if (cl.items & RIT_MULTI_ROCKETS) - Sbar_DrawPic (224, 0, rsb_ammo[2]); + if(cl.items & RIT_SHELLS) + Sbar_DrawPic(224, 0, sb_ammo[0]); + else if(cl.items & RIT_NAILS) + Sbar_DrawPic(224, 0, sb_ammo[1]); + else if(cl.items & RIT_ROCKETS) + Sbar_DrawPic(224, 0, sb_ammo[2]); + else if(cl.items & RIT_CELLS) + Sbar_DrawPic(224, 0, sb_ammo[3]); + else if(cl.items & RIT_LAVA_NAILS) + Sbar_DrawPic(224, 0, rsb_ammo[0]); + else if(cl.items & RIT_PLASMA_AMMO) + Sbar_DrawPic(224, 0, rsb_ammo[1]); + else if(cl.items & RIT_MULTI_ROCKETS) + Sbar_DrawPic(224, 0, rsb_ammo[2]); } else { - if (cl.items & IT_SHELLS) - Sbar_DrawPic (224, 0, sb_ammo[0]); - else if (cl.items & IT_NAILS) - Sbar_DrawPic (224, 0, sb_ammo[1]); - else if (cl.items & IT_ROCKETS) - Sbar_DrawPic (224, 0, sb_ammo[2]); - else if (cl.items & IT_CELLS) - Sbar_DrawPic (224, 0, sb_ammo[3]); + if(cl.items & IT_SHELLS) + Sbar_DrawPic(224, 0, sb_ammo[0]); + else if(cl.items & IT_NAILS) + Sbar_DrawPic(224, 0, sb_ammo[1]); + else if(cl.items & IT_ROCKETS) + Sbar_DrawPic(224, 0, sb_ammo[2]); + else if(cl.items & IT_CELLS) + Sbar_DrawPic(224, 0, sb_ammo[3]); } - Sbar_DrawNum (248, 0, cl.stats[STAT_AMMO], 3, - cl.stats[STAT_AMMO] <= 10); + Sbar_DrawNum(248, 0, cl.stats[STAT_AMMO], 3, + cl.stats[STAT_AMMO] <= 10); } //johnfitz -- removed the vid.width > 320 check here - if (cl.gametype == GAME_DEATHMATCH) - Sbar_MiniDeathmatchOverlay (); + if(cl.gametype == GAME_DEATHMATCH) + Sbar_MiniDeathmatchOverlay(); } //============================================================================= @@ -1071,27 +1077,27 @@ Sbar_IntermissionNumber ================== */ -void Sbar_IntermissionNumber (int32_t x, int32_t y, int32_t num, int32_t digits, int32_t color) +void Sbar_IntermissionNumber(int32_t x, int32_t y, int32_t num, int32_t digits, int32_t color) { - char str[12]; - char *ptr; - int32_t l, frame; + char str[12]; + char *ptr; + int32_t l, frame; - l = Sbar_itoa (num, str); + l = Sbar_itoa(num, str); ptr = str; - if (l > digits) - ptr += (l-digits); - if (l < digits) - x += (digits-l)*24; + if(l > digits) + ptr += (l - digits); + if(l < digits) + x += (digits - l) * 24; - while (*ptr) + while(*ptr) { - if (*ptr == '-') + if(*ptr == '-') frame = STAT_MINUS; else - frame = *ptr -'0'; + frame = *ptr - '0'; - Draw_Pic (x,y,sb_nums[color][frame]); //johnfitz -- stretched menus + Draw_Pic(x, y, sb_nums[color][frame]); //johnfitz -- stretched menus x += 24; ptr++; } @@ -1103,62 +1109,62 @@ Sbar_DeathmatchOverlay ================== */ -void Sbar_DeathmatchOverlay (void) +void Sbar_DeathmatchOverlay(void) { - qpic_t *pic; - int32_t i, k, l; - int32_t top, bottom; - int32_t x, y, f; - char num[12]; - scoreboard_t *s; + qpic_t *pic; + int32_t i, k, l; + int32_t top, bottom; + int32_t x, y, f; + char num[12]; + scoreboard_t *s; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - pic = Draw_CachePic ("gfx/ranking.lmp"); - M_DrawPic ((320-pic->width)/2, 8, pic); + pic = Draw_CachePic("gfx/ranking.lmp"); + M_DrawPic((320 - pic->width) / 2, 8, pic); // scores - Sbar_SortFrags (); + Sbar_SortFrags(); // draw the text l = scoreboardlines; x = 80; //johnfitz -- simplified becuase some positioning is handled elsewhere y = 40; - for (i = 0; i < l; i++) + for(i = 0; i < l; i++) { k = fragsort[i]; s = &cl.scores[k]; - if (!s->name[0]) + if(!s->name[0]) continue; - // draw background + // draw background top = s->colors & 0xf0; - bottom = (s->colors & 15)<<4; - top = Sbar_ColorForMap (top); - bottom = Sbar_ColorForMap (bottom); + bottom = (s->colors & 15) << 4; + top = Sbar_ColorForMap(top); + bottom = Sbar_ColorForMap(bottom); - Draw_Fill ( x, y, 40, 4, top, 1); //johnfitz -- stretched overlays - Draw_Fill ( x, y+4, 40, 4, bottom, 1); //johnfitz -- stretched overlays + Draw_Fill(x, y, 40, 4, top, 1); //johnfitz -- stretched overlays + Draw_Fill(x, y + 4, 40, 4, bottom, 1); //johnfitz -- stretched overlays - // draw number + // draw number f = s->frags; - sprintf (num, "%3" PRIi32 "",f); + sprintf(num, "%3" PRIi32 "", f); - Draw_Character ( x+8 , y, num[0]); //johnfitz -- stretched overlays - Draw_Character ( x+16 , y, num[1]); //johnfitz -- stretched overlays - Draw_Character ( x+24 , y, num[2]); //johnfitz -- stretched overlays + Draw_Character(x + 8, y, num[0]); //johnfitz -- stretched overlays + Draw_Character(x + 16, y, num[1]); //johnfitz -- stretched overlays + Draw_Character(x + 24, y, num[2]); //johnfitz -- stretched overlays - if (k == cl.viewentity - 1) - Draw_Character ( x - 8, y, 12); //johnfitz -- stretched overlays + if(k == cl.viewentity - 1) + Draw_Character(x - 8, y, 12); //johnfitz -- stretched overlays - // draw name - M_Print (x+64, y, s->name); //johnfitz -- was Draw_String, changed for stretched overlays + // draw name + M_Print(x + 64, y, s->name); //johnfitz -- was Draw_String, changed for stretched overlays y += 10; } - GL_SetCanvas (CANVAS_SBAR); //johnfitz + GL_SetCanvas(CANVAS_SBAR); //johnfitz } /* @@ -1166,72 +1172,72 @@ void Sbar_DeathmatchOverlay (void) Sbar_MiniDeathmatchOverlay ================== */ -void Sbar_MiniDeathmatchOverlay (void) +void Sbar_MiniDeathmatchOverlay(void) { - int32_t i, k, top, bottom, x, y, f, numlines; - char num[12]; - float scale; //johnfitz - scoreboard_t *s; + int32_t i, k, top, bottom, x, y, f, numlines; + char num[12]; + float scale; //johnfitz + scoreboard_t *s; - scale = CLAMP (1.0, scr_sbarscale.value, (float)glwidth / 320.0); //johnfitz + scale = CLAMP(1.0, scr_sbarscale.value, (float)glwidth / 320.0); //johnfitz //MAX_SCOREBOARDNAME = 32, so total width for this overlay plus sbar is 632, but we can cut off some i guess - if (glwidth/scale < 512 || scr_viewsize.value >= 120) //johnfitz -- test should consider scr_sbarscale + if(glwidth / scale < 512 || scr_viewsize.value >= 120) //johnfitz -- test should consider scr_sbarscale return; // scores - Sbar_SortFrags (); + Sbar_SortFrags(); // draw the text numlines = (scr_viewsize.value >= 110) ? 3 : 6; //johnfitz //find us - for (i = 0; i < scoreboardlines; i++) - if (fragsort[i] == cl.viewentity - 1) + for(i = 0; i < scoreboardlines; i++) + if(fragsort[i] == cl.viewentity - 1) break; - if (i == scoreboardlines) // we're not there + if(i == scoreboardlines) // we're not there i = 0; else // figure out start - i = i - numlines/2; - if (i > scoreboardlines - numlines) + i = i - numlines / 2; + if(i > scoreboardlines - numlines) i = scoreboardlines - numlines; - if (i < 0) + if(i < 0) i = 0; x = 324; y = (scr_viewsize.value >= 110) ? 24 : 0; //johnfitz -- start at the right place - for ( ; i < scoreboardlines && y <= 48; i++, y+=8) //johnfitz -- change y init, test, inc + for(; i < scoreboardlines && y <= 48; i++, y += 8) //johnfitz -- change y init, test, inc { k = fragsort[i]; s = &cl.scores[k]; - if (!s->name[0]) + if(!s->name[0]) continue; - // colors + // colors top = s->colors & 0xf0; - bottom = (s->colors & 15)<<4; - top = Sbar_ColorForMap (top); - bottom = Sbar_ColorForMap (bottom); + bottom = (s->colors & 15) << 4; + top = Sbar_ColorForMap(top); + bottom = Sbar_ColorForMap(bottom); - Draw_Fill (x, y+1, 40, 4, top, 1); - Draw_Fill (x, y+5, 40, 3, bottom, 1); + Draw_Fill(x, y + 1, 40, 4, top, 1); + Draw_Fill(x, y + 5, 40, 3, bottom, 1); - // number + // number f = s->frags; - sprintf (num, "%3" PRIi32 "",f); - Draw_Character (x+ 8, y, num[0]); - Draw_Character (x+16, y, num[1]); - Draw_Character (x+24, y, num[2]); + sprintf(num, "%3" PRIi32 "", f); + Draw_Character(x + 8, y, num[0]); + Draw_Character(x + 16, y, num[1]); + Draw_Character(x + 24, y, num[2]); - // brackets - if (k == cl.viewentity - 1) + // brackets + if(k == cl.viewentity - 1) { - Draw_Character (x, y, 16); - Draw_Character (x+32, y, 17); + Draw_Character(x, y, 16); + Draw_Character(x + 32, y, 17); } - // name - Draw_String (x+48, y, s->name); + // name + Draw_String(x + 48, y, s->name); } } @@ -1240,40 +1246,40 @@ void Sbar_MiniDeathmatchOverlay (void) Sbar_IntermissionOverlay ================== */ -void Sbar_IntermissionOverlay (void) +void Sbar_IntermissionOverlay(void) { - qpic_t *pic; - int32_t dig; - int32_t num; + qpic_t *pic; + int32_t dig; + int32_t num; - if (cl.gametype == GAME_DEATHMATCH) + if(cl.gametype == GAME_DEATHMATCH) { - Sbar_DeathmatchOverlay (); + Sbar_DeathmatchOverlay(); return; } - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - pic = Draw_CachePic ("gfx/complete.lmp"); - Draw_Pic (64, 24, pic); + pic = Draw_CachePic("gfx/complete.lmp"); + Draw_Pic(64, 24, pic); - pic = Draw_CachePic ("gfx/inter.lmp"); - Draw_Pic (0, 56, pic); + pic = Draw_CachePic("gfx/inter.lmp"); + Draw_Pic(0, 56, pic); - dig = cl.completed_time/60; - Sbar_IntermissionNumber (152, 64, dig, 3, 0); //johnfitz -- was 160 - num = cl.completed_time - dig*60; - Draw_Pic (224,64,sb_colon); //johnfitz -- was 234 - Draw_Pic (240,64,sb_nums[0][num/10]); //johnfitz -- was 246 - Draw_Pic (264,64,sb_nums[0][num%10]); //johnfitz -- was 266 + dig = cl.completed_time / 60; + Sbar_IntermissionNumber(152, 64, dig, 3, 0); //johnfitz -- was 160 + num = cl.completed_time - dig * 60; + Draw_Pic(224, 64, sb_colon); //johnfitz -- was 234 + Draw_Pic(240, 64, sb_nums[0][num / 10]); //johnfitz -- was 246 + Draw_Pic(264, 64, sb_nums[0][num % 10]); //johnfitz -- was 266 - Sbar_IntermissionNumber (152, 104, cl.stats[STAT_SECRETS], 3, 0); //johnfitz -- was 160 - Draw_Pic (224,104,sb_slash); //johnfitz -- was 232 - Sbar_IntermissionNumber (240, 104, cl.stats[STAT_TOTALSECRETS], 3, 0); //johnfitz -- was 248 + Sbar_IntermissionNumber(152, 104, cl.stats[STAT_SECRETS], 3, 0); //johnfitz -- was 160 + Draw_Pic(224, 104, sb_slash); //johnfitz -- was 232 + Sbar_IntermissionNumber(240, 104, cl.stats[STAT_TOTALSECRETS], 3, 0); //johnfitz -- was 248 - Sbar_IntermissionNumber (152, 144, cl.stats[STAT_MONSTERS], 3, 0); //johnfitz -- was 160 - Draw_Pic (224,144,sb_slash); //johnfitz -- was 232 - Sbar_IntermissionNumber (240, 144, cl.stats[STAT_TOTALMONSTERS], 3, 0); //johnfitz -- was 248 + Sbar_IntermissionNumber(152, 144, cl.stats[STAT_MONSTERS], 3, 0); //johnfitz -- was 160 + Draw_Pic(224, 144, sb_slash); //johnfitz -- was 232 + Sbar_IntermissionNumber(240, 144, cl.stats[STAT_TOTALMONSTERS], 3, 0); //johnfitz -- was 248 } @@ -1282,13 +1288,13 @@ void Sbar_IntermissionOverlay (void) Sbar_FinaleOverlay ================== */ -void Sbar_FinaleOverlay (void) +void Sbar_FinaleOverlay(void) { - qpic_t *pic; + qpic_t *pic; - GL_SetCanvas (CANVAS_MENU); //johnfitz + GL_SetCanvas(CANVAS_MENU); //johnfitz - pic = Draw_CachePic ("gfx/finale.lmp"); - Draw_Pic ( (320 - pic->width)/2, 16, pic); //johnfitz -- stretched menus + pic = Draw_CachePic("gfx/finale.lmp"); + Draw_Pic((320 - pic->width) / 2, 16, pic); //johnfitz -- stretched menus } diff --git a/source/sbar.h b/source/sbar.h index 695f065..ff88c0f 100644 --- a/source/sbar.h +++ b/source/sbar.h @@ -26,21 +26,21 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // the status bar is only redrawn if something has changed, but if anything // does, the entire thing will be redrawn for the next vid.numpages frames. -extern int32_t sb_lines; // scan lines to draw +extern int32_t sb_lines; // scan lines to draw -void Sbar_Init (void); -void Sbar_LoadPics (void); +void Sbar_Init(void); +void Sbar_LoadPics(void); -void Sbar_Changed (void); +void Sbar_Changed(void); // call whenever any of the client stats represented on the sbar changes -void Sbar_Draw (void); +void Sbar_Draw(void); // called every frame by screen -void Sbar_IntermissionOverlay (void); +void Sbar_IntermissionOverlay(void); // called each frame after the level has been completed -void Sbar_FinaleOverlay (void); +void Sbar_FinaleOverlay(void); -#endif /* _QUAKE_SBAR_H */ +#endif /* _QUAKE_SBAR_H */ diff --git a/source/screen.h b/source/screen.h index c994982..8751e70 100644 --- a/source/screen.h +++ b/source/screen.h @@ -25,39 +25,40 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // screen.h -void SCR_Init (void); -void SCR_LoadPics (void); +void SCR_Init(void); +void SCR_LoadPics(void); -void SCR_UpdateScreen (void); +void SCR_UpdateScreen(void); -void SCR_SizeUp (void); -void SCR_SizeDown (void); -void SCR_BringDownConsole (void); -void SCR_CenterPrint (const char *str); +void SCR_SizeUp(void); +void SCR_SizeDown(void); +void SCR_BringDownConsole(void); +void SCR_CenterPrint(const char *str); -void SCR_BeginLoadingPlaque (void); -void SCR_EndLoadingPlaque (void); +void SCR_BeginLoadingPlaque(void); +void SCR_EndLoadingPlaque(void); -int32_t SCR_ModalMessage (const char *text, float timeout); //johnfitz -- added timeout +int32_t SCR_ModalMessage(const char *text, float timeout); //johnfitz -- added timeout -extern float scr_con_current; -extern float scr_conlines; // lines of console to display +extern float scr_con_current; +extern float scr_conlines; // lines of console to display -extern int32_t sb_lines; +extern int32_t sb_lines; -extern int32_t clearnotify; // set to 0 whenever notify text is drawn -extern bool scr_disabled_for_loading; -extern bool scr_skipupdate; +extern int32_t clearnotify; // set to 0 whenever notify text is drawn +extern bool scr_disabled_for_loading; +extern bool scr_skipupdate; -extern cvar_t scr_viewsize; +extern cvar_t scr_viewsize; -extern cvar_t scr_sbaralpha; //johnfitz +extern cvar_t scr_sbaralpha; //johnfitz -void SCR_UpdateWholeScreen (void); +void SCR_UpdateWholeScreen(void); //johnfitz -- stuff for 2d drawing control -typedef enum { +typedef enum +{ CANVAS_NONE, CANVAS_DEFAULT, CANVAS_CONSOLE, @@ -70,15 +71,15 @@ typedef enum { CANVAS_TOPRIGHT, CANVAS_INVALID = -1 } canvastype; -extern cvar_t scr_menuscale; -extern cvar_t scr_sbarscale; -extern cvar_t scr_conwidth; -extern cvar_t scr_conscale; -extern cvar_t scr_scale; -extern cvar_t scr_crosshairscale; +extern cvar_t scr_menuscale; +extern cvar_t scr_sbarscale; +extern cvar_t scr_conwidth; +extern cvar_t scr_conscale; +extern cvar_t scr_scale; +extern cvar_t scr_crosshairscale; //johnfitz extern int32_t scr_tileclear_updates; //johnfitz -#endif /* _QUAKE_SCREEN_H */ +#endif /* _QUAKE_SCREEN_H */ diff --git a/source/server.h b/source/server.h index ea00a5b..915e56c 100644 --- a/source/server.h +++ b/source/server.h @@ -27,11 +27,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. typedef struct { - int32_t maxclients; - int32_t maxclientslimit; - struct client_s *clients; // [maxclients] - int32_t serverflags; // episode completion information - bool changelevel_issued; // cleared when at SV_SpawnServer + int32_t maxclients; + int32_t maxclientslimit; + struct client_s *clients; // [maxclients] + int32_t serverflags; // episode completion information + bool changelevel_issued; // cleared when at SV_SpawnServer } server_static_t; //============================================================================= @@ -40,193 +40,193 @@ typedef enum {ss_loading, ss_active} server_state_t; typedef struct { - bool active; // false if only a net client + bool active; // false if only a net client - bool paused; - bool loadgame; // handle connections specially + bool paused; + bool loadgame; // handle connections specially - double time; + double time; - int32_t lastcheck; // used by PF_checkclient - double lastchecktime; + int32_t lastcheck; // used by PF_checkclient + double lastchecktime; - char name[64]; // map name - char modelname[64]; // maps/.bsp, for model_precache[0] - struct qmodel_s *worldmodel; - const char *model_precache[MAX_MODELS]; // NULL terminated - struct qmodel_s *models[MAX_MODELS]; - const char *sound_precache[MAX_SOUNDS]; // NULL terminated - const char *lightstyles[MAX_LIGHTSTYLES]; - int32_t num_edicts; - int32_t max_edicts; - edict_t *edicts; // can NOT be array indexed, because - // edict_t is variable sized, but can - // be used to reference the world ent - server_state_t state; // some actions are only valid during load + char name[64]; // map name + char modelname[64]; // maps/.bsp, for model_precache[0] + struct qmodel_s *worldmodel; + const char *model_precache[MAX_MODELS]; // NULL terminated + struct qmodel_s *models[MAX_MODELS]; + const char *sound_precache[MAX_SOUNDS]; // NULL terminated + const char *lightstyles[MAX_LIGHTSTYLES]; + int32_t num_edicts; + int32_t max_edicts; + edict_t *edicts; // can NOT be array indexed, because + // edict_t is variable sized, but can + // be used to reference the world ent + server_state_t state; // some actions are only valid during load - sizebuf_t datagram; - byte datagram_buf[MAX_DATAGRAM]; + sizebuf_t datagram; + byte datagram_buf[MAX_DATAGRAM]; - sizebuf_t reliable_datagram; // copied to all clients at end of frame - byte reliable_datagram_buf[MAX_DATAGRAM]; + sizebuf_t reliable_datagram; // copied to all clients at end of frame + byte reliable_datagram_buf[MAX_DATAGRAM]; - sizebuf_t signon; - byte signon_buf[MAX_MSGLEN-2]; //johnfitz -- was 8192, now uses MAX_MSGLEN + sizebuf_t signon; + byte signon_buf[MAX_MSGLEN - 2]; //johnfitz -- was 8192, now uses MAX_MSGLEN - unsigned protocol; //johnfitz - unsigned protocolflags; + unsigned protocol; //johnfitz + unsigned protocolflags; } server_t; -#define NUM_PING_TIMES 16 -#define NUM_SPAWN_PARMS 16 +#define NUM_PING_TIMES 16 +#define NUM_SPAWN_PARMS 16 typedef struct client_s { - bool active; // false = client is free - bool spawned; // false = don't send datagrams - bool dropasap; // has been told to go to another level - bool sendsignon; // only valid before spawned + bool active; // false = client is free + bool spawned; // false = don't send datagrams + bool dropasap; // has been told to go to another level + bool sendsignon; // only valid before spawned - double last_message; // reliable messages must be sent - // periodically + double last_message; // reliable messages must be sent + // periodically - struct qsocket_s *netconnection; // communications handle + struct qsocket_s *netconnection; // communications handle - usercmd_t cmd; // movement - vec3_t wishdir; // intended motion calced from cmd + usercmd_t cmd; // movement + vec3_t wishdir; // intended motion calced from cmd - sizebuf_t message; // can be added to at any time, - // copied and clear once per frame - byte msgbuf[MAX_MSGLEN]; - edict_t *edict; // EDICT_NUM(clientnum+1) - char name[32]; // for printing to other people - int32_t colors; + sizebuf_t message; // can be added to at any time, + // copied and clear once per frame + byte msgbuf[MAX_MSGLEN]; + edict_t *edict; // EDICT_NUM(clientnum+1) + char name[32]; // for printing to other people + int32_t colors; - float ping_times[NUM_PING_TIMES]; - int32_t num_pings; // ping_times[num_pings%NUM_PING_TIMES] + float ping_times[NUM_PING_TIMES]; + int32_t num_pings; // ping_times[num_pings%NUM_PING_TIMES] // spawn parms are carried from level to level - float spawn_parms[NUM_SPAWN_PARMS]; + float spawn_parms[NUM_SPAWN_PARMS]; // client known data for deltas - int32_t old_frags; + int32_t old_frags; } client_t; //============================================================================= // edict->movetype values -#define MOVETYPE_NONE 0 // never moves -#define MOVETYPE_ANGLENOCLIP 1 -#define MOVETYPE_ANGLECLIP 2 -#define MOVETYPE_WALK 3 // gravity -#define MOVETYPE_STEP 4 // gravity, special edge handling -#define MOVETYPE_FLY 5 -#define MOVETYPE_TOSS 6 // gravity -#define MOVETYPE_PUSH 7 // no clip to world, push and crush -#define MOVETYPE_NOCLIP 8 -#define MOVETYPE_FLYMISSILE 9 // extra size to monsters -#define MOVETYPE_BOUNCE 10 +#define MOVETYPE_NONE 0 // never moves +#define MOVETYPE_ANGLENOCLIP 1 +#define MOVETYPE_ANGLECLIP 2 +#define MOVETYPE_WALK 3 // gravity +#define MOVETYPE_STEP 4 // gravity, special edge handling +#define MOVETYPE_FLY 5 +#define MOVETYPE_TOSS 6 // gravity +#define MOVETYPE_PUSH 7 // no clip to world, push and crush +#define MOVETYPE_NOCLIP 8 +#define MOVETYPE_FLYMISSILE 9 // extra size to monsters +#define MOVETYPE_BOUNCE 10 // edict->solid values -#define SOLID_NOT 0 // no interaction with other objects -#define SOLID_TRIGGER 1 // touch on edge, but not blocking -#define SOLID_BBOX 2 // touch on edge, block -#define SOLID_SLIDEBOX 3 // touch on edge, but not an onground -#define SOLID_BSP 4 // bsp clip, touch on edge, block +#define SOLID_NOT 0 // no interaction with other objects +#define SOLID_TRIGGER 1 // touch on edge, but not blocking +#define SOLID_BBOX 2 // touch on edge, block +#define SOLID_SLIDEBOX 3 // touch on edge, but not an onground +#define SOLID_BSP 4 // bsp clip, touch on edge, block // edict->deadflag values -#define DEAD_NO 0 -#define DEAD_DYING 1 -#define DEAD_DEAD 2 +#define DEAD_NO 0 +#define DEAD_DYING 1 +#define DEAD_DEAD 2 -#define DAMAGE_NO 0 -#define DAMAGE_YES 1 -#define DAMAGE_AIM 2 +#define DAMAGE_NO 0 +#define DAMAGE_YES 1 +#define DAMAGE_AIM 2 // edict->flags -#define FL_FLY 1 -#define FL_SWIM 2 -//#define FL_GLIMPSE 4 -#define FL_CONVEYOR 4 -#define FL_CLIENT 8 -#define FL_INWATER 16 -#define FL_MONSTER 32 -#define FL_GODMODE 64 -#define FL_NOTARGET 128 -#define FL_ITEM 256 -#define FL_ONGROUND 512 -#define FL_PARTIALGROUND 1024 // not all corners are valid -#define FL_WATERJUMP 2048 // player jumping out of water -#define FL_JUMPRELEASED 4096 // for jump debouncing +#define FL_FLY 1 +#define FL_SWIM 2 +//#define FL_GLIMPSE 4 +#define FL_CONVEYOR 4 +#define FL_CLIENT 8 +#define FL_INWATER 16 +#define FL_MONSTER 32 +#define FL_GODMODE 64 +#define FL_NOTARGET 128 +#define FL_ITEM 256 +#define FL_ONGROUND 512 +#define FL_PARTIALGROUND 1024 // not all corners are valid +#define FL_WATERJUMP 2048 // player jumping out of water +#define FL_JUMPRELEASED 4096 // for jump debouncing // entity effects -#define EF_BRIGHTFIELD 1 -#define EF_MUZZLEFLASH 2 -#define EF_BRIGHTLIGHT 4 -#define EF_DIMLIGHT 8 +#define EF_BRIGHTFIELD 1 +#define EF_MUZZLEFLASH 2 +#define EF_BRIGHTLIGHT 4 +#define EF_DIMLIGHT 8 -#define SPAWNFLAG_NOT_EASY 256 -#define SPAWNFLAG_NOT_MEDIUM 512 -#define SPAWNFLAG_NOT_HARD 1024 -#define SPAWNFLAG_NOT_DEATHMATCH 2048 +#define SPAWNFLAG_NOT_EASY 256 +#define SPAWNFLAG_NOT_MEDIUM 512 +#define SPAWNFLAG_NOT_HARD 1024 +#define SPAWNFLAG_NOT_DEATHMATCH 2048 //============================================================================ -extern cvar_t teamplay; -extern cvar_t skill; -extern cvar_t deathmatch; -extern cvar_t coop; -extern cvar_t fraglimit; -extern cvar_t timelimit; +extern cvar_t teamplay; +extern cvar_t skill; +extern cvar_t deathmatch; +extern cvar_t coop; +extern cvar_t fraglimit; +extern cvar_t timelimit; -extern server_static_t svs; // persistant server info -extern server_t sv; // local server +extern server_static_t svs; // persistant server info +extern server_t sv; // local server -extern client_t *host_client; +extern client_t *host_client; -extern edict_t *sv_player; +extern edict_t *sv_player; //=========================================================== -void SV_Init (void); +void SV_Init(void); -void SV_StartParticle (vec3_t org, vec3_t dir, int32_t color, int32_t count); -void SV_StartSound (edict_t *entity, int32_t channel, const char *sample, int32_t volume, - float attenuation); +void SV_StartParticle(vec3_t org, vec3_t dir, int32_t color, int32_t count); +void SV_StartSound(edict_t *entity, int32_t channel, const char *sample, int32_t volume, + float attenuation); -void SV_DropClient (bool crash); +void SV_DropClient(bool crash); -void SV_SendClientMessages (void); -void SV_ClearDatagram (void); +void SV_SendClientMessages(void); +void SV_ClearDatagram(void); -int32_t SV_ModelIndex (const char *name); +int32_t SV_ModelIndex(const char *name); -void SV_SetIdealPitch (void); +void SV_SetIdealPitch(void); -void SV_AddUpdates (void); +void SV_AddUpdates(void); -void SV_ClientThink (void); -void SV_AddClientToServer (struct qsocket_s *ret); +void SV_ClientThink(void); +void SV_AddClientToServer(struct qsocket_s *ret); -void SV_ClientPrintf (const char *fmt, ...) FUNC_PRINTF(1,2); -void SV_BroadcastPrintf (const char *fmt, ...) FUNC_PRINTF(1,2); +void SV_ClientPrintf(const char *fmt, ...) FUNC_PRINTF(1, 2); +void SV_BroadcastPrintf(const char *fmt, ...) FUNC_PRINTF(1, 2); -void SV_Physics (void); +void SV_Physics(void); -bool SV_CheckBottom (edict_t *ent); -bool SV_movestep (edict_t *ent, vec3_t move, bool relink); +bool SV_CheckBottom(edict_t *ent); +bool SV_movestep(edict_t *ent, vec3_t move, bool relink); -void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg); +void SV_WriteClientdataToMessage(edict_t *ent, sizebuf_t *msg); -void SV_MoveToGoal (void); +void SV_MoveToGoal(void); -void SV_CheckForNewClients (void); -void SV_RunClients (void); -void SV_SaveSpawnparms (); -void SV_SpawnServer (const char *server); +void SV_CheckForNewClients(void); +void SV_RunClients(void); +void SV_SaveSpawnparms(); +void SV_SpawnServer(const char *server); -#endif /* _QUAKE_SERVER_H */ +#endif /* _QUAKE_SERVER_H */ diff --git a/source/snd_codec.c b/source/snd_codec.c index dfea2e2..c5f22f3 100644 --- a/source/snd_codec.c +++ b/source/snd_codec.c @@ -54,7 +54,7 @@ static void S_CodecRegister(snd_codec_t *codec) S_CodecInit ================= */ -void S_CodecInit (void) +void S_CodecInit(void) { snd_codec_t *codec; codecs = NULL; @@ -79,7 +79,7 @@ void S_CodecInit (void) #endif codec = codecs; - while (codec) + while(codec) { codec->initialize(); codec = codec->next; @@ -91,10 +91,10 @@ void S_CodecInit (void) S_CodecShutdown ================= */ -void S_CodecShutdown (void) +void S_CodecShutdown(void) { snd_codec_t *codec = codecs; - while (codec) + while(codec) { codec->shutdown(); codec = codec->next; @@ -107,90 +107,94 @@ void S_CodecShutdown (void) S_CodecOpenStream ================= */ -snd_stream_t *S_CodecOpenStreamType (const char *filename, uint32_t type) +snd_stream_t *S_CodecOpenStreamType(const char *filename, uint32_t type) { snd_codec_t *codec; snd_stream_t *stream; - if (type == CODECTYPE_NONE) + if(type == CODECTYPE_NONE) { Con_Printf("Bad type for %s\n", filename); return NULL; } codec = codecs; - while (codec) + while(codec) { - if (type == codec->type) + if(type == codec->type) break; codec = codec->next; } - if (!codec) + if(!codec) { Con_Printf("Unknown type for %s\n", filename); return NULL; } stream = S_CodecUtilOpen(filename, codec); - if (stream) { - if (codec->codec_open(stream)) + if(stream) + { + if(codec->codec_open(stream)) stream->status = STREAM_PLAY; - else S_CodecUtilClose(&stream); + else S_CodecUtilClose(&stream); } return stream; } -snd_stream_t *S_CodecOpenStreamExt (const char *filename) +snd_stream_t *S_CodecOpenStreamExt(const char *filename) { snd_codec_t *codec; snd_stream_t *stream; const char *ext; ext = COM_FileGetExtension(filename); - if (! *ext) + if(! *ext) { Con_Printf("No extension for %s\n", filename); return NULL; } codec = codecs; - while (codec) + while(codec) { - if (!q_strcasecmp(ext, codec->ext)) + if(!q_strcasecmp(ext, codec->ext)) break; codec = codec->next; } - if (!codec) + if(!codec) { Con_Printf("Unknown extension for %s\n", filename); return NULL; } stream = S_CodecUtilOpen(filename, codec); - if (stream) { - if (codec->codec_open(stream)) + if(stream) + { + if(codec->codec_open(stream)) stream->status = STREAM_PLAY; - else S_CodecUtilClose(&stream); + else S_CodecUtilClose(&stream); } return stream; } -snd_stream_t *S_CodecOpenStreamAny (const char *filename) +snd_stream_t *S_CodecOpenStreamAny(const char *filename) { snd_codec_t *codec; snd_stream_t *stream; const char *ext; ext = COM_FileGetExtension(filename); - if (! *ext) /* try all available */ + if(! *ext) /* try all available */ { char tmp[MAX_QPATH]; codec = codecs; - while (codec) + while(codec) { q_snprintf(tmp, sizeof(tmp), "%s.%s", filename, codec->ext); stream = S_CodecUtilOpen(tmp, codec); - if (stream) { - if (codec->codec_open(stream)) { + if(stream) + { + if(codec->codec_open(stream)) + { stream->status = STREAM_PLAY; return stream; } @@ -201,57 +205,58 @@ snd_stream_t *S_CodecOpenStreamAny (const char *filename) return NULL; } - else /* use the name as is */ + else /* use the name as is */ { codec = codecs; - while (codec) + while(codec) { - if (!q_strcasecmp(ext, codec->ext)) + if(!q_strcasecmp(ext, codec->ext)) break; codec = codec->next; } - if (!codec) + if(!codec) { Con_Printf("Unknown extension for %s\n", filename); return NULL; } stream = S_CodecUtilOpen(filename, codec); - if (stream) { - if (codec->codec_open(stream)) + if(stream) + { + if(codec->codec_open(stream)) stream->status = STREAM_PLAY; - else S_CodecUtilClose(&stream); + else S_CodecUtilClose(&stream); } return stream; } } -bool S_CodecForwardStream (snd_stream_t *stream, uint32_t type) +bool S_CodecForwardStream(snd_stream_t *stream, uint32_t type) { snd_codec_t *codec = codecs; - while (codec) + while(codec) { - if (type == codec->type) + if(type == codec->type) break; codec = codec->next; } - if (!codec) return false; + if(!codec) return false; stream->codec = codec; return codec->codec_open(stream); } -void S_CodecCloseStream (snd_stream_t *stream) +void S_CodecCloseStream(snd_stream_t *stream) { stream->status = STREAM_NONE; stream->codec->codec_close(stream); } -int32_t S_CodecRewindStream (snd_stream_t *stream) +int32_t S_CodecRewindStream(snd_stream_t *stream) { return stream->codec->codec_rewind(stream); } -int32_t S_CodecReadStream (snd_stream_t *stream, int32_t bytes, void *buffer) +int32_t S_CodecReadStream(snd_stream_t *stream, int32_t bytes, void *buffer) { return stream->codec->codec_read(stream, bytes, buffer); } @@ -268,7 +273,7 @@ snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec) /* Try to open the file */ length = (long) COM_FOpenFile(filename, &handle, NULL); pak = file_from_pak; - if (length == -1) + if(length == -1) { Con_DPrintf("Couldn't open %s\n", filename); return NULL; @@ -294,12 +299,12 @@ void S_CodecUtilClose(snd_stream_t **stream) *stream = NULL; } -int32_t S_CodecIsAvailable (uint32_t type) +int32_t S_CodecIsAvailable(uint32_t type) { snd_codec_t *codec = codecs; - while (codec) + while(codec) { - if (type == codec->type) + if(type == codec->type) return codec->initialized; codec = codec->next; } diff --git a/source/snd_codec.h b/source/snd_codec.h index 3ebca6e..8e595ad 100644 --- a/source/snd_codec.h +++ b/source/snd_codec.h @@ -37,7 +37,8 @@ typedef struct snd_info_s int32_t dataofs; } snd_info_t; -typedef enum { +typedef enum +{ STREAM_NONE = -1, STREAM_INIT, STREAM_PAUSE, @@ -50,55 +51,55 @@ typedef struct snd_stream_s { fshandle_t fh; bool pak; - char name[MAX_QPATH]; /* name of the source file */ + char name[MAX_QPATH]; /* name of the source file */ snd_info_t info; stream_status_t status; - snd_codec_t *codec; /* codec handling this stream */ - void *priv; /* data private to the codec. */ + snd_codec_t *codec; /* codec handling this stream */ + void *priv; /* data private to the codec. */ } snd_stream_t; -void S_CodecInit (void); -void S_CodecShutdown (void); +void S_CodecInit(void); +void S_CodecShutdown(void); /* Callers of the following S_CodecOpenStream* functions * are reponsible for attaching any path to the filename */ -snd_stream_t *S_CodecOpenStreamType (const char *filename, uint32_t type); - /* Decides according to the required type. */ +snd_stream_t *S_CodecOpenStreamType(const char *filename, uint32_t type); +/* Decides according to the required type. */ -snd_stream_t *S_CodecOpenStreamAny (const char *filename); - /* Decides according to file extension. if the - * name has no extension, try all available. */ +snd_stream_t *S_CodecOpenStreamAny(const char *filename); +/* Decides according to file extension. if the + * name has no extension, try all available. */ -snd_stream_t *S_CodecOpenStreamExt (const char *filename); - /* Decides according to file extension. the name - * MUST have an extension. */ +snd_stream_t *S_CodecOpenStreamExt(const char *filename); +/* Decides according to file extension. the name + * MUST have an extension. */ -void S_CodecCloseStream (snd_stream_t *stream); -int32_t S_CodecReadStream (snd_stream_t *stream, int32_t bytes, void *buffer); -int32_t S_CodecRewindStream (snd_stream_t *stream); +void S_CodecCloseStream(snd_stream_t *stream); +int32_t S_CodecReadStream(snd_stream_t *stream, int32_t bytes, void *buffer); +int32_t S_CodecRewindStream(snd_stream_t *stream); snd_stream_t *S_CodecUtilOpen(const char *filename, snd_codec_t *codec); void S_CodecUtilClose(snd_stream_t **stream); -#define CODECTYPE_NONE 0 -#define CODECTYPE_MID (1U << 0) -#define CODECTYPE_MOD (1U << 1) -#define CODECTYPE_FLAC (1U << 2) -#define CODECTYPE_WAV (1U << 3) -#define CODECTYPE_MP3 (1U << 4) -#define CODECTYPE_VORBIS (1U << 5) -#define CODECTYPE_OPUS (1U << 6) -#define CODECTYPE_UMX (1U << 7) +#define CODECTYPE_NONE 0 +#define CODECTYPE_MID (1U << 0) +#define CODECTYPE_MOD (1U << 1) +#define CODECTYPE_FLAC (1U << 2) +#define CODECTYPE_WAV (1U << 3) +#define CODECTYPE_MP3 (1U << 4) +#define CODECTYPE_VORBIS (1U << 5) +#define CODECTYPE_OPUS (1U << 6) +#define CODECTYPE_UMX (1U << 7) -#define CODECTYPE_WAVE CODECTYPE_WAV -#define CODECTYPE_MIDI CODECTYPE_MID +#define CODECTYPE_WAVE CODECTYPE_WAV +#define CODECTYPE_MIDI CODECTYPE_MID -int32_t S_CodecIsAvailable (uint32_t type); - /* return 1 if available, 0 if codec failed init - * or -1 if no such codec is present. */ +int32_t S_CodecIsAvailable(uint32_t type); +/* return 1 if available, 0 if codec failed init + * or -1 if no such codec is present. */ -#endif /* _SND_CODEC_H_ */ +#endif /* _SND_CODEC_H_ */ diff --git a/source/snd_codeci.h b/source/snd_codeci.h index 2d00a45..1361a9a 100644 --- a/source/snd_codeci.h +++ b/source/snd_codeci.h @@ -36,9 +36,9 @@ typedef void (*CODEC_CLOSE)(snd_stream_t *stream); struct snd_codec_s { - uint32_t type; /* handled data type. (1U << n) */ - bool initialized; /* init succeedded */ - const char *ext; /* expected extension */ + uint32_t type; /* handled data type. (1U << n) */ + bool initialized; /* init succeedded */ + const char *ext; /* expected extension */ CODEC_INIT initialize; CODEC_SHUTDOWN shutdown; CODEC_OPEN codec_open; @@ -48,8 +48,8 @@ struct snd_codec_s snd_codec_t *next; }; -bool S_CodecForwardStream (snd_stream_t *stream, uint32_t type); - /* Forward a stream to another codec of 'type' type. */ +bool S_CodecForwardStream(snd_stream_t *stream, uint32_t type); +/* Forward a stream to another codec of 'type' type. */ -#endif /* _SND_CODECI_H_ */ +#endif /* _SND_CODECI_H_ */ diff --git a/source/snd_dma.c b/source/snd_dma.c index 26a19c0..e9710ed 100644 --- a/source/snd_dma.c +++ b/source/snd_dma.c @@ -28,56 +28,56 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "snd_codec.h" #include "bgmusic.h" -static void S_Play (void); -static void S_PlayVol (void); -static void S_SoundList (void); -static void S_Update_ (void); -void S_StopAllSounds (bool clear); -static void S_StopAllSoundsC (void); +static void S_Play(void); +static void S_PlayVol(void); +static void S_SoundList(void); +static void S_Update_(void); +void S_StopAllSounds(bool clear); +static void S_StopAllSoundsC(void); // ======================================================================= // Internal sound data & structures // ======================================================================= -channel_t snd_channels[MAX_CHANNELS]; -int32_t total_channels; +channel_t snd_channels[MAX_CHANNELS]; +int32_t total_channels; -static int32_t snd_blocked = 0; -static bool snd_initialized = false; +static int32_t snd_blocked = 0; +static bool snd_initialized = false; -static dma_t sn; -volatile dma_t *shm = NULL; +static dma_t sn; +volatile dma_t *shm = NULL; -vec3_t listener_origin; -vec3_t listener_forward; -vec3_t listener_right; -vec3_t listener_up; +vec3_t listener_origin; +vec3_t listener_forward; +vec3_t listener_right; +vec3_t listener_up; -#define sound_nominal_clip_dist 1000.0 +#define sound_nominal_clip_dist 1000.0 -int32_t soundtime; // sample PAIRS -int32_t paintedtime; // sample PAIRS +int32_t soundtime; // sample PAIRS +int32_t paintedtime; // sample PAIRS -int32_t s_rawend; -portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; +int32_t s_rawend; +portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; -#define MAX_SFX 1024 -static sfx_t *known_sfx = NULL; // hunk allocated [MAX_SFX] -static int32_t num_sfx; +#define MAX_SFX 1024 +static sfx_t *known_sfx = NULL; // hunk allocated [MAX_SFX] +static int32_t num_sfx; -static sfx_t *ambient_sfx[NUM_AMBIENTS]; +static sfx_t *ambient_sfx[NUM_AMBIENTS]; -static bool sound_started = false; +static bool sound_started = false; -cvar_t bgmvolume = {"bgmvolume", "1", CVAR_ARCHIVE}; -cvar_t sfxvolume = {"volume", "0.7", CVAR_ARCHIVE}; +cvar_t bgmvolume = {"bgmvolume", "1", CVAR_ARCHIVE}; +cvar_t sfxvolume = {"volume", "0.7", CVAR_ARCHIVE}; -cvar_t precache = {"precache", "1", CVAR_NONE}; -cvar_t loadas8bit = {"loadas8bit", "0", CVAR_NONE}; +cvar_t precache = {"precache", "1", CVAR_NONE}; +cvar_t loadas8bit = {"loadas8bit", "0", CVAR_NONE}; -cvar_t sndspeed = {"sndspeed", "11025", CVAR_NONE}; -cvar_t snd_mixspeed = {"snd_mixspeed", "44100", CVAR_NONE}; +cvar_t sndspeed = {"sndspeed", "11025", CVAR_NONE}; +cvar_t snd_mixspeed = {"snd_mixspeed", "44100", CVAR_NONE}; #if defined(_WIN32) #define SND_FILTERQUALITY_DEFAULT "5" @@ -85,27 +85,28 @@ cvar_t snd_mixspeed = {"snd_mixspeed", "44100", CVAR_NONE}; #define SND_FILTERQUALITY_DEFAULT "1" #endif -cvar_t snd_filterquality = {"snd_filterquality", SND_FILTERQUALITY_DEFAULT, - CVAR_NONE}; +cvar_t snd_filterquality = {"snd_filterquality", SND_FILTERQUALITY_DEFAULT, + CVAR_NONE + }; -static cvar_t nosound = {"nosound", "0", CVAR_NONE}; -static cvar_t ambient_level = {"ambient_level", "0.3", CVAR_NONE}; -static cvar_t ambient_fade = {"ambient_fade", "100", CVAR_NONE}; -static cvar_t snd_noextraupdate = {"snd_noextraupdate", "0", CVAR_NONE}; -static cvar_t snd_show = {"snd_show", "0", CVAR_NONE}; -static cvar_t _snd_mixahead = {"_snd_mixahead", "0.1", CVAR_ARCHIVE}; +static cvar_t nosound = {"nosound", "0", CVAR_NONE}; +static cvar_t ambient_level = {"ambient_level", "0.3", CVAR_NONE}; +static cvar_t ambient_fade = {"ambient_fade", "100", CVAR_NONE}; +static cvar_t snd_noextraupdate = {"snd_noextraupdate", "0", CVAR_NONE}; +static cvar_t snd_show = {"snd_show", "0", CVAR_NONE}; +static cvar_t _snd_mixahead = {"_snd_mixahead", "0.1", CVAR_ARCHIVE}; -static void S_SoundInfo_f (void) +static void S_SoundInfo_f(void) { - if (!sound_started || !shm) + if(!sound_started || !shm) { - Con_Printf ("sound system not started\n"); + Con_Printf("sound system not started\n"); return; } Con_Printf("%" PRIi32 " bit, %s, %" PRIi32 " Hz\n", shm->samplebits, - (shm->channels == 2) ? "stereo" : "mono", shm->speed); + (shm->channels == 2) ? "stereo" : "mono", shm->speed); Con_Printf("%5" PRIi32 " samples\n", shm->samples); Con_Printf("%5" PRIi32 " samplepos\n", shm->samplepos); Con_Printf("%5" PRIi32 " submission_chunk\n", shm->submission_chunk); @@ -114,19 +115,19 @@ static void S_SoundInfo_f (void) } -static void SND_Callback_sfxvolume (cvar_t *var) +static void SND_Callback_sfxvolume(cvar_t *var) { (void)var; - SND_InitScaletable (); + SND_InitScaletable(); } -static void SND_Callback_snd_filterquality (cvar_t *var) +static void SND_Callback_snd_filterquality(cvar_t *var) { (void)var; - if (snd_filterquality.value < 1 || snd_filterquality.value > 5) + if(snd_filterquality.value < 1 || snd_filterquality.value > 5) { - Con_Printf ("snd_filterquality must be between 1 and 5\n"); - Cvar_SetQuick (&snd_filterquality, SND_FILTERQUALITY_DEFAULT); + Con_Printf("snd_filterquality must be between 1 and 5\n"); + Cvar_SetQuick(&snd_filterquality, SND_FILTERQUALITY_DEFAULT); } } @@ -135,23 +136,23 @@ static void SND_Callback_snd_filterquality (cvar_t *var) S_Startup ================ */ -void S_Startup (void) +void S_Startup(void) { - if (!snd_initialized) + if(!snd_initialized) return; sound_started = SNDDMA_Init(&sn); - if (!sound_started) + if(!sound_started) { Con_Printf("Failed initializing sound\n"); } else { Con_Printf("Audio: %" PRIi32 " bit, %s, %" PRIi32 " Hz\n", - shm->samplebits, - (shm->channels == 2) ? "stereo" : "mono", - shm->speed); + shm->samplebits, + (shm->channels == 2) ? "stereo" : "mono", + shm->speed); } } @@ -161,11 +162,11 @@ void S_Startup (void) S_Init ================ */ -void S_Init (void) +void S_Init(void) { int32_t i; - if (snd_initialized) + if(snd_initialized) { Con_Printf("Sound is already initialized\n"); return; @@ -185,7 +186,7 @@ void S_Init (void) Cvar_RegisterVariable(&snd_mixspeed); Cvar_RegisterVariable(&snd_filterquality); - if (safemode || COM_CheckParm("-nosound")) + if(safemode || COM_CheckParm("-nosound")) return; Con_Printf("\nSound Initialization\n"); @@ -197,56 +198,56 @@ void S_Init (void) Cmd_AddCommand("soundinfo", S_SoundInfo_f); i = COM_CheckParm("-sndspeed"); - if (i && i < com_argc-1) + if(i && i < com_argc - 1) { - Cvar_SetQuick (&sndspeed, com_argv[i+1]); + Cvar_SetQuick(&sndspeed, com_argv[i + 1]); } i = COM_CheckParm("-mixspeed"); - if (i && i < com_argc-1) + if(i && i < com_argc - 1) { - Cvar_SetQuick (&snd_mixspeed, com_argv[i+1]); + Cvar_SetQuick(&snd_mixspeed, com_argv[i + 1]); } - if (host_parms->memsize < 0x800000) + if(host_parms->memsize < 0x800000) { - Cvar_SetQuick (&loadas8bit, "1"); - Con_Printf ("loading all sounds as 8bit\n"); + Cvar_SetQuick(&loadas8bit, "1"); + Con_Printf("loading all sounds as 8bit\n"); } Cvar_SetCallback(&sfxvolume, SND_Callback_sfxvolume); Cvar_SetCallback(&snd_filterquality, &SND_Callback_snd_filterquality); - SND_InitScaletable (); + SND_InitScaletable(); - known_sfx = (sfx_t *) Hunk_AllocName (MAX_SFX*sizeof(sfx_t), "sfx_t"); + known_sfx = (sfx_t *) Hunk_AllocName(MAX_SFX * sizeof(sfx_t), "sfx_t"); num_sfx = 0; snd_initialized = true; - S_Startup (); - if (sound_started == 0) + S_Startup(); + if(sound_started == 0) return; // provides a tick sound until washed clean // if (shm->buffer) -// shm->buffer[4] = shm->buffer[5] = 0x7f; // force a pop for debugging +// shm->buffer[4] = shm->buffer[5] = 0x7f; // force a pop for debugging - ambient_sfx[AMBIENT_WATER] = S_PrecacheSound ("ambience/water1.wav"); - ambient_sfx[AMBIENT_SKY] = S_PrecacheSound ("ambience/wind2.wav"); + ambient_sfx[AMBIENT_WATER] = S_PrecacheSound("ambience/water1.wav"); + ambient_sfx[AMBIENT_SKY] = S_PrecacheSound("ambience/wind2.wav"); - S_CodecInit (); + S_CodecInit(); - S_StopAllSounds (true); + S_StopAllSounds(true); } // ======================================================================= // Shutdown sound engine // ======================================================================= -void S_Shutdown (void) +void S_Shutdown(void) { - if (!sound_started) + if(!sound_started) return; sound_started = 0; @@ -269,31 +270,31 @@ S_FindName ================== */ -static sfx_t *S_FindName (const char *name) +static sfx_t *S_FindName(const char *name) { - int32_t i; - sfx_t *sfx; + int32_t i; + sfx_t *sfx; - if (!name) - Sys_Error ("S_FindName: NULL"); + if(!name) + Sys_Error("S_FindName: NULL"); - if (Q_strlen(name) >= MAX_QPATH) - Sys_Error ("Sound name too long: %s", name); + if(Q_strlen(name) >= MAX_QPATH) + Sys_Error("Sound name too long: %s", name); // see if already loaded - for (i = 0; i < num_sfx; i++) + for(i = 0; i < num_sfx; i++) { - if (!Q_strcmp(known_sfx[i].name, name)) + if(!Q_strcmp(known_sfx[i].name, name)) { return &known_sfx[i]; } } - if (num_sfx == MAX_SFX) - Sys_Error ("S_FindName: out of sfx_t"); + if(num_sfx == MAX_SFX) + Sys_Error("S_FindName: out of sfx_t"); sfx = &known_sfx[i]; - q_strlcpy (sfx->name, name, sizeof(sfx->name)); + q_strlcpy(sfx->name, name, sizeof(sfx->name)); num_sfx++; @@ -307,15 +308,15 @@ S_TouchSound ================== */ -void S_TouchSound (const char *name) +void S_TouchSound(const char *name) { - sfx_t *sfx; + sfx_t *sfx; - if (!sound_started) + if(!sound_started) return; - sfx = S_FindName (name); - Cache_Check (&sfx->cache); + sfx = S_FindName(name); + Cache_Check(&sfx->cache); } /* @@ -324,18 +325,18 @@ S_PrecacheSound ================== */ -sfx_t *S_PrecacheSound (const char *name) +sfx_t *S_PrecacheSound(const char *name) { - sfx_t *sfx; + sfx_t *sfx; - if (!sound_started || nosound.value) + if(!sound_started || nosound.value) return NULL; - sfx = S_FindName (name); + sfx = S_FindName(name); // cache it in - if (precache.value) - S_LoadSound (sfx); + if(precache.value) + S_LoadSound(sfx); return sfx; } @@ -350,40 +351,41 @@ SND_PickChannel picks a channel based on priorities, empty slots, number of channels ================= */ -channel_t *SND_PickChannel (int32_t entnum, int32_t entchannel) +channel_t *SND_PickChannel(int32_t entnum, int32_t entchannel) { - int32_t ch_idx; - int32_t first_to_die; - int32_t life_left; + int32_t ch_idx; + int32_t first_to_die; + int32_t life_left; // Check for replacement sound, or find the best one to replace first_to_die = -1; life_left = 0x7fffffff; - for (ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; ch_idx++) + for(ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; ch_idx++) { - if (entchannel != 0 // channel 0 never overrides - && snd_channels[ch_idx].entnum == entnum - && (snd_channels[ch_idx].entchannel == entchannel || entchannel == -1) ) - { // always override sound from same entity + if(entchannel != 0 // channel 0 never overrides + && snd_channels[ch_idx].entnum == entnum + && (snd_channels[ch_idx].entchannel == entchannel || entchannel == -1)) + { + // always override sound from same entity first_to_die = ch_idx; break; } // don't let monster sounds override player sounds - if (snd_channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity && snd_channels[ch_idx].sfx) + if(snd_channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity && snd_channels[ch_idx].sfx) continue; - if (snd_channels[ch_idx].end - paintedtime < life_left) + if(snd_channels[ch_idx].end - paintedtime < life_left) { life_left = snd_channels[ch_idx].end - paintedtime; first_to_die = ch_idx; } } - if (first_to_die == -1) + if(first_to_die == -1) return NULL; - if (snd_channels[first_to_die].sfx) + if(snd_channels[first_to_die].sfx) snd_channels[first_to_die].sfx = NULL; return &snd_channels[first_to_die]; @@ -396,15 +398,15 @@ SND_Spatialize spatializes a channel ================= */ -void SND_Spatialize (channel_t *ch) +void SND_Spatialize(channel_t *ch) { - vec_t dot; - vec_t dist; - vec_t lscale, rscale, scale; - vec3_t source_vec; + vec_t dot; + vec_t dist; + vec_t lscale, rscale, scale; + vec3_t source_vec; // anything coming from the view entity will always be full volume - if (ch->entnum == cl.viewentity) + if(ch->entnum == cl.viewentity) { ch->leftvol = ch->master_vol; ch->rightvol = ch->master_vol; @@ -416,7 +418,7 @@ void SND_Spatialize (channel_t *ch) dist = VectorNormalize(source_vec) * ch->dist_mult; dot = DotProduct(listener_right, source_vec); - if (shm->channels == 1) + if(shm->channels == 1) { rscale = 1.0; lscale = 1.0; @@ -429,13 +431,13 @@ void SND_Spatialize (channel_t *ch) // add in distance effect scale = (1.0 - dist) * rscale; - ch->rightvol = (int32_t) (ch->master_vol * scale); - if (ch->rightvol < 0) + ch->rightvol = (int32_t)(ch->master_vol * scale); + if(ch->rightvol < 0) ch->rightvol = 0; scale = (1.0 - dist) * lscale; - ch->leftvol = (int32_t) (ch->master_vol * scale); - if (ch->leftvol < 0) + ch->leftvol = (int32_t)(ch->master_vol * scale); + if(ch->leftvol < 0) ch->leftvol = 0; } @@ -444,45 +446,45 @@ void SND_Spatialize (channel_t *ch) // Start a sound effect // ======================================================================= -void S_StartSound (int32_t entnum, int32_t entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation) +void S_StartSound(int32_t entnum, int32_t entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation) { - channel_t *target_chan, *check; - sfxcache_t *sc; - int32_t ch_idx; - int32_t skip; + channel_t *target_chan, *check; + sfxcache_t *sc; + int32_t ch_idx; + int32_t skip; - if (!sound_started) + if(!sound_started) return; - if (!sfx) + if(!sfx) return; - if (nosound.value) + if(nosound.value) return; // pick a channel to play on target_chan = SND_PickChannel(entnum, entchannel); - if (!target_chan) + if(!target_chan) return; // spatialize - memset (target_chan, 0, sizeof(*target_chan)); + memset(target_chan, 0, sizeof(*target_chan)); VectorCopy(origin, target_chan->origin); target_chan->dist_mult = attenuation / sound_nominal_clip_dist; - target_chan->master_vol = (int32_t) (fvol * 255); + target_chan->master_vol = (int32_t)(fvol * 255); target_chan->entnum = entnum; target_chan->entchannel = entchannel; SND_Spatialize(target_chan); - if (!target_chan->leftvol && !target_chan->rightvol) - return; // not audible at all + if(!target_chan->leftvol && !target_chan->rightvol) + return; // not audible at all // new channel - sc = S_LoadSound (sfx); - if (!sc) + sc = S_LoadSound(sfx); + if(!sc) { target_chan->sfx = NULL; - return; // couldn't load the sound's data + return; // couldn't load the sound's data } target_chan->sfx = sfx; @@ -492,22 +494,22 @@ void S_StartSound (int32_t entnum, int32_t entchannel, sfx_t *sfx, vec3_t origin // if an identical sound has also been started this frame, offset the pos // a bit to keep it from just making the first one louder check = &snd_channels[NUM_AMBIENTS]; - for (ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; ch_idx++, check++) + for(ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; ch_idx++, check++) { - if (check == target_chan) + if(check == target_chan) continue; - if (check->sfx == sfx && !check->pos) + if(check->sfx == sfx && !check->pos) { /* skip = rand () % (int32_t)(0.1 * shm->speed); if (skip >= target_chan->end) - skip = target_chan->end - 1; + skip = target_chan->end - 1; */ /* LordHavoc: fixed skip calculations */ skip = 0.1 * shm->speed; /* 0.1 * sc->speed */ - if (skip > sc->length) + if(skip > sc->length) skip = sc->length; - if (skip > 0) + if(skip > 0) skip = rand() % skip; target_chan->pos += skip; target_chan->end -= skip; @@ -516,14 +518,14 @@ void S_StartSound (int32_t entnum, int32_t entchannel, sfx_t *sfx, vec3_t origin } } -void S_StopSound (int32_t entnum, int32_t entchannel) +void S_StopSound(int32_t entnum, int32_t entchannel) { - int32_t i; + int32_t i; - for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++) + for(i = 0; i < MAX_DYNAMIC_CHANNELS; i++) { - if (snd_channels[i].entnum == entnum - && snd_channels[i].entchannel == entchannel) + if(snd_channels[i].entnum == entnum + && snd_channels[i].entchannel == entchannel) { snd_channels[i].end = 0; snd_channels[i].sfx = NULL; @@ -532,53 +534,53 @@ void S_StopSound (int32_t entnum, int32_t entchannel) } } -void S_StopAllSounds (bool clear) +void S_StopAllSounds(bool clear) { - int32_t i; + int32_t i; - if (!sound_started) + if(!sound_started) return; - total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics + total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; // no statics - for (i = 0; i < MAX_CHANNELS; i++) + for(i = 0; i < MAX_CHANNELS; i++) { - if (snd_channels[i].sfx) + if(snd_channels[i].sfx) snd_channels[i].sfx = NULL; } memset(snd_channels, 0, MAX_CHANNELS * sizeof(channel_t)); - if (clear) - S_ClearBuffer (); + if(clear) + S_ClearBuffer(); } -static void S_StopAllSoundsC (void) +static void S_StopAllSoundsC(void) { - S_StopAllSounds (true); + S_StopAllSounds(true); } -void S_ClearBuffer (void) +void S_ClearBuffer(void) { - int32_t clear; + int32_t clear; - if (!sound_started || !shm) + if(!sound_started || !shm) return; - SNDDMA_LockBuffer (); - if (! shm->buffer) + SNDDMA_LockBuffer(); + if(! shm->buffer) return; s_rawend = 0; - if (shm->samplebits == 8 && !shm->signed8) + if(shm->samplebits == 8 && !shm->signed8) clear = 0x80; else clear = 0; memset(shm->buffer, clear, shm->samples * shm->samplebits / 8); - SNDDMA_Submit (); + SNDDMA_Submit(); } @@ -587,40 +589,40 @@ void S_ClearBuffer (void) S_StaticSound ================= */ -void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation) +void S_StaticSound(sfx_t *sfx, vec3_t origin, float vol, float attenuation) { - channel_t *ss; - sfxcache_t *sc; + channel_t *ss; + sfxcache_t *sc; - if (!sfx) + if(!sfx) return; - if (total_channels == MAX_CHANNELS) + if(total_channels == MAX_CHANNELS) { - Con_Printf ("total_channels == MAX_CHANNELS\n"); + Con_Printf("total_channels == MAX_CHANNELS\n"); return; } ss = &snd_channels[total_channels]; total_channels++; - sc = S_LoadSound (sfx); - if (!sc) + sc = S_LoadSound(sfx); + if(!sc) return; - if (sc->loopstart == -1) + if(sc->loopstart == -1) { - Con_Printf ("Sound %s not looped\n", sfx->name); + Con_Printf("Sound %s not looped\n", sfx->name); return; } ss->sfx = sfx; - VectorCopy (origin, ss->origin); + VectorCopy(origin, ss->origin); ss->master_vol = (int32_t)vol; ss->dist_mult = (attenuation / 64) / sound_nominal_clip_dist; ss->end = paintedtime + sc->length; - SND_Spatialize (ss); + SND_Spatialize(ss); } @@ -631,47 +633,47 @@ void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation) S_UpdateAmbientSounds =================== */ -static void S_UpdateAmbientSounds (void) +static void S_UpdateAmbientSounds(void) { - mleaf_t *l; - int32_t vol, ambient_channel; - channel_t *chan; + mleaf_t *l; + int32_t vol, ambient_channel; + channel_t *chan; // no ambients when disconnected - if (cls.state != ca_connected) + if(cls.state != ca_connected) return; // calc ambient sound levels - if (!cl.worldmodel) + if(!cl.worldmodel) return; - l = Mod_PointInLeaf (listener_origin, cl.worldmodel); - if (!l || !ambient_level.value) + l = Mod_PointInLeaf(listener_origin, cl.worldmodel); + if(!l || !ambient_level.value) { - for (ambient_channel = 0; ambient_channel < NUM_AMBIENTS; ambient_channel++) + for(ambient_channel = 0; ambient_channel < NUM_AMBIENTS; ambient_channel++) snd_channels[ambient_channel].sfx = NULL; return; } - for (ambient_channel = 0; ambient_channel < NUM_AMBIENTS; ambient_channel++) + for(ambient_channel = 0; ambient_channel < NUM_AMBIENTS; ambient_channel++) { chan = &snd_channels[ambient_channel]; chan->sfx = ambient_sfx[ambient_channel]; - vol = (int32_t) (ambient_level.value * l->ambient_sound_level[ambient_channel]); - if (vol < 8) + vol = (int32_t)(ambient_level.value * l->ambient_sound_level[ambient_channel]); + if(vol < 8) vol = 0; - // don't adjust volume too fast - if (chan->master_vol < vol) + // don't adjust volume too fast + if(chan->master_vol < vol) { - chan->master_vol += (int32_t) (host_frametime * ambient_fade.value); - if (chan->master_vol > vol) + chan->master_vol += (int32_t)(host_frametime * ambient_fade.value); + if(chan->master_vol > vol) chan->master_vol = vol; } - else if (chan->master_vol > vol) + else if(chan->master_vol > vol) { - chan->master_vol -= (int32_t) (host_frametime * ambient_fade.value); - if (chan->master_vol < vol) + chan->master_vol -= (int32_t)(host_frametime * ambient_fade.value); + if(chan->master_vol < vol) chan->master_vol = vol; } @@ -682,7 +684,7 @@ static void S_UpdateAmbientSounds (void) /* =================== -S_RawSamples (from QuakeII) +S_RawSamples (from QuakeII) Streaming music support. Byte swapping of data must be handled by the codec. @@ -690,25 +692,25 @@ Expects data in signed 16 bit, or unsigned 8 bit format. =================== */ -void S_RawSamples (int32_t samples, int32_t rate, int32_t width, int32_t channels, byte *data, float volume) +void S_RawSamples(int32_t samples, int32_t rate, int32_t width, int32_t channels, byte *data, float volume) { int32_t i; int32_t src, dst; float scale; int32_t intVolume; - if (s_rawend < paintedtime) + if(s_rawend < paintedtime) s_rawend = paintedtime; scale = (float) rate / shm->speed; - intVolume = (int32_t) (256 * volume); + intVolume = (int32_t)(256 * volume); - if (channels == 2 && width == 2) + if(channels == 2 && width == 2) { - for (i = 0; ; i++) + for(i = 0; ; i++) { src = i * scale; - if (src >= samples) + if(src >= samples) break; dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; @@ -716,12 +718,12 @@ void S_RawSamples (int32_t samples, int32_t rate, int32_t width, int32_t channel s_rawsamples [dst].right = ((int16_t *) data)[src * 2 + 1] * intVolume; } } - else if (channels == 1 && width == 2) + else if(channels == 1 && width == 2) { - for (i = 0; ; i++) + for(i = 0; ; i++) { src = i * scale; - if (src >= samples) + if(src >= samples) break; dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; @@ -729,36 +731,36 @@ void S_RawSamples (int32_t samples, int32_t rate, int32_t width, int32_t channel s_rawsamples [dst].right = ((int16_t *) data)[src] * intVolume; } } - else if (channels == 2 && width == 1) + else if(channels == 2 && width == 1) { intVolume *= 256; - for (i = 0; ; i++) + for(i = 0; ; i++) { src = i * scale; - if (src >= samples) + if(src >= samples) break; dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - // s_rawsamples [dst].left = ((int8_t *) data)[src * 2] * intVolume; - // s_rawsamples [dst].right = ((int8_t *) data)[src * 2 + 1] * intVolume; + // s_rawsamples [dst].left = ((int8_t *) data)[src * 2] * intVolume; + // s_rawsamples [dst].right = ((int8_t *) data)[src * 2 + 1] * intVolume; s_rawsamples [dst].left = (((byte *) data)[src * 2] - 128) * intVolume; s_rawsamples [dst].right = (((byte *) data)[src * 2 + 1] - 128) * intVolume; } } - else if (channels == 1 && width == 1) + else if(channels == 1 && width == 1) { intVolume *= 256; - for (i = 0; ; i++) + for(i = 0; ; i++) { src = i * scale; - if (src >= samples) + if(src >= samples) break; dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - // s_rawsamples [dst].left = ((int8_t *) data)[src] * intVolume; - // s_rawsamples [dst].right = ((int8_t *) data)[src] * intVolume; + // s_rawsamples [dst].left = ((int8_t *) data)[src] * intVolume; + // s_rawsamples [dst].right = ((int8_t *) data)[src] * intVolume; s_rawsamples [dst].left = (((byte *) data)[src] - 128) * intVolume; s_rawsamples [dst].right = (((byte *) data)[src] - 128) * intVolume; } @@ -772,14 +774,14 @@ S_Update Called once each time through the main loop ============ */ -void S_Update (vec3_t origin, vec3_t forward, vec3_t right, vec3_t up) +void S_Update(vec3_t origin, vec3_t forward, vec3_t right, vec3_t up) { - int32_t i, j; - int32_t total; - channel_t *ch; - channel_t *combine; + int32_t i, j; + int32_t total; + channel_t *ch; + channel_t *combine; - if (!sound_started || (snd_blocked > 0)) + if(!sound_started || (snd_blocked > 0)) return; VectorCopy(origin, listener_origin); @@ -788,48 +790,48 @@ void S_Update (vec3_t origin, vec3_t forward, vec3_t right, vec3_t up) VectorCopy(up, listener_up); // update general area ambient sound sources - S_UpdateAmbientSounds (); + S_UpdateAmbientSounds(); combine = NULL; // update spatialization for static and dynamic sounds ch = snd_channels + NUM_AMBIENTS; - for (i = NUM_AMBIENTS; i < total_channels; i++, ch++) + for(i = NUM_AMBIENTS; i < total_channels; i++, ch++) { - if (!ch->sfx) + if(!ch->sfx) continue; - SND_Spatialize(ch); // respatialize channel - if (!ch->leftvol && !ch->rightvol) + SND_Spatialize(ch); // respatialize channel + if(!ch->leftvol && !ch->rightvol) continue; - // try to combine static sounds with a previous channel of the same - // sound effect so we don't mix five torches every frame + // try to combine static sounds with a previous channel of the same + // sound effect so we don't mix five torches every frame - if (i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS) + if(i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS) { - // see if it can just use the last one - if (combine && combine->sfx == ch->sfx) + // see if it can just use the last one + if(combine && combine->sfx == ch->sfx) { combine->leftvol += ch->leftvol; combine->rightvol += ch->rightvol; ch->leftvol = ch->rightvol = 0; continue; } - // search for one + // search for one combine = snd_channels + MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; - for (j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; j < i; j++, combine++) + for(j = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; j < i; j++, combine++) { - if (combine->sfx == ch->sfx) + if(combine->sfx == ch->sfx) break; } - if (j == total_channels) + if(j == total_channels) { combine = NULL; } else { - if (combine != ch) + if(combine != ch) { combine->leftvol += ch->leftvol; combine->rightvol += ch->rightvol; @@ -843,34 +845,34 @@ void S_Update (vec3_t origin, vec3_t forward, vec3_t right, vec3_t up) // // debugging output // - if (snd_show.value) + if(snd_show.value) { total = 0; ch = snd_channels; - for (i = 0; i < total_channels; i++, ch++) + for(i = 0; i < total_channels; i++, ch++) { - if (ch->sfx && (ch->leftvol || ch->rightvol) ) + if(ch->sfx && (ch->leftvol || ch->rightvol)) { total++; } } - Con_Printf ("----(%" PRIi32 ")----\n", total); + Con_Printf("----(%" PRIi32 ")----\n", total); } // add raw data from streamed samples -// BGM_Update(); // moved to the main loop just before S_Update () +// BGM_Update(); // moved to the main loop just before S_Update () // mix some sound S_Update_(); } -static void GetSoundtime (void) +static void GetSoundtime(void) { - int32_t samplepos; - static int32_t buffers; - static int32_t oldsamplepos; - int32_t fullsamples; + int32_t samplepos; + static int32_t buffers; + static int32_t oldsamplepos; + int32_t fullsamples; fullsamples = shm->samples / shm->channels; @@ -878,48 +880,49 @@ static void GetSoundtime (void) // calls to S_Update. Oh well. samplepos = SNDDMA_GetDMAPos(); - if (samplepos < oldsamplepos) + if(samplepos < oldsamplepos) { - buffers++; // buffer wrapped + buffers++; // buffer wrapped - if (paintedtime > 0x40000000) - { // time to chop things off to avoid 32 bit limits + if(paintedtime > 0x40000000) + { + // time to chop things off to avoid 32 bit limits buffers = 0; paintedtime = fullsamples; - S_StopAllSounds (true); + S_StopAllSounds(true); } } oldsamplepos = samplepos; - soundtime = buffers*fullsamples + samplepos/shm->channels; + soundtime = buffers * fullsamples + samplepos / shm->channels; } -void S_ExtraUpdate (void) +void S_ExtraUpdate(void) { - if (snd_noextraupdate.value) - return; // don't pollute timings + if(snd_noextraupdate.value) + return; // don't pollute timings S_Update_(); } -static void S_Update_ (void) +static void S_Update_(void) { - uint32_t endtime; - int32_t samps; + uint32_t endtime; + int32_t samps; - if (!sound_started || (snd_blocked > 0)) + if(!sound_started || (snd_blocked > 0)) return; - SNDDMA_LockBuffer (); - if (! shm->buffer) + SNDDMA_LockBuffer(); + if(! shm->buffer) return; // Updates DMA time GetSoundtime(); // check to make sure that we haven't overshot - if (paintedtime < soundtime) + if(paintedtime < soundtime) { - // Con_Printf ("S_Update_ : overflow\n"); + // Con_Printf ("S_Update_ : overflow\n"); paintedtime = soundtime; } @@ -928,34 +931,34 @@ static void S_Update_ (void) samps = shm->samples >> (shm->channels - 1); endtime = q_min(endtime, (uint32_t)(soundtime + samps)); - S_PaintChannels (endtime); + S_PaintChannels(endtime); - SNDDMA_Submit (); + SNDDMA_Submit(); } -void S_BlockSound (void) +void S_BlockSound(void) { -/* FIXME: do we really need the blocking at the - * driver level? - */ - if (sound_started && snd_blocked == 0) /* ++snd_blocked == 1 */ + /* FIXME: do we really need the blocking at the + * driver level? + */ + if(sound_started && snd_blocked == 0) /* ++snd_blocked == 1 */ { snd_blocked = 1; - S_ClearBuffer (); - if (shm) + S_ClearBuffer(); + if(shm) SNDDMA_BlockSound(); } } -void S_UnblockSound (void) +void S_UnblockSound(void) { - if (!sound_started || !snd_blocked) + if(!sound_started || !snd_blocked) return; - if (snd_blocked == 1) /* --snd_blocked == 0 */ + if(snd_blocked == 1) /* --snd_blocked == 0 */ { snd_blocked = 0; SNDDMA_UnblockSound(); - S_ClearBuffer (); + S_ClearBuffer(); } } @@ -967,18 +970,18 @@ console functions =============================================================================== */ -static void S_Play (void) +static void S_Play(void) { static int32_t hash = 345; - int32_t i; - char name[256]; - sfx_t *sfx; + int32_t i; + char name[256]; + sfx_t *sfx; i = 1; - while (i < Cmd_Argc()) + while(i < Cmd_Argc()) { q_strlcpy(name, Cmd_Argv(i), sizeof(name)); - if (!Q_strrchr(Cmd_Argv(i), '.')) + if(!Q_strrchr(Cmd_Argv(i), '.')) { q_strlcat(name, ".wav", sizeof(name)); } @@ -988,19 +991,19 @@ static void S_Play (void) } } -static void S_PlayVol (void) +static void S_PlayVol(void) { static int32_t hash = 543; - int32_t i; - float vol; - char name[256]; - sfx_t *sfx; + int32_t i; + float vol; + char name[256]; + sfx_t *sfx; i = 1; - while (i < Cmd_Argc()) + while(i < Cmd_Argc()) { q_strlcpy(name, Cmd_Argv(i), sizeof(name)); - if (!Q_strrchr(Cmd_Argv(i), '.')) + if(!Q_strrchr(Cmd_Argv(i), '.')) { q_strlcat(name, ".wav", sizeof(name)); } @@ -1011,61 +1014,61 @@ static void S_PlayVol (void) } } -static void S_SoundList (void) +static void S_SoundList(void) { - int32_t i; - sfx_t *sfx; - sfxcache_t *sc; - int32_t size, total; + int32_t i; + sfx_t *sfx; + sfxcache_t *sc; + int32_t size, total; total = 0; - for (sfx = known_sfx, i = 0; i < num_sfx; i++, sfx++) + for(sfx = known_sfx, i = 0; i < num_sfx; i++, sfx++) { - sc = (sfxcache_t *) Cache_Check (&sfx->cache); - if (!sc) + sc = (sfxcache_t *) Cache_Check(&sfx->cache); + if(!sc) continue; - size = sc->length*sc->width*(sc->stereo + 1); + size = sc->length * sc->width * (sc->stereo + 1); total += size; - if (sc->loopstart >= 0) - Con_SafePrintf ("L"); //johnfitz -- was Con_Printf + if(sc->loopstart >= 0) + Con_SafePrintf("L"); //johnfitz -- was Con_Printf else - Con_SafePrintf (" "); //johnfitz -- was Con_Printf - Con_SafePrintf("(%2" PRIi32 "b) %6" PRIi32 " : %s\n", sc->width*8, size, sfx->name); //johnfitz -- was Con_Printf + Con_SafePrintf(" "); //johnfitz -- was Con_Printf + Con_SafePrintf("(%2" PRIi32 "b) %6" PRIi32 " : %s\n", sc->width * 8, size, sfx->name); //johnfitz -- was Con_Printf } - Con_Printf ("%" PRIi32" PRIi32 "" sou" PRIi32 "ds, %" PRIi32 " bytes\n", num_sfx, total); //johnfitz -- added count + Con_Printf("%" PRIi32" PRIi32 "" sou" PRIi32 "ds, %" PRIi32 " bytes\n", num_sfx, total); //johnfitz -- added count } -void S_LocalSound (const char *name) +void S_LocalSound(const char *name) { - sfx_t *sfx; + sfx_t *sfx; - if (nosound.value) + if(nosound.value) return; - if (!sound_started) + if(!sound_started) return; - sfx = S_PrecacheSound (name); - if (!sfx) + sfx = S_PrecacheSound(name); + if(!sfx) { - Con_Printf ("S_LocalSound: can't cache %s\n", name); + Con_Printf("S_LocalSound: can't cache %s\n", name); return; } - S_StartSound (cl.viewentity, -1, sfx, vec3_origin, 1, 1); + S_StartSound(cl.viewentity, -1, sfx, vec3_origin, 1, 1); } -void S_ClearPrecache (void) +void S_ClearPrecache(void) { } -void S_BeginPrecaching (void) +void S_BeginPrecaching(void) { } -void S_EndPrecaching (void) +void S_EndPrecaching(void) { } diff --git a/source/snd_flac.c b/source/snd_flac.c index ca8b630..596043f 100644 --- a/source/snd_flac.c +++ b/source/snd_flac.c @@ -38,36 +38,37 @@ #endif #ifdef LEGACY_FLAC -#define FLAC__StreamDecoder FLAC__SeekableStreamDecoder -#define FLAC__StreamDecoderReadStatus FLAC__SeekableStreamDecoderReadStatus -#define FLAC__StreamDecoderSeekStatus FLAC__SeekableStreamDecoderSeekStatus -#define FLAC__StreamDecoderTellStatus FLAC__SeekableStreamDecoderTellStatus -#define FLAC__StreamDecoderLengthStatus FLAC__SeekableStreamDecoderLengthStatus +#define FLAC__StreamDecoder FLAC__SeekableStreamDecoder +#define FLAC__StreamDecoderReadStatus FLAC__SeekableStreamDecoderReadStatus +#define FLAC__StreamDecoderSeekStatus FLAC__SeekableStreamDecoderSeekStatus +#define FLAC__StreamDecoderTellStatus FLAC__SeekableStreamDecoderTellStatus +#define FLAC__StreamDecoderLengthStatus FLAC__SeekableStreamDecoderLengthStatus -#define FLAC__stream_decoder_new FLAC__seekable_stream_decoder_new -#define FLAC__stream_decoder_finish FLAC__seekable_stream_decoder_finish -#define FLAC__stream_decoder_delete FLAC__seekable_stream_decoder_delete -#define FLAC__stream_decoder_process_single FLAC__seekable_stream_decoder_process_single -#define FLAC__stream_decoder_seek_absolute FLAC__seekable_stream_decoder_seek_absolute -#define FLAC__stream_decoder_process_until_end_of_metadata FLAC__seekable_stream_decoder_process_until_end_of_metadata -#define FLAC__stream_decoder_get_state FLAC__seekable_stream_decoder_get_state +#define FLAC__stream_decoder_new FLAC__seekable_stream_decoder_new +#define FLAC__stream_decoder_finish FLAC__seekable_stream_decoder_finish +#define FLAC__stream_decoder_delete FLAC__seekable_stream_decoder_delete +#define FLAC__stream_decoder_process_single FLAC__seekable_stream_decoder_process_single +#define FLAC__stream_decoder_seek_absolute FLAC__seekable_stream_decoder_seek_absolute +#define FLAC__stream_decoder_process_until_end_of_metadata FLAC__seekable_stream_decoder_process_until_end_of_metadata +#define FLAC__stream_decoder_get_state FLAC__seekable_stream_decoder_get_state -#define FLAC__STREAM_DECODER_INIT_STATUS_OK FLAC__SEEKABLE_STREAM_DECODER_OK -#define FLAC__STREAM_DECODER_READ_STATUS_CONTINUE FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK -#define FLAC__STREAM_DECODER_READ_STATUS_ABORT FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR -#define FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK /* !!! */ -#define FLAC__STREAM_DECODER_WRITE_STATUS_ABORT FLAC__STREAM_DECODER_WRITE_STATUS_ABORT -#define FLAC__STREAM_DECODER_SEEK_STATUS_OK FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK -#define FLAC__STREAM_DECODER_SEEK_STATUS_ERROR FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR -#define FLAC__STREAM_DECODER_TELL_STATUS_OK FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK -#define FLAC__STREAM_DECODER_TELL_STATUS_ERROR FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_ERROR -#define FLAC__STREAM_DECODER_LENGTH_STATUS_OK FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK +#define FLAC__STREAM_DECODER_INIT_STATUS_OK FLAC__SEEKABLE_STREAM_DECODER_OK +#define FLAC__STREAM_DECODER_READ_STATUS_CONTINUE FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK +#define FLAC__STREAM_DECODER_READ_STATUS_ABORT FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR +#define FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK /* !!! */ +#define FLAC__STREAM_DECODER_WRITE_STATUS_ABORT FLAC__STREAM_DECODER_WRITE_STATUS_ABORT +#define FLAC__STREAM_DECODER_SEEK_STATUS_OK FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK +#define FLAC__STREAM_DECODER_SEEK_STATUS_ERROR FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR +#define FLAC__STREAM_DECODER_TELL_STATUS_OK FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK +#define FLAC__STREAM_DECODER_TELL_STATUS_ERROR FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_ERROR +#define FLAC__STREAM_DECODER_LENGTH_STATUS_OK FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK typedef unsigned FLAC_SIZE_T; #else typedef size_t FLAC_SIZE_T; #endif -typedef struct { +typedef struct +{ FLAC__StreamDecoder *decoder; fshandle_t *file; snd_info_t *info; @@ -77,27 +78,27 @@ typedef struct { /* CALLBACK FUNCTIONS: */ static void -flac_error_func (const FLAC__StreamDecoder *decoder, - FLAC__StreamDecoderErrorStatus status, void *client_data) +flac_error_func(const FLAC__StreamDecoder *decoder, + FLAC__StreamDecoderErrorStatus status, void *client_data) { (void)decoder; flacfile_t *ff = (flacfile_t *) client_data; ff->error = -1; - Con_Printf ("FLAC: decoder error %" PRIi32 "\n", status); + Con_Printf("FLAC: decoder error %" PRIi32 "\n", status); } static FLAC__StreamDecoderReadStatus -flac_read_func (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], - FLAC_SIZE_T *bytes, void *client_data) +flac_read_func(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], + FLAC_SIZE_T *bytes, void *client_data) { flacfile_t *ff = (flacfile_t *) client_data; (void)decoder; - if (*bytes > 0) + if(*bytes > 0) { *bytes = FS_fread(buffer, 1, *bytes, ff->file); - if (FS_ferror(ff->file)) + if(FS_ferror(ff->file)) return FLAC__STREAM_DECODER_READ_STATUS_ABORT; - if (*bytes == 0) + if(*bytes == 0) return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; } @@ -105,79 +106,81 @@ flac_read_func (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], } static FLAC__StreamDecoderSeekStatus -flac_seek_func (const FLAC__StreamDecoder *decoder, - FLAC__uint64 absolute_byte_offset, void *client_data) +flac_seek_func(const FLAC__StreamDecoder *decoder, + FLAC__uint64 absolute_byte_offset, void *client_data) { flacfile_t *ff = (flacfile_t *) client_data; (void)decoder; - if (FS_fseek(ff->file, (long)absolute_byte_offset, SEEK_SET) < 0) + if(FS_fseek(ff->file, (long)absolute_byte_offset, SEEK_SET) < 0) return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR; return FLAC__STREAM_DECODER_SEEK_STATUS_OK; } static FLAC__StreamDecoderTellStatus -flac_tell_func (const FLAC__StreamDecoder *decoder, - FLAC__uint64 *absolute_byte_offset, void *client_data) +flac_tell_func(const FLAC__StreamDecoder *decoder, + FLAC__uint64 *absolute_byte_offset, void *client_data) { flacfile_t *ff = (flacfile_t *) client_data; - long pos = FS_ftell (ff->file); + long pos = FS_ftell(ff->file); (void)decoder; - if (pos < 0) return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; + if(pos < 0) return FLAC__STREAM_DECODER_TELL_STATUS_ERROR; *absolute_byte_offset = (FLAC__uint64) pos; return FLAC__STREAM_DECODER_TELL_STATUS_OK; } static FLAC__StreamDecoderLengthStatus -flac_length_func (const FLAC__StreamDecoder *decoder, - FLAC__uint64 *stream_length, void *client_data) +flac_length_func(const FLAC__StreamDecoder *decoder, + FLAC__uint64 *stream_length, void *client_data) { flacfile_t *ff = (flacfile_t *) client_data; (void)decoder; - *stream_length = (FLAC__uint64) FS_filelength (ff->file); + *stream_length = (FLAC__uint64) FS_filelength(ff->file); return FLAC__STREAM_DECODER_LENGTH_STATUS_OK; } static FLAC__bool -flac_eof_func (const FLAC__StreamDecoder *decoder, void *client_data) +flac_eof_func(const FLAC__StreamDecoder *decoder, void *client_data) { flacfile_t *ff = (flacfile_t *) client_data; (void)decoder; - if (FS_feof (ff->file)) return true; + if(FS_feof(ff->file)) return true; return false; } static FLAC__StreamDecoderWriteStatus -flac_write_func (const FLAC__StreamDecoder *decoder, - const FLAC__Frame *frame, const FLAC__int32 * const buffer[], - void *client_data) +flac_write_func(const FLAC__StreamDecoder *decoder, + const FLAC__Frame *frame, const FLAC__int32 * const buffer[], + void *client_data) { flacfile_t *ff = (flacfile_t *) client_data; (void)decoder; - if (!ff->buffer) { - ff->buffer = (byte *) malloc (ff->info->blocksize * ff->info->channels * ff->info->width); - if (!ff->buffer) { + if(!ff->buffer) + { + ff->buffer = (byte *) malloc(ff->info->blocksize * ff->info->channels * ff->info->width); + if(!ff->buffer) + { ff->error = -1; /* needn't set this here, but... */ Con_Printf("Insufficient memory for fLaC audio\n"); return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; } } - if (ff->info->channels == 1) + if(ff->info->channels == 1) { unsigned i; const FLAC__int32 *in = buffer[0]; - if (ff->info->bits == 8) + if(ff->info->bits == 8) { byte *out = ff->buffer; - for (i = 0; i < frame->header.blocksize; i++) + for(i = 0; i < frame->header.blocksize; i++) *out++ = *in++ + 128; } else { int16_t *out = (int16_t *) ff->buffer; - for (i = 0; i < frame->header.blocksize; i++) + for(i = 0; i < frame->header.blocksize; i++) *out++ = *in++; } } @@ -187,11 +190,11 @@ flac_write_func (const FLAC__StreamDecoder *decoder, const FLAC__int32 *li = buffer[0]; const FLAC__int32 *ri = buffer[1]; - if (ff->info->bits == 8) + if(ff->info->bits == 8) { char *lo = (char *) ff->buffer + 0; char *ro = (char *) ff->buffer + 1; - for (i = 0; i < frame->header.blocksize; i++, lo++, ro++) + for(i = 0; i < frame->header.blocksize; i++, lo++, ro++) { *lo++ = *li++ + 128; *ro++ = *ri++ + 128; @@ -201,7 +204,7 @@ flac_write_func (const FLAC__StreamDecoder *decoder, { int16_t *lo = (int16_t *) ff->buffer + 0; int16_t *ro = (int16_t *) ff->buffer + 1; - for (i = 0; i < frame->header.blocksize; i++, lo++, ro++) + for(i = 0; i < frame->header.blocksize; i++, lo++, ro++) { *lo++ = *li++; *ro++ = *ri++; @@ -215,41 +218,41 @@ flac_write_func (const FLAC__StreamDecoder *decoder, } static void -flac_meta_func (const FLAC__StreamDecoder *decoder, - const FLAC__StreamMetadata *metadata, void *client_data) +flac_meta_func(const FLAC__StreamDecoder *decoder, + const FLAC__StreamMetadata *metadata, void *client_data) { flacfile_t *ff = (flacfile_t *) client_data; (void)decoder; - if (metadata->type == FLAC__METADATA_TYPE_STREAMINFO) + if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) { ff->info->rate = metadata->data.stream_info.sample_rate; ff->info->bits = metadata->data.stream_info.bits_per_sample; ff->info->width = ff->info->bits / 8; ff->info->channels = metadata->data.stream_info.channels; ff->info->blocksize = metadata->data.stream_info.max_blocksize; - ff->info->dataofs = 0; /* got the STREAMINFO metadata */ + ff->info->dataofs = 0; /* got the STREAMINFO metadata */ } } -static bool S_FLAC_CodecInitialize (void) +static bool S_FLAC_CodecInitialize(void) { return true; } -static void S_FLAC_CodecShutdown (void) +static void S_FLAC_CodecShutdown(void) { } -static bool S_FLAC_CodecOpenStream (snd_stream_t *stream) +static bool S_FLAC_CodecOpenStream(snd_stream_t *stream) { flacfile_t *ff; int32_t rc; ff = (flacfile_t *) Z_Malloc(sizeof(flacfile_t)); - ff->decoder = FLAC__stream_decoder_new (); - if (ff->decoder == NULL) + ff->decoder = FLAC__stream_decoder_new(); + if(ff->decoder == NULL) { Con_Printf("Unable to create fLaC decoder\n"); goto _fail; @@ -261,129 +264,135 @@ static bool S_FLAC_CodecOpenStream (snd_stream_t *stream) ff->info->dataofs = -1; /* check for STREAMINFO metadata existence */ #ifdef LEGACY_FLAC - FLAC__seekable_stream_decoder_set_error_callback (ff->decoder, flac_error_func); - FLAC__seekable_stream_decoder_set_read_callback (ff->decoder, flac_read_func); - FLAC__seekable_stream_decoder_set_seek_callback (ff->decoder, flac_seek_func); - FLAC__seekable_stream_decoder_set_tell_callback (ff->decoder, flac_tell_func); - FLAC__seekable_stream_decoder_set_length_callback (ff->decoder, flac_length_func); - FLAC__seekable_stream_decoder_set_eof_callback (ff->decoder, flac_eof_func); - FLAC__seekable_stream_decoder_set_write_callback (ff->decoder, flac_write_func); - FLAC__seekable_stream_decoder_set_metadata_callback (ff->decoder, flac_meta_func); - FLAC__seekable_stream_decoder_set_client_data (ff->decoder, ff); - rc = FLAC__seekable_stream_decoder_init (ff->decoder); + FLAC__seekable_stream_decoder_set_error_callback(ff->decoder, flac_error_func); + FLAC__seekable_stream_decoder_set_read_callback(ff->decoder, flac_read_func); + FLAC__seekable_stream_decoder_set_seek_callback(ff->decoder, flac_seek_func); + FLAC__seekable_stream_decoder_set_tell_callback(ff->decoder, flac_tell_func); + FLAC__seekable_stream_decoder_set_length_callback(ff->decoder, flac_length_func); + FLAC__seekable_stream_decoder_set_eof_callback(ff->decoder, flac_eof_func); + FLAC__seekable_stream_decoder_set_write_callback(ff->decoder, flac_write_func); + FLAC__seekable_stream_decoder_set_metadata_callback(ff->decoder, flac_meta_func); + FLAC__seekable_stream_decoder_set_client_data(ff->decoder, ff); + rc = FLAC__seekable_stream_decoder_init(ff->decoder); #else rc = FLAC__stream_decoder_init_stream(ff->decoder, - flac_read_func, - flac_seek_func, - flac_tell_func, - flac_length_func, - flac_eof_func, - flac_write_func, - flac_meta_func, - flac_error_func, - ff); + flac_read_func, + flac_seek_func, + flac_tell_func, + flac_length_func, + flac_eof_func, + flac_write_func, + flac_meta_func, + flac_error_func, + ff); #endif - if (rc != FLAC__STREAM_DECODER_INIT_STATUS_OK) /* unlikely */ + if(rc != FLAC__STREAM_DECODER_INIT_STATUS_OK) /* unlikely */ { - Con_Printf ("FLAC: decoder init error %" PRIi32 "\n", rc); + Con_Printf("FLAC: decoder init error %" PRIi32 "\n", rc); goto _fail; } - rc = FLAC__stream_decoder_process_until_end_of_metadata (ff->decoder); - if (rc == false || ff->error) + rc = FLAC__stream_decoder_process_until_end_of_metadata(ff->decoder); + if(rc == false || ff->error) { rc = FLAC__stream_decoder_get_state(ff->decoder); Con_Printf("%s not a valid flac file? (decoder state %" PRIi32 ")\n", - stream->name, rc); + stream->name, rc); goto _fail; } - if (ff->info->dataofs < 0) + if(ff->info->dataofs < 0) { Con_Printf("%s has no STREAMINFO\n", stream->name); goto _fail; } - if (ff->info->bits != 8 && ff->info->bits != 16) + if(ff->info->bits != 8 && ff->info->bits != 16) { Con_Printf("%s is not 8 or 16 bit\n", stream->name); goto _fail; } - if (ff->info->channels != 1 && ff->info->channels != 2) + if(ff->info->channels != 1 && ff->info->channels != 2) { Con_Printf("Unsupported number of channels %" PRIi32 " in %s\n", - ff->info->channels, stream->name); + ff->info->channels, stream->name); goto _fail; } return true; _fail: - if (ff->decoder) + if(ff->decoder) { - FLAC__stream_decoder_finish (ff->decoder); - FLAC__stream_decoder_delete (ff->decoder); + FLAC__stream_decoder_finish(ff->decoder); + FLAC__stream_decoder_delete(ff->decoder); } Z_Free(ff); return false; } -static int32_t S_FLAC_CodecReadStream (snd_stream_t *stream, int32_t len, void *buffer) +static int32_t S_FLAC_CodecReadStream(snd_stream_t *stream, int32_t len, void *buffer) { flacfile_t *ff = (flacfile_t *) stream->priv; byte *buf = (byte *) buffer; int32_t count = 0; - while (len) { + while(len) + { int32_t res = 0; - if (ff->size == ff->pos) - FLAC__stream_decoder_process_single (ff->decoder); - if (ff->error) return -1; + if(ff->size == ff->pos) + FLAC__stream_decoder_process_single(ff->decoder); + if(ff->error) return -1; res = ff->size - ff->pos; - if (res > len) + if(res > len) res = len; - if (res > 0) { - memcpy (buf, ff->buffer + ff->pos, res); + if(res > 0) + { + memcpy(buf, ff->buffer + ff->pos, res); count += res; len -= res; buf += res; ff->pos += res; - } else if (res < 0) { /* error */ + } + else if(res < 0) /* error */ + { return -1; - } else { - Con_DPrintf ("FLAC: EOF\n"); + } + else + { + Con_DPrintf("FLAC: EOF\n"); break; } } return count; } -static void S_FLAC_CodecCloseStream (snd_stream_t *stream) +static void S_FLAC_CodecCloseStream(snd_stream_t *stream) { flacfile_t *ff = (flacfile_t *) stream->priv; - FLAC__stream_decoder_finish (ff->decoder); - FLAC__stream_decoder_delete (ff->decoder); + FLAC__stream_decoder_finish(ff->decoder); + FLAC__stream_decoder_delete(ff->decoder); - if (ff->buffer) - free(ff->buffer); + if(ff->buffer) + free(ff->buffer); Z_Free(ff); S_CodecUtilClose(&stream); } -static int32_t S_FLAC_CodecRewindStream (snd_stream_t *stream) +static int32_t S_FLAC_CodecRewindStream(snd_stream_t *stream) { flacfile_t *ff = (flacfile_t *) stream->priv; ff->pos = ff->size = 0; - if (FLAC__stream_decoder_seek_absolute(ff->decoder, 0)) return 0; + if(FLAC__stream_decoder_seek_absolute(ff->decoder, 0)) return 0; return -1; } snd_codec_t flac_codec = { CODECTYPE_FLAC, - true, /* always available. */ + true, /* always available. */ "flac", S_FLAC_CodecInitialize, S_FLAC_CodecShutdown, @@ -394,5 +403,5 @@ snd_codec_t flac_codec = NULL }; -#endif /* USE_CODEC_FLAC */ +#endif /* USE_CODEC_FLAC */ diff --git a/source/snd_flac.h b/source/snd_flac.h index 4cedf82..8fc7f3c 100644 --- a/source/snd_flac.h +++ b/source/snd_flac.h @@ -7,7 +7,7 @@ extern snd_codec_t flac_codec; -#endif /* USE_CODEC_FLAC */ +#endif /* USE_CODEC_FLAC */ -#endif /* ! _SND_FLAC_H_ */ +#endif /* ! _SND_FLAC_H_ */ diff --git a/source/snd_mem.c b/source/snd_mem.c index 48b4d92..de5afd7 100644 --- a/source/snd_mem.c +++ b/source/snd_mem.c @@ -27,28 +27,28 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ResampleSfx ================ */ -static void ResampleSfx (sfx_t *sfx, int32_t inrate, int32_t inwidth, byte *data) +static void ResampleSfx(sfx_t *sfx, int32_t inrate, int32_t inwidth, byte *data) { - int32_t outcount; - int32_t srcsample; - float stepscale; - int32_t i; - int32_t sample, samplefrac, fracstep; - sfxcache_t *sc; + int32_t outcount; + int32_t srcsample; + float stepscale; + int32_t i; + int32_t sample, samplefrac, fracstep; + sfxcache_t *sc; - sc = (sfxcache_t *) Cache_Check (&sfx->cache); - if (!sc) + sc = (sfxcache_t *) Cache_Check(&sfx->cache); + if(!sc) return; - stepscale = (float)inrate / shm->speed; // this is usually 0.5, 1, or 2 + stepscale = (float)inrate / shm->speed; // this is usually 0.5, 1, or 2 outcount = sc->length / stepscale; sc->length = outcount; - if (sc->loopstart != -1) + if(sc->loopstart != -1) sc->loopstart = sc->loopstart / stepscale; sc->speed = shm->speed; - if (loadas8bit.value) + if(loadas8bit.value) sc->width = 1; else sc->width = inwidth; @@ -56,26 +56,26 @@ static void ResampleSfx (sfx_t *sfx, int32_t inrate, int32_t inwidth, byte *data // resample / decimate to the current source rate - if (stepscale == 1 && inwidth == 1 && sc->width == 1) + if(stepscale == 1 && inwidth == 1 && sc->width == 1) { // fast special case - for (i = 0; i < outcount; i++) - ((int8_t *)sc->data)[i] = (int32_t)( (uint8_t)(data[i]) - 128); + for(i = 0; i < outcount; i++) + ((int8_t *)sc->data)[i] = (int32_t)((uint8_t)(data[i]) - 128); } else { // general case samplefrac = 0; - fracstep = stepscale*256; - for (i = 0; i < outcount; i++) + fracstep = stepscale * 256; + for(i = 0; i < outcount; i++) { srcsample = samplefrac >> 8; samplefrac += fracstep; - if (inwidth == 2) - sample = LittleShort ( ((int16_t *)data)[srcsample] ); + if(inwidth == 2) + sample = LittleShort(((int16_t *)data)[srcsample]); else - sample = (int32_t)( (uint8_t)(data[srcsample]) - 128) << 8; - if (sc->width == 2) + sample = (int32_t)((uint8_t)(data[srcsample]) - 128) << 8; + if(sc->width == 2) ((int16_t *)sc->data)[i] = sample; else ((int8_t *)sc->data)[i] = sample >> 8; @@ -90,19 +90,19 @@ static void ResampleSfx (sfx_t *sfx, int32_t inrate, int32_t inwidth, byte *data S_LoadSound ============== */ -sfxcache_t *S_LoadSound (sfx_t *s) +sfxcache_t *S_LoadSound(sfx_t *s) { - char namebuffer[256]; - byte *data; - wavinfo_t info; - int32_t len; - float stepscale; - sfxcache_t *sc; - byte stackbuf[1*1024]; // avoid dirtying the cache heap + char namebuffer[256]; + byte *data; + wavinfo_t info; + int32_t len; + float stepscale; + sfxcache_t *sc; + byte stackbuf[1 * 1024]; // avoid dirtying the cache heap // see if still in memory - sc = (sfxcache_t *) Cache_Check (&s->cache); - if (sc) + sc = (sfxcache_t *) Cache_Check(&s->cache); + if(sc) return sc; // Con_Printf ("S_LoadSound: %x\n", (int32_t)stackbuf); @@ -115,20 +115,20 @@ sfxcache_t *S_LoadSound (sfx_t *s) data = COM_LoadStackFile(namebuffer, stackbuf, sizeof(stackbuf), NULL); - if (!data) + if(!data) { - Con_Printf ("Couldn't load %s\n", namebuffer); + Con_Printf("Couldn't load %s\n", namebuffer); return NULL; } - info = GetWavinfo (s->name, data, com_filesize); - if (info.channels != 1) + info = GetWavinfo(s->name, data, com_filesize); + if(info.channels != 1) { - Con_Printf ("%s is a stereo sample\n",s->name); + Con_Printf("%s is a stereo sample\n", s->name); return NULL; } - if (info.width != 1 && info.width != 2) + if(info.width != 1 && info.width != 2) { Con_Printf("%s is not 8 or 16 bit\n", s->name); return NULL; @@ -139,14 +139,14 @@ sfxcache_t *S_LoadSound (sfx_t *s) len = len * info.width * info.channels; - if (info.samples == 0 || len == 0) + if(info.samples == 0 || len == 0) { Con_Printf("%s has zero samples\n", s->name); return NULL; } - sc = (sfxcache_t *) Cache_Alloc ( &s->cache, len + sizeof(sfxcache_t), s->name); - if (!sc) + sc = (sfxcache_t *) Cache_Alloc(&s->cache, len + sizeof(sfxcache_t), s->name); + if(!sc) return NULL; sc->length = info.samples; @@ -155,7 +155,7 @@ sfxcache_t *S_LoadSound (sfx_t *s) sc->width = info.width; sc->stereo = info.channels; - ResampleSfx (s, sc->speed, sc->width, data + info.dataofs); + ResampleSfx(s, sc->speed, sc->width, data + info.dataofs); return sc; } @@ -170,38 +170,38 @@ WAV loading =============================================================================== */ -static byte *data_p; -static byte *iff_end; -static byte *last_chunk; -static byte *iff_data; -static int32_t iff_chunk_len; +static byte *data_p; +static byte *iff_end; +static byte *last_chunk; +static byte *iff_data; +static int32_t iff_chunk_len; -static int16_t GetLittleShort (void) +static int16_t GetLittleShort(void) { int16_t val = 0; val = *data_p; - val = val + (*(data_p+1)<<8); + val = val + (*(data_p + 1) << 8); data_p += 2; return val; } -static int32_t GetLittleLong (void) +static int32_t GetLittleLong(void) { int32_t val = 0; val = *data_p; - val = val + (*(data_p+1)<<8); - val = val + (*(data_p+2)<<16); - val = val + (*(data_p+3)<<24); + val = val + (*(data_p + 1) << 8); + val = val + (*(data_p + 2) << 16); + val = val + (*(data_p + 3) << 24); data_p += 4; return val; } -static void FindNextChunk (const char *name) +static void FindNextChunk(const char *name) { - while (1) + while(1) { - // Need at least 8 bytes for a chunk - if (last_chunk + 8 >= iff_end) + // Need at least 8 bytes for a chunk + if(last_chunk + 8 >= iff_end) { data_p = NULL; return; @@ -209,7 +209,7 @@ static void FindNextChunk (const char *name) data_p = last_chunk + 4; iff_chunk_len = GetLittleLong(); - if (iff_chunk_len < 0 || iff_chunk_len > iff_end - data_p) + if(iff_chunk_len < 0 || iff_chunk_len > iff_end - data_p) { data_p = NULL; Con_DPrintf2("bad \"%s\" chunk length (%" PRIi32 ")\n", name, iff_chunk_len); @@ -217,32 +217,33 @@ static void FindNextChunk (const char *name) } last_chunk = data_p + ((iff_chunk_len + 1) & ~1); data_p -= 8; - if (!Q_strncmp((char *)data_p, name, 4)) + if(!Q_strncmp((char *)data_p, name, 4)) return; } } -static void FindChunk (const char *name) +static void FindChunk(const char *name) { last_chunk = iff_data; - FindNextChunk (name); + FindNextChunk(name); } #if 0 -static void DumpChunks (void) +static void DumpChunks(void) { - char str[5]; + char str[5]; str[4] = 0; data_p = iff_data; do { - memcpy (str, data_p, 4); + memcpy(str, data_p, 4); data_p += 4; iff_chunk_len = GetLittleLong(); - Con_Printf ("0x%x : %s (%" PRIi32 ")\n", (int32_t)(data_p - 4), str, iff_chunk_len); + Con_Printf("0x%x : %s (%" PRIi32 ")\n", (int32_t)(data_p - 4), str, iff_chunk_len); data_p += (iff_chunk_len + 1) & ~1; - } while (data_p < iff_end); + } + while(data_p < iff_end); } #endif @@ -251,16 +252,16 @@ static void DumpChunks (void) GetWavinfo ============ */ -wavinfo_t GetWavinfo (const char *name, byte *wav, int32_t wavlength) +wavinfo_t GetWavinfo(const char *name, byte *wav, int32_t wavlength) { - wavinfo_t info; - int32_t i; - int32_t format; - int32_t samples; + wavinfo_t info; + int32_t i; + int32_t format; + int32_t samples; - memset (&info, 0, sizeof(info)); + memset(&info, 0, sizeof(info)); - if (!wav) + if(!wav) return info; iff_data = wav; @@ -268,7 +269,7 @@ wavinfo_t GetWavinfo (const char *name, byte *wav, int32_t wavlength) // find "RIFF" chunk FindChunk("RIFF"); - if (!(data_p && !Q_strncmp((char *)data_p + 8, "WAVE", 4))) + if(!(data_p && !Q_strncmp((char *)data_p + 8, "WAVE", 4))) { Con_Printf("%s missing RIFF/WAVE chunks\n", name); return info; @@ -277,18 +278,18 @@ wavinfo_t GetWavinfo (const char *name, byte *wav, int32_t wavlength) // get "fmt " chunk iff_data = data_p + 12; #if 0 - DumpChunks (); + DumpChunks(); #endif FindChunk("fmt "); - if (!data_p) + if(!data_p) { Con_Printf("%s is missing fmt chunk\n", name); return info; } data_p += 8; format = GetLittleShort(); - if (format != WAV_FORMAT_PCM) + if(format != WAV_FORMAT_PCM) { Con_Printf("%s is not Microsoft PCM format\n", name); return info; @@ -298,28 +299,29 @@ wavinfo_t GetWavinfo (const char *name, byte *wav, int32_t wavlength) info.rate = GetLittleLong(); data_p += 4 + 2; i = GetLittleShort(); - if (i != 8 && i != 16) + if(i != 8 && i != 16) return info; info.width = i / 8; // get cue chunk FindChunk("cue "); - if (data_p) + if(data_p) { data_p += 32; info.loopstart = GetLittleLong(); - // Con_Printf("loopstart=%" PRIi32 "\n", sfx->loopstart); + // Con_Printf("loopstart=%" PRIi32 "\n", sfx->loopstart); - // if the next chunk is a LIST chunk, look for a cue length marker - FindNextChunk ("LIST"); - if (data_p) + // if the next chunk is a LIST chunk, look for a cue length marker + FindNextChunk("LIST"); + if(data_p) { - if (!strncmp((char *)data_p + 28, "mark", 4)) - { // this is not a proper parse, but it works with cooledit... + if(!strncmp((char *)data_p + 28, "mark", 4)) + { + // this is not a proper parse, but it works with cooledit... data_p += 24; - i = GetLittleLong(); // samples in loop + i = GetLittleLong(); // samples in loop info.samples = info.loopstart + i; - // Con_Printf("looped length: %" PRIi32 "\n", i); + // Con_Printf("looped length: %" PRIi32 "\n", i); } } } @@ -328,7 +330,7 @@ wavinfo_t GetWavinfo (const char *name, byte *wav, int32_t wavlength) // find data chunk FindChunk("data"); - if (!data_p) + if(!data_p) { Con_Printf("%s is missing data chunk\n", name); return info; @@ -337,10 +339,10 @@ wavinfo_t GetWavinfo (const char *name, byte *wav, int32_t wavlength) data_p += 4; samples = GetLittleLong() / info.width; - if (info.samples) + if(info.samples) { - if (samples < info.samples) - Sys_Error ("%s has a bad loop length", name); + if(samples < info.samples) + Sys_Error("%s has a bad loop length", name); } else info.samples = samples; diff --git a/source/snd_mikmod.c b/source/snd_mikmod.c index b00d357..37d685f 100644 --- a/source/snd_mikmod.c +++ b/source/snd_mikmod.c @@ -42,57 +42,58 @@ #define DMODE_SIMDMIXER 0x0800 /* enable SIMD mixing */ #endif -typedef struct _mik_priv { -/* struct MREADER in libmikmod <= 3.2.0-beta2 - * doesn't have iobase members. adding them here - * so that if we compile against 3.2.0-beta2, we - * can still run OK against 3.2.0b3 and newer. */ +typedef struct _mik_priv +{ + /* struct MREADER in libmikmod <= 3.2.0-beta2 + * doesn't have iobase members. adding them here + * so that if we compile against 3.2.0-beta2, we + * can still run OK against 3.2.0b3 and newer. */ struct MREADER reader; long iobase, prev_iobase; fshandle_t *fh; MODULE *module; } mik_priv_t; -static int32_t MIK_Seek (MREADER *r, long ofs, int32_t whence) +static int32_t MIK_Seek(MREADER *r, long ofs, int32_t whence) { return FS_fseek(((mik_priv_t *)r)->fh, ofs, whence); } -static long MIK_Tell (MREADER *r) +static long MIK_Tell(MREADER *r) { return FS_ftell(((mik_priv_t *)r)->fh); } -static BOOL MIK_Read (MREADER *r, void *ptr, size_t siz) +static BOOL MIK_Read(MREADER *r, void *ptr, size_t siz) { return !!FS_fread(ptr, siz, 1, ((mik_priv_t *)r)->fh); } -static int32_t MIK_Get (MREADER *r) +static int32_t MIK_Get(MREADER *r) { return FS_fgetc(((mik_priv_t *)r)->fh); } -static BOOL MIK_Eof (MREADER *r) +static BOOL MIK_Eof(MREADER *r) { return FS_feof(((mik_priv_t *)r)->fh); } -static bool S_MIKMOD_CodecInitialize (void) +static bool S_MIKMOD_CodecInitialize(void) { - if (mikmod_codec.initialized) + if(mikmod_codec.initialized) return true; /* set mode flags to only we like: */ md_mode = 0; - if ((shm->samplebits / 8) == 2) + if((shm->samplebits / 8) == 2) md_mode |= DMODE_16BITS; - if (shm->channels == 2) + if(shm->channels == 2) md_mode |= DMODE_STEREO; - md_mode |= DMODE_SOFT_MUSIC; /* this is a software-only mixer */ + md_mode |= DMODE_SOFT_MUSIC; /* this is a software-only mixer */ /* md_mixfreq is UWORD, so something like 96000 isn't OK */ - md_mixfreq = (shm->speed < 65536)? shm->speed : 48000; + md_mixfreq = (shm->speed < 65536) ? shm->speed : 48000; /* keeping md_device as 0 which is default (auto-detect: we * only register drv_nos, and it will be the only one found.) @@ -102,31 +103,31 @@ static bool S_MIKMOD_CodecInitialize (void) /* just tone down overall volume md_volume from 128 to 96? */ md_volume = 96; - MikMod_RegisterDriver(&drv_nos); /* only need the "nosound" driver, none else */ + MikMod_RegisterDriver(&drv_nos); /* only need the "nosound" driver, none else */ MikMod_RegisterAllLoaders(); - if (S_MIKMOD_initlib(NULL)) + if(S_MIKMOD_initlib(NULL)) { Con_DPrintf("Could not initialize MikMod: %s\n", MikMod_strerror(MikMod_errno)); return false; } /* this can't get set with drv_nos, but whatever, be safe: */ - md_mode &= ~DMODE_SIMDMIXER; /* SIMD mixer is buggy when combined with HQMIXER */ + md_mode &= ~DMODE_SIMDMIXER; /* SIMD mixer is buggy when combined with HQMIXER */ mikmod_codec.initialized = true; return true; } -static void S_MIKMOD_CodecShutdown (void) +static void S_MIKMOD_CodecShutdown(void) { - if (mikmod_codec.initialized) + if(mikmod_codec.initialized) { mikmod_codec.initialized = false; MikMod_Exit(); } } -static bool S_MIKMOD_CodecOpenStream (snd_stream_t *stream) +static bool S_MIKMOD_CodecOpenStream(snd_stream_t *stream) { mik_priv_t *priv; @@ -140,7 +141,7 @@ static bool S_MIKMOD_CodecOpenStream (snd_stream_t *stream) priv->fh = &stream->fh; priv->module = Player_LoadGeneric((MREADER *)stream->priv, 64, 0); - if (!priv->module) + if(!priv->module) { Con_DPrintf("Could not load module: %s\n", MikMod_strerror(MikMod_errno)); Z_Free(stream->priv); @@ -153,26 +154,26 @@ static bool S_MIKMOD_CodecOpenStream (snd_stream_t *stream) * don't wrap to restart position when module is finished) are OK with us as * set internally by libmikmod::Player_Init(). */ /* just change the loop setting to 0, i.e. don't process in-module loops: */ - priv->module->loop = 0; + priv->module->loop = 0; Player_Start(priv->module); - stream->info.rate = md_mixfreq; - stream->info.bits = (md_mode & DMODE_16BITS)? 16: 8; - stream->info.width = stream->info.bits / 8; - stream->info.channels = (md_mode & DMODE_STEREO)? 2 : 1; -/* Con_DPrintf("Playing %s (%" PRIi32 " chn)\n", priv->module->songname, priv->module->numchn);*/ + stream->info.rate = md_mixfreq; + stream->info.bits = (md_mode & DMODE_16BITS) ? 16 : 8; + stream->info.width = stream->info.bits / 8; + stream->info.channels = (md_mode & DMODE_STEREO) ? 2 : 1; + /* Con_DPrintf("Playing %s (%" PRIi32 " chn)\n", priv->module->songname, priv->module->numchn);*/ return true; } -static int32_t S_MIKMOD_CodecReadStream (snd_stream_t *stream, int32_t bytes, void *buffer) +static int32_t S_MIKMOD_CodecReadStream(snd_stream_t *stream, int32_t bytes, void *buffer) { - if (!Player_Active()) + if(!Player_Active()) return 0; return (int32_t) VC_WriteBytes((SBYTE *)buffer, bytes); } -static void S_MIKMOD_CodecCloseStream (snd_stream_t *stream) +static void S_MIKMOD_CodecCloseStream(snd_stream_t *stream) { Player_Stop(); Player_Free(((mik_priv_t *)stream->priv)->module); @@ -180,9 +181,9 @@ static void S_MIKMOD_CodecCloseStream (snd_stream_t *stream) S_CodecUtilClose(&stream); } -static int32_t S_MIKMOD_CodecRewindStream (snd_stream_t *stream) +static int32_t S_MIKMOD_CodecRewindStream(snd_stream_t *stream) { - Player_SetPosition (0); + Player_SetPosition(0); return 0; } @@ -200,5 +201,5 @@ snd_codec_t mikmod_codec = NULL }; -#endif /* USE_CODEC_MIKMOD */ +#endif /* USE_CODEC_MIKMOD */ diff --git a/source/snd_mikmod.h b/source/snd_mikmod.h index 9f0338b..1244ee0 100644 --- a/source/snd_mikmod.h +++ b/source/snd_mikmod.h @@ -7,7 +7,7 @@ extern snd_codec_t mikmod_codec; -#endif /* USE_CODEC_MIKMOD */ +#endif /* USE_CODEC_MIKMOD */ -#endif /* ! _SND_MIKMOD_H_ */ +#endif /* ! _SND_MIKMOD_H_ */ diff --git a/source/snd_mix.c b/source/snd_mix.c index 96e7573..352886e 100644 --- a/source/snd_mix.c +++ b/source/snd_mix.c @@ -23,77 +23,77 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -#define PAINTBUFFER_SIZE 2048 +#define PAINTBUFFER_SIZE 2048 portable_samplepair_t paintbuffer[PAINTBUFFER_SIZE]; -int32_t snd_scaletable[32][256]; -int32_t *snd_p, snd_linear_count; -int16_t *snd_out; +int32_t snd_scaletable[32][256]; +int32_t *snd_p, snd_linear_count; +int16_t *snd_out; -static int32_t snd_vol; +static int32_t snd_vol; -static void Snd_WriteLinearBlastStereo16 (void) +static void Snd_WriteLinearBlastStereo16(void) { - int32_t i; - int32_t val; + int32_t i; + int32_t val; - for (i = 0; i < snd_linear_count; i += 2) + for(i = 0; i < snd_linear_count; i += 2) { val = snd_p[i] / 256; - if (val > 0x7fff) + if(val > 0x7fff) snd_out[i] = 0x7fff; - else if (val < (int16_t)0x8000) + else if(val < (int16_t)0x8000) snd_out[i] = (int16_t)0x8000; else snd_out[i] = val; - val = snd_p[i+1] / 256; - if (val > 0x7fff) - snd_out[i+1] = 0x7fff; - else if (val < (int16_t)0x8000) - snd_out[i+1] = (int16_t)0x8000; + val = snd_p[i + 1] / 256; + if(val > 0x7fff) + snd_out[i + 1] = 0x7fff; + else if(val < (int16_t)0x8000) + snd_out[i + 1] = (int16_t)0x8000; else - snd_out[i+1] = val; + snd_out[i + 1] = val; } } -static void S_TransferStereo16 (int32_t endtime) +static void S_TransferStereo16(int32_t endtime) { - int32_t lpos; - int32_t lpaintedtime; + int32_t lpos; + int32_t lpaintedtime; snd_p = (int32_t *) paintbuffer; lpaintedtime = paintedtime; - while (lpaintedtime < endtime) + while(lpaintedtime < endtime) { - // handle recirculating buffer issues + // handle recirculating buffer issues lpos = lpaintedtime & ((shm->samples >> 1) - 1); snd_out = (int16_t *)shm->buffer + (lpos << 1); snd_linear_count = (shm->samples >> 1) - lpos; - if (lpaintedtime + snd_linear_count > endtime) + if(lpaintedtime + snd_linear_count > endtime) snd_linear_count = endtime - lpaintedtime; snd_linear_count <<= 1; - // write a linear blast of samples - Snd_WriteLinearBlastStereo16 (); + // write a linear blast of samples + Snd_WriteLinearBlastStereo16(); snd_p += snd_linear_count; lpaintedtime += (snd_linear_count >> 1); } } -static void S_TransferPaintBuffer (int32_t endtime) +static void S_TransferPaintBuffer(int32_t endtime) { - int32_t out_idx, out_mask; - int32_t count, step, val; - int32_t *p; + int32_t out_idx, out_mask; + int32_t count, step, val; + int32_t *p; - if (shm->samplebits == 16 && shm->channels == 2) + if(shm->samplebits == 16 && shm->channels == 2) { - S_TransferStereo16 (endtime); + S_TransferStereo16(endtime); return; } @@ -103,46 +103,46 @@ static void S_TransferPaintBuffer (int32_t endtime) out_idx = paintedtime * shm->channels & out_mask; step = 3 - shm->channels; - if (shm->samplebits == 16) + if(shm->samplebits == 16) { int16_t *out = (int16_t *)shm->buffer; - while (count--) + while(count--) { val = *p / 256; - p+= step; - if (val > 0x7fff) + p += step; + if(val > 0x7fff) val = 0x7fff; - else if (val < (int16_t)0x8000) + else if(val < (int16_t)0x8000) val = (int16_t)0x8000; out[out_idx] = val; out_idx = (out_idx + 1) & out_mask; } } - else if (shm->samplebits == 8 && !shm->signed8) + else if(shm->samplebits == 8 && !shm->signed8) { uint8_t *out = shm->buffer; - while (count--) + while(count--) { val = *p / 256; - p+= step; - if (val > 0x7fff) + p += step; + if(val > 0x7fff) val = 0x7fff; - else if (val < (int16_t)0x8000) + else if(val < (int16_t)0x8000) val = (int16_t)0x8000; out[out_idx] = (val / 256) + 128; out_idx = (out_idx + 1) & out_mask; } } - else if (shm->samplebits == 8) /* S8 format, e.g. with Amiga AHI */ + else if(shm->samplebits == 8) /* S8 format, e.g. with Amiga AHI */ { int8_t *out = (int8_t *) shm->buffer; - while (count--) + while(count--) { val = *p / 256; - p+= step; - if (val > 0x7fff) + p += step; + if(val > 0x7fff) val = 0x7fff; - else if (val < (int16_t)0x8000) + else if(val < (int16_t)0x8000) val = (int16_t)0x8000; out[out_idx] = (val / 256); out_idx = (out_idx + 1) & out_mask; @@ -165,60 +165,61 @@ f_c is the filter cutoff frequency, as a fraction of the samplerate static void S_MakeBlackmanWindowKernel(float *kernel, int32_t M, float f_c) { int32_t i; - for (i = 0; i <= M; i++) + for(i = 0; i <= M; i++) { - if (i == M/2) + if(i == M / 2) { kernel[i] = 2 * M_PI * f_c; } else { - kernel[i] = ( sin(2 * M_PI * f_c * (i - M/2.0)) / (i - (M/2.0)) ) - * (0.42 - 0.5*cos(2 * M_PI * i / (double)M) - + 0.08*cos(4 * M_PI * i / (double)M) ); + kernel[i] = (sin(2 * M_PI * f_c * (i - M / 2.0)) / (i - (M / 2.0))) + * (0.42 - 0.5 * cos(2 * M_PI * i / (double)M) + + 0.08 * cos(4 * M_PI * i / (double)M)); } } // normalize the kernel so all of the values sum to 1 { float sum = 0; - for (i = 0; i <= M; i++) + for(i = 0; i <= M; i++) { sum += kernel[i]; } - for (i = 0; i <= M; i++) + for(i = 0; i <= M; i++) { kernel[i] /= sum; } } } -typedef struct { +typedef struct +{ float *memory; // kernelsize floats float *kernel; // kernelsize floats int32_t kernelsize; // M+1, rounded up to be a multiple of 16 - int32_t M; // M value used to make kernel, even - int32_t parity; // 0-3 - float f_c; // cutoff frequency, [0..1], fraction of sample rate + int32_t M; // M value used to make kernel, even + int32_t parity; // 0-3 + float f_c; // cutoff frequency, [0..1], fraction of sample rate } filter_t; static void S_UpdateFilter(filter_t *filter, int32_t M, float f_c) { - if (filter->f_c != f_c || filter->M != M) + if(filter->f_c != f_c || filter->M != M) { - if (filter->memory != NULL) free(filter->memory); - if (filter->kernel != NULL) free(filter->kernel); + if(filter->memory != NULL) free(filter->memory); + if(filter->kernel != NULL) free(filter->kernel); filter->M = M; filter->f_c = f_c; filter->parity = 0; - // M + 1 rounded up to the next multiple of 16 + // M + 1 rounded up to the next multiple of 16 filter->kernelsize = (M + 1) + 16 - ((M + 1) % 16); filter->memory = (float *) calloc(filter->kernelsize, sizeof(float)); filter->kernel = (float *) calloc(filter->kernelsize, sizeof(float)); - + S_MakeBlackmanWindowKernel(filter->kernel, M, f_c); } } @@ -249,9 +250,9 @@ static void S_ApplyFilter(filter_t *filter, int32_t *data, int32_t stride, int32 // memory holds the previous filter->kernelsize samples of input. memcpy(input, filter->memory, filter->kernelsize * sizeof(float)); - for (i=0; ikernelsize+i] = data[i * stride] / (32768.0 * 256.0); + input[filter->kernelsize + i] = data[i * stride] / (32768.0 * 256.0); } // copy out the last filter->kernelsize samples to 'memory' for next time @@ -260,23 +261,23 @@ static void S_ApplyFilter(filter_t *filter, int32_t *data, int32_t stride, int32 // apply the filter parity = filter->parity; - for (i=0; i PAINTBUFFER_SIZE) + if(endtime - paintedtime > PAINTBUFFER_SIZE) end = paintedtime + PAINTBUFFER_SIZE; - // clear the paint buffer + // clear the paint buffer memset(paintbuffer, 0, (end - paintedtime) * sizeof(portable_samplepair_t)); - // paint in the channels. + // paint in the channels. ch = snd_channels; - for (i = 0; i < total_channels; i++, ch++) + for(i = 0; i < total_channels; i++, ch++) { - if (!ch->sfx) + if(!ch->sfx) continue; - if (!ch->leftvol && !ch->rightvol) + if(!ch->leftvol && !ch->rightvol) continue; - sc = S_LoadSound (ch->sfx); - if (!sc) + sc = S_LoadSound(ch->sfx); + if(!sc) continue; ltime = paintedtime; - while (ltime < end) - { // paint up to end - if (ch->end < end) + while(ltime < end) + { + // paint up to end + if(ch->end < end) count = ch->end - ltime; else count = end - ltime; - if (count > 0) + if(count > 0) { // the last param to SND_PaintChannelFrom is the index // to start painting to in the paintbuffer, usually 0. - if (sc->width == 1) + if(sc->width == 1) SND_PaintChannelFrom8(ch, sc, count, ltime - paintedtime); else SND_PaintChannelFrom16(ch, sc, count, ltime - paintedtime); @@ -385,16 +397,17 @@ void S_PaintChannels (int32_t endtime) ltime += count; } - // if at end of loop, restart - if (ltime >= ch->end) + // if at end of loop, restart + if(ltime >= ch->end) { - if (sc->loopstart >= 0) + if(sc->loopstart >= 0) { ch->pos = sc->loopstart; ch->end = ltime + sc->length - ch->pos; } else - { // channel just stopped + { + // channel just stopped ch->sfx = NULL; break; } @@ -402,90 +415,91 @@ void S_PaintChannels (int32_t endtime) } } - // clip each sample to 0dB, then reduce by 6dB (to leave some headroom for - // the lowpass filter and the music). the lowpass will smooth out the - // clipping - for (i=0; ispeed == 44100) + // apply a lowpass filter + if(sndspeed.value == 11025 && shm->speed == 44100) { static filter_t memory_l, memory_r; S_LowpassFilter((int32_t *)paintbuffer, 2, end - paintedtime, &memory_l); S_LowpassFilter(((int32_t *)paintbuffer) + 1, 2, end - paintedtime, &memory_r); } - // paint in the music - if (s_rawend >= paintedtime) - { // copy from the streaming sound source - int32_t s; - int32_t stop; + // paint in the music + if(s_rawend >= paintedtime) + { + // copy from the streaming sound source + int32_t s; + int32_t stop; stop = (end < s_rawend) ? end : s_rawend; - for (i = paintedtime; i < stop; i++) + for(i = paintedtime; i < stop; i++) { s = i & (MAX_RAW_SAMPLES - 1); - // lower music by 6db to match sfx + // lower music by 6db to match sfx paintbuffer[i - paintedtime].left += s_rawsamples[s].left / 2; paintbuffer[i - paintedtime].right += s_rawsamples[s].right / 2; } - // if (i != end) - // Con_Printf ("partial stream\n"); - // else - // Con_Printf ("full stream\n"); + // if (i != end) + // Con_Printf ("partial stream\n"); + // else + // Con_Printf ("full stream\n"); } - // transfer out according to DMA format + // transfer out according to DMA format S_TransferPaintBuffer(end); paintedtime = end; } } -void SND_InitScaletable (void) +void SND_InitScaletable(void) { - int32_t i, j; - int32_t scale; + int32_t i, j; + int32_t scale; - for (i = 0; i < 32; i++) + for(i = 0; i < 32; i++) { scale = i * 8 * 256 * sfxvolume.value; - for (j = 0; j < 256; j++) + for(j = 0; j < 256; j++) { - /* When compiling with gcc-4.1.0 at optimisations O1 and - higher, the tricky int8_t type conversion is not - guaranteed. Therefore we explicity calculate the signed - value from the index as required. From Kevin Shanahan. - See: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=26719 - */ - // snd_scaletable[i][j] = ((int8_t)j) * scale; + /* When compiling with gcc-4.1.0 at optimisations O1 and + higher, the tricky int8_t type conversion is not + guaranteed. Therefore we explicity calculate the signed + value from the index as required. From Kevin Shanahan. + See: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=26719 + */ + // snd_scaletable[i][j] = ((int8_t)j) * scale; snd_scaletable[i][j] = ((j < 128) ? j : j - 256) * scale; } } } -static void SND_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int32_t count, int32_t paintbufferstart) +static void SND_PaintChannelFrom8(channel_t *ch, sfxcache_t *sc, int32_t count, int32_t paintbufferstart) { - int32_t data; - int32_t *lscale, *rscale; - uint8_t *sfx; - int32_t i; + int32_t data; + int32_t *lscale, *rscale; + uint8_t *sfx; + int32_t i; - if (ch->leftvol > 255) + if(ch->leftvol > 255) ch->leftvol = 255; - if (ch->rightvol > 255) + if(ch->rightvol > 255) ch->rightvol = 255; lscale = snd_scaletable[ch->leftvol >> 3]; rscale = snd_scaletable[ch->rightvol >> 3]; sfx = (uint8_t *)sc->data + ch->pos; - for (i = 0; i < count; i++) + for(i = 0; i < count; i++) { data = sfx[i]; paintbuffer[paintbufferstart + i].left += lscale[data]; @@ -495,13 +509,13 @@ static void SND_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int32_t count, ch->pos += count; } -static void SND_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int32_t count, int32_t paintbufferstart) +static void SND_PaintChannelFrom16(channel_t *ch, sfxcache_t *sc, int32_t count, int32_t paintbufferstart) { - int32_t data; - int32_t left, right; - int32_t leftvol, rightvol; - int16_t *sfx; - int32_t i; + int32_t data; + int32_t left, right; + int32_t leftvol, rightvol; + int16_t *sfx; + int32_t i; leftvol = ch->leftvol * snd_vol; rightvol = ch->rightvol * snd_vol; @@ -509,13 +523,13 @@ static void SND_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int32_t count rightvol /= 256; sfx = (int16_t *)sc->data + ch->pos; - for (i = 0; i < count; i++) + for(i = 0; i < count; i++) { data = sfx[i]; - // this was causing integer overflow as observed in quakespasm - // with the warpspasm mod moved >>8 to left/right volume above. - // left = (data * leftvol) >> 8; - // right = (data * rightvol) >> 8; + // this was causing integer overflow as observed in quakespasm + // with the warpspasm mod moved >>8 to left/right volume above. + // left = (data * leftvol) >> 8; + // right = (data * rightvol) >> 8; left = data * leftvol; right = data * rightvol; paintbuffer[paintbufferstart + i].left += left; diff --git a/source/snd_mp3.c b/source/snd_mp3.c index f41bec9..a7203e6 100644 --- a/source/snd_mp3.c +++ b/source/snd_mp3.c @@ -48,20 +48,20 @@ static mad_timer_t const mad_timer_zero_stub = {0, 0}; /* MAD returns values with MAD_F_FRACBITS (28) bits of precision, though it's not certain that all of them are meaningful. Default to 16 bits to align with most users expectation of output file should be 16 bits. */ -#define MP3_MAD_SAMPLEBITS 16 -#define MP3_MAD_SAMPLEWIDTH 2 -#define MP3_BUFFER_SIZE (5 * 8192) +#define MP3_MAD_SAMPLEBITS 16 +#define MP3_MAD_SAMPLEWIDTH 2 +#define MP3_BUFFER_SIZE (5 * 8192) /* Private data */ typedef struct _mp3_priv_t { uint8_t mp3_buffer[MP3_BUFFER_SIZE]; - struct mad_stream stream; - struct mad_frame frame; - struct mad_synth synth; - mad_timer_t timer; - ptrdiff_t cursamp; - size_t frame_count; + struct mad_stream stream; + struct mad_frame frame; + struct mad_synth synth; + mad_timer_t timer; + ptrdiff_t cursamp; + size_t frame_count; } mp3_priv_t; /* This function merges the functions tagtype() and id3_tag_query() @@ -69,8 +69,8 @@ typedef struct _mp3_priv_t * Returns 0 if the frame is not an ID3 tag, tag length if it is */ static inline bool tag_is_id3v1(const uint8_t *data, size_t length) { - if (length >= 3 && - data[0] == 'T' && data[1] == 'A' && data[2] == 'G') + if(length >= 3 && + data[0] == 'T' && data[1] == 'A' && data[2] == 'G') { return true; } @@ -79,10 +79,10 @@ static inline bool tag_is_id3v1(const uint8_t *data, size_t length) static inline bool tag_is_id3v2(const uint8_t *data, size_t length) { - if (length >= 10 && - (data[0] == 'I' && data[1] == 'D' && data[2] == '3') && - data[3] < 0xff && data[4] < 0xff && - data[6] < 0x80 && data[7] < 0x80 && data[8] < 0x80 && data[9] < 0x80) + if(length >= 10 && + (data[0] == 'I' && data[1] == 'D' && data[2] == '3') && + data[3] < 0xff && data[4] < 0xff && + data[6] < 0x80 && data[7] < 0x80 && data[8] < 0x80 && data[9] < 0x80) { return true; } @@ -97,14 +97,14 @@ static inline bool tag_is_apetag(const uint8_t *data, size_t length) { uint32_t v; - if (length < 32) return false; - if (memcmp(data,"APETAGEX",8) != 0) + if(length < 32) return false; + if(memcmp(data, "APETAGEX", 8) != 0) return false; - v = (data[11]<<24) | (data[10]<<16) | (data[9]<<8) | data[8]; - if (v != 2000U/* && v != 1000U*/) + v = (data[11] << 24) | (data[10] << 16) | (data[9] << 8) | data[8]; + if(v != 2000U/* && v != 1000U*/) return false; v = 0; - if (memcmp(&data[24],&v,4) != 0 || memcmp(&data[28],&v,4) != 0) + if(memcmp(&data[24], &v, 4) != 0 || memcmp(&data[28], &v, 4) != 0) return false; return true; } @@ -113,23 +113,23 @@ static size_t mp3_tagsize(const uint8_t *data, size_t length) { size_t size; - if (tag_is_id3v1(data, length)) + if(tag_is_id3v1(data, length)) return 128; - if (tag_is_id3v2(data, length)) + if(tag_is_id3v2(data, length)) { uint8_t flags = data[5]; - size = 10 + (data[6]<<21) + (data[7]<<14) + (data[8]<<7) + data[9]; - if (flags & ID3_TAG_FLAG_FOOTERPRESENT) + size = 10 + (data[6] << 21) + (data[7] << 14) + (data[8] << 7) + data[9]; + if(flags & ID3_TAG_FLAG_FOOTERPRESENT) size += 10; - for ( ; size < length && !data[size]; ++size) + for(; size < length && !data[size]; ++size) ; /* Consume padding */ return size; } - if (tag_is_apetag(data, length)) + if(tag_is_apetag(data, length)) { - size = (data[15]<<24) | (data[14]<<16) | (data[13]<<8) | data[12]; + size = (data[15] << 24) | (data[14] << 16) | (data[13] << 8) | data[12]; size += 32; return size; } @@ -160,7 +160,7 @@ static int32_t mp3_inputtag(snd_stream_t *stream) */ remaining = p->stream.bufend - p->stream.next_frame; tagsize = mp3_tagsize(p->stream.this_frame, remaining); - if (tagsize != 0) + if(tagsize != 0) { mad_stream_skip(&p->stream, tagsize); rc = 0; @@ -199,11 +199,11 @@ static int32_t mp3_inputdata(snd_stream_t *stream) memmove(p->mp3_buffer, p->stream.next_frame, remaining); bytes_read = FS_fread(p->mp3_buffer + remaining, 1, - MP3_BUFFER_SIZE - remaining, &stream->fh); - if (bytes_read == 0) + MP3_BUFFER_SIZE - remaining, &stream->fh); + if(bytes_read == 0) return -1; - mad_stream_buffer(&p->stream, p->mp3_buffer, bytes_read+remaining); + mad_stream_buffer(&p->stream, p->mp3_buffer, bytes_read + remaining); p->stream.error = MAD_ERROR_NONE; return 0; @@ -224,7 +224,7 @@ static int32_t mp3_startread(snd_stream_t *stream) * can be processed later. */ ReadSize = FS_fread(p->mp3_buffer, 1, MP3_BUFFER_SIZE, &stream->fh); - if (!ReadSize || FS_ferror(&stream->fh)) + if(!ReadSize || FS_ferror(&stream->fh)) return -1; mad_stream_buffer(&p->stream, p->mp3_buffer, ReadSize); @@ -234,12 +234,12 @@ static int32_t mp3_startread(snd_stream_t *stream) * at the beginning of the audio file. */ p->stream.error = MAD_ERROR_NONE; - while (mad_frame_decode(&p->frame,&p->stream)) + while(mad_frame_decode(&p->frame, &p->stream)) { /* check whether input buffer needs a refill */ - if (p->stream.error == MAD_ERROR_BUFLEN) + if(p->stream.error == MAD_ERROR_BUFLEN) { - if (mp3_inputdata(stream) == -1) + if(mp3_inputdata(stream) == -1) return -1;/* EOF with no valid data */ continue; @@ -256,7 +256,7 @@ static int32_t mp3_startread(snd_stream_t *stream) p->stream.error = MAD_ERROR_NONE; } - if (p->stream.error) + if(p->stream.error) { Con_Printf("MP3: No valid MP3 frame found\n"); return -1; @@ -277,8 +277,8 @@ static int32_t mp3_startread(snd_stream_t *stream) p->frame_count = 1; - mad_timer_add(&p->timer,p->frame.header.duration); - mad_synth_frame(&p->synth,&p->frame); + mad_timer_add(&p->timer, p->frame.header.duration); + mad_synth_frame(&p->synth, &p->frame); stream->info.rate = p->synth.pcm.samplerate; stream->info.bits = MP3_MAD_SAMPLEBITS; stream->info.width = MP3_MAD_SAMPLEWIDTH; @@ -304,20 +304,20 @@ static int32_t mp3_decode(snd_stream_t *stream, byte *buf, int32_t len) x = (p->synth.pcm.length - p->cursamp) * stream->info.channels; donow = q_min(len, x); i = 0; - while (i < donow) + while(i < donow) { - for (chan = 0; chan < stream->info.channels; chan++) + for(chan = 0; chan < stream->info.channels; chan++) { sample = p->synth.pcm.samples[chan][p->cursamp]; /* convert from fixed to int16_t, * write in host-endian format. */ - if (sample <= -MAD_F_ONE) + if(sample <= -MAD_F_ONE) sample = -0x7FFF; - else if (sample >= MAD_F_ONE) + else if(sample >= MAD_F_ONE) sample = 0x7FFF; else sample >>= (MAD_F_FRACBITS + 1 - 16); - if (host_bigendian) + if(host_bigendian) { *buf++ = (sample >> 8) & 0xFF; *buf++ = sample & 0xFF; @@ -335,13 +335,13 @@ static int32_t mp3_decode(snd_stream_t *stream, byte *buf, int32_t len) len -= donow; done += donow; - if (len == 0) + if(len == 0) break; /* check whether input buffer needs a refill */ - if (p->stream.error == MAD_ERROR_BUFLEN) + if(p->stream.error == MAD_ERROR_BUFLEN) { - if (mp3_inputdata(stream) == -1) + if(mp3_inputdata(stream) == -1) { /* check feof() ?? */ Con_DPrintf("mp3 EOF\n"); @@ -349,21 +349,21 @@ static int32_t mp3_decode(snd_stream_t *stream, byte *buf, int32_t len) } } - if (mad_frame_decode(&p->frame, &p->stream)) + if(mad_frame_decode(&p->frame, &p->stream)) { - if (MAD_RECOVERABLE(p->stream.error)) + if(MAD_RECOVERABLE(p->stream.error)) { mp3_inputtag(stream); continue; } else { - if (p->stream.error == MAD_ERROR_BUFLEN) + if(p->stream.error == MAD_ERROR_BUFLEN) continue; else { Con_Printf("MP3: unrecoverable frame level error (%s)\n", - mad_stream_errorstr(&p->stream)); + mad_stream_errorstr(&p->stream)); break; } } @@ -372,7 +372,8 @@ static int32_t mp3_decode(snd_stream_t *stream, byte *buf, int32_t len) mad_timer_add(&p->timer, p->frame.header.duration); mad_synth_frame(&p->synth, &p->frame); p->cursamp = 0; - } while (1); + } + while(1); return done; } @@ -388,34 +389,34 @@ static int32_t mp3_stopread(snd_stream_t *stream) return 0; } -static bool S_MP3_CodecInitialize (void) +static bool S_MP3_CodecInitialize(void) { return true; } -static void S_MP3_CodecShutdown (void) +static void S_MP3_CodecShutdown(void) { } -static bool S_MP3_CodecOpenStream (snd_stream_t *stream) +static bool S_MP3_CodecOpenStream(snd_stream_t *stream) { int32_t err; stream->priv = calloc(1, sizeof(mp3_priv_t)); - if (!stream->priv) + if(!stream->priv) { Con_Printf("Insufficient memory for MP3 audio\n"); return false; } err = mp3_startread(stream); - if (err != 0) + if(err != 0) { Con_Printf("%s is not a valid mp3 file\n", stream->name); } - else if (stream->info.channels != 1 && stream->info.channels != 2) + else if(stream->info.channels != 1 && stream->info.channels != 2) { Con_Printf("Unsupported number of channels %" PRIi32 " in %s\n", - stream->info.channels, stream->name); + stream->info.channels, stream->name); } else { @@ -425,25 +426,25 @@ static bool S_MP3_CodecOpenStream (snd_stream_t *stream) return false; } -static int32_t S_MP3_CodecReadStream (snd_stream_t *stream, int32_t bytes, void *buffer) +static int32_t S_MP3_CodecReadStream(snd_stream_t *stream, int32_t bytes, void *buffer) { int32_t res = mp3_decode(stream, (byte *)buffer, bytes / stream->info.width); return res * stream->info.width; } -static void S_MP3_CodecCloseStream (snd_stream_t *stream) +static void S_MP3_CodecCloseStream(snd_stream_t *stream) { mp3_stopread(stream); free(stream->priv); S_CodecUtilClose(&stream); } -static int32_t S_MP3_CodecRewindStream (snd_stream_t *stream) +static int32_t S_MP3_CodecRewindStream(snd_stream_t *stream) { mp3_priv_t *p = (mp3_priv_t *) stream->priv; size_t initial_bitrate = p->frame.header.bitrate; size_t tagsize = 0, consumed = 0; - int32_t vbr = 0; /* Variable Bit Rate, bool */ + int32_t vbr = 0; /* Variable Bit Rate, bool */ bool depadded = false; /* Reset all */ @@ -460,47 +461,48 @@ static int32_t S_MP3_CodecRewindStream (snd_stream_t *stream) mad_frame_init(&p->frame); mad_synth_init(&p->synth); - while (1) /* Read data from the MP3 file */ + while(1) /* Read data from the MP3 file */ { int32_t bytes_read, padding = 0; size_t leftover = p->stream.bufend - p->stream.next_frame; memcpy(p->mp3_buffer, p->stream.this_frame, leftover); bytes_read = FS_fread(p->mp3_buffer + leftover, (size_t) 1, - MP3_BUFFER_SIZE - leftover, &stream->fh); - if (bytes_read <= 0) + MP3_BUFFER_SIZE - leftover, &stream->fh); + if(bytes_read <= 0) { Con_DPrintf("seek failure. unexpected EOF (frames=%" PRIu32 " leftover=%" PRIu32 ")\n", - p->frame_count, leftover); + p->frame_count, leftover); break; } - for ( ; !depadded && padding < bytes_read && !p->mp3_buffer[padding]; ++padding) + for(; !depadded && padding < bytes_read && !p->mp3_buffer[padding]; ++padding) ; depadded = true; mad_stream_buffer(&p->stream, p->mp3_buffer + padding, leftover + bytes_read - padding); - while (1) /* Decode frame headers */ + while(1) /* Decode frame headers */ { static uint16_t samples; p->stream.error = MAD_ERROR_NONE; /* Not an audio frame */ - if (mad_header_decode(&p->frame.header, &p->stream) == -1) + if(mad_header_decode(&p->frame.header, &p->stream) == -1) { - if (p->stream.error == MAD_ERROR_BUFLEN) - break; /* Normal behaviour; get some more data from the file */ - if (!MAD_RECOVERABLE(p->stream.error)) + if(p->stream.error == MAD_ERROR_BUFLEN) + break; /* Normal behaviour; get some more data from the file */ + if(!MAD_RECOVERABLE(p->stream.error)) { Con_DPrintf("unrecoverable MAD error\n"); break; } - if (p->stream.error == MAD_ERROR_LOSTSYNC) + if(p->stream.error == MAD_ERROR_LOSTSYNC) { size_t available = (p->stream.bufend - p->stream.this_frame); tagsize = mp3_tagsize(p->stream.this_frame, (size_t) available); - if (tagsize) - { /* It's some ID3 tags, so just skip */ - if (tagsize >= available) + if(tagsize) + { + /* It's some ID3 tags, so just skip */ + if(tagsize >= available) { FS_fseek(&stream->fh, (ptrdiff_t)tagsize - (ptrdiff_t)available, @@ -529,7 +531,7 @@ static int32_t S_MP3_CodecRewindStream (snd_stream_t *stream) p->frame_count++; mad_timer_add(&p->timer, p->frame.header.duration); - mad_frame_decode(&p->frame,&p->stream); + mad_frame_decode(&p->frame, &p->stream); mad_synth_frame(&p->synth, &p->frame); p->cursamp = 0; return 0; @@ -542,7 +544,7 @@ static int32_t S_MP3_CodecRewindStream (snd_stream_t *stream) snd_codec_t mp3_codec = { CODECTYPE_MP3, - true, /* always available. */ + true, /* always available. */ "mp3", S_MP3_CodecInitialize, S_MP3_CodecShutdown, @@ -553,5 +555,5 @@ snd_codec_t mp3_codec = NULL }; -#endif /* USE_CODEC_MP3 */ +#endif /* USE_CODEC_MP3 */ diff --git a/source/snd_mp3.h b/source/snd_mp3.h index d54ae4d..29e4935 100644 --- a/source/snd_mp3.h +++ b/source/snd_mp3.h @@ -7,7 +7,7 @@ extern snd_codec_t mp3_codec; -#endif /* USE_CODEC_MP3 */ +#endif /* USE_CODEC_MP3 */ -#endif /* ! _SND_MP3_H_ */ +#endif /* ! _SND_MP3_H_ */ diff --git a/source/snd_mpg123.c b/source/snd_mpg123.c index 0575b55..83aff24 100644 --- a/source/snd_mpg123.c +++ b/source/snd_mpg123.c @@ -31,7 +31,7 @@ #if !defined(MPG123_API_VERSION) || (MPG123_API_VERSION < 24) #error minimum required libmpg123 version is 1.12.0 (api version 24) -#endif /* MPG123_API_VERSION */ +#endif /* MPG123_API_VERSION */ /* Private data */ typedef struct _mp3_priv_t @@ -45,29 +45,29 @@ typedef struct _mp3_priv_t * however our FS_fread() and FS_fseek() return fread() and fseek() * compatible values. */ -static ssize_t mp3_read (void *f, void *buf, size_t size) +static ssize_t mp3_read(void *f, void *buf, size_t size) { ssize_t ret = (ssize_t) FS_fread(buf, 1, size, (fshandle_t *)f); - if (ret == 0 && errno != 0) + if(ret == 0 && errno != 0) ret = -1; return ret; } -static off_t mp3_seek (void *f, off_t offset, int32_t whence) +static off_t mp3_seek(void *f, off_t offset, int32_t whence) { - if (f == NULL) return (-1); - if (FS_fseek((fshandle_t *)f, (long) offset, whence) < 0) - return (off_t)-1; + if(f == NULL) return (-1); + if(FS_fseek((fshandle_t *)f, (long) offset, whence) < 0) + return (off_t) -1; return (off_t) FS_ftell((fshandle_t *)f); } -static bool S_MP3_CodecInitialize (void) +static bool S_MP3_CodecInitialize(void) { - if (!mp3_codec.initialized) + if(!mp3_codec.initialized) { - if (mpg123_init() != MPG123_OK) + if(mpg123_init() != MPG123_OK) { - Con_Printf ("Could not initialize mpg123\n"); + Con_Printf("Could not initialize mpg123\n"); return false; } mp3_codec.initialized = true; @@ -77,16 +77,16 @@ static bool S_MP3_CodecInitialize (void) return true; } -static void S_MP3_CodecShutdown (void) +static void S_MP3_CodecShutdown(void) { - if (mp3_codec.initialized) + if(mp3_codec.initialized) { mp3_codec.initialized = false; mpg123_exit(); } } -static bool S_MP3_CodecOpenStream (snd_stream_t *stream) +static bool S_MP3_CodecOpenStream(snd_stream_t *stream) { long rate = 0; int32_t encoding = 0, channels = 0; @@ -95,28 +95,28 @@ static bool S_MP3_CodecOpenStream (snd_stream_t *stream) stream->priv = Z_Malloc(sizeof(mp3_priv_t)); priv = (mp3_priv_t *) stream->priv; priv->handle = mpg123_new(NULL, NULL); - if (priv->handle == NULL) + if(priv->handle == NULL) { Con_Printf("Unable to allocate mpg123 handle\n"); goto _fail; } priv->handle_newed = 1; - if (mpg123_replace_reader_handle(priv->handle, mp3_read, mp3_seek, NULL) != MPG123_OK || - mpg123_open_handle(priv->handle, &stream->fh) != MPG123_OK) + if(mpg123_replace_reader_handle(priv->handle, mp3_read, mp3_seek, NULL) != MPG123_OK || + mpg123_open_handle(priv->handle, &stream->fh) != MPG123_OK) { Con_Printf("Unable to open mpg123 handle\n"); goto _fail; } priv->handle_opened = 1; - if (mpg123_getformat(priv->handle, &rate, &channels, &encoding) != MPG123_OK) + if(mpg123_getformat(priv->handle, &rate, &channels, &encoding) != MPG123_OK) { Con_Printf("Unable to retrieve mpg123 format for %s\n", stream->name); goto _fail; } - switch (channels) + switch(channels) { case MPG123_MONO: stream->info.channels = 1; @@ -131,14 +131,14 @@ static bool S_MP3_CodecOpenStream (snd_stream_t *stream) stream->info.rate = rate; - switch (encoding) + switch(encoding) { case MPG123_ENC_UNSIGNED_8: stream->info.bits = 8; stream->info.width = 1; break; case MPG123_ENC_SIGNED_8: - /* unsupported: force mpg123 to convert */ + /* unsupported: force mpg123 to convert */ stream->info.bits = 8; stream->info.width = 1; encoding = MPG123_ENC_UNSIGNED_8; @@ -149,13 +149,13 @@ static bool S_MP3_CodecOpenStream (snd_stream_t *stream) break; case MPG123_ENC_UNSIGNED_16: default: - /* unsupported: force mpg123 to convert */ + /* unsupported: force mpg123 to convert */ stream->info.bits = 16; stream->info.width = 2; encoding = MPG123_ENC_SIGNED_16; break; } - if (mpg123_format_support(priv->handle, rate, encoding) == 0) + if(mpg123_format_support(priv->handle, rate, encoding) == 0) { Con_Printf("Unsupported format for %s\n", stream->name); goto _fail; @@ -165,23 +165,23 @@ static bool S_MP3_CodecOpenStream (snd_stream_t *stream) return true; _fail: - if (priv) + if(priv) { - if (priv->handle_opened) + if(priv->handle_opened) mpg123_close(priv->handle); - if (priv->handle_newed) + if(priv->handle_newed) mpg123_delete(priv->handle); Z_Free(stream->priv); } return false; } -static int32_t S_MP3_CodecReadStream (snd_stream_t *stream, int32_t bytes, void *buffer) +static int32_t S_MP3_CodecReadStream(snd_stream_t *stream, int32_t bytes, void *buffer) { mp3_priv_t *priv = (mp3_priv_t *) stream->priv; size_t bytes_read = 0; - int32_t res = mpg123_read (priv->handle, (uint8_t *)buffer, (size_t)bytes, &bytes_read); - switch (res) + int32_t res = mpg123_read(priv->handle, (uint8_t *)buffer, (size_t)bytes, &bytes_read); + switch(res) { case MPG123_DONE: Con_DPrintf("mp3 EOF\n"); @@ -191,7 +191,7 @@ static int32_t S_MP3_CodecReadStream (snd_stream_t *stream, int32_t bytes, void return -1; /* error */ } -static void S_MP3_CodecCloseStream (snd_stream_t *stream) +static void S_MP3_CodecCloseStream(snd_stream_t *stream) { mp3_priv_t *priv = (mp3_priv_t *) stream->priv; mpg123_close(priv->handle); @@ -200,11 +200,11 @@ static void S_MP3_CodecCloseStream (snd_stream_t *stream) S_CodecUtilClose(&stream); } -static int32_t S_MP3_CodecRewindStream (snd_stream_t *stream) +static int32_t S_MP3_CodecRewindStream(snd_stream_t *stream) { mp3_priv_t *priv = (mp3_priv_t *) stream->priv; off_t res = mpg123_seek(priv->handle, 0, SEEK_SET); - if (res >= 0) return (0); + if(res >= 0) return (0); return res; } @@ -222,5 +222,5 @@ snd_codec_t mp3_codec = NULL }; -#endif /* USE_CODEC_MP3 */ +#endif /* USE_CODEC_MP3 */ diff --git a/source/snd_opus.c b/source/snd_opus.c index e30b637..7d88d06 100644 --- a/source/snd_opus.c +++ b/source/snd_opus.c @@ -34,35 +34,35 @@ /* CALLBACK FUNCTIONS: */ -static int32_t opc_fclose (void *f) +static int32_t opc_fclose(void *f) { (void)f; - return 0; /* we fclose() elsewhere. */ + return 0; /* we fclose() elsewhere. */ } -static int32_t opc_fread (void *f, uint8_t *buf, int32_t size) +static int32_t opc_fread(void *f, uint8_t *buf, int32_t size) { int32_t ret; - if (size < 0) + if(size < 0) { errno = EINVAL; return -1; } ret = (int32_t) FS_fread(buf, 1, (size_t)size, (fshandle_t *)f); - if (ret == 0 && errno != 0) + if(ret == 0 && errno != 0) ret = -1; return ret; } -static int32_t opc_fseek (void *f, opus_int64 off, int32_t whence) +static int32_t opc_fseek(void *f, opus_int64 off, int32_t whence) { - if (f == NULL) return (-1); + if(f == NULL) return (-1); return FS_fseek((fshandle_t *)f, (long) off, whence); } -static opus_int64 opc_ftell (void *f) +static opus_int64 opc_ftell(void *f) { return (opus_int64) FS_ftell((fshandle_t *)f); } @@ -70,21 +70,21 @@ static opus_int64 opc_ftell (void *f) static const OpusFileCallbacks opc_qfs = { (int32_t (*)(void *, uint8_t *, int32_t)) opc_fread, - (int32_t (*)(void *, opus_int64, int32_t)) opc_fseek, - (opus_int64 (*)(void *)) opc_ftell, - (int32_t (*)(void *)) opc_fclose + (int32_t (*)(void *, opus_int64, int32_t)) opc_fseek, + (opus_int64(*)(void *)) opc_ftell, + (int32_t (*)(void *)) opc_fclose }; -static bool S_OPUS_CodecInitialize (void) +static bool S_OPUS_CodecInitialize(void) { return true; } -static void S_OPUS_CodecShutdown (void) +static void S_OPUS_CodecShutdown(void) { } -static bool S_OPUS_CodecOpenStream (snd_stream_t *stream) +static bool S_OPUS_CodecOpenStream(snd_stream_t *stream) { OggOpusFile *opFile; const OpusHead *op_info; @@ -92,23 +92,23 @@ static bool S_OPUS_CodecOpenStream (snd_stream_t *stream) int32_t res; opFile = op_open_callbacks(&stream->fh, &opc_qfs, NULL, 0, &res); - if (!opFile) + if(!opFile) { Con_Printf("%s is not a valid Opus file (error %" PRIi32 ").\n", - stream->name, res); + stream->name, res); goto _fail; } stream->priv = opFile; - if (!op_seekable(opFile)) + if(!op_seekable(opFile)) { Con_Printf("Opus stream %s not seekable.\n", stream->name); goto _fail; } op_info = op_head(opFile, -1); - if (!op_info) + if(!op_info) { Con_Printf("Unable to get stream information for %s.\n", stream->name); goto _fail; @@ -116,17 +116,17 @@ static bool S_OPUS_CodecOpenStream (snd_stream_t *stream) /* FIXME: handle section changes */ numstreams = op_info->stream_count; - if (numstreams != 1) + if(numstreams != 1) { Con_Printf("More than one (%" PRIi64 ") stream in %s\n", - (long)op_info->stream_count, stream->name); + (long)op_info->stream_count, stream->name); goto _fail; } - if (op_info->channel_count != 1 && op_info->channel_count != 2) + if(op_info->channel_count != 1 && op_info->channel_count != 2) { Con_Printf("Unsupported number of channels %" PRIi32 " in %s\n", - op_info->channel_count, stream->name); + op_info->channel_count, stream->name); goto _fail; } @@ -142,61 +142,61 @@ static bool S_OPUS_CodecOpenStream (snd_stream_t *stream) return true; _fail: - if (opFile) + if(opFile) op_free(opFile); return false; } -static int32_t S_OPUS_CodecReadStream (snd_stream_t *stream, int32_t bytes, void *buffer) +static int32_t S_OPUS_CodecReadStream(snd_stream_t *stream, int32_t bytes, void *buffer) { - int32_t section; /* FIXME: handle section changes */ - int32_t cnt, res, rem; - opus_int16 * ptr; + int32_t section; /* FIXME: handle section changes */ + int32_t cnt, res, rem; + opus_int16 * ptr; rem = bytes / stream->info.width; - if (rem / stream->info.channels <= 0) + if(rem / stream->info.channels <= 0) return 0; cnt = 0; ptr = (opus_int16 *) buffer; - while (1) + while(1) { - /* op_read() yields 16-bit output using native endian ordering. returns - * the number of samples read per channel on success, or a negative value - * on failure. */ + /* op_read() yields 16-bit output using native endian ordering. returns + * the number of samples read per channel on success, or a negative value + * on failure. */ res = op_read((OggOpusFile *)stream->priv, ptr, rem, §ion); - if (res <= 0) + if(res <= 0) break; cnt += res; res *= stream->info.channels; rem -= res; - if (rem <= 0) + if(rem <= 0) break; ptr += res; } - if (res < 0) + if(res < 0) return res; cnt *= (stream->info.channels * stream->info.width); return cnt; } -static void S_OPUS_CodecCloseStream (snd_stream_t *stream) +static void S_OPUS_CodecCloseStream(snd_stream_t *stream) { op_free((OggOpusFile *)stream->priv); S_CodecUtilClose(&stream); } -static int32_t S_OPUS_CodecRewindStream (snd_stream_t *stream) +static int32_t S_OPUS_CodecRewindStream(snd_stream_t *stream) { - return op_pcm_seek ((OggOpusFile *)stream->priv, 0); + return op_pcm_seek((OggOpusFile *)stream->priv, 0); } snd_codec_t opus_codec = { CODECTYPE_OPUS, - true, /* always available. */ + true, /* always available. */ "opus", S_OPUS_CodecInitialize, S_OPUS_CodecShutdown, @@ -207,5 +207,5 @@ snd_codec_t opus_codec = NULL }; -#endif /* USE_CODEC_OPUS */ +#endif /* USE_CODEC_OPUS */ diff --git a/source/snd_opus.h b/source/snd_opus.h index 4c2a25f..aa5a53d 100644 --- a/source/snd_opus.h +++ b/source/snd_opus.h @@ -7,7 +7,7 @@ extern snd_codec_t opus_codec; -#endif /* USE_CODEC_OPUS */ +#endif /* USE_CODEC_OPUS */ -#endif /* ! _SND_OPUS_H_ */ +#endif /* ! _SND_OPUS_H_ */ diff --git a/source/snd_sdl.c b/source/snd_sdl.c index 872d4cb..2f12746 100644 --- a/source/snd_sdl.c +++ b/source/snd_sdl.c @@ -26,31 +26,32 @@ #include -static int32_t buffersize; +static int32_t buffersize; -static void SDLCALL paint_audio (void *unused, Uint8 *stream, int32_t len) +static void SDLCALL paint_audio(void *unused, Uint8 *stream, int32_t len) { - int32_t pos, tobufend; - int32_t len1, len2; + int32_t pos, tobufend; + int32_t len1, len2; (void)unused; - if (!shm) - { /* shouldn't happen, but just in case */ + if(!shm) + { + /* shouldn't happen, but just in case */ memset(stream, 0, len); return; } pos = (shm->samplepos * (shm->samplebits / 8)); - if (pos >= buffersize) + if(pos >= buffersize) shm->samplepos = pos = 0; tobufend = buffersize - pos; /* bytes to buffer's end. */ len1 = len; len2 = 0; - if (len1 > tobufend) + if(len1 > tobufend) { len1 = tobufend; len2 = len - len1; @@ -58,27 +59,28 @@ static void SDLCALL paint_audio (void *unused, Uint8 *stream, int32_t len) memcpy(stream, shm->buffer + pos, len1); - if (len2 <= 0) + if(len2 <= 0) { shm->samplepos += (len1 / (shm->samplebits / 8)); } else - { /* wraparound? */ + { + /* wraparound? */ memcpy(stream + len1, shm->buffer, len2); shm->samplepos = (len2 / (shm->samplebits / 8)); } - if (shm->samplepos >= buffersize) + if(shm->samplepos >= buffersize) shm->samplepos = 0; } -bool SNDDMA_Init (dma_t *dma) +bool SNDDMA_Init(dma_t *dma) { SDL_AudioSpec desired, obtained; - int32_t tmp, val; - char drivername[128]; + int32_t tmp, val; + char drivername[128]; - if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) + if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { Con_Printf("Couldn't init SDL audio: %s\n", SDL_GetError()); return false; @@ -88,13 +90,13 @@ bool SNDDMA_Init (dma_t *dma) desired.freq = tmp = snd_mixspeed.value; desired.format = (loadas8bit.value) ? AUDIO_U8 : AUDIO_S16SYS; desired.channels = 2; /* = desired_channels; */ - if (desired.freq <= 11025) + if(desired.freq <= 11025) desired.samples = 256; - else if (desired.freq <= 22050) + else if(desired.freq <= 22050) desired.samples = 512; - else if (desired.freq <= 44100) + else if(desired.freq <= 44100) desired.samples = 1024; - else if (desired.freq <= 56000) + else if(desired.freq <= 56000) desired.samples = 2048; /* for 48 kHz */ else desired.samples = 4096; /* for 96 kHz */ @@ -102,7 +104,7 @@ bool SNDDMA_Init (dma_t *dma) desired.userdata = NULL; /* Open the audio device */ - if (SDL_OpenAudio(&desired, &obtained) == -1) + if(SDL_OpenAudio(&desired, &obtained) == -1) { Con_Printf("Couldn't open SDL audio: %s\n", SDL_GetError()); SDL_QuitSubSystem(SDL_INIT_AUDIO); @@ -110,35 +112,36 @@ bool SNDDMA_Init (dma_t *dma) } /* Make sure we can support the audio format */ - switch (obtained.format) + switch(obtained.format) { - case AUDIO_S8: /* maybe needed by AHI */ + case AUDIO_S8: /* maybe needed by AHI */ case AUDIO_U8: case AUDIO_S16SYS: /* Supported */ break; default: - Con_Printf ("Unsupported audio format received (%" PRIu32 ")\n", obtained.format); + Con_Printf("Unsupported audio format received (%" PRIu32 ")\n", obtained.format); SDL_CloseAudio(); SDL_QuitSubSystem(SDL_INIT_AUDIO); return false; } - memset ((void *) dma, 0, sizeof(dma_t)); + memset((void *) dma, 0, sizeof(dma_t)); shm = dma; /* Fill the audio DMA information block */ shm->samplebits = (obtained.format & 0xFF); /* first byte of format is bits */ shm->signed8 = (obtained.format == AUDIO_S8); - if (obtained.freq != tmp) - Con_Printf ("Warning: Rate set (%" PRIi32 ") didn't match requested rate (%" PRIi32 ")!\n", obtained.freq, tmp); + if(obtained.freq != tmp) + Con_Printf("Warning: Rate set (%" PRIi32 ") didn't match requested rate (%" PRIi32 ")!\n", obtained.freq, tmp); shm->speed = obtained.freq; shm->channels = obtained.channels; tmp = (obtained.samples * obtained.channels) * 10; - if (tmp & (tmp - 1)) - { /* make it a power of two */ + if(tmp & (tmp - 1)) + { + /* make it a power of two */ val = 1; - while (val < tmp) + while(val < tmp) val <<= 1; tmp = val; @@ -147,25 +150,25 @@ bool SNDDMA_Init (dma_t *dma) shm->samplepos = 0; shm->submission_chunk = 1; - Con_Printf ("SDL audio spec : %" PRIi32 " Hz, %" PRIi32 " samples, %" PRIi32 " channels\n", - obtained.freq, obtained.samples, obtained.channels); + Con_Printf("SDL audio spec : %" PRIi32 " Hz, %" PRIi32 " samples, %" PRIi32 " channels\n", + obtained.freq, obtained.samples, obtained.channels); { const char *driver = SDL_GetCurrentAudioDriver(); const char *device = SDL_GetAudioDeviceName(0, SDL_FALSE); q_snprintf(drivername, sizeof(drivername), "%s - %s", - driver != NULL ? driver : "(UNKNOWN)", - device != NULL ? device : "(UNKNOWN)"); + driver != NULL ? driver : "(UNKNOWN)", + device != NULL ? device : "(UNKNOWN)"); } buffersize = shm->samples * (shm->samplebits / 8); - Con_Printf ("SDL audio driver: %s, %" PRIi32 " bytes buffer\n", drivername, buffersize); + Con_Printf("SDL audio driver: %s, %" PRIi32 " bytes buffer\n", drivername, buffersize); - shm->buffer = (uint8_t *) calloc (1, buffersize); - if (!shm->buffer) + shm->buffer = (uint8_t *) calloc(1, buffersize); + if(!shm->buffer) { SDL_CloseAudio(); SDL_QuitSubSystem(SDL_INIT_AUDIO); shm = NULL; - Con_Printf ("Failed allocating memory for SDL audio\n"); + Con_Printf("Failed allocating memory for SDL audio\n"); return false; } @@ -174,41 +177,41 @@ bool SNDDMA_Init (dma_t *dma) return true; } -int32_t SNDDMA_GetDMAPos (void) +int32_t SNDDMA_GetDMAPos(void) { return shm->samplepos; } -void SNDDMA_Shutdown (void) +void SNDDMA_Shutdown(void) { - if (shm) + if(shm) { - Con_Printf ("Shutting down SDL sound\n"); + Con_Printf("Shutting down SDL sound\n"); SDL_CloseAudio(); SDL_QuitSubSystem(SDL_INIT_AUDIO); - if (shm->buffer) - free (shm->buffer); + if(shm->buffer) + free(shm->buffer); shm->buffer = NULL; shm = NULL; } } -void SNDDMA_LockBuffer (void) +void SNDDMA_LockBuffer(void) { - SDL_LockAudio (); + SDL_LockAudio(); } -void SNDDMA_Submit (void) +void SNDDMA_Submit(void) { SDL_UnlockAudio(); } -void SNDDMA_BlockSound (void) +void SNDDMA_BlockSound(void) { SDL_PauseAudio(1); } -void SNDDMA_UnblockSound (void) +void SNDDMA_UnblockSound(void) { SDL_PauseAudio(0); } diff --git a/source/snd_umx.c b/source/snd_umx.c index 838354f..421056b 100644 --- a/source/snd_umx.c +++ b/source/snd_umx.c @@ -33,25 +33,27 @@ #include "snd_codeci.h" #include "snd_umx.h" -typedef int32_t fci_t; /* FCompactIndex */ +typedef int32_t fci_t; /* FCompactIndex */ -#define UPKG_HDR_TAG 0x9e2a83c1 +#define UPKG_HDR_TAG 0x9e2a83c1 -struct _genhist { /* for upkg versions >= 68 */ +struct _genhist /* for upkg versions >= 68 */ +{ int32_t export_count; int32_t name_count; }; -struct upkg_hdr { - uint32_t tag; /* UPKG_HDR_TAG */ +struct upkg_hdr +{ + uint32_t tag; /* UPKG_HDR_TAG */ int32_t file_version; uint32_t pkg_flags; - int32_t name_count; /* number of names in name table (>= 0) */ - int32_t name_offset; /* offset to name table (>= 0) */ - int32_t export_count; /* num. exports in export table (>= 0) */ - int32_t export_offset; /* offset to export table (>= 0) */ - int32_t import_count; /* num. imports in export table (>= 0) */ - int32_t import_offset; /* offset to import table (>= 0) */ + int32_t name_count; /* number of names in name table (>= 0) */ + int32_t name_offset; /* offset to name table (>= 0) */ + int32_t export_count; /* num. exports in export table (>= 0) */ + int32_t export_offset; /* offset to export table (>= 0) */ + int32_t import_count; /* num. imports in export table (>= 0) */ + int32_t import_offset; /* offset to import table (>= 0) */ /* number of GUIDs in heritage table (>= 1) and table's offset: * only with versions < 68. */ @@ -61,20 +63,21 @@ struct upkg_hdr { * and export_count and name_count dwords for each generation: */ uint32_t guid[4]; int32_t generation_count; -#define UPKG_HDR_SIZE 64 /* 64 bytes up until here */ +#define UPKG_HDR_SIZE 64 /* 64 bytes up until here */ /*struct _genhist *gen;*/ }; _Static_assert(sizeof(struct upkg_hdr) == UPKG_HDR_SIZE, "upkg_hdr not correct size"); -#define UMUSIC_IT 0 -#define UMUSIC_S3M 1 -#define UMUSIC_XM 2 -#define UMUSIC_MOD 3 -#define UMUSIC_WAV 4 -#define UMUSIC_MP2 5 +#define UMUSIC_IT 0 +#define UMUSIC_S3M 1 +#define UMUSIC_XM 2 +#define UMUSIC_MOD 3 +#define UMUSIC_WAV 4 +#define UMUSIC_MP2 5 -static const char *mustype[] = { +static const char *mustype[] = +{ "IT", "S3M", "XM", "MOD", "WAV", "MP2", NULL }; @@ -85,7 +88,7 @@ static const char *mustype[] = { * also see Unreal Wiki: * http://wiki.beyondunreal.com/Legacy:Package_File_Format/Data_Details */ -static fci_t get_fci (const char *in, int32_t *pos) +static fci_t get_fci(const char *in, int32_t *pos) { int32_t a; int32_t size; @@ -93,19 +96,23 @@ static fci_t get_fci (const char *in, int32_t *pos) size = 1; a = in[0] & 0x3f; - if (in[0] & 0x40) { + if(in[0] & 0x40) + { size++; a |= (in[1] & 0x7f) << 6; - if (in[1] & 0x80) { + if(in[1] & 0x80) + { size++; a |= (in[2] & 0x7f) << 13; - if (in[2] & 0x80) { + if(in[2] & 0x80) + { size++; a |= (in[3] & 0x7f) << 20; - if (in[3] & 0x80) { + if(in[3] & 0x80) + { size++; a |= (in[4] & 0x3f) << 27; } @@ -113,7 +120,7 @@ static fci_t get_fci (const char *in, int32_t *pos) } } - if (in[0] & 0x80) + if(in[0] & 0x80) a = -a; *pos += size; @@ -121,43 +128,48 @@ static fci_t get_fci (const char *in, int32_t *pos) return a; } -static int32_t get_objtype (fshandle_t *f, int32_t ofs, int32_t type) +static int32_t get_objtype(fshandle_t *f, int32_t ofs, int32_t type) { char sig[16]; _retry: FS_fseek(f, ofs, SEEK_SET); FS_fread(sig, 16, 1, f); - if (type == UMUSIC_IT) { - if (memcmp(sig, "IMPM", 4) == 0) + if(type == UMUSIC_IT) + { + if(memcmp(sig, "IMPM", 4) == 0) return UMUSIC_IT; return -1; } - if (type == UMUSIC_XM) { - if (memcmp(sig, "Extended Module:", 16) != 0) + if(type == UMUSIC_XM) + { + if(memcmp(sig, "Extended Module:", 16) != 0) return -1; FS_fread(sig, 16, 1, f); - if (sig[0] != ' ') return -1; + if(sig[0] != ' ') return -1; FS_fread(sig, 16, 1, f); - if (sig[5] != 0x1a) return -1; + if(sig[5] != 0x1a) return -1; return UMUSIC_XM; } - if (type == UMUSIC_MP2) { + if(type == UMUSIC_MP2) + { uint8_t *p = (uint8_t *)sig; uint16_t u = ((p[0] << 8) | p[1]) & 0xFFFE; - if (u == 0xFFFC || u == 0xFFF4) + if(u == 0xFFFC || u == 0xFFF4) return UMUSIC_MP2; return -1; } - if (type == UMUSIC_WAV) { - if (memcmp(sig, "RIFF", 4) == 0 && memcmp(&sig[8], "WAVE", 4) == 0) + if(type == UMUSIC_WAV) + { + if(memcmp(sig, "RIFF", 4) == 0 && memcmp(&sig[8], "WAVE", 4) == 0) return UMUSIC_WAV; return -1; } FS_fseek(f, ofs + 44, SEEK_SET); FS_fread(sig, 4, 1, f); - if (type == UMUSIC_S3M) { - if (memcmp(sig, "SCRM", 4) == 0) + if(type == UMUSIC_S3M) + { + if(memcmp(sig, "SCRM", 4) == 0) return UMUSIC_S3M; /*return -1;*/ /* SpaceMarines.umx and Starseek.umx from Return to NaPali @@ -168,8 +180,9 @@ _retry: FS_fseek(f, ofs + 1080, SEEK_SET); FS_fread(sig, 4, 1, f); - if (type == UMUSIC_MOD) { - if (memcmp(sig, "M.K.", 4) == 0 || memcmp(sig, "M!K!", 4) == 0) + if(type == UMUSIC_MOD) + { + if(memcmp(sig, "M.K.", 4) == 0 || memcmp(sig, "M!K!", 4) == 0) return UMUSIC_MOD; return -1; } @@ -177,55 +190,59 @@ _retry: return -1; } -static int32_t read_export (fshandle_t *f, const struct upkg_hdr *hdr, - int32_t *ofs, int32_t *objsize) +static int32_t read_export(fshandle_t *f, const struct upkg_hdr *hdr, + int32_t *ofs, int32_t *objsize) { char buf[40]; int32_t idx = 0, t; FS_fseek(f, *ofs, SEEK_SET); - if (FS_fread(buf, 4, 10, f) < 10) + if(FS_fread(buf, 4, 10, f) < 10) return -1; - if (hdr->file_version < 40) idx += 8; /* 00 00 00 00 00 00 00 00 */ - if (hdr->file_version < 60) idx += 16; /* 81 00 00 00 00 00 FF FF FF FF FF FF FF FF 00 00 */ - get_fci(&buf[idx], &idx); /* skip junk */ - t = get_fci(&buf[idx], &idx); /* type_name */ - if (hdr->file_version > 61) idx += 4; /* skip export size */ + if(hdr->file_version < 40) idx += 8; /* 00 00 00 00 00 00 00 00 */ + if(hdr->file_version < 60) idx += 16; /* 81 00 00 00 00 00 FF FF FF FF FF FF FF FF 00 00 */ + get_fci(&buf[idx], &idx); /* skip junk */ + t = get_fci(&buf[idx], &idx); /* type_name */ + if(hdr->file_version > 61) idx += 4; /* skip export size */ *objsize = get_fci(&buf[idx], &idx); - *ofs += idx; /* offset for real data */ + *ofs += idx; /* offset for real data */ - return t; /* return type_name index */ + return t; /* return type_name index */ } static int32_t read_typname(fshandle_t *f, const struct upkg_hdr *hdr, - int32_t idx, char *out) + int32_t idx, char *out) { int32_t i, s; long l; char buf[64]; - if (idx >= hdr->name_count) return -1; + if(idx >= hdr->name_count) return -1; buf[63] = '\0'; - for (i = 0, l = 0; i <= idx; i++) { + for(i = 0, l = 0; i <= idx; i++) + { FS_fseek(f, hdr->name_offset + l, SEEK_SET); FS_fread(buf, 1, 63, f); - if (hdr->file_version >= 64) { + if(hdr->file_version >= 64) + { s = *(int8_t *)buf; /* numchars *including* terminator */ - if (s <= 0 || s > 64) return -1; - l += s + 5; /* 1 for buf[0], 4 for int32_t name_flags */ - } else { + if(s <= 0 || s > 64) return -1; + l += s + 5; /* 1 for buf[0], 4 for int32_t name_flags */ + } + else + { l += (long)strlen(buf); - l += 5; /* 1 for terminator, 4 for int32_t name_flags */ + l += 5; /* 1 for terminator, 4 for int32_t name_flags */ } } - strcpy(out, (hdr->file_version >= 64)? &buf[1] : buf); + strcpy(out, (hdr->file_version >= 64) ? &buf[1] : buf); return 0; } -static int32_t probe_umx (fshandle_t *f, const struct upkg_hdr *hdr, - int32_t *ofs, int32_t *objsize) +static int32_t probe_umx(fshandle_t *f, const struct upkg_hdr *hdr, + int32_t *ofs, int32_t *objsize) { int32_t i, idx, t; int32_t s, pos; @@ -233,47 +250,49 @@ static int32_t probe_umx (fshandle_t *f, const struct upkg_hdr *hdr, char buf[64]; idx = 0; - fsiz = FS_filelength (f); + fsiz = FS_filelength(f); /* Find the offset and size of the first IT, S3M or XM * by parsing the exports table. The umx files should * have only one export. Kran32.umx from Unreal has two, * but both pointing to the same music. */ - if (hdr->export_offset >= fsiz) return -1; + if(hdr->export_offset >= fsiz) return -1; memset(buf, 0, 64); FS_fseek(f, hdr->export_offset, SEEK_SET); FS_fread(buf, 1, 64, f); - get_fci(&buf[idx], &idx); /* skip class_index */ - get_fci(&buf[idx], &idx); /* skip super_index */ - if (hdr->file_version >= 60) idx += 4; /* skip int32 package_index */ - get_fci(&buf[idx], &idx); /* skip object_name */ - idx += 4; /* skip int32 object_flags */ + get_fci(&buf[idx], &idx); /* skip class_index */ + get_fci(&buf[idx], &idx); /* skip super_index */ + if(hdr->file_version >= 60) idx += 4; /* skip int32 package_index */ + get_fci(&buf[idx], &idx); /* skip object_name */ + idx += 4; /* skip int32 object_flags */ - s = get_fci(&buf[idx], &idx); /* get serial_size */ - if (s <= 0) return -1; - pos = get_fci(&buf[idx],&idx); /* get serial_offset */ - if (pos < 0 || pos > fsiz - 40) return -1; + s = get_fci(&buf[idx], &idx); /* get serial_size */ + if(s <= 0) return -1; + pos = get_fci(&buf[idx], &idx); /* get serial_offset */ + if(pos < 0 || pos > fsiz - 40) return -1; - if ((t = read_export(f, hdr, &pos, &s)) < 0) return -1; - if (s <= 0 || s > fsiz - pos) return -1; + if((t = read_export(f, hdr, &pos, &s)) < 0) return -1; + if(s <= 0 || s > fsiz - pos) return -1; - if (read_typname(f, hdr, t, buf) < 0) return -1; - for (i = 0; mustype[i] != NULL; i++) { - if (!q_strcasecmp(buf, mustype[i])) { + if(read_typname(f, hdr, t, buf) < 0) return -1; + for(i = 0; mustype[i] != NULL; i++) + { + if(!q_strcasecmp(buf, mustype[i])) + { t = i; break; } } - if (mustype[i] == NULL) return -1; - if ((t = get_objtype(f, pos, t)) < 0) return -1; + if(mustype[i] == NULL) return -1; + if((t = get_objtype(f, pos, t)) < 0) return -1; *ofs = pos; *objsize = s; return t; } -static int32_t probe_header (void *header) +static int32_t probe_header(void *header) { struct upkg_hdr *hdr; uint8_t *p; @@ -283,28 +302,34 @@ static int32_t probe_header (void *header) /* byte swap the header - all members are 32 bit LE values */ p = (uint8_t *) header; swp = (uint32_t *) header; - for (i = 0; i < UPKG_HDR_SIZE/4; i++, p += 4) { + for(i = 0; i < UPKG_HDR_SIZE / 4; i++, p += 4) + { swp[i] = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); } hdr = (struct upkg_hdr *) header; - if (hdr->tag != UPKG_HDR_TAG) { + if(hdr->tag != UPKG_HDR_TAG) + { Con_DPrintf("Unknown header tag 0x%x\n", hdr->tag); return -1; } - if (hdr->name_count < 0 || - hdr->name_offset < 0 || - hdr->export_count < 0 || - hdr->export_offset < 0 || - hdr->import_count < 0 || - hdr->import_offset < 0 ) { + if(hdr->name_count < 0 || + hdr->name_offset < 0 || + hdr->export_count < 0 || + hdr->export_offset < 0 || + hdr->import_count < 0 || + hdr->import_offset < 0) + { Con_DPrintf("Negative values in header\n"); return -1; } - switch (hdr->file_version) { - case 35: case 37: /* Unreal beta - */ - case 40: case 41: /* 1998 */ + switch(hdr->file_version) + { + case 35: + case 37: /* Unreal beta - */ + case 40: + case 41: /* 1998 */ case 61:/* Unreal */ case 62:/* Unreal Tournament */ case 63:/* Return to NaPali */ @@ -313,7 +338,7 @@ static int32_t probe_header (void *header) case 68:/* Unreal Tournament */ case 69:/* Tactical Ops */ case 75:/* Harry Potter and the Philosopher's Stone */ - case 76: /* mpeg layer II data */ + case 76: /* mpeg layer II data */ case 83:/* Mobile Forces */ return 0; } @@ -322,34 +347,35 @@ static int32_t probe_header (void *header) return -1; } -static int32_t process_upkg (fshandle_t *f, int32_t *ofs, int32_t *objsize) +static int32_t process_upkg(fshandle_t *f, int32_t *ofs, int32_t *objsize) { char header[UPKG_HDR_SIZE]; - if (FS_fread(header, 1, UPKG_HDR_SIZE, f) < UPKG_HDR_SIZE) + if(FS_fread(header, 1, UPKG_HDR_SIZE, f) < UPKG_HDR_SIZE) return -1; - if (probe_header(header) < 0) + if(probe_header(header) < 0) return -1; return probe_umx(f, (struct upkg_hdr *)header, ofs, objsize); } -static bool S_UMX_CodecInitialize (void) +static bool S_UMX_CodecInitialize(void) { return true; } -static void S_UMX_CodecShutdown (void) +static void S_UMX_CodecShutdown(void) { } -static bool S_UMX_CodecOpenStream (snd_stream_t *stream) +static bool S_UMX_CodecOpenStream(snd_stream_t *stream) { int32_t type; int32_t ofs = 0, size = 0; type = process_upkg(&stream->fh, &ofs, &size); - if (type < 0) { + if(type < 0) + { Con_DPrintf("%s: unrecognized umx\n", stream->name); return false; } @@ -361,30 +387,34 @@ static bool S_UMX_CodecOpenStream (snd_stream_t *stream) stream->fh.length = size; FS_fseek(&stream->fh, 0, SEEK_SET); - switch (type) { + switch(type) + { case UMUSIC_IT: case UMUSIC_S3M: case UMUSIC_XM: - case UMUSIC_MOD: return S_CodecForwardStream(stream, CODECTYPE_MOD); - case UMUSIC_WAV: return S_CodecForwardStream(stream, CODECTYPE_WAV); - case UMUSIC_MP2: return S_CodecForwardStream(stream, CODECTYPE_MP3); + case UMUSIC_MOD: + return S_CodecForwardStream(stream, CODECTYPE_MOD); + case UMUSIC_WAV: + return S_CodecForwardStream(stream, CODECTYPE_WAV); + case UMUSIC_MP2: + return S_CodecForwardStream(stream, CODECTYPE_MP3); } return false; } -static int32_t S_UMX_CodecReadStream (snd_stream_t *stream, int32_t bytes, void *buffer) +static int32_t S_UMX_CodecReadStream(snd_stream_t *stream, int32_t bytes, void *buffer) { (void)stream, (void)bytes, (void)buffer; return -1; } -static void S_UMX_CodecCloseStream (snd_stream_t *stream) +static void S_UMX_CodecCloseStream(snd_stream_t *stream) { S_CodecUtilClose(&stream); } -static int32_t S_UMX_CodecRewindStream (snd_stream_t *stream) +static int32_t S_UMX_CodecRewindStream(snd_stream_t *stream) { (void)stream; return -1; @@ -393,7 +423,7 @@ static int32_t S_UMX_CodecRewindStream (snd_stream_t *stream) snd_codec_t umx_codec = { CODECTYPE_UMX, - true, /* always available. */ + true, /* always available. */ "umx", S_UMX_CodecInitialize, S_UMX_CodecShutdown, diff --git a/source/snd_umx.h b/source/snd_umx.h index e48bacc..58ede10 100644 --- a/source/snd_umx.h +++ b/source/snd_umx.h @@ -4,5 +4,5 @@ extern snd_codec_t umx_codec; -#endif /* ! _SND_UMX_H_ */ +#endif /* ! _SND_UMX_H_ */ diff --git a/source/snd_vorbis.c b/source/snd_vorbis.c index bbf5da1..2db01eb 100644 --- a/source/snd_vorbis.c +++ b/source/snd_vorbis.c @@ -45,36 +45,36 @@ /* CALLBACK FUNCTIONS: */ -static int32_t ovc_fclose (void *f) +static int32_t ovc_fclose(void *f) { (void)f; - return 0; /* we fclose() elsewhere. */ + return 0; /* we fclose() elsewhere. */ } -static int32_t ovc_fseek (void *f, ogg_int64_t off, int32_t whence) +static int32_t ovc_fseek(void *f, ogg_int64_t off, int32_t whence) { - if (f == NULL) return (-1); + if(f == NULL) return (-1); return FS_fseek((fshandle_t *)f, (long) off, whence); } static ov_callbacks ovc_qfs = { - (size_t (*)(void *, size_t, size_t, void *)) FS_fread, - (int32_t (*)(void *, ogg_int64_t, int32_t)) ovc_fseek, - (int32_t (*)(void *)) ovc_fclose, - (long (*)(void *)) FS_ftell + (size_t (*)(void *, size_t, size_t, void *)) FS_fread, + (int32_t (*)(void *, ogg_int64_t, int32_t)) ovc_fseek, + (int32_t (*)(void *)) ovc_fclose, + (long (*)(void *)) FS_ftell }; -static bool S_VORBIS_CodecInitialize (void) +static bool S_VORBIS_CodecInitialize(void) { return true; } -static void S_VORBIS_CodecShutdown (void) +static void S_VORBIS_CodecShutdown(void) { } -static bool S_VORBIS_CodecOpenStream (snd_stream_t *stream) +static bool S_VORBIS_CodecOpenStream(snd_stream_t *stream) { OggVorbis_File *ovFile; vorbis_info *ovf_info; @@ -84,21 +84,21 @@ static bool S_VORBIS_CodecOpenStream (snd_stream_t *stream) ovFile = (OggVorbis_File *) Z_Malloc(sizeof(OggVorbis_File)); stream->priv = ovFile; res = ov_open_callbacks(&stream->fh, ovFile, NULL, 0, ovc_qfs); - if (res != 0) + if(res != 0) { Con_Printf("%s is not a valid Ogg Vorbis file (error %" PRIi32 ").\n", - stream->name, res); + stream->name, res); goto _fail; } - if (!ov_seekable(ovFile)) + if(!ov_seekable(ovFile)) { Con_Printf("Stream %s not seekable.\n", stream->name); goto _fail; } ovf_info = ov_info(ovFile, 0); - if (!ovf_info) + if(!ovf_info) { Con_Printf("Unable to get stream info for %s.\n", stream->name); goto _fail; @@ -106,17 +106,17 @@ static bool S_VORBIS_CodecOpenStream (snd_stream_t *stream) /* FIXME: handle section changes */ numstreams = ov_streams(ovFile); - if (numstreams != 1) + if(numstreams != 1) { Con_Printf("More than one (%" PRIi64 ") stream in %s.\n", - numstreams, stream->name); + numstreams, stream->name); goto _fail; } - if (ovf_info->channels != 1 && ovf_info->channels != 2) + if(ovf_info->channels != 1 && ovf_info->channels != 2) { Con_Printf("Unsupported number of channels %" PRIi32 " in %s\n", - ovf_info->channels, stream->name); + ovf_info->channels, stream->name); goto _fail; } @@ -127,70 +127,71 @@ static bool S_VORBIS_CodecOpenStream (snd_stream_t *stream) return true; _fail: - if (res == 0) + if(res == 0) ov_clear(ovFile); Z_Free(ovFile); return false; } -static int32_t S_VORBIS_CodecReadStream (snd_stream_t *stream, int32_t bytes, void *buffer) +static int32_t S_VORBIS_CodecReadStream(snd_stream_t *stream, int32_t bytes, void *buffer) { - int32_t section; /* FIXME: handle section changes */ - int32_t cnt, res, rem; - char * ptr; + int32_t section; /* FIXME: handle section changes */ + int32_t cnt, res, rem; + char * ptr; - cnt = 0; rem = bytes; + cnt = 0; + rem = bytes; ptr = (char *) buffer; - while (1) + while(1) { - /* # ov_read() from libvorbisfile returns the decoded PCM audio - * in requested endianness, signedness and word size. - * # ov_read() from Tremor (libvorbisidec) returns decoded audio - * always in host-endian, signed 16 bit PCM format. - * # For both of the libraries, if the audio is multichannel, - * the channels are interleaved in the output buffer. - */ - res = ov_read( (OggVorbis_File *)stream->priv, ptr, rem, + /* # ov_read() from libvorbisfile returns the decoded PCM audio + * in requested endianness, signedness and word size. + * # ov_read() from Tremor (libvorbisidec) returns decoded audio + * always in host-endian, signed 16 bit PCM format. + * # For both of the libraries, if the audio is multichannel, + * the channels are interleaved in the output buffer. + */ + res = ov_read((OggVorbis_File *)stream->priv, ptr, rem, #ifndef VORBIS_USE_TREMOR - host_bigendian, - VORBIS_SAMPLEWIDTH, - VORBIS_SIGNED_DATA, + host_bigendian, + VORBIS_SAMPLEWIDTH, + VORBIS_SIGNED_DATA, #endif - §ion ); - if (res <= 0) + & section); + if(res <= 0) break; rem -= res; cnt += res; - if (rem <= 0) + if(rem <= 0) break; ptr += res; } - if (res < 0) + if(res < 0) return res; return cnt; } -static void S_VORBIS_CodecCloseStream (snd_stream_t *stream) +static void S_VORBIS_CodecCloseStream(snd_stream_t *stream) { ov_clear((OggVorbis_File *)stream->priv); Z_Free(stream->priv); S_CodecUtilClose(&stream); } -static int32_t S_VORBIS_CodecRewindStream (snd_stream_t *stream) +static int32_t S_VORBIS_CodecRewindStream(snd_stream_t *stream) { -/* for libvorbisfile, the ov_time_seek() position argument - * is seconds as doubles, whereas for Tremor libvorbisidec - * it is milliseconds as 64 bit integers. - */ - return ov_time_seek ((OggVorbis_File *)stream->priv, 0); + /* for libvorbisfile, the ov_time_seek() position argument + * is seconds as doubles, whereas for Tremor libvorbisidec + * it is milliseconds as 64 bit integers. + */ + return ov_time_seek((OggVorbis_File *)stream->priv, 0); } snd_codec_t vorbis_codec = { CODECTYPE_VORBIS, - true, /* always available. */ + true, /* always available. */ "ogg", S_VORBIS_CodecInitialize, S_VORBIS_CodecShutdown, @@ -201,5 +202,5 @@ snd_codec_t vorbis_codec = NULL }; -#endif /* USE_CODEC_VORBIS */ +#endif /* USE_CODEC_VORBIS */ diff --git a/source/snd_vorbis.h b/source/snd_vorbis.h index 0f1cc9e..2d2ceff 100644 --- a/source/snd_vorbis.h +++ b/source/snd_vorbis.h @@ -7,7 +7,7 @@ extern snd_codec_t vorbis_codec; -#endif /* USE_CODEC_VORBIS */ +#endif /* USE_CODEC_VORBIS */ -#endif /* ! _SND_VORBIS_H_ */ +#endif /* ! _SND_VORBIS_H_ */ diff --git a/source/spritegn.h b/source/spritegn.h index da10e43..4ac261b 100644 --- a/source/spritegn.h +++ b/source/spritegn.h @@ -63,55 +63,60 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #endif -#define SPRITE_VERSION 1 +#define SPRITE_VERSION 1 // must match definition in modelgen.h #ifndef SYNCTYPE_T #define SYNCTYPE_T -typedef enum {ST_SYNC=0, ST_RAND } synctype_t; +typedef enum {ST_SYNC = 0, ST_RAND } synctype_t; #endif // TODO: shorten these? -typedef struct { - int32_t ident; - int32_t version; - int32_t type; - float boundingradius; - int32_t width; - int32_t height; - int32_t numframes; - float beamlength; - synctype_t synctype; +typedef struct +{ + int32_t ident; + int32_t version; + int32_t type; + float boundingradius; + int32_t width; + int32_t height; + int32_t numframes; + float beamlength; + synctype_t synctype; } dsprite_t; -#define SPR_VP_PARALLEL_UPRIGHT 0 -#define SPR_FACING_UPRIGHT 1 -#define SPR_VP_PARALLEL 2 -#define SPR_ORIENTED 3 -#define SPR_VP_PARALLEL_ORIENTED 4 +#define SPR_VP_PARALLEL_UPRIGHT 0 +#define SPR_FACING_UPRIGHT 1 +#define SPR_VP_PARALLEL 2 +#define SPR_ORIENTED 3 +#define SPR_VP_PARALLEL_ORIENTED 4 -typedef struct { - int32_t origin[2]; - int32_t width; - int32_t height; +typedef struct +{ + int32_t origin[2]; + int32_t width; + int32_t height; } dspriteframe_t; -typedef struct { - int32_t numframes; +typedef struct +{ + int32_t numframes; } dspritegroup_t; -typedef struct { - float interval; +typedef struct +{ + float interval; } dspriteinterval_t; -typedef enum { SPR_SINGLE=0, SPR_GROUP } spriteframetype_t; +typedef enum { SPR_SINGLE = 0, SPR_GROUP } spriteframetype_t; -typedef struct { - spriteframetype_t type; +typedef struct +{ + spriteframetype_t type; } dspriteframetype_t; -#define IDSPRITEHEADER (('P'<<24)+('S'<<16)+('D'<<8)+'I') - // little-endian "IDSP" +#define IDSPRITEHEADER (('P'<<24)+('S'<<16)+('D'<<8)+'I') +// little-endian "IDSP" -#endif /* __SPRITEGEN_H */ +#endif /* __SPRITEGEN_H */ diff --git a/source/stb_image_write.h b/source/stb_image_write.h index 5f5e527..e09ceac 100644 --- a/source/stb_image_write.h +++ b/source/stb_image_write.h @@ -83,7 +83,7 @@ USAGE: TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed data, set the global variable 'stbi_write_tga_with_rle' to 0. - + JPEG does ignore alpha channels in input data; quality is between 1 and 100. Higher quality looks better but results in a bigger image. JPEG baseline (no JPEG progressive). @@ -116,7 +116,7 @@ CREDITS: Thatcher Ulrich github:poppolopoppo Patrick Boettcher - + LICENSE See end of file for license information. @@ -155,12 +155,12 @@ STBIWDEF int32_t stbi_write_jpg_to_func(stbi_write_func *func, void *context, in #ifdef STB_IMAGE_WRITE_IMPLEMENTATION #ifdef _WIN32 - #ifndef _CRT_SECURE_NO_WARNINGS - #define _CRT_SECURE_NO_WARNINGS - #endif - #ifndef _CRT_NONSTDC_NO_DEPRECATE - #define _CRT_NONSTDC_NO_DEPRECATE - #endif +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS +#endif +#ifndef _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_NONSTDC_NO_DEPRECATE +#endif #endif #ifndef STBI_WRITE_NO_STDIO @@ -205,44 +205,44 @@ STBIWDEF int32_t stbi_write_jpg_to_func(stbi_write_func *func, void *context, in typedef struct { - stbi_write_func *func; - void *context; + stbi_write_func *func; + void *context; } stbi__write_context; // initialize a callback-based context static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) { - s->func = c; - s->context = context; + s->func = c; + s->context = context; } #ifndef STBI_WRITE_NO_STDIO static void stbi__stdio_write(void *context, void *data, int32_t size) { - fwrite(data,1,size,(FILE*) context); + fwrite(data, 1, size, (FILE*) context); } static int32_t stbi__start_write_file(stbi__write_context *s, const char *filename) { - FILE *f = fopen(filename, "wb"); - stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); - return f != NULL; + FILE *f = fopen(filename, "wb"); + stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); + return f != NULL; } static void stbi__end_write_file(stbi__write_context *s) { - fclose((FILE *)s->context); + fclose((FILE *)s->context); } #endif // !STBI_WRITE_NO_STDIO typedef uint32_t stbiw_uint32; -typedef int32_t stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; +typedef int32_t stb_image_write_test[sizeof(stbiw_uint32) == 4 ? 1 : -1]; static void stbiw__putc(stbi__write_context *s, uint8_t c) { - s->func(s->context, &c, 1); + s->func(s->context, &c, 1); } /* *************************************************************************** @@ -253,336 +253,378 @@ static void stbiw__putc(stbi__write_context *s, uint8_t c) * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html */ -static const uint8_t stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, - 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; +static const uint8_t stbiw__jpg_ZigZag[] = { 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, + 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63 + }; -static void stbiw__jpg_writeBits(stbi__write_context *s, int32_t *bitBufP, int32_t *bitCntP, const uint16_t *bs) { - int32_t bitBuf = *bitBufP, bitCnt = *bitCntP; - bitCnt += bs[1]; - bitBuf |= bs[0] << (24 - bitCnt); - while(bitCnt >= 8) { - uint8_t c = (bitBuf >> 16) & 255; - stbiw__putc(s, c); - if(c == 255) { - stbiw__putc(s, 0); - } - bitBuf <<= 8; - bitCnt -= 8; - } - *bitBufP = bitBuf; - *bitCntP = bitCnt; +static void stbiw__jpg_writeBits(stbi__write_context *s, int32_t *bitBufP, int32_t *bitCntP, const uint16_t *bs) +{ + int32_t bitBuf = *bitBufP, bitCnt = *bitCntP; + bitCnt += bs[1]; + bitBuf |= bs[0] << (24 - bitCnt); + while(bitCnt >= 8) + { + uint8_t c = (bitBuf >> 16) & 255; + stbiw__putc(s, c); + if(c == 255) + { + stbiw__putc(s, 0); + } + bitBuf <<= 8; + bitCnt -= 8; + } + *bitBufP = bitBuf; + *bitCntP = bitCnt; } -static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { - float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; - float z1, z2, z3, z4, z5, z11, z13; +static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) +{ + float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; + float z1, z2, z3, z4, z5, z11, z13; - float tmp0 = d0 + d7; - float tmp7 = d0 - d7; - float tmp1 = d1 + d6; - float tmp6 = d1 - d6; - float tmp2 = d2 + d5; - float tmp5 = d2 - d5; - float tmp3 = d3 + d4; - float tmp4 = d3 - d4; + float tmp0 = d0 + d7; + float tmp7 = d0 - d7; + float tmp1 = d1 + d6; + float tmp6 = d1 - d6; + float tmp2 = d2 + d5; + float tmp5 = d2 - d5; + float tmp3 = d3 + d4; + float tmp4 = d3 - d4; - // Even part - float tmp10 = tmp0 + tmp3; // phase 2 - float tmp13 = tmp0 - tmp3; - float tmp11 = tmp1 + tmp2; - float tmp12 = tmp1 - tmp2; + // Even part + float tmp10 = tmp0 + tmp3; // phase 2 + float tmp13 = tmp0 - tmp3; + float tmp11 = tmp1 + tmp2; + float tmp12 = tmp1 - tmp2; - d0 = tmp10 + tmp11; // phase 3 - d4 = tmp10 - tmp11; + d0 = tmp10 + tmp11; // phase 3 + d4 = tmp10 - tmp11; - z1 = (tmp12 + tmp13) * 0.707106781f; // c4 - d2 = tmp13 + z1; // phase 5 - d6 = tmp13 - z1; + z1 = (tmp12 + tmp13) * 0.707106781f; // c4 + d2 = tmp13 + z1; // phase 5 + d6 = tmp13 - z1; - // Odd part - tmp10 = tmp4 + tmp5; // phase 2 - tmp11 = tmp5 + tmp6; - tmp12 = tmp6 + tmp7; + // Odd part + tmp10 = tmp4 + tmp5; // phase 2 + tmp11 = tmp5 + tmp6; + tmp12 = tmp6 + tmp7; - // The rotator is modified from fig 4-8 to avoid extra negations. - z5 = (tmp10 - tmp12) * 0.382683433f; // c6 - z2 = tmp10 * 0.541196100f + z5; // c2-c6 - z4 = tmp12 * 1.306562965f + z5; // c2+c6 - z3 = tmp11 * 0.707106781f; // c4 + // The rotator is modified from fig 4-8 to avoid extra negations. + z5 = (tmp10 - tmp12) * 0.382683433f; // c6 + z2 = tmp10 * 0.541196100f + z5; // c2-c6 + z4 = tmp12 * 1.306562965f + z5; // c2+c6 + z3 = tmp11 * 0.707106781f; // c4 - z11 = tmp7 + z3; // phase 5 - z13 = tmp7 - z3; + z11 = tmp7 + z3; // phase 5 + z13 = tmp7 - z3; - *d5p = z13 + z2; // phase 6 - *d3p = z13 - z2; - *d1p = z11 + z4; - *d7p = z11 - z4; + *d5p = z13 + z2; // phase 6 + *d3p = z13 - z2; + *d1p = z11 + z4; + *d7p = z11 - z4; - *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; + *d0p = d0; + *d2p = d2; + *d4p = d4; + *d6p = d6; } -static void stbiw__jpg_calcBits(int32_t val, uint16_t bits[2]) { - int32_t tmp1 = val < 0 ? -val : val; - val = val < 0 ? val-1 : val; - bits[1] = 1; - while(tmp1 >>= 1) { - ++bits[1]; - } - bits[0] = val & ((1<>= 1) + { + ++bits[1]; + } + bits[0] = val & ((1 << bits[1]) - 1); } -static int32_t stbiw__jpg_processDU(stbi__write_context *s, int32_t *bitBuf, int32_t *bitCnt, float *CDU, float *fdtbl, int32_t DC, const uint16_t HTDC[256][2], const uint16_t HTAC[256][2]) { - uint16_t EOB[2]; - uint16_t M16zeroes[2]; - int32_t dataOff, i, diff, end0pos; - int32_t DU[64]; +static int32_t stbiw__jpg_processDU(stbi__write_context *s, int32_t *bitBuf, int32_t *bitCnt, float *CDU, float *fdtbl, int32_t DC, const uint16_t HTDC[256][2], const uint16_t HTAC[256][2]) +{ + uint16_t EOB[2]; + uint16_t M16zeroes[2]; + int32_t dataOff, i, diff, end0pos; + int32_t DU[64]; - EOB[0] = HTAC[0x00][0]; - EOB[1] = HTAC[0x00][1]; - M16zeroes[0] = HTAC[0xF0][0]; - M16zeroes[1] = HTAC[0xF0][1]; + EOB[0] = HTAC[0x00][0]; + EOB[1] = HTAC[0x00][1]; + M16zeroes[0] = HTAC[0xF0][0]; + M16zeroes[1] = HTAC[0xF0][1]; - // DCT rows - for(dataOff=0; dataOff<64; dataOff+=8) { - stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+1], &CDU[dataOff+2], &CDU[dataOff+3], &CDU[dataOff+4], &CDU[dataOff+5], &CDU[dataOff+6], &CDU[dataOff+7]); - } - // DCT columns - for(dataOff=0; dataOff<8; ++dataOff) { - stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+8], &CDU[dataOff+16], &CDU[dataOff+24], &CDU[dataOff+32], &CDU[dataOff+40], &CDU[dataOff+48], &CDU[dataOff+56]); - } - // Quantize/descale/zigzag the coefficients - for(i=0; i<64; ++i) { - float v = CDU[i]*fdtbl[i]; - // DU[stbiw__jpg_ZigZag[i]] = (int32_t)(v < 0 ? ceilf(v - 0.5f) : floorf(v + 0.5f)); - // ceilf() and floorf() are C99, not C89, but I /think/ they're not needed here anyway? - DU[stbiw__jpg_ZigZag[i]] = (int32_t)(v < 0 ? v - 0.5f : v + 0.5f); - } + // DCT rows + for(dataOff = 0; dataOff < 64; dataOff += 8) + { + stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff + 1], &CDU[dataOff + 2], &CDU[dataOff + 3], &CDU[dataOff + 4], &CDU[dataOff + 5], &CDU[dataOff + 6], &CDU[dataOff + 7]); + } + // DCT columns + for(dataOff = 0; dataOff < 8; ++dataOff) + { + stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff + 8], &CDU[dataOff + 16], &CDU[dataOff + 24], &CDU[dataOff + 32], &CDU[dataOff + 40], &CDU[dataOff + 48], &CDU[dataOff + 56]); + } + // Quantize/descale/zigzag the coefficients + for(i = 0; i < 64; ++i) + { + float v = CDU[i] * fdtbl[i]; + // DU[stbiw__jpg_ZigZag[i]] = (int32_t)(v < 0 ? ceilf(v - 0.5f) : floorf(v + 0.5f)); + // ceilf() and floorf() are C99, not C89, but I /think/ they're not needed here anyway? + DU[stbiw__jpg_ZigZag[i]] = (int32_t)(v < 0 ? v - 0.5f : v + 0.5f); + } - // Encode DC - diff = DU[0] - DC; - if (diff == 0) { - stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[0]); - } else { - uint16_t bits[2]; - stbiw__jpg_calcBits(diff, bits); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[bits[1]]); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); - } - // Encode ACs - end0pos = 63; - for(; (end0pos>0)&&(DU[end0pos]==0); --end0pos) { - } - // end0pos = first element in reverse order !=0 - if(end0pos == 0) { - stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); - return DU[0]; - } - for(i = 1; i <= end0pos; ++i) { - int32_t startpos = i; - int32_t nrzeroes; - uint16_t bits[2]; - for (; DU[i]==0 && i<=end0pos; ++i) { - } - nrzeroes = i-startpos; - if ( nrzeroes >= 16 ) { - int32_t lng = nrzeroes>>4; - int32_t nrmarker; - for (nrmarker=1; nrmarker <= lng; ++nrmarker) - stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); - nrzeroes &= 15; - } - stbiw__jpg_calcBits(DU[i], bits); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); - } - if(end0pos != 63) { - stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); - } - return DU[0]; + // Encode DC + diff = DU[0] - DC; + if(diff == 0) + { + stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[0]); + } + else + { + uint16_t bits[2]; + stbiw__jpg_calcBits(diff, bits); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[bits[1]]); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); + } + // Encode ACs + end0pos = 63; + for(; (end0pos > 0) && (DU[end0pos] == 0); --end0pos) + { + } + // end0pos = first element in reverse order !=0 + if(end0pos == 0) + { + stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); + return DU[0]; + } + for(i = 1; i <= end0pos; ++i) + { + int32_t startpos = i; + int32_t nrzeroes; + uint16_t bits[2]; + for(; DU[i] == 0 && i <= end0pos; ++i) + { + } + nrzeroes = i - startpos; + if(nrzeroes >= 16) + { + int32_t lng = nrzeroes >> 4; + int32_t nrmarker; + for(nrmarker = 1; nrmarker <= lng; ++nrmarker) + stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); + nrzeroes &= 15; + } + stbiw__jpg_calcBits(DU[i], bits); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes << 4) + bits[1]]); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); + } + if(end0pos != 63) + { + stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); + } + return DU[0]; } -static int32_t stbi_write_jpg_core(stbi__write_context *s, int32_t width, int32_t height, int32_t comp, const void* data, int32_t quality) { - // Constants that don't pollute global namespace - static const uint8_t std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; - static const uint8_t std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; - static const uint8_t std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; - static const uint8_t std_ac_luminance_values[] = { - 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, - 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, - 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, - 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, - 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, - 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, - 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa - }; - static const uint8_t std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; - static const uint8_t std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; - static const uint8_t std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; - static const uint8_t std_ac_chrominance_values[] = { - 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, - 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, - 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, - 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, - 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, - 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, - 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa - }; - // Huffman tables - static const uint16_t YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; - static const uint16_t UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; - static const uint16_t YAC_HT[256][2] = { - {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} - }; - static const uint16_t UVAC_HT[256][2] = { - {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} - }; - static const int32_t YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, - 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; - static const int32_t UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, - 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; - static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, - 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; +static int32_t stbi_write_jpg_core(stbi__write_context *s, int32_t width, int32_t height, int32_t comp, const void* data, int32_t quality) +{ + // Constants that don't pollute global namespace + static const uint8_t std_dc_luminance_nrcodes[] = {0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0}; + static const uint8_t std_dc_luminance_values[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; + static const uint8_t std_ac_luminance_nrcodes[] = {0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d}; + static const uint8_t std_ac_luminance_values[] = + { + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, + 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, + 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa + }; + static const uint8_t std_dc_chrominance_nrcodes[] = {0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0}; + static const uint8_t std_dc_chrominance_values[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; + static const uint8_t std_ac_chrominance_nrcodes[] = {0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77}; + static const uint8_t std_ac_chrominance_values[] = + { + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, + 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, + 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa + }; + // Huffman tables + static const uint16_t YDC_HT[256][2] = { {0, 2}, {2, 3}, {3, 3}, {4, 3}, {5, 3}, {6, 3}, {14, 4}, {30, 5}, {62, 6}, {126, 7}, {254, 8}, {510, 9}}; + static const uint16_t UVDC_HT[256][2] = { {0, 2}, {1, 2}, {2, 2}, {6, 3}, {14, 4}, {30, 5}, {62, 6}, {126, 7}, {254, 8}, {510, 9}, {1022, 10}, {2046, 11}}; + static const uint16_t YAC_HT[256][2] = + { + {10, 4}, {0, 2}, {1, 2}, {4, 3}, {11, 4}, {26, 5}, {120, 7}, {248, 8}, {1014, 10}, {65410, 16}, {65411, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {12, 4}, {27, 5}, {121, 7}, {502, 9}, {2038, 11}, {65412, 16}, {65413, 16}, {65414, 16}, {65415, 16}, {65416, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {28, 5}, {249, 8}, {1015, 10}, {4084, 12}, {65417, 16}, {65418, 16}, {65419, 16}, {65420, 16}, {65421, 16}, {65422, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {58, 6}, {503, 9}, {4085, 12}, {65423, 16}, {65424, 16}, {65425, 16}, {65426, 16}, {65427, 16}, {65428, 16}, {65429, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {59, 6}, {1016, 10}, {65430, 16}, {65431, 16}, {65432, 16}, {65433, 16}, {65434, 16}, {65435, 16}, {65436, 16}, {65437, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {122, 7}, {2039, 11}, {65438, 16}, {65439, 16}, {65440, 16}, {65441, 16}, {65442, 16}, {65443, 16}, {65444, 16}, {65445, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {123, 7}, {4086, 12}, {65446, 16}, {65447, 16}, {65448, 16}, {65449, 16}, {65450, 16}, {65451, 16}, {65452, 16}, {65453, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {250, 8}, {4087, 12}, {65454, 16}, {65455, 16}, {65456, 16}, {65457, 16}, {65458, 16}, {65459, 16}, {65460, 16}, {65461, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {504, 9}, {32704, 15}, {65462, 16}, {65463, 16}, {65464, 16}, {65465, 16}, {65466, 16}, {65467, 16}, {65468, 16}, {65469, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {505, 9}, {65470, 16}, {65471, 16}, {65472, 16}, {65473, 16}, {65474, 16}, {65475, 16}, {65476, 16}, {65477, 16}, {65478, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {506, 9}, {65479, 16}, {65480, 16}, {65481, 16}, {65482, 16}, {65483, 16}, {65484, 16}, {65485, 16}, {65486, 16}, {65487, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {1017, 10}, {65488, 16}, {65489, 16}, {65490, 16}, {65491, 16}, {65492, 16}, {65493, 16}, {65494, 16}, {65495, 16}, {65496, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {1018, 10}, {65497, 16}, {65498, 16}, {65499, 16}, {65500, 16}, {65501, 16}, {65502, 16}, {65503, 16}, {65504, 16}, {65505, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {2040, 11}, {65506, 16}, {65507, 16}, {65508, 16}, {65509, 16}, {65510, 16}, {65511, 16}, {65512, 16}, {65513, 16}, {65514, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {65515, 16}, {65516, 16}, {65517, 16}, {65518, 16}, {65519, 16}, {65520, 16}, {65521, 16}, {65522, 16}, {65523, 16}, {65524, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {2041, 11}, {65525, 16}, {65526, 16}, {65527, 16}, {65528, 16}, {65529, 16}, {65530, 16}, {65531, 16}, {65532, 16}, {65533, 16}, {65534, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0} + }; + static const uint16_t UVAC_HT[256][2] = + { + {0, 2}, {1, 2}, {4, 3}, {10, 4}, {24, 5}, {25, 5}, {56, 6}, {120, 7}, {500, 9}, {1014, 10}, {4084, 12}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {11, 4}, {57, 6}, {246, 8}, {501, 9}, {2038, 11}, {4085, 12}, {65416, 16}, {65417, 16}, {65418, 16}, {65419, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {26, 5}, {247, 8}, {1015, 10}, {4086, 12}, {32706, 15}, {65420, 16}, {65421, 16}, {65422, 16}, {65423, 16}, {65424, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {27, 5}, {248, 8}, {1016, 10}, {4087, 12}, {65425, 16}, {65426, 16}, {65427, 16}, {65428, 16}, {65429, 16}, {65430, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {58, 6}, {502, 9}, {65431, 16}, {65432, 16}, {65433, 16}, {65434, 16}, {65435, 16}, {65436, 16}, {65437, 16}, {65438, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {59, 6}, {1017, 10}, {65439, 16}, {65440, 16}, {65441, 16}, {65442, 16}, {65443, 16}, {65444, 16}, {65445, 16}, {65446, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {121, 7}, {2039, 11}, {65447, 16}, {65448, 16}, {65449, 16}, {65450, 16}, {65451, 16}, {65452, 16}, {65453, 16}, {65454, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {122, 7}, {2040, 11}, {65455, 16}, {65456, 16}, {65457, 16}, {65458, 16}, {65459, 16}, {65460, 16}, {65461, 16}, {65462, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {249, 8}, {65463, 16}, {65464, 16}, {65465, 16}, {65466, 16}, {65467, 16}, {65468, 16}, {65469, 16}, {65470, 16}, {65471, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {503, 9}, {65472, 16}, {65473, 16}, {65474, 16}, {65475, 16}, {65476, 16}, {65477, 16}, {65478, 16}, {65479, 16}, {65480, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {504, 9}, {65481, 16}, {65482, 16}, {65483, 16}, {65484, 16}, {65485, 16}, {65486, 16}, {65487, 16}, {65488, 16}, {65489, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {505, 9}, {65490, 16}, {65491, 16}, {65492, 16}, {65493, 16}, {65494, 16}, {65495, 16}, {65496, 16}, {65497, 16}, {65498, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {506, 9}, {65499, 16}, {65500, 16}, {65501, 16}, {65502, 16}, {65503, 16}, {65504, 16}, {65505, 16}, {65506, 16}, {65507, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {2041, 11}, {65508, 16}, {65509, 16}, {65510, 16}, {65511, 16}, {65512, 16}, {65513, 16}, {65514, 16}, {65515, 16}, {65516, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {16352, 14}, {65517, 16}, {65518, 16}, {65519, 16}, {65520, 16}, {65521, 16}, {65522, 16}, {65523, 16}, {65524, 16}, {65525, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, + {1018, 10}, {32707, 15}, {65526, 16}, {65527, 16}, {65528, 16}, {65529, 16}, {65530, 16}, {65531, 16}, {65532, 16}, {65533, 16}, {65534, 16}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0} + }; + static const int32_t YQT[] = {16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, + 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99 + }; + static const int32_t UVQT[] = {17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 + }; + static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, + 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f + }; - int32_t row, col, i, k; - float fdtbl_Y[64], fdtbl_UV[64]; - uint8_t YTable[64], UVTable[64]; + int32_t row, col, i, k; + float fdtbl_Y[64], fdtbl_UV[64]; + uint8_t YTable[64], UVTable[64]; - if(!data || !width || !height || comp > 4 || comp < 1) { - return 0; - } + if(!data || !width || !height || comp > 4 || comp < 1) + { + return 0; + } - quality = quality ? quality : 90; - quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; - quality = quality < 50 ? 5000 / quality : 200 - quality * 2; + quality = quality ? quality : 90; + quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; + quality = quality < 50 ? 5000 / quality : 200 - quality * 2; - for(i = 0; i < 64; ++i) { - int32_t uvti, yti = (YQT[i]*quality+50)/100; - YTable[stbiw__jpg_ZigZag[i]] = (uint8_t) (yti < 1 ? 1 : yti > 255 ? 255 : yti); - uvti = (UVQT[i]*quality+50)/100; - UVTable[stbiw__jpg_ZigZag[i]] = (uint8_t) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); - } + for(i = 0; i < 64; ++i) + { + int32_t uvti, yti = (YQT[i] * quality + 50) / 100; + YTable[stbiw__jpg_ZigZag[i]] = (uint8_t)(yti < 1 ? 1 : yti > 255 ? 255 : yti); + uvti = (UVQT[i] * quality + 50) / 100; + UVTable[stbiw__jpg_ZigZag[i]] = (uint8_t)(uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); + } - for(row = 0, k = 0; row < 8; ++row) { - for(col = 0; col < 8; ++col, ++k) { - fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); - fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); - } - } + for(row = 0, k = 0; row < 8; ++row) + { + for(col = 0; col < 8; ++col, ++k) + { + fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); + fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); + } + } - // Write Headers - { - static const uint8_t head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; - static const uint8_t head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; - uint8_t head1[] = { 0xFF,0xC0,0,0x11,8, /*[5]*/0,/*[6]*/0,/*[7]*/0,/*[8]*/0, - 3,1,0x11,0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; - head1[5] = (uint8_t)(height>>8); - head1[6] = STBIW_UCHAR(height); - head1[7] = (uint8_t)(width>>8); - head1[8] = STBIW_UCHAR(width); - s->func(s->context, (void*)head0, sizeof(head0)); - s->func(s->context, (void*)YTable, sizeof(YTable)); - stbiw__putc(s, 1); - s->func(s->context, UVTable, sizeof(UVTable)); - s->func(s->context, (void*)head1, sizeof(head1)); - s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); - s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); - stbiw__putc(s, 0x10); // HTYACinfo - s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); - s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); - stbiw__putc(s, 1); // HTUDCinfo - s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); - s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); - stbiw__putc(s, 0x11); // HTUACinfo - s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); - s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); - s->func(s->context, (void*)head2, sizeof(head2)); - } + // Write Headers + { + static const uint8_t head0[] = { 0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, 'J', 'F', 'I', 'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0xFF, 0xDB, 0, 0x84, 0 }; + static const uint8_t head2[] = { 0xFF, 0xDA, 0, 0xC, 3, 1, 0, 2, 0x11, 3, 0x11, 0, 0x3F, 0 }; + uint8_t head1[] = { 0xFF, 0xC0, 0, 0x11, 8, /*[5]*/0,/*[6]*/0,/*[7]*/0,/*[8]*/0, + 3, 1, 0x11, 0, 2, 0x11, 1, 3, 0x11, 1, 0xFF, 0xC4, 0x01, 0xA2, 0 + }; + head1[5] = (uint8_t)(height >> 8); + head1[6] = STBIW_UCHAR(height); + head1[7] = (uint8_t)(width >> 8); + head1[8] = STBIW_UCHAR(width); + s->func(s->context, (void*)head0, sizeof(head0)); + s->func(s->context, (void*)YTable, sizeof(YTable)); + stbiw__putc(s, 1); + s->func(s->context, UVTable, sizeof(UVTable)); + s->func(s->context, (void*)head1, sizeof(head1)); + s->func(s->context, (void*)(std_dc_luminance_nrcodes + 1), sizeof(std_dc_luminance_nrcodes) - 1); + s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); + stbiw__putc(s, 0x10); // HTYACinfo + s->func(s->context, (void*)(std_ac_luminance_nrcodes + 1), sizeof(std_ac_luminance_nrcodes) - 1); + s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); + stbiw__putc(s, 1); // HTUDCinfo + s->func(s->context, (void*)(std_dc_chrominance_nrcodes + 1), sizeof(std_dc_chrominance_nrcodes) - 1); + s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); + stbiw__putc(s, 0x11); // HTUACinfo + s->func(s->context, (void*)(std_ac_chrominance_nrcodes + 1), sizeof(std_ac_chrominance_nrcodes) - 1); + s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); + s->func(s->context, (void*)head2, sizeof(head2)); + } - // Encode 8x8 macroblocks - { - static const uint16_t fillBits[] = {0x7F, 7}; - const uint8_t *imageData = (const uint8_t *)data; - int32_t DCY=0, DCU=0, DCV=0; - int32_t bitBuf=0, bitCnt=0; - // comp == 2 is grey+alpha (alpha is ignored) - int32_t ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; - int32_t x, y, pos; - for(y = 0; y < height; y += 8) { - for(x = 0; x < width; x += 8) { - float YDU[64], UDU[64], VDU[64]; - for(row = y, pos = 0; row < y+8; ++row) { - for(col = x; col < x+8; ++col, ++pos) { - int32_t p = row*width*comp + col*comp; - float r, g, b; - if(row >= height) { - p -= width*comp*(row+1 - height); - } - if(col >= width) { - p -= comp*(col+1 - width); - } + // Encode 8x8 macroblocks + { + static const uint16_t fillBits[] = {0x7F, 7}; + const uint8_t *imageData = (const uint8_t *)data; + int32_t DCY = 0, DCU = 0, DCV = 0; + int32_t bitBuf = 0, bitCnt = 0; + // comp == 2 is grey+alpha (alpha is ignored) + int32_t ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; + int32_t x, y, pos; + for(y = 0; y < height; y += 8) + { + for(x = 0; x < width; x += 8) + { + float YDU[64], UDU[64], VDU[64]; + for(row = y, pos = 0; row < y + 8; ++row) + { + for(col = x; col < x + 8; ++col, ++pos) + { + int32_t p = row * width * comp + col * comp; + float r, g, b; + if(row >= height) + { + p -= width * comp * (row + 1 - height); + } + if(col >= width) + { + p -= comp * (col + 1 - width); + } - r = imageData[p+0]; - g = imageData[p+ofsG]; - b = imageData[p+ofsB]; - YDU[pos]=+0.29900f*r+0.58700f*g+0.11400f*b-128; - UDU[pos]=-0.16874f*r-0.33126f*g+0.50000f*b; - VDU[pos]=+0.50000f*r-0.41869f*g-0.08131f*b; - } - } + r = imageData[p + 0]; + g = imageData[p + ofsG]; + b = imageData[p + ofsB]; + YDU[pos] = +0.29900f * r + 0.58700f * g + 0.11400f * b - 128; + UDU[pos] = -0.16874f * r - 0.33126f * g + 0.50000f * b; + VDU[pos] = +0.50000f * r - 0.41869f * g - 0.08131f * b; + } + } - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); - DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); - } - } + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + } + } - // Do the bit alignment of the EOI marker - stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); - } + // Do the bit alignment of the EOI marker + stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); + } - // EOI - stbiw__putc(s, 0xFF); - stbiw__putc(s, 0xD9); + // EOI + stbiw__putc(s, 0xFF); + stbiw__putc(s, 0xD9); - return 1; + return 1; } #if 0 /* not used in QuakeSpasm */ STBIWDEF int32_t stbi_write_jpg_to_func(stbi_write_func *func, void *context, int32_t x, int32_t y, int32_t comp, const void *data, int32_t quality) { - stbi__write_context s; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); + stbi__write_context s; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); } #endif @@ -590,13 +632,15 @@ STBIWDEF int32_t stbi_write_jpg_to_func(stbi_write_func *func, void *context, in #ifndef STBI_WRITE_NO_STDIO STBIWDEF int32_t stbi_write_jpg(char const *filename, int32_t x, int32_t y, int32_t comp, const void *data, int32_t quality) { - stbi__write_context s; - if (stbi__start_write_file(&s,filename)) { - int32_t r = stbi_write_jpg_core(&s, x, y, comp, data, quality); - stbi__end_write_file(&s); - return r; - } else - return 0; + stbi__write_context s; + if(stbi__start_write_file(&s, filename)) + { + int32_t r = stbi_write_jpg_core(&s, x, y, comp, data, quality); + stbi__end_write_file(&s); + return r; + } + else + return 0; } #endif @@ -629,7 +673,7 @@ STBIWDEF int32_t stbi_write_jpg(char const *filename, int32_t x, int32_t y, int3 add HDR output fix monochrome BMP 0.95 (2014-08-17) - add monochrome TGA output + add monochrome TGA output 0.94 (2014-05-31) rename private functions to avoid conflicts with stb_image.h 0.93 (2014-05-27) @@ -647,38 +691,38 @@ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */ diff --git a/source/strl_fn.h b/source/strl_fn.h index af7fc14..4ef350f 100644 --- a/source/strl_fn.h +++ b/source/strl_fn.h @@ -1,11 +1,11 @@ -/* header file for BSD strlcat and strlcpy */ +/* header file for BSD strlcat and strlcpy */ #ifndef __STRLFUNCS_H #define __STRLFUNCS_H /* use our own copies of strlcpy and strlcat taken from OpenBSD */ -extern size_t q_strlcpy (char *dst, const char *src, size_t size); -extern size_t q_strlcat (char *dst, const char *src, size_t size); +extern size_t q_strlcpy(char *dst, const char *src, size_t size); +extern size_t q_strlcat(char *dst, const char *src, size_t size); -#endif /* __STRLFUNCS_H */ +#endif /* __STRLFUNCS_H */ diff --git a/source/strlcat.c b/source/strlcat.c index 48b91f6..255dcf4 100644 --- a/source/strlcat.c +++ b/source/strlcat.c @@ -1,4 +1,4 @@ -/* $OpenBSD: strlcat.c,v 1.13 2005/08/08 08:05:37 espie Exp $ */ +/* $OpenBSD: strlcat.c,v 1.13 2005/08/08 08:05:37 espie Exp $ */ /* * Copyright (c) 1998 Todd C. Miller @@ -30,7 +30,7 @@ */ size_t -q_strlcat (char *dst, const char *src, size_t siz) +q_strlcat(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; @@ -38,15 +38,17 @@ q_strlcat (char *dst, const char *src, size_t siz) size_t dlen; /* Find the end of dst and adjust bytes left but don't go past end */ - while (n-- != 0 && *d != '\0') + while(n-- != 0 && *d != '\0') d++; dlen = d - dst; n = siz - dlen; - if (n == 0) + if(n == 0) return(dlen + strlen(s)); - while (*s != '\0') { - if (n != 1) { + while(*s != '\0') + { + if(n != 1) + { *d++ = *s; n--; } @@ -54,6 +56,6 @@ q_strlcat (char *dst, const char *src, size_t siz) } *d = '\0'; - return(dlen + (s - src)); /* count does not include NUL */ + return(dlen + (s - src)); /* count does not include NUL */ } diff --git a/source/strlcpy.c b/source/strlcpy.c index 754e70d..618f493 100644 --- a/source/strlcpy.c +++ b/source/strlcpy.c @@ -1,4 +1,4 @@ -/* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */ +/* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */ /* * Copyright (c) 1998 Todd C. Miller @@ -28,28 +28,31 @@ */ size_t -q_strlcpy (char *dst, const char *src, size_t siz) +q_strlcpy(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; size_t n = siz; /* Copy as many bytes as will fit */ - if (n != 0) { - while (--n != 0) { - if ((*d++ = *s++) == '\0') + if(n != 0) + { + while(--n != 0) + { + if((*d++ = *s++) == '\0') break; } } /* Not enough room in dst, add NUL and traverse rest of src */ - if (n == 0) { - if (siz != 0) - *d = '\0'; /* NUL-terminate dst */ - while (*s++) + if(n == 0) + { + if(siz != 0) + *d = '\0'; /* NUL-terminate dst */ + while(*s++) ; } - return(s - src - 1); /* count does not include NUL */ + return(s - src - 1); /* count does not include NUL */ } diff --git a/source/sv_main.c b/source/sv_main.c index 6318c5f..5fb13a7 100644 --- a/source/sv_main.c +++ b/source/sv_main.c @@ -23,14 +23,14 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -server_t sv; -server_static_t svs; +server_t sv; +server_static_t svs; -static char localmodels[MAX_MODELS][8]; // inline model names for precache +static char localmodels[MAX_MODELS][8]; // inline model names for precache -int32_t sv_protocol = PROTOCOL_FITZQUAKE; //johnfitz +int32_t sv_protocol = PROTOCOL_FITZQUAKE; //johnfitz -extern bool pr_alpha_supported; //johnfitz +extern bool pr_alpha_supported; //johnfitz //============================================================================ @@ -39,28 +39,28 @@ extern bool pr_alpha_supported; //johnfitz SV_Protocol_f =============== */ -void SV_Protocol_f (void) +void SV_Protocol_f(void) { int32_t i; - switch (Cmd_Argc()) + switch(Cmd_Argc()) { case 1: - Con_Printf ("\"sv_protocol\" is \"%" PRIi32 "\"\n", sv_protocol); + Con_Printf("\"sv_protocol\" is \"%" PRIi32 "\"\n", sv_protocol); break; case 2: i = atoi(Cmd_Argv(1)); - if (i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) - Con_Printf ("sv_protocol must be %" PRIi32 " or %" PRIi32 " or %" PRIi32 "\n", PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ); + if(i != PROTOCOL_NETQUAKE && i != PROTOCOL_FITZQUAKE && i != PROTOCOL_RMQ) + Con_Printf("sv_protocol must be %" PRIi32 " or %" PRIi32 " or %" PRIi32 "\n", PROTOCOL_NETQUAKE, PROTOCOL_FITZQUAKE, PROTOCOL_RMQ); else { sv_protocol = i; - if (sv.active) - Con_Printf ("changes will not take effect until the next level load.\n"); + if(sv.active) + Con_Printf("changes will not take effect until the next level load.\n"); } break; default: - Con_SafePrintf ("usage: sv_protocol \n"); + Con_SafePrintf("usage: sv_protocol \n"); break; } } @@ -70,50 +70,50 @@ void SV_Protocol_f (void) SV_Init =============== */ -void SV_Init (void) +void SV_Init(void) { - int32_t i; - const char *p; - extern cvar_t sv_maxvelocity; - extern cvar_t sv_gravity; - extern cvar_t sv_nostep; - extern cvar_t sv_freezenonclients; - extern cvar_t sv_friction; - extern cvar_t sv_edgefriction; - extern cvar_t sv_stopspeed; - extern cvar_t sv_maxspeed; - extern cvar_t sv_accelerate; - extern cvar_t sv_idealpitchscale; - extern cvar_t sv_aim; - extern cvar_t sv_altnoclip; //johnfitz + int32_t i; + const char *p; + extern cvar_t sv_maxvelocity; + extern cvar_t sv_gravity; + extern cvar_t sv_nostep; + extern cvar_t sv_freezenonclients; + extern cvar_t sv_friction; + extern cvar_t sv_edgefriction; + extern cvar_t sv_stopspeed; + extern cvar_t sv_maxspeed; + extern cvar_t sv_accelerate; + extern cvar_t sv_idealpitchscale; + extern cvar_t sv_aim; + extern cvar_t sv_altnoclip; //johnfitz sv.edicts = NULL; // ericw -- sv.edicts switched to use malloc() - Cvar_RegisterVariable (&sv_maxvelocity); - Cvar_RegisterVariable (&sv_gravity); - Cvar_RegisterVariable (&sv_friction); - Cvar_SetCallback (&sv_gravity, Host_Callback_Notify); - Cvar_SetCallback (&sv_friction, Host_Callback_Notify); - Cvar_RegisterVariable (&sv_edgefriction); - Cvar_RegisterVariable (&sv_stopspeed); - Cvar_RegisterVariable (&sv_maxspeed); - Cvar_SetCallback (&sv_maxspeed, Host_Callback_Notify); - Cvar_RegisterVariable (&sv_accelerate); - Cvar_RegisterVariable (&sv_idealpitchscale); - Cvar_RegisterVariable (&sv_aim); - Cvar_RegisterVariable (&sv_nostep); - Cvar_RegisterVariable (&sv_freezenonclients); - Cvar_RegisterVariable (&sv_altnoclip); //johnfitz + Cvar_RegisterVariable(&sv_maxvelocity); + Cvar_RegisterVariable(&sv_gravity); + Cvar_RegisterVariable(&sv_friction); + Cvar_SetCallback(&sv_gravity, Host_Callback_Notify); + Cvar_SetCallback(&sv_friction, Host_Callback_Notify); + Cvar_RegisterVariable(&sv_edgefriction); + Cvar_RegisterVariable(&sv_stopspeed); + Cvar_RegisterVariable(&sv_maxspeed); + Cvar_SetCallback(&sv_maxspeed, Host_Callback_Notify); + Cvar_RegisterVariable(&sv_accelerate); + Cvar_RegisterVariable(&sv_idealpitchscale); + Cvar_RegisterVariable(&sv_aim); + Cvar_RegisterVariable(&sv_nostep); + Cvar_RegisterVariable(&sv_freezenonclients); + Cvar_RegisterVariable(&sv_altnoclip); //johnfitz - Cmd_AddCommand ("sv_protocol", &SV_Protocol_f); //johnfitz + Cmd_AddCommand("sv_protocol", &SV_Protocol_f); //johnfitz - for (i=0 ; i MAX_DATAGRAM-16) + if(sv.datagram.cursize > MAX_DATAGRAM - 16) return; - MSG_WriteByte (&sv.datagram, svc_particle); - MSG_WriteCoord (&sv.datagram, org[0], sv.protocolflags); - MSG_WriteCoord (&sv.datagram, org[1], sv.protocolflags); - MSG_WriteCoord (&sv.datagram, org[2], sv.protocolflags); - for (i=0 ; i<3 ; i++) + MSG_WriteByte(&sv.datagram, svc_particle); + MSG_WriteCoord(&sv.datagram, org[0], sv.protocolflags); + MSG_WriteCoord(&sv.datagram, org[1], sv.protocolflags); + MSG_WriteCoord(&sv.datagram, org[2], sv.protocolflags); + for(i = 0 ; i < 3 ; i++) { - v = dir[i]*16; - if (v > 127) + v = dir[i] * 16; + if(v > 127) v = 127; - else if (v < -128) + else if(v < -128) v = -128; - MSG_WriteChar (&sv.datagram, v); + MSG_WriteChar(&sv.datagram, v); } - MSG_WriteByte (&sv.datagram, count); - MSG_WriteByte (&sv.datagram, color); + MSG_WriteByte(&sv.datagram, count); + MSG_WriteByte(&sv.datagram, color); } /* @@ -185,55 +185,55 @@ Larger attenuations will drop off. (max 4 attenuation) ================== */ -void SV_StartSound (edict_t *entity, int32_t channel, const char *sample, int32_t volume, float attenuation) +void SV_StartSound(edict_t *entity, int32_t channel, const char *sample, int32_t volume, float attenuation) { - int32_t sound_num, ent; - int32_t i, field_mask; + int32_t sound_num, ent; + int32_t i, field_mask; - if (volume < 0 || volume > 255) - Host_Error ("SV_StartSound: volume = %" PRIi32 "", volume); + if(volume < 0 || volume > 255) + Host_Error("SV_StartSound: volume = %" PRIi32 "", volume); - if (attenuation < 0 || attenuation > 4) - Host_Error ("SV_StartSound: attenuation = %f", attenuation); + if(attenuation < 0 || attenuation > 4) + Host_Error("SV_StartSound: attenuation = %f", attenuation); - if (channel < 0 || channel > 7) - Host_Error ("SV_StartSound: channel = %" PRIi32 "", channel); + if(channel < 0 || channel > 7) + Host_Error("SV_StartSound: channel = %" PRIi32 "", channel); - if (sv.datagram.cursize > MAX_DATAGRAM-16) + if(sv.datagram.cursize > MAX_DATAGRAM - 16) return; // find precache number for sound - for (sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) + for(sound_num = 1; sound_num < MAX_SOUNDS && sv.sound_precache[sound_num]; sound_num++) { - if (!strcmp(sample, sv.sound_precache[sound_num])) + if(!strcmp(sample, sv.sound_precache[sound_num])) break; } - if (sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) + if(sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num]) { - Con_Printf ("SV_StartSound: %s not precacheed\n", sample); + Con_Printf("SV_StartSound: %s not precacheed\n", sample); return; } ent = NUM_FOR_EDICT(entity); field_mask = 0; - if (volume != DEFAULT_SOUND_PACKET_VOLUME) + if(volume != DEFAULT_SOUND_PACKET_VOLUME) field_mask |= SND_VOLUME; - if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION) + if(attenuation != DEFAULT_SOUND_PACKET_ATTENUATION) field_mask |= SND_ATTENUATION; //johnfitz -- PROTOCOL_FITZQUAKE - if (ent >= 8192) + if(ent >= 8192) { - if (sv.protocol == PROTOCOL_NETQUAKE) + if(sv.protocol == PROTOCOL_NETQUAKE) return; //don't send any info protocol can't support else field_mask |= SND_LARGEENTITY; } - if (sound_num >= 256 || channel >= 8) + if(sound_num >= 256 || channel >= 8) { - if (sv.protocol == PROTOCOL_NETQUAKE) + if(sv.protocol == PROTOCOL_NETQUAKE) return; //don't send any info protocol can't support else field_mask |= SND_LARGESOUND; @@ -241,29 +241,29 @@ void SV_StartSound (edict_t *entity, int32_t channel, const char *sample, int32_ //johnfitz // directed messages go only to the entity the are targeted on - MSG_WriteByte (&sv.datagram, svc_sound); - MSG_WriteByte (&sv.datagram, field_mask); - if (field_mask & SND_VOLUME) - MSG_WriteByte (&sv.datagram, volume); - if (field_mask & SND_ATTENUATION) - MSG_WriteByte (&sv.datagram, attenuation*64); + MSG_WriteByte(&sv.datagram, svc_sound); + MSG_WriteByte(&sv.datagram, field_mask); + if(field_mask & SND_VOLUME) + MSG_WriteByte(&sv.datagram, volume); + if(field_mask & SND_ATTENUATION) + MSG_WriteByte(&sv.datagram, attenuation * 64); //johnfitz -- PROTOCOL_FITZQUAKE - if (field_mask & SND_LARGEENTITY) + if(field_mask & SND_LARGEENTITY) { - MSG_WriteShort (&sv.datagram, ent); - MSG_WriteByte (&sv.datagram, channel); + MSG_WriteShort(&sv.datagram, ent); + MSG_WriteByte(&sv.datagram, channel); } else - MSG_WriteShort (&sv.datagram, (ent<<3) | channel); - if (field_mask & SND_LARGESOUND) - MSG_WriteShort (&sv.datagram, sound_num); + MSG_WriteShort(&sv.datagram, (ent << 3) | channel); + if(field_mask & SND_LARGESOUND) + MSG_WriteShort(&sv.datagram, sound_num); else - MSG_WriteByte (&sv.datagram, sound_num); + MSG_WriteByte(&sv.datagram, sound_num); //johnfitz - for (i = 0; i < 3; i++) - MSG_WriteCoord (&sv.datagram, entity->v.origin[i]+0.5*(entity->v.mins[i]+entity->v.maxs[i]), sv.protocolflags); + for(i = 0; i < 3; i++) + MSG_WriteCoord(&sv.datagram, entity->v.origin[i] + 0.5 * (entity->v.mins[i] + entity->v.maxs[i]), sv.protocolflags); } /* @@ -282,60 +282,60 @@ Sends the first message from the server to a connected client. This will be sent on the initial connection and upon each server load. ================ */ -void SV_SendServerinfo (client_t *client) +void SV_SendServerinfo(client_t *client) { - const char **s; - char message[2048]; - int32_t i; //johnfitz + const char **s; + char message[2048]; + int32_t i; //johnfitz - MSG_WriteByte (&client->message, svc_print); - sprintf (message, "%c\nFITZQUAKE " FITZQUAKE_VERSION " SERVER (%" PRIi32 " CRC)\n", 2, pr_crc); //johnfitz -- include fitzquake version - MSG_WriteString (&client->message,message); + MSG_WriteByte(&client->message, svc_print); + sprintf(message, "%c\nFITZQUAKE " FITZQUAKE_VERSION " SERVER (%" PRIi32 " CRC)\n", 2, pr_crc); //johnfitz -- include fitzquake version + MSG_WriteString(&client->message, message); - MSG_WriteByte (&client->message, svc_serverinfo); - MSG_WriteLong (&client->message, sv.protocol); //johnfitz -- sv.protocol instead of PROTOCOL_VERSION + MSG_WriteByte(&client->message, svc_serverinfo); + MSG_WriteLong(&client->message, sv.protocol); //johnfitz -- sv.protocol instead of PROTOCOL_VERSION - if (sv.protocol == PROTOCOL_RMQ) + if(sv.protocol == PROTOCOL_RMQ) { // mh - now send protocol flags so that the client knows the protocol features to expect - MSG_WriteLong (&client->message, sv.protocolflags); + MSG_WriteLong(&client->message, sv.protocolflags); } - MSG_WriteByte (&client->message, svs.maxclients); + MSG_WriteByte(&client->message, svs.maxclients); - if (!coop.value && deathmatch.value) - MSG_WriteByte (&client->message, GAME_DEATHMATCH); + if(!coop.value && deathmatch.value) + MSG_WriteByte(&client->message, GAME_DEATHMATCH); else - MSG_WriteByte (&client->message, GAME_COOP); + MSG_WriteByte(&client->message, GAME_COOP); - MSG_WriteString (&client->message, PR_GetString(sv.edicts->v.message)); + MSG_WriteString(&client->message, PR_GetString(sv.edicts->v.message)); //johnfitz -- only send the first 256 model and sound precaches if protocol is 15 - for (i=0,s = sv.model_precache+1 ; *s; s++,i++) - if (sv.protocol != PROTOCOL_NETQUAKE || i < 256) - MSG_WriteString (&client->message, *s); - MSG_WriteByte (&client->message, 0); + for(i = 0, s = sv.model_precache + 1 ; *s; s++, i++) + if(sv.protocol != PROTOCOL_NETQUAKE || i < 256) + MSG_WriteString(&client->message, *s); + MSG_WriteByte(&client->message, 0); - for (i=0,s = sv.sound_precache+1 ; *s ; s++,i++) - if (sv.protocol != PROTOCOL_NETQUAKE || i < 256) - MSG_WriteString (&client->message, *s); - MSG_WriteByte (&client->message, 0); + for(i = 0, s = sv.sound_precache + 1 ; *s ; s++, i++) + if(sv.protocol != PROTOCOL_NETQUAKE || i < 256) + MSG_WriteString(&client->message, *s); + MSG_WriteByte(&client->message, 0); //johnfitz // send music - MSG_WriteByte (&client->message, svc_cdtrack); - MSG_WriteByte (&client->message, sv.edicts->v.sounds); - MSG_WriteByte (&client->message, sv.edicts->v.sounds); + MSG_WriteByte(&client->message, svc_cdtrack); + MSG_WriteByte(&client->message, sv.edicts->v.sounds); + MSG_WriteByte(&client->message, sv.edicts->v.sounds); // set view - MSG_WriteByte (&client->message, svc_setview); - MSG_WriteShort (&client->message, NUM_FOR_EDICT(client->edict)); + MSG_WriteByte(&client->message, svc_setview); + MSG_WriteShort(&client->message, NUM_FOR_EDICT(client->edict)); - MSG_WriteByte (&client->message, svc_signonnum); - MSG_WriteByte (&client->message, 1); + MSG_WriteByte(&client->message, svc_signonnum); + MSG_WriteByte(&client->message, 1); client->sendsignon = true; - client->spawned = false; // need prespawn, spawn, etc + client->spawned = false; // need prespawn, spawn, etc } /* @@ -346,50 +346,50 @@ Initializes a client_t for a new net connection. This will only be called once for a player each game, not once for each level change. ================ */ -void SV_ConnectClient (int32_t clientnum) +void SV_ConnectClient(int32_t clientnum) { - edict_t *ent; - client_t *client; - int32_t edictnum; + edict_t *ent; + client_t *client; + int32_t edictnum; struct qsocket_s *netconnection; - int32_t i; - float spawn_parms[NUM_SPAWN_PARMS]; + int32_t i; + float spawn_parms[NUM_SPAWN_PARMS]; client = svs.clients + clientnum; - Con_DPrintf ("Client %s connected\n", NET_QSocketGetAddressString(client->netconnection)); + Con_DPrintf("Client %s connected\n", NET_QSocketGetAddressString(client->netconnection)); - edictnum = clientnum+1; + edictnum = clientnum + 1; ent = EDICT_NUM(edictnum); // set up the client_t netconnection = client->netconnection; - if (sv.loadgame) - memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms)); - memset (client, 0, sizeof(*client)); + if(sv.loadgame) + memcpy(spawn_parms, client->spawn_parms, sizeof(spawn_parms)); + memset(client, 0, sizeof(*client)); client->netconnection = netconnection; - strcpy (client->name, "unconnected"); + strcpy(client->name, "unconnected"); client->active = true; client->spawned = false; client->edict = ent; client->message.data = client->msgbuf; client->message.maxsize = sizeof(client->msgbuf); - client->message.allowoverflow = true; // we can catch it + client->message.allowoverflow = true; // we can catch it - if (sv.loadgame) - memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms)); + if(sv.loadgame) + memcpy(client->spawn_parms, spawn_parms, sizeof(spawn_parms)); else { - // call the progs to get default spawn parms for the new client - PR_ExecuteProgram (pr_global_struct->SetNewParms); - for (i=0 ; iSetNewParms); + for(i = 0 ; i < NUM_SPAWN_PARMS ; i++) client->spawn_parms[i] = (&pr_global_struct->parm1)[i]; } - SV_SendServerinfo (client); + SV_SendServerinfo(client); } @@ -399,31 +399,31 @@ SV_CheckForNewClients =================== */ -void SV_CheckForNewClients (void) +void SV_CheckForNewClients(void) { - struct qsocket_s *ret; - int32_t i; + struct qsocket_s *ret; + int32_t i; // // check for new connections // - while (1) + while(1) { - ret = NET_CheckNewConnections (); - if (!ret) + ret = NET_CheckNewConnections(); + if(!ret) break; - // - // init a new client structure - // - for (i=0 ; icontents < 0) + // if this is a leaf, accumulate the pvs bits + if(node->contents < 0) { - if (node->contents != CONTENTS_SOLID) + if(node->contents != CONTENTS_SOLID) { - pvs = Mod_LeafPVS ( (mleaf_t *)node, worldmodel); //johnfitz -- worldmodel as a parameter - for (i=0 ; iplane; - d = DotProduct (org, plane->normal) - plane->dist; - if (d > 8) + d = DotProduct(org, plane->normal) - plane->dist; + if(d > 8) node = node->children[0]; - else if (d < -8) + else if(d < -8) node = node->children[1]; else - { // go down both - SV_AddToFatPVS (org, node->children[0], worldmodel); //johnfitz -- worldmodel as a parameter + { + // go down both + SV_AddToFatPVS(org, node->children[0], worldmodel); //johnfitz -- worldmodel as a parameter node = node->children[1]; } } @@ -507,19 +508,19 @@ Calculates a PVS that is the inclusive or of all leafs within 8 pixels of the given point. ============= */ -byte *SV_FatPVS (vec3_t org, qmodel_t *worldmodel) //johnfitz -- added worldmodel as a parameter +byte *SV_FatPVS(vec3_t org, qmodel_t *worldmodel) //johnfitz -- added worldmodel as a parameter { - fatbytes = (worldmodel->numleafs+7)>>3; // ericw -- was +31, assumed to be a bug/typo - if (fatpvs == NULL || fatbytes > fatpvs_capacity) + fatbytes = (worldmodel->numleafs + 7) >> 3; // ericw -- was +31, assumed to be a bug/typo + if(fatpvs == NULL || fatbytes > fatpvs_capacity) { fatpvs_capacity = fatbytes; - fatpvs = (byte *) realloc (fatpvs, fatpvs_capacity); - if (!fatpvs) - Sys_Error ("SV_FatPVS: realloc() failed on %" PRIi32 " bytes", fatpvs_capacity); + fatpvs = (byte *) realloc(fatpvs, fatpvs_capacity); + if(!fatpvs) + Sys_Error("SV_FatPVS: realloc() failed on %" PRIi32 " bytes", fatpvs_capacity); } - Q_memset (fatpvs, 0, fatbytes); - SV_AddToFatPVS (org, worldmodel->nodes, worldmodel); //johnfitz -- worldmodel as a parameter + Q_memset(fatpvs, 0, fatbytes); + SV_AddToFatPVS(org, worldmodel->nodes, worldmodel); //johnfitz -- worldmodel as a parameter return fatpvs; } @@ -530,17 +531,17 @@ SV_VisibleToClient -- johnfitz PVS test encapsulated in a nice function ============= */ -bool SV_VisibleToClient (edict_t *client, edict_t *test, qmodel_t *worldmodel) +bool SV_VisibleToClient(edict_t *client, edict_t *test, qmodel_t *worldmodel) { - byte *pvs; - vec3_t org; - int32_t i; + byte *pvs; + vec3_t org; + int32_t i; - VectorAdd (client->v.origin, client->v.view_ofs, org); - pvs = SV_FatPVS (org, worldmodel); + VectorAdd(client->v.origin, client->v.view_ofs, org); + pvs = SV_FatPVS(org, worldmodel); - for (i=0 ; i < test->num_leafs ; i++) - if (pvs[test->leafnums[i] >> 3] & (1 << (test->leafnums[i]&7) )) + for(i = 0 ; i < test->num_leafs ; i++) + if(pvs[test->leafnums[i] >> 3] & (1 << (test->leafnums[i] & 7))) return true; return false; @@ -554,37 +555,37 @@ SV_WriteEntitiesToClient ============= */ -void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg) +void SV_WriteEntitiesToClient(edict_t *clent, sizebuf_t *msg) { - int32_t e, i; - int32_t bits; - byte *pvs; - vec3_t org; - float miss; - edict_t *ent; + int32_t e, i; + int32_t bits; + byte *pvs; + vec3_t org; + float miss; + edict_t *ent; // find the client's PVS - VectorAdd (clent->v.origin, clent->v.view_ofs, org); - pvs = SV_FatPVS (org, sv.worldmodel); + VectorAdd(clent->v.origin, clent->v.view_ofs, org); + pvs = SV_FatPVS(org, sv.worldmodel); // send over all entities (excpet the client) that touch the pvs ent = NEXT_EDICT(sv.edicts); - for (e=1 ; ev.modelindex || !PR_GetString(ent->v.model)[0]) + if(!ent->v.modelindex || !PR_GetString(ent->v.model)[0]) continue; //johnfitz -- don't send model>255 entities if protocol is 15 - if (sv.protocol == PROTOCOL_NETQUAKE && (int32_t)ent->v.modelindex & 0xFF00) + if(sv.protocol == PROTOCOL_NETQUAKE && (int32_t)ent->v.modelindex & 0xFF00) continue; // ignore if not touching a PV leaf - for (i=0 ; i < ent->num_leafs ; i++) - if (pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i]&7) )) + for(i = 0 ; i < ent->num_leafs ; i++) + if(pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i] & 7))) break; // ericw -- added ent->num_leafs < MAX_ENT_LEAFS condition. @@ -593,18 +594,18 @@ void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg) // for us to say whether it's in the PVS, so don't try to vis cull it. // this commonly happens with rotators, because they often have huge bboxes // spanning the entire map, or really tall lifts, etc. - if (i == ent->num_leafs && ent->num_leafs < MAX_ENT_LEAFS) - continue; // not visible + if(i == ent->num_leafs && ent->num_leafs < MAX_ENT_LEAFS) + continue; // not visible } //johnfitz -- max size for protocol 15 is 18 bytes, not 16 as originally //assumed here. And, for protocol 85 the max size is actually 24 bytes. - if (msg->cursize + 24 > msg->maxsize) + if(msg->cursize + 24 > msg->maxsize) { //johnfitz -- less spammy overflow message - if (!dev_overflows.packetsize || dev_overflows.packetsize + CONSOLE_RESPAM_TIME < realtime ) + if(!dev_overflows.packetsize || dev_overflows.packetsize + CONSOLE_RESPAM_TIME < realtime) { - Con_Printf ("Packet overflow!\n"); + Con_Printf("Packet overflow!\n"); dev_overflows.packetsize = realtime; } goto stats; @@ -614,133 +615,133 @@ void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg) // send an update bits = 0; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { miss = ent->v.origin[i] - ent->baseline.origin[i]; - if ( miss < -0.1 || miss > 0.1 ) - bits |= U_ORIGIN1< 0.1) + bits |= U_ORIGIN1 << i; } - if ( ent->v.angles[0] != ent->baseline.angles[0] ) + if(ent->v.angles[0] != ent->baseline.angles[0]) bits |= U_ANGLE1; - if ( ent->v.angles[1] != ent->baseline.angles[1] ) + if(ent->v.angles[1] != ent->baseline.angles[1]) bits |= U_ANGLE2; - if ( ent->v.angles[2] != ent->baseline.angles[2] ) + if(ent->v.angles[2] != ent->baseline.angles[2]) bits |= U_ANGLE3; - if (ent->v.movetype == MOVETYPE_STEP) - bits |= U_STEP; // don't mess up the step animation + if(ent->v.movetype == MOVETYPE_STEP) + bits |= U_STEP; // don't mess up the step animation - if (ent->baseline.colormap != ent->v.colormap) + if(ent->baseline.colormap != ent->v.colormap) bits |= U_COLORMAP; - if (ent->baseline.skin != ent->v.skin) + if(ent->baseline.skin != ent->v.skin) bits |= U_SKIN; - if (ent->baseline.frame != ent->v.frame) + if(ent->baseline.frame != ent->v.frame) bits |= U_FRAME; - if (ent->baseline.effects != ent->v.effects) + if(ent->baseline.effects != ent->v.effects) bits |= U_EFFECTS; - if (ent->baseline.modelindex != ent->v.modelindex) + if(ent->baseline.modelindex != ent->v.modelindex) bits |= U_MODEL; //johnfitz -- alpha - if (pr_alpha_supported) + if(pr_alpha_supported) { // TODO: find a cleaner place to put this code - eval_t *val; + eval_t *val; val = GetEdictFieldValue(ent, "alpha"); - if (val) + if(val) ent->alpha = ENTALPHA_ENCODE(val->_float); } //don't send invisible entities unless they have effects - if (ent->alpha == ENTALPHA_ZERO && !ent->v.effects) + if(ent->alpha == ENTALPHA_ZERO && !ent->v.effects) continue; //johnfitz //johnfitz -- PROTOCOL_FITZQUAKE - if (sv.protocol != PROTOCOL_NETQUAKE) + if(sv.protocol != PROTOCOL_NETQUAKE) { - if (ent->baseline.alpha != ent->alpha) bits |= U_ALPHA; - if (bits & U_FRAME && (int32_t)ent->v.frame & 0xFF00) bits |= U_FRAME2; - if (bits & U_MODEL && (int32_t)ent->v.modelindex & 0xFF00) bits |= U_MODEL2; - if (ent->sendinterval) bits |= U_LERPFINISH; - if (bits >= 65536) bits |= U_EXTEND1; - if (bits >= 16777216) bits |= U_EXTEND2; + if(ent->baseline.alpha != ent->alpha) bits |= U_ALPHA; + if(bits & U_FRAME && (int32_t)ent->v.frame & 0xFF00) bits |= U_FRAME2; + if(bits & U_MODEL && (int32_t)ent->v.modelindex & 0xFF00) bits |= U_MODEL2; + if(ent->sendinterval) bits |= U_LERPFINISH; + if(bits >= 65536) bits |= U_EXTEND1; + if(bits >= 16777216) bits |= U_EXTEND2; } //johnfitz - if (e >= 256) + if(e >= 256) bits |= U_LONGENTITY; - if (bits >= 256) + if(bits >= 256) bits |= U_MOREBITS; - // - // write the message - // - MSG_WriteByte (msg, bits | U_SIGNAL); + // + // write the message + // + MSG_WriteByte(msg, bits | U_SIGNAL); - if (bits & U_MOREBITS) - MSG_WriteByte (msg, bits>>8); + if(bits & U_MOREBITS) + MSG_WriteByte(msg, bits >> 8); //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & U_EXTEND1) - MSG_WriteByte(msg, bits>>16); - if (bits & U_EXTEND2) - MSG_WriteByte(msg, bits>>24); + if(bits & U_EXTEND1) + MSG_WriteByte(msg, bits >> 16); + if(bits & U_EXTEND2) + MSG_WriteByte(msg, bits >> 24); //johnfitz - if (bits & U_LONGENTITY) - MSG_WriteShort (msg,e); + if(bits & U_LONGENTITY) + MSG_WriteShort(msg, e); else - MSG_WriteByte (msg,e); + MSG_WriteByte(msg, e); - if (bits & U_MODEL) - MSG_WriteByte (msg, ent->v.modelindex); - if (bits & U_FRAME) - MSG_WriteByte (msg, ent->v.frame); - if (bits & U_COLORMAP) - MSG_WriteByte (msg, ent->v.colormap); - if (bits & U_SKIN) - MSG_WriteByte (msg, ent->v.skin); - if (bits & U_EFFECTS) - MSG_WriteByte (msg, ent->v.effects); - if (bits & U_ORIGIN1) - MSG_WriteCoord (msg, ent->v.origin[0], sv.protocolflags); - if (bits & U_ANGLE1) + if(bits & U_MODEL) + MSG_WriteByte(msg, ent->v.modelindex); + if(bits & U_FRAME) + MSG_WriteByte(msg, ent->v.frame); + if(bits & U_COLORMAP) + MSG_WriteByte(msg, ent->v.colormap); + if(bits & U_SKIN) + MSG_WriteByte(msg, ent->v.skin); + if(bits & U_EFFECTS) + MSG_WriteByte(msg, ent->v.effects); + if(bits & U_ORIGIN1) + MSG_WriteCoord(msg, ent->v.origin[0], sv.protocolflags); + if(bits & U_ANGLE1) MSG_WriteAngle(msg, ent->v.angles[0], sv.protocolflags); - if (bits & U_ORIGIN2) - MSG_WriteCoord (msg, ent->v.origin[1], sv.protocolflags); - if (bits & U_ANGLE2) + if(bits & U_ORIGIN2) + MSG_WriteCoord(msg, ent->v.origin[1], sv.protocolflags); + if(bits & U_ANGLE2) MSG_WriteAngle(msg, ent->v.angles[1], sv.protocolflags); - if (bits & U_ORIGIN3) - MSG_WriteCoord (msg, ent->v.origin[2], sv.protocolflags); - if (bits & U_ANGLE3) + if(bits & U_ORIGIN3) + MSG_WriteCoord(msg, ent->v.origin[2], sv.protocolflags); + if(bits & U_ANGLE3) MSG_WriteAngle(msg, ent->v.angles[2], sv.protocolflags); //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & U_ALPHA) + if(bits & U_ALPHA) MSG_WriteByte(msg, ent->alpha); - if (bits & U_FRAME2) + if(bits & U_FRAME2) MSG_WriteByte(msg, (int32_t)ent->v.frame >> 8); - if (bits & U_MODEL2) + if(bits & U_MODEL2) MSG_WriteByte(msg, (int32_t)ent->v.modelindex >> 8); - if (bits & U_LERPFINISH) - MSG_WriteByte(msg, (byte)(Q_rint((ent->v.nextthink-sv.time)*255))); + if(bits & U_LERPFINISH) + MSG_WriteByte(msg, (byte)(Q_rint((ent->v.nextthink - sv.time) * 255))); //johnfitz } //johnfitz -- devstats stats: - if (msg->cursize > 1024 && dev_peakstats.packetsize <= 1024) - Con_DWarning ("%" PRIi32 " byte packet exceeds standard limit of 1024 (max = %" PRIi32 ").\n", msg->cursize, msg->maxsize); + if(msg->cursize > 1024 && dev_peakstats.packetsize <= 1024) + Con_DWarning("%" PRIi32 " byte packet exceeds standard limit of 1024 (max = %" PRIi32 ").\n", msg->cursize, msg->maxsize); dev_stats.packetsize = msg->cursize; dev_peakstats.packetsize = q_max(msg->cursize, dev_peakstats.packetsize); //johnfitz @@ -752,13 +753,13 @@ SV_CleanupEnts ============= */ -void SV_CleanupEnts (void) +void SV_CleanupEnts(void) { - int32_t e; - edict_t *ent; + int32_t e; + edict_t *ent; ent = NEXT_EDICT(sv.edicts); - for (e=1 ; ev.effects = (int32_t)ent->v.effects & ~EF_MUZZLEFLASH; } @@ -770,25 +771,25 @@ SV_WriteClientdataToMessage ================== */ -void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg) +void SV_WriteClientdataToMessage(edict_t *ent, sizebuf_t *msg) { - int32_t bits; - int32_t i; - edict_t *other; - int32_t items; - eval_t *val; + int32_t bits; + int32_t i; + edict_t *other; + int32_t items; + eval_t *val; // // send a damage message // - if (ent->v.dmg_take || ent->v.dmg_save) + if(ent->v.dmg_take || ent->v.dmg_save) { other = PROG_TO_EDICT(ent->v.dmg_inflictor); - MSG_WriteByte (msg, svc_damage); - MSG_WriteByte (msg, ent->v.dmg_save); - MSG_WriteByte (msg, ent->v.dmg_take); - for (i=0 ; i<3 ; i++) - MSG_WriteCoord (msg, other->v.origin[i] + 0.5*(other->v.mins[i] + other->v.maxs[i]), sv.protocolflags ); + MSG_WriteByte(msg, svc_damage); + MSG_WriteByte(msg, ent->v.dmg_save); + MSG_WriteByte(msg, ent->v.dmg_take); + for(i = 0 ; i < 3 ; i++) + MSG_WriteCoord(msg, other->v.origin[i] + 0.5 * (other->v.mins[i] + other->v.maxs[i]), sv.protocolflags); ent->v.dmg_take = 0; ent->v.dmg_save = 0; @@ -797,152 +798,152 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg) // // send the current viewpos offset from the view entity // - SV_SetIdealPitch (); // how much to look up / down ideally + SV_SetIdealPitch(); // how much to look up / down ideally // a fixangle might get lost in a dropped packet. Oh well. - if ( ent->v.fixangle ) + if(ent->v.fixangle) { - MSG_WriteByte (msg, svc_setangle); - for (i=0 ; i < 3 ; i++) - MSG_WriteAngle (msg, ent->v.angles[i], sv.protocolflags ); + MSG_WriteByte(msg, svc_setangle); + for(i = 0 ; i < 3 ; i++) + MSG_WriteAngle(msg, ent->v.angles[i], sv.protocolflags); ent->v.fixangle = 0; } bits = 0; - if (ent->v.view_ofs[2] != DEFAULT_VIEWHEIGHT) + if(ent->v.view_ofs[2] != DEFAULT_VIEWHEIGHT) bits |= SU_VIEWHEIGHT; - if (ent->v.idealpitch) + if(ent->v.idealpitch) bits |= SU_IDEALPITCH; // stuff the sigil bits into the high bits of items for sbar, or else // mix in items2 val = GetEdictFieldValue(ent, "items2"); - if (val) + if(val) items = (int32_t)ent->v.items | ((int32_t)val->_float << 23); else items = (int32_t)ent->v.items | ((int32_t)pr_global_struct->serverflags << 28); bits |= SU_ITEMS; - if ( (int32_t)ent->v.flags & FL_ONGROUND) + if((int32_t)ent->v.flags & FL_ONGROUND) bits |= SU_ONGROUND; - if ( ent->v.waterlevel >= 2) + if(ent->v.waterlevel >= 2) bits |= SU_INWATER; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { - if (ent->v.punchangle[i]) - bits |= (SU_PUNCH1<v.velocity[i]) - bits |= (SU_VELOCITY1<v.punchangle[i]) + bits |= (SU_PUNCH1 << i); + if(ent->v.velocity[i]) + bits |= (SU_VELOCITY1 << i); } - if (ent->v.weaponframe) + if(ent->v.weaponframe) bits |= SU_WEAPONFRAME; - if (ent->v.armorvalue) + if(ent->v.armorvalue) bits |= SU_ARMOR; // if (ent->v.weapon) - bits |= SU_WEAPON; + bits |= SU_WEAPON; //johnfitz -- PROTOCOL_FITZQUAKE - if (sv.protocol != PROTOCOL_NETQUAKE) + if(sv.protocol != PROTOCOL_NETQUAKE) { - if (bits & SU_WEAPON && SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) & 0xFF00) bits |= SU_WEAPON2; - if ((int32_t)ent->v.armorvalue & 0xFF00) bits |= SU_ARMOR2; - if ((int32_t)ent->v.currentammo & 0xFF00) bits |= SU_AMMO2; - if ((int32_t)ent->v.ammo_shells & 0xFF00) bits |= SU_SHELLS2; - if ((int32_t)ent->v.ammo_nails & 0xFF00) bits |= SU_NAILS2; - if ((int32_t)ent->v.ammo_rockets & 0xFF00) bits |= SU_ROCKETS2; - if ((int32_t)ent->v.ammo_cells & 0xFF00) bits |= SU_CELLS2; - if (bits & SU_WEAPONFRAME && (int32_t)ent->v.weaponframe & 0xFF00) bits |= SU_WEAPONFRAME2; - if (bits & SU_WEAPON && ent->alpha != ENTALPHA_DEFAULT) bits |= SU_WEAPONALPHA; //for now, weaponalpha = client entity alpha - if (bits >= 65536) bits |= SU_EXTEND1; - if (bits >= 16777216) bits |= SU_EXTEND2; + if(bits & SU_WEAPON && SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) & 0xFF00) bits |= SU_WEAPON2; + if((int32_t)ent->v.armorvalue & 0xFF00) bits |= SU_ARMOR2; + if((int32_t)ent->v.currentammo & 0xFF00) bits |= SU_AMMO2; + if((int32_t)ent->v.ammo_shells & 0xFF00) bits |= SU_SHELLS2; + if((int32_t)ent->v.ammo_nails & 0xFF00) bits |= SU_NAILS2; + if((int32_t)ent->v.ammo_rockets & 0xFF00) bits |= SU_ROCKETS2; + if((int32_t)ent->v.ammo_cells & 0xFF00) bits |= SU_CELLS2; + if(bits & SU_WEAPONFRAME && (int32_t)ent->v.weaponframe & 0xFF00) bits |= SU_WEAPONFRAME2; + if(bits & SU_WEAPON && ent->alpha != ENTALPHA_DEFAULT) bits |= SU_WEAPONALPHA; //for now, weaponalpha = client entity alpha + if(bits >= 65536) bits |= SU_EXTEND1; + if(bits >= 16777216) bits |= SU_EXTEND2; } //johnfitz // send the data - MSG_WriteByte (msg, svc_clientdata); - MSG_WriteShort (msg, bits); + MSG_WriteByte(msg, svc_clientdata); + MSG_WriteShort(msg, bits); //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & SU_EXTEND1) MSG_WriteByte(msg, bits>>16); - if (bits & SU_EXTEND2) MSG_WriteByte(msg, bits>>24); + if(bits & SU_EXTEND1) MSG_WriteByte(msg, bits >> 16); + if(bits & SU_EXTEND2) MSG_WriteByte(msg, bits >> 24); //johnfitz - if (bits & SU_VIEWHEIGHT) - MSG_WriteChar (msg, ent->v.view_ofs[2]); + if(bits & SU_VIEWHEIGHT) + MSG_WriteChar(msg, ent->v.view_ofs[2]); - if (bits & SU_IDEALPITCH) - MSG_WriteChar (msg, ent->v.idealpitch); + if(bits & SU_IDEALPITCH) + MSG_WriteChar(msg, ent->v.idealpitch); - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { - if (bits & (SU_PUNCH1<v.punchangle[i]); - if (bits & (SU_VELOCITY1<v.velocity[i]/16); + if(bits & (SU_PUNCH1 << i)) + MSG_WriteChar(msg, ent->v.punchangle[i]); + if(bits & (SU_VELOCITY1 << i)) + MSG_WriteChar(msg, ent->v.velocity[i] / 16); } -// [always sent] if (bits & SU_ITEMS) - MSG_WriteLong (msg, items); +// [always sent] if (bits & SU_ITEMS) + MSG_WriteLong(msg, items); - if (bits & SU_WEAPONFRAME) - MSG_WriteByte (msg, ent->v.weaponframe); - if (bits & SU_ARMOR) - MSG_WriteByte (msg, ent->v.armorvalue); - if (bits & SU_WEAPON) - MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v.weaponmodel))); + if(bits & SU_WEAPONFRAME) + MSG_WriteByte(msg, ent->v.weaponframe); + if(bits & SU_ARMOR) + MSG_WriteByte(msg, ent->v.armorvalue); + if(bits & SU_WEAPON) + MSG_WriteByte(msg, SV_ModelIndex(PR_GetString(ent->v.weaponmodel))); - MSG_WriteShort (msg, ent->v.health); - MSG_WriteByte (msg, ent->v.currentammo); - MSG_WriteByte (msg, ent->v.ammo_shells); - MSG_WriteByte (msg, ent->v.ammo_nails); - MSG_WriteByte (msg, ent->v.ammo_rockets); - MSG_WriteByte (msg, ent->v.ammo_cells); + MSG_WriteShort(msg, ent->v.health); + MSG_WriteByte(msg, ent->v.currentammo); + MSG_WriteByte(msg, ent->v.ammo_shells); + MSG_WriteByte(msg, ent->v.ammo_nails); + MSG_WriteByte(msg, ent->v.ammo_rockets); + MSG_WriteByte(msg, ent->v.ammo_cells); - if (standard_quake) + if(standard_quake) { - MSG_WriteByte (msg, ent->v.weapon); + MSG_WriteByte(msg, ent->v.weapon); } else { - for(i=0;i<32;i++) + for(i = 0; i < 32; i++) { - if ( ((int32_t)ent->v.weapon) & (1<v.weapon) & (1 << i)) { - MSG_WriteByte (msg, i); + MSG_WriteByte(msg, i); break; } } } //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & SU_WEAPON2) - MSG_WriteByte (msg, SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) >> 8); - if (bits & SU_ARMOR2) - MSG_WriteByte (msg, (int32_t)ent->v.armorvalue >> 8); - if (bits & SU_AMMO2) - MSG_WriteByte (msg, (int32_t)ent->v.currentammo >> 8); - if (bits & SU_SHELLS2) - MSG_WriteByte (msg, (int32_t)ent->v.ammo_shells >> 8); - if (bits & SU_NAILS2) - MSG_WriteByte (msg, (int32_t)ent->v.ammo_nails >> 8); - if (bits & SU_ROCKETS2) - MSG_WriteByte (msg, (int32_t)ent->v.ammo_rockets >> 8); - if (bits & SU_CELLS2) - MSG_WriteByte (msg, (int32_t)ent->v.ammo_cells >> 8); - if (bits & SU_WEAPONFRAME2) - MSG_WriteByte (msg, (int32_t)ent->v.weaponframe >> 8); - if (bits & SU_WEAPONALPHA) - MSG_WriteByte (msg, ent->alpha); //for now, weaponalpha = client entity alpha + if(bits & SU_WEAPON2) + MSG_WriteByte(msg, SV_ModelIndex(PR_GetString(ent->v.weaponmodel)) >> 8); + if(bits & SU_ARMOR2) + MSG_WriteByte(msg, (int32_t)ent->v.armorvalue >> 8); + if(bits & SU_AMMO2) + MSG_WriteByte(msg, (int32_t)ent->v.currentammo >> 8); + if(bits & SU_SHELLS2) + MSG_WriteByte(msg, (int32_t)ent->v.ammo_shells >> 8); + if(bits & SU_NAILS2) + MSG_WriteByte(msg, (int32_t)ent->v.ammo_nails >> 8); + if(bits & SU_ROCKETS2) + MSG_WriteByte(msg, (int32_t)ent->v.ammo_rockets >> 8); + if(bits & SU_CELLS2) + MSG_WriteByte(msg, (int32_t)ent->v.ammo_cells >> 8); + if(bits & SU_WEAPONFRAME2) + MSG_WriteByte(msg, (int32_t)ent->v.weaponframe >> 8); + if(bits & SU_WEAPONALPHA) + MSG_WriteByte(msg, ent->alpha); //for now, weaponalpha = client entity alpha //johnfitz } @@ -951,36 +952,36 @@ void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg) SV_SendClientDatagram ======================= */ -bool SV_SendClientDatagram (client_t *client) +bool SV_SendClientDatagram(client_t *client) { - byte buf[MAX_DATAGRAM]; - sizebuf_t msg; + byte buf[MAX_DATAGRAM]; + sizebuf_t msg; msg.data = buf; msg.maxsize = sizeof(buf); msg.cursize = 0; //johnfitz -- if client is nonlocal, use smaller max size so packets aren't fragmented - if (Q_strcmp(NET_QSocketGetAddressString(client->netconnection), "LOCAL") != 0) + if(Q_strcmp(NET_QSocketGetAddressString(client->netconnection), "LOCAL") != 0) msg.maxsize = DATAGRAM_MTU; //johnfitz - MSG_WriteByte (&msg, svc_time); - MSG_WriteFloat (&msg, sv.time); + MSG_WriteByte(&msg, svc_time); + MSG_WriteFloat(&msg, sv.time); // add the client specific data to the datagram - SV_WriteClientdataToMessage (client->edict, &msg); + SV_WriteClientdataToMessage(client->edict, &msg); - SV_WriteEntitiesToClient (client->edict, &msg); + SV_WriteEntitiesToClient(client->edict, &msg); // copy the server datagram if there is space - if (msg.cursize + sv.datagram.cursize < msg.maxsize) - SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize); + if(msg.cursize + sv.datagram.cursize < msg.maxsize) + SZ_Write(&msg, sv.datagram.data, sv.datagram.cursize); // send the datagram - if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1) + if(NET_SendUnreliableMessage(client->netconnection, &msg) == -1) { - SV_DropClient (true);// if the message couldn't send, kick off + SV_DropClient(true); // if the message couldn't send, kick off return false; } @@ -992,37 +993,37 @@ bool SV_SendClientDatagram (client_t *client) SV_UpdateToReliableMessages ======================= */ -void SV_UpdateToReliableMessages (void) +void SV_UpdateToReliableMessages(void) { - int32_t i, j; + int32_t i, j; client_t *client; // check for changes to be sent over the reliable streams - for (i=0, host_client = svs.clients ; iold_frags != host_client->edict->v.frags) + if(host_client->old_frags != host_client->edict->v.frags) { - for (j=0, client = svs.clients ; jactive) + if(!client->active) continue; - MSG_WriteByte (&client->message, svc_updatefrags); - MSG_WriteByte (&client->message, i); - MSG_WriteShort (&client->message, host_client->edict->v.frags); + MSG_WriteByte(&client->message, svc_updatefrags); + MSG_WriteByte(&client->message, i); + MSG_WriteShort(&client->message, host_client->edict->v.frags); } host_client->old_frags = host_client->edict->v.frags; } } - for (j=0, client = svs.clients ; jactive) + if(!client->active) continue; - SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize); + SZ_Write(&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize); } - SZ_Clear (&sv.reliable_datagram); + SZ_Clear(&sv.reliable_datagram); } @@ -1034,19 +1035,19 @@ Send a nop message without trashing or sending the accumulated client message buffer ======================= */ -void SV_SendNop (client_t *client) +void SV_SendNop(client_t *client) { - sizebuf_t msg; - byte buf[4]; + sizebuf_t msg; + byte buf[4]; msg.data = buf; msg.maxsize = sizeof(buf); msg.cursize = 0; - MSG_WriteChar (&msg, svc_nop); + MSG_WriteChar(&msg, svc_nop); - if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1) - SV_DropClient (true); // if the message couldn't send, kick off + if(NET_SendUnreliableMessage(client->netconnection, &msg) == -1) + SV_DropClient(true); // if the message couldn't send, kick off client->last_message = realtime; } @@ -1055,65 +1056,65 @@ void SV_SendNop (client_t *client) SV_SendClientMessages ======================= */ -void SV_SendClientMessages (void) +void SV_SendClientMessages(void) { - int32_t i; + int32_t i; // update frags, names, etc - SV_UpdateToReliableMessages (); + SV_UpdateToReliableMessages(); // build individual updates - for (i=0, host_client = svs.clients ; iactive) + if(!host_client->active) continue; - if (host_client->spawned) + if(host_client->spawned) { - if (!SV_SendClientDatagram (host_client)) + if(!SV_SendClientDatagram(host_client)) continue; } else { - // the player isn't totally in the game yet - // send small keepalive messages if too much time has passed - // send a full message when the next signon stage has been requested - // some other message data (name changes, etc) may accumulate - // between signon stages - if (!host_client->sendsignon) + // the player isn't totally in the game yet + // send small keepalive messages if too much time has passed + // send a full message when the next signon stage has been requested + // some other message data (name changes, etc) may accumulate + // between signon stages + if(!host_client->sendsignon) { - if (realtime - host_client->last_message > 5) - SV_SendNop (host_client); - continue; // don't send out non-signon messages + if(realtime - host_client->last_message > 5) + SV_SendNop(host_client); + continue; // don't send out non-signon messages } } // check for an overflowed message. Should only happen // on a very fucked up connection that backs up a lot, then // changes level - if (host_client->message.overflowed) + if(host_client->message.overflowed) { - SV_DropClient (true); + SV_DropClient(true); host_client->message.overflowed = false; continue; } - if (host_client->message.cursize || host_client->dropasap) + if(host_client->message.cursize || host_client->dropasap) { - if (!NET_CanSendMessage (host_client->netconnection)) + if(!NET_CanSendMessage(host_client->netconnection)) { // I_Printf ("can't write\n"); continue; } - if (host_client->dropasap) - SV_DropClient (false); // went to another level + if(host_client->dropasap) + SV_DropClient(false); // went to another level else { - if (NET_SendMessage (host_client->netconnection - , &host_client->message) == -1) - SV_DropClient (true); // if the message couldn't send, kick off - SZ_Clear (&host_client->message); + if(NET_SendMessage(host_client->netconnection + , &host_client->message) == -1) + SV_DropClient(true); // if the message couldn't send, kick off + SZ_Clear(&host_client->message); host_client->last_message = realtime; host_client->sendsignon = false; } @@ -1122,7 +1123,7 @@ void SV_SendClientMessages (void) // clear muzzle flashes - SV_CleanupEnts (); + SV_CleanupEnts(); } @@ -1140,18 +1141,18 @@ SV_ModelIndex ================ */ -int32_t SV_ModelIndex (const char *name) +int32_t SV_ModelIndex(const char *name) { - int32_t i; + int32_t i; - if (!name || !name[0]) + if(!name || !name[0]) return 0; - for (i=0 ; ifree) + if(svent->free) continue; - if (entnum > svs.maxclients && !svent->v.modelindex) + if(entnum > svs.maxclients && !svent->v.modelindex) continue; - // - // create entity baseline - // - VectorCopy (svent->v.origin, svent->baseline.origin); - VectorCopy (svent->v.angles, svent->baseline.angles); + // + // create entity baseline + // + VectorCopy(svent->v.origin, svent->baseline.origin); + VectorCopy(svent->v.angles, svent->baseline.angles); svent->baseline.frame = svent->v.frame; svent->baseline.skin = svent->v.skin; - if (entnum > 0 && entnum <= svs.maxclients) + if(entnum > 0 && entnum <= svs.maxclients) { svent->baseline.colormap = entnum; svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl"); @@ -1198,63 +1199,63 @@ void SV_CreateBaseline (void) //johnfitz -- PROTOCOL_FITZQUAKE bits = 0; - if (sv.protocol == PROTOCOL_NETQUAKE) //still want to send baseline in PROTOCOL_NETQUAKE, so reset these values + if(sv.protocol == PROTOCOL_NETQUAKE) //still want to send baseline in PROTOCOL_NETQUAKE, so reset these values { - if (svent->baseline.modelindex & 0xFF00) + if(svent->baseline.modelindex & 0xFF00) svent->baseline.modelindex = 0; - if (svent->baseline.frame & 0xFF00) + if(svent->baseline.frame & 0xFF00) svent->baseline.frame = 0; svent->baseline.alpha = ENTALPHA_DEFAULT; } else //decide which extra data needs to be sent { - if (svent->baseline.modelindex & 0xFF00) + if(svent->baseline.modelindex & 0xFF00) bits |= B_LARGEMODEL; - if (svent->baseline.frame & 0xFF00) + if(svent->baseline.frame & 0xFF00) bits |= B_LARGEFRAME; - if (svent->baseline.alpha != ENTALPHA_DEFAULT) + if(svent->baseline.alpha != ENTALPHA_DEFAULT) bits |= B_ALPHA; } //johnfitz - // - // add to the message - // + // + // add to the message + // //johnfitz -- PROTOCOL_FITZQUAKE - if (bits) - MSG_WriteByte (&sv.signon, svc_spawnbaseline2); + if(bits) + MSG_WriteByte(&sv.signon, svc_spawnbaseline2); else - MSG_WriteByte (&sv.signon, svc_spawnbaseline); + MSG_WriteByte(&sv.signon, svc_spawnbaseline); //johnfitz - MSG_WriteShort (&sv.signon,entnum); + MSG_WriteShort(&sv.signon, entnum); //johnfitz -- PROTOCOL_FITZQUAKE - if (bits) - MSG_WriteByte (&sv.signon, bits); + if(bits) + MSG_WriteByte(&sv.signon, bits); - if (bits & B_LARGEMODEL) - MSG_WriteShort (&sv.signon, svent->baseline.modelindex); + if(bits & B_LARGEMODEL) + MSG_WriteShort(&sv.signon, svent->baseline.modelindex); else - MSG_WriteByte (&sv.signon, svent->baseline.modelindex); + MSG_WriteByte(&sv.signon, svent->baseline.modelindex); - if (bits & B_LARGEFRAME) - MSG_WriteShort (&sv.signon, svent->baseline.frame); + if(bits & B_LARGEFRAME) + MSG_WriteShort(&sv.signon, svent->baseline.frame); else - MSG_WriteByte (&sv.signon, svent->baseline.frame); + MSG_WriteByte(&sv.signon, svent->baseline.frame); //johnfitz - MSG_WriteByte (&sv.signon, svent->baseline.colormap); - MSG_WriteByte (&sv.signon, svent->baseline.skin); - for (i=0 ; i<3 ; i++) + MSG_WriteByte(&sv.signon, svent->baseline.colormap); + MSG_WriteByte(&sv.signon, svent->baseline.skin); + for(i = 0 ; i < 3 ; i++) { MSG_WriteCoord(&sv.signon, svent->baseline.origin[i], sv.protocolflags); MSG_WriteAngle(&sv.signon, svent->baseline.angles[i], sv.protocolflags); } //johnfitz -- PROTOCOL_FITZQUAKE - if (bits & B_ALPHA) - MSG_WriteByte (&sv.signon, svent->baseline.alpha); + if(bits & B_ALPHA) + MSG_WriteByte(&sv.signon, svent->baseline.alpha); //johnfitz } } @@ -1267,21 +1268,21 @@ SV_SendReconnect Tell all the clients that the server is changing levels ================ */ -void SV_SendReconnect (void) +void SV_SendReconnect(void) { - byte data[128]; - sizebuf_t msg; + byte data[128]; + sizebuf_t msg; msg.data = data; msg.cursize = 0; msg.maxsize = sizeof(data); - MSG_WriteChar (&msg, svc_stufftext); - MSG_WriteString (&msg, "reconnect\n"); - NET_SendToAll (&msg, 5.0); + MSG_WriteChar(&msg, svc_stufftext); + MSG_WriteString(&msg, "reconnect\n"); + NET_SendToAll(&msg, 5.0); - if (!isDedicated) - Cmd_ExecuteString ("reconnect\n", src_command); + if(!isDedicated) + Cmd_ExecuteString("reconnect\n", src_command); } @@ -1293,21 +1294,21 @@ Grabs the current state of each client for saving across the transition to another level ================ */ -void SV_SaveSpawnparms (void) +void SV_SaveSpawnparms(void) { - int32_t i, j; + int32_t i, j; svs.serverflags = pr_global_struct->serverflags; - for (i=0, host_client = svs.clients ; iactive) + if(!host_client->active) continue; - // call the progs to get default spawn parms for the new client + // call the progs to get default spawn parms for the new client pr_global_struct->self = EDICT_TO_PROG(host_client->edict); - PR_ExecuteProgram (pr_global_struct->SetChangeParms); - for (j=0 ; jSetChangeParms); + for(j = 0 ; j < NUM_SPAWN_PARMS ; j++) host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j]; } } @@ -1320,53 +1321,53 @@ SV_SpawnServer This is called at the start of each level ================ */ -extern float scr_centertime_off; -void SV_SpawnServer (const char *server) +extern float scr_centertime_off; +void SV_SpawnServer(const char *server) { - static char dummy[8] = { 0,0,0,0,0,0,0,0 }; - edict_t *ent; - int32_t i; + static char dummy[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + edict_t *ent; + int32_t i; // let's not have any servers with no name - if (hostname.string[0] == 0) - Cvar_Set ("hostname", "UNNAMED"); + if(hostname.string[0] == 0) + Cvar_Set("hostname", "UNNAMED"); scr_centertime_off = 0; - Con_DPrintf ("SpawnServer: %s\n",server); - svs.changelevel_issued = false; // now safe to issue another + Con_DPrintf("SpawnServer: %s\n", server); + svs.changelevel_issued = false; // now safe to issue another // // tell all connected clients that we are going to a new level // - if (sv.active) + if(sv.active) { - SV_SendReconnect (); + SV_SendReconnect(); } // // make cvars consistant // - if (coop.value) - Cvar_Set ("deathmatch", "0"); + if(coop.value) + Cvar_Set("deathmatch", "0"); current_skill = (int32_t)(skill.value + 0.5); - if (current_skill < 0) + if(current_skill < 0) current_skill = 0; - if (current_skill > 3) + if(current_skill > 3) current_skill = 3; - Cvar_SetValue ("skill", (float)current_skill); + Cvar_SetValue("skill", (float)current_skill); // // set up the new server // //memset (&sv, 0, sizeof(sv)); - Host_ClearMemory (); + Host_ClearMemory(); - q_strlcpy (sv.name, server, sizeof(sv.name)); + q_strlcpy(sv.name, server, sizeof(sv.name)); sv.protocol = sv_protocol; // johnfitz - if (sv.protocol == PROTOCOL_RMQ) + if(sv.protocol == PROTOCOL_RMQ) { // set up the protocol flags used by this server // (note - these could be cvar-ised so that server admins could choose the protocol features used by their servers) @@ -1375,12 +1376,12 @@ void SV_SpawnServer (const char *server) else sv.protocolflags = 0; // load progs to get entity field count - PR_LoadProgs (); + PR_LoadProgs(); // allocate server memory /* Host_ClearMemory() called above already cleared the whole sv structure */ - sv.max_edicts = CLAMP (MIN_EDICTS,(int32_t)max_edicts.value,MAX_EDICTS); //johnfitz -- max_edicts cvar - sv.edicts = (edict_t *) malloc (sv.max_edicts*pr_edict_size); // ericw -- sv.edicts switched to use malloc() + sv.max_edicts = CLAMP(MIN_EDICTS, (int32_t)max_edicts.value, MAX_EDICTS); //johnfitz -- max_edicts cvar + sv.edicts = (edict_t *) malloc(sv.max_edicts * pr_edict_size); // ericw -- sv.edicts switched to use malloc() sv.datagram.maxsize = sizeof(sv.datagram_buf); sv.datagram.cursize = 0; @@ -1395,11 +1396,11 @@ void SV_SpawnServer (const char *server) sv.signon.data = sv.signon_buf; // leave slots at start for clients only - sv.num_edicts = svs.maxclients+1; - memset(sv.edicts, 0, sv.num_edicts*pr_edict_size); // ericw -- sv.edicts switched to use malloc() - for (i=0 ; inumsubmodels ; i++) + for(i = 1 ; i < sv.worldmodel->numsubmodels ; i++) { - sv.model_precache[1+i] = localmodels[i]; - sv.models[i+1] = Mod_ForName (localmodels[i], false); + sv.model_precache[1 + i] = localmodels[i]; + sv.models[i + 1] = Mod_ForName(localmodels[i], false); } // // load the rest of the entities // ent = EDICT_NUM(0); - memset (&ent->v, 0, progs->entityfields * 4); + memset(&ent->v, 0, progs->entityfields * 4); ent->free = false; ent->v.model = PR_SetEngineString(sv.worldmodel->name); - ent->v.modelindex = 1; // world model + ent->v.modelindex = 1; // world model ent->v.solid = SOLID_BSP; ent->v.movetype = MOVETYPE_PUSH; - if (coop.value) + if(coop.value) pr_global_struct->coop = coop.value; else pr_global_struct->deathmatch = deathmatch.value; @@ -1454,7 +1455,7 @@ void SV_SpawnServer (const char *server) // serverflags are for cross level information (sigils) pr_global_struct->serverflags = svs.serverflags; - ED_LoadFromFile (sv.worldmodel->entities); + ED_LoadFromFile(sv.worldmodel->entities); sv.active = true; @@ -1463,22 +1464,22 @@ void SV_SpawnServer (const char *server) // run two frames to allow everything to settle host_frametime = 0.1; - SV_Physics (); - SV_Physics (); + SV_Physics(); + SV_Physics(); // create a baseline for more efficient communications - SV_CreateBaseline (); + SV_CreateBaseline(); //johnfitz -- warn if signon buffer larger than standard server can handle - if (sv.signon.cursize > 8000-2) //max size that will fit into 8000-sized client->message buffer with 2 extra bytes on the end - Con_DWarning ("%" PRIi32 " byte signon buffer exceeds standard limit of 7998 (max = %" PRIi32 ").\n", sv.signon.cursize, sv.signon.maxsize); + if(sv.signon.cursize > 8000 - 2) //max size that will fit into 8000-sized client->message buffer with 2 extra bytes on the end + Con_DWarning("%" PRIi32 " byte signon buffer exceeds standard limit of 7998 (max = %" PRIi32 ").\n", sv.signon.cursize, sv.signon.maxsize); //johnfitz // send serverinfo to all connected clients - for (i=0,host_client = svs.clients ; iactive) - SV_SendServerinfo (host_client); + for(i = 0, host_client = svs.clients ; i < svs.maxclients ; i++, host_client++) + if(host_client->active) + SV_SendServerinfo(host_client); - Con_DPrintf ("Server spawned.\n"); + Con_DPrintf("Server spawned.\n"); } diff --git a/source/sv_move.c b/source/sv_move.c index 0315341..8cb7e8d 100644 --- a/source/sv_move.c +++ b/source/sv_move.c @@ -23,7 +23,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -#define STEPSIZE 18 +#define STEPSIZE 18 /* ============= @@ -36,31 +36,31 @@ is not a staircase. */ int32_t c_yes, c_no; -bool SV_CheckBottom (edict_t *ent) +bool SV_CheckBottom(edict_t *ent) { - vec3_t mins, maxs, start, stop; - trace_t trace; - int32_t x, y; - float mid, bottom; + vec3_t mins, maxs, start, stop; + trace_t trace; + int32_t x, y; + float mid, bottom; - VectorAdd (ent->v.origin, ent->v.mins, mins); - VectorAdd (ent->v.origin, ent->v.maxs, maxs); + VectorAdd(ent->v.origin, ent->v.mins, mins); + VectorAdd(ent->v.origin, ent->v.maxs, maxs); // if all of the points under the corners are solid world, don't bother // with the tougher checks // the corners must be within 16 of the midpoint start[2] = mins[2] - 1; - for (x=0 ; x<=1 ; x++) - for (y=0 ; y<=1 ; y++) + for(x = 0 ; x <= 1 ; x++) + for(y = 0 ; y <= 1 ; y++) { start[0] = x ? maxs[0] : mins[0]; start[1] = y ? maxs[1] : mins[1]; - if (SV_PointContents (start) != CONTENTS_SOLID) + if(SV_PointContents(start) != CONTENTS_SOLID) goto realcheck; } c_yes++; - return true; // we got out easy + return true; // we got out easy realcheck: c_no++; @@ -70,27 +70,27 @@ realcheck: start[2] = mins[2]; // the midpoint must be within 16 of the bottom - start[0] = stop[0] = (mins[0] + maxs[0])*0.5; - start[1] = stop[1] = (mins[1] + maxs[1])*0.5; - stop[2] = start[2] - 2*STEPSIZE; - trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); + start[0] = stop[0] = (mins[0] + maxs[0]) * 0.5; + start[1] = stop[1] = (mins[1] + maxs[1]) * 0.5; + stop[2] = start[2] - 2 * STEPSIZE; + trace = SV_Move(start, vec3_origin, vec3_origin, stop, true, ent); - if (trace.fraction == 1.0) + if(trace.fraction == 1.0) return false; mid = bottom = trace.endpos[2]; // the corners must be within 16 of the midpoint - for (x=0 ; x<=1 ; x++) - for (y=0 ; y<=1 ; y++) + for(x = 0 ; x <= 1 ; x++) + for(y = 0 ; y <= 1 ; y++) { start[0] = stop[0] = x ? maxs[0] : mins[0]; start[1] = stop[1] = y ? maxs[1] : mins[1]; - trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); + trace = SV_Move(start, vec3_origin, vec3_origin, stop, true, ent); - if (trace.fraction != 1.0 && trace.endpos[2] > bottom) + if(trace.fraction != 1.0 && trace.endpos[2] > bottom) bottom = trace.endpos[2]; - if (trace.fraction == 1.0 || mid - trace.endpos[2] > STEPSIZE) + if(trace.fraction == 1.0 || mid - trace.endpos[2] > STEPSIZE) return false; } @@ -109,48 +109,48 @@ possible, no move is done, false is returned, and pr_global_struct->trace_normal is set to the normal of the blocking wall ============= */ -bool SV_movestep (edict_t *ent, vec3_t move, bool relink) +bool SV_movestep(edict_t *ent, vec3_t move, bool relink) { - float dz; - vec3_t oldorg, neworg, end; - trace_t trace; - int32_t i; - edict_t *enemy; + float dz; + vec3_t oldorg, neworg, end; + trace_t trace; + int32_t i; + edict_t *enemy; // try the move - VectorCopy (ent->v.origin, oldorg); - VectorAdd (ent->v.origin, move, neworg); + VectorCopy(ent->v.origin, oldorg); + VectorAdd(ent->v.origin, move, neworg); // flying monsters don't step up - if ( (int32_t)ent->v.flags & (FL_SWIM | FL_FLY) ) + if((int32_t)ent->v.flags & (FL_SWIM | FL_FLY)) { - // try one move with vertical motion, then one without - for (i=0 ; i<2 ; i++) + // try one move with vertical motion, then one without + for(i = 0 ; i < 2 ; i++) { - VectorAdd (ent->v.origin, move, neworg); + VectorAdd(ent->v.origin, move, neworg); enemy = PROG_TO_EDICT(ent->v.enemy); - if (i == 0 && enemy != sv.edicts) + if(i == 0 && enemy != sv.edicts) { dz = ent->v.origin[2] - PROG_TO_EDICT(ent->v.enemy)->v.origin[2]; - if (dz > 40) + if(dz > 40) neworg[2] -= 8; - if (dz < 30) + if(dz < 30) neworg[2] += 8; } - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, neworg, false, ent); + trace = SV_Move(ent->v.origin, ent->v.mins, ent->v.maxs, neworg, false, ent); - if (trace.fraction == 1) + if(trace.fraction == 1) { - if ( ((int32_t)ent->v.flags & FL_SWIM) && SV_PointContents(trace.endpos) == CONTENTS_EMPTY ) - return false; // swim monster left water + if(((int32_t)ent->v.flags & FL_SWIM) && SV_PointContents(trace.endpos) == CONTENTS_EMPTY) + return false; // swim monster left water - VectorCopy (trace.endpos, ent->v.origin); - if (relink) - SV_LinkEdict (ent, true); + VectorCopy(trace.endpos, ent->v.origin); + if(relink) + SV_LinkEdict(ent, true); return true; } - if (enemy == sv.edicts) + if(enemy == sv.edicts) break; } @@ -159,54 +159,55 @@ bool SV_movestep (edict_t *ent, vec3_t move, bool relink) // push down from a step height above the wished position neworg[2] += STEPSIZE; - VectorCopy (neworg, end); - end[2] -= STEPSIZE*2; + VectorCopy(neworg, end); + end[2] -= STEPSIZE * 2; - trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); + trace = SV_Move(neworg, ent->v.mins, ent->v.maxs, end, false, ent); - if (trace.allsolid) + if(trace.allsolid) return false; - if (trace.startsolid) + if(trace.startsolid) { neworg[2] -= STEPSIZE; - trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); - if (trace.allsolid || trace.startsolid) + trace = SV_Move(neworg, ent->v.mins, ent->v.maxs, end, false, ent); + if(trace.allsolid || trace.startsolid) return false; } - if (trace.fraction == 1) + if(trace.fraction == 1) { - // if monster had the ground pulled out, go ahead and fall - if ( (int32_t)ent->v.flags & FL_PARTIALGROUND ) + // if monster had the ground pulled out, go ahead and fall + if((int32_t)ent->v.flags & FL_PARTIALGROUND) { - VectorAdd (ent->v.origin, move, ent->v.origin); - if (relink) - SV_LinkEdict (ent, true); + VectorAdd(ent->v.origin, move, ent->v.origin); + if(relink) + SV_LinkEdict(ent, true); ent->v.flags = (int32_t)ent->v.flags & ~FL_ONGROUND; // Con_Printf ("fall down\n"); return true; } - return false; // walked off an edge + return false; // walked off an edge } // check point traces down for dangling corners - VectorCopy (trace.endpos, ent->v.origin); + VectorCopy(trace.endpos, ent->v.origin); - if (!SV_CheckBottom (ent)) + if(!SV_CheckBottom(ent)) { - if ( (int32_t)ent->v.flags & FL_PARTIALGROUND ) - { // entity had floor mostly pulled out from underneath it + if((int32_t)ent->v.flags & FL_PARTIALGROUND) + { + // entity had floor mostly pulled out from underneath it // and is trying to correct - if (relink) - SV_LinkEdict (ent, true); + if(relink) + SV_LinkEdict(ent, true); return true; } - VectorCopy (oldorg, ent->v.origin); + VectorCopy(oldorg, ent->v.origin); return false; } - if ( (int32_t)ent->v.flags & FL_PARTIALGROUND ) + if((int32_t)ent->v.flags & FL_PARTIALGROUND) { // Con_Printf ("back on ground\n"); ent->v.flags = (int32_t)ent->v.flags & ~FL_PARTIALGROUND; @@ -214,8 +215,8 @@ bool SV_movestep (edict_t *ent, vec3_t move, bool relink) ent->v.groundentity = EDICT_TO_PROG(trace.ent); // the move is ok - if (relink) - SV_LinkEdict (ent, true); + if(relink) + SV_LinkEdict(ent, true); return true; } @@ -231,32 +232,33 @@ facing it. ====================== */ -void PF_changeyaw (void); -bool SV_StepDirection (edict_t *ent, float yaw, float dist) +void PF_changeyaw(void); +bool SV_StepDirection(edict_t *ent, float yaw, float dist) { - vec3_t move, oldorigin; - float delta; + vec3_t move, oldorigin; + float delta; ent->v.ideal_yaw = yaw; PF_changeyaw(); - yaw = yaw*M_PI*2 / 360; - move[0] = cos(yaw)*dist; - move[1] = sin(yaw)*dist; + yaw = yaw * M_PI * 2 / 360; + move[0] = cos(yaw) * dist; + move[1] = sin(yaw) * dist; move[2] = 0; - VectorCopy (ent->v.origin, oldorigin); - if (SV_movestep (ent, move, false)) + VectorCopy(ent->v.origin, oldorigin); + if(SV_movestep(ent, move, false)) { delta = ent->v.angles[YAW] - ent->v.ideal_yaw; - if (delta > 45 && delta < 315) - { // not turned far enough, so don't take the step - VectorCopy (oldorigin, ent->v.origin); + if(delta > 45 && delta < 315) + { + // not turned far enough, so don't take the step + VectorCopy(oldorigin, ent->v.origin); } - SV_LinkEdict (ent, true); + SV_LinkEdict(ent, true); return true; } - SV_LinkEdict (ent, true); + SV_LinkEdict(ent, true); return false; } @@ -267,7 +269,7 @@ SV_FixCheckBottom ====================== */ -void SV_FixCheckBottom (edict_t *ent) +void SV_FixCheckBottom(edict_t *ent) { // Con_Printf ("SV_FixCheckBottom\n"); @@ -282,87 +284,87 @@ SV_NewChaseDir ================ */ -#define DI_NODIR -1 -void SV_NewChaseDir (edict_t *actor, edict_t *enemy, float dist) +#define DI_NODIR -1 +void SV_NewChaseDir(edict_t *actor, edict_t *enemy, float dist) { - float deltax,deltay; - float d[3]; - float tdir, olddir, turnaround; + float deltax, deltay; + float d[3]; + float tdir, olddir, turnaround; - olddir = anglemod( (int32_t)(actor->v.ideal_yaw/45)*45 ); + olddir = anglemod((int32_t)(actor->v.ideal_yaw / 45) * 45); turnaround = anglemod(olddir - 180); deltax = enemy->v.origin[0] - actor->v.origin[0]; deltay = enemy->v.origin[1] - actor->v.origin[1]; - if (deltax>10) - d[1]= 0; - else if (deltax<-10) - d[1]= 180; + if(deltax > 10) + d[1] = 0; + else if(deltax < -10) + d[1] = 180; else - d[1]= DI_NODIR; - if (deltay<-10) - d[2]= 270; - else if (deltay>10) - d[2]= 90; + d[1] = DI_NODIR; + if(deltay < -10) + d[2] = 270; + else if(deltay > 10) + d[2] = 90; else - d[2]= DI_NODIR; + d[2] = DI_NODIR; // try direct route - if (d[1] != DI_NODIR && d[2] != DI_NODIR) + if(d[1] != DI_NODIR && d[2] != DI_NODIR) { - if (d[1] == 0) + if(d[1] == 0) tdir = d[2] == 90 ? 45 : 315; else tdir = d[2] == 90 ? 135 : 215; - if (tdir != turnaround && SV_StepDirection(actor, tdir, dist)) + if(tdir != turnaround && SV_StepDirection(actor, tdir, dist)) return; } // try other directions - if ( ((rand()&3) & 1) || abs((int32_t)deltay)>abs((int32_t)deltax)) // ericw -- explicit int32_t cast to suppress clang suggestion to use fabsf + if(((rand() & 3) & 1) || abs((int32_t)deltay) > abs((int32_t)deltax)) // ericw -- explicit int32_t cast to suppress clang suggestion to use fabsf { - tdir=d[1]; - d[1]=d[2]; - d[2]=tdir; + tdir = d[1]; + d[1] = d[2]; + d[2] = tdir; } - if (d[1]!=DI_NODIR && d[1]!=turnaround - && SV_StepDirection(actor, d[1], dist)) - return; + if(d[1] != DI_NODIR && d[1] != turnaround + && SV_StepDirection(actor, d[1], dist)) + return; - if (d[2]!=DI_NODIR && d[2]!=turnaround - && SV_StepDirection(actor, d[2], dist)) - return; + if(d[2] != DI_NODIR && d[2] != turnaround + && SV_StepDirection(actor, d[2], dist)) + return; -/* there is no direct path to the player, so pick another direction */ + /* there is no direct path to the player, so pick another direction */ - if (olddir!=DI_NODIR && SV_StepDirection(actor, olddir, dist)) - return; + if(olddir != DI_NODIR && SV_StepDirection(actor, olddir, dist)) + return; - if (rand()&1) /*randomly determine direction of search*/ + if(rand() & 1) /*randomly determine direction of search*/ { - for (tdir=0 ; tdir<=315 ; tdir += 45) - if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) - return; + for(tdir = 0 ; tdir <= 315 ; tdir += 45) + if(tdir != turnaround && SV_StepDirection(actor, tdir, dist)) + return; } else { - for (tdir=315 ; tdir >=0 ; tdir -= 45) - if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) - return; + for(tdir = 315 ; tdir >= 0 ; tdir -= 45) + if(tdir != turnaround && SV_StepDirection(actor, tdir, dist)) + return; } - if (turnaround != DI_NODIR && SV_StepDirection(actor, turnaround, dist) ) - return; + if(turnaround != DI_NODIR && SV_StepDirection(actor, turnaround, dist)) + return; - actor->v.ideal_yaw = olddir; // can't move + actor->v.ideal_yaw = olddir; // can't move // if a bridge was pulled out from underneath a monster, it may not have // a valid standing position at all - if (!SV_CheckBottom (actor)) - SV_FixCheckBottom (actor); + if(!SV_CheckBottom(actor)) + SV_FixCheckBottom(actor); } @@ -372,15 +374,15 @@ SV_CloseEnough ====================== */ -bool SV_CloseEnough (edict_t *ent, edict_t *goal, float dist) +bool SV_CloseEnough(edict_t *ent, edict_t *goal, float dist) { - int32_t i; + int32_t i; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { - if (goal->v.absmin[i] > ent->v.absmax[i] + dist) + if(goal->v.absmin[i] > ent->v.absmax[i] + dist) return false; - if (goal->v.absmax[i] < ent->v.absmin[i] - dist) + if(goal->v.absmax[i] < ent->v.absmin[i] - dist) return false; } return true; @@ -392,30 +394,30 @@ SV_MoveToGoal ====================== */ -void SV_MoveToGoal (void) +void SV_MoveToGoal(void) { - edict_t *ent, *goal; - float dist; + edict_t *ent, *goal; + float dist; ent = PROG_TO_EDICT(pr_global_struct->self); goal = PROG_TO_EDICT(ent->v.goalentity); dist = G_FLOAT(OFS_PARM0); - if ( !( (int32_t)ent->v.flags & (FL_ONGROUND|FL_FLY|FL_SWIM) ) ) + if(!((int32_t)ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM))) { G_FLOAT(OFS_RETURN) = 0; return; } // if the next step hits the enemy, return immediately - if ( PROG_TO_EDICT(ent->v.enemy) != sv.edicts && SV_CloseEnough (ent, goal, dist) ) + if(PROG_TO_EDICT(ent->v.enemy) != sv.edicts && SV_CloseEnough(ent, goal, dist)) return; // bump around... - if ( (rand()&3)==1 || - !SV_StepDirection (ent, ent->v.ideal_yaw, dist)) + if((rand() & 3) == 1 || + !SV_StepDirection(ent, ent->v.ideal_yaw, dist)) { - SV_NewChaseDir (ent, goal, dist); + SV_NewChaseDir(ent, goal, dist); } } diff --git a/source/sv_phys.c b/source/sv_phys.c index b91bb87..aa5e256 100644 --- a/source/sv_phys.c +++ b/source/sv_phys.c @@ -41,41 +41,41 @@ solid_edge items only clip against bsp models. */ -cvar_t sv_friction = {"sv_friction","4",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t sv_stopspeed = {"sv_stopspeed","100",CVAR_NONE}; -cvar_t sv_gravity = {"sv_gravity","800",CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t sv_maxvelocity = {"sv_maxvelocity","2000",CVAR_NONE}; -cvar_t sv_nostep = {"sv_nostep","0",CVAR_NONE}; -cvar_t sv_freezenonclients = {"sv_freezenonclients","0",CVAR_NONE}; +cvar_t sv_friction = {"sv_friction", "4", CVAR_NOTIFY | CVAR_SERVERINFO}; +cvar_t sv_stopspeed = {"sv_stopspeed", "100", CVAR_NONE}; +cvar_t sv_gravity = {"sv_gravity", "800", CVAR_NOTIFY | CVAR_SERVERINFO}; +cvar_t sv_maxvelocity = {"sv_maxvelocity", "2000", CVAR_NONE}; +cvar_t sv_nostep = {"sv_nostep", "0", CVAR_NONE}; +cvar_t sv_freezenonclients = {"sv_freezenonclients", "0", CVAR_NONE}; -#define MOVE_EPSILON 0.01 +#define MOVE_EPSILON 0.01 -void SV_Physics_Toss (edict_t *ent); +void SV_Physics_Toss(edict_t *ent); /* ================ SV_CheckAllEnts ================ */ -void SV_CheckAllEnts (void) +void SV_CheckAllEnts(void) { - int32_t e; - edict_t *check; + int32_t e; + edict_t *check; // see if any solid entities are inside the final position check = NEXT_EDICT(sv.edicts); - for (e=1 ; efree) + if(check->free) continue; - if (check->v.movetype == MOVETYPE_PUSH - || check->v.movetype == MOVETYPE_NONE - || check->v.movetype == MOVETYPE_NOCLIP) + if(check->v.movetype == MOVETYPE_PUSH + || check->v.movetype == MOVETYPE_NONE + || check->v.movetype == MOVETYPE_NOCLIP) continue; - if (SV_TestEntityPosition (check)) - Con_Printf ("entity in invalid position\n"); + if(SV_TestEntityPosition(check)) + Con_Printf("entity in invalid position\n"); } } @@ -84,28 +84,28 @@ void SV_CheckAllEnts (void) SV_CheckVelocity ================ */ -void SV_CheckVelocity (edict_t *ent) +void SV_CheckVelocity(edict_t *ent) { - int32_t i; + int32_t i; // // bound velocity // - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { - if (IS_NAN(ent->v.velocity[i])) + if(IS_NAN(ent->v.velocity[i])) { - Con_Printf ("Got a NaN velocity on %s\n", PR_GetString(ent->v.classname)); + Con_Printf("Got a NaN velocity on %s\n", PR_GetString(ent->v.classname)); ent->v.velocity[i] = 0; } - if (IS_NAN(ent->v.origin[i])) + if(IS_NAN(ent->v.origin[i])) { - Con_Printf ("Got a NaN origin on %s\n", PR_GetString(ent->v.classname)); + Con_Printf("Got a NaN origin on %s\n", PR_GetString(ent->v.classname)); ent->v.origin[i] = 0; } - if (ent->v.velocity[i] > sv_maxvelocity.value) + if(ent->v.velocity[i] > sv_maxvelocity.value) ent->v.velocity[i] = sv_maxvelocity.value; - else if (ent->v.velocity[i] < -sv_maxvelocity.value) + else if(ent->v.velocity[i] < -sv_maxvelocity.value) ent->v.velocity[i] = -sv_maxvelocity.value; } } @@ -120,20 +120,20 @@ in a frame. Not used for pushmove objects, because they must be exact. Returns false if the entity removed itself. ============= */ -bool SV_RunThink (edict_t *ent) +bool SV_RunThink(edict_t *ent) { - float thinktime; - float oldframe; //johnfitz - int32_t i; //johnfitz + float thinktime; + float oldframe; //johnfitz + int32_t i; //johnfitz thinktime = ent->v.nextthink; - if (thinktime <= 0 || thinktime > sv.time + host_frametime) + if(thinktime <= 0 || thinktime > sv.time + host_frametime) return true; - if (thinktime < sv.time) - thinktime = sv.time; // don't let things stay in the past. - // it is possible to start that way - // by a trigger with a local time. + if(thinktime < sv.time) + thinktime = sv.time; // don't let things stay in the past. + // it is possible to start that way + // by a trigger with a local time. oldframe = ent->v.frame; //johnfitz @@ -141,16 +141,16 @@ bool SV_RunThink (edict_t *ent) pr_global_struct->time = thinktime; pr_global_struct->self = EDICT_TO_PROG(ent); pr_global_struct->other = EDICT_TO_PROG(sv.edicts); - PR_ExecuteProgram (ent->v.think); + PR_ExecuteProgram(ent->v.think); //johnfitz -- PROTOCOL_FITZQUAKE //capture interval to nextthink here and send it to client for better //lerp timing, but only if interval is not 0.1 (which client assumes) ent->sendinterval = false; - if (!ent->free && ent->v.nextthink && (ent->v.movetype == MOVETYPE_STEP || ent->v.frame != oldframe)) + if(!ent->free && ent->v.nextthink && (ent->v.movetype == MOVETYPE_STEP || ent->v.frame != oldframe)) { - i = Q_rint((ent->v.nextthink-thinktime)*255); - if (i >= 0 && i < 256 && i != 25 && i != 26) //25 and 26 are close enough to 0.1 to not send + i = Q_rint((ent->v.nextthink - thinktime) * 255); + if(i >= 0 && i < 256 && i != 25 && i != 26) //25 and 26 are close enough to 0.1 to not send ent->sendinterval = true; } //johnfitz @@ -165,26 +165,26 @@ SV_Impact Two entities have touched, so run their touch functions ================== */ -void SV_Impact (edict_t *e1, edict_t *e2) +void SV_Impact(edict_t *e1, edict_t *e2) { - int32_t old_self, old_other; + int32_t old_self, old_other; old_self = pr_global_struct->self; old_other = pr_global_struct->other; pr_global_struct->time = sv.time; - if (e1->v.touch && e1->v.solid != SOLID_NOT) + if(e1->v.touch && e1->v.solid != SOLID_NOT) { pr_global_struct->self = EDICT_TO_PROG(e1); pr_global_struct->other = EDICT_TO_PROG(e2); - PR_ExecuteProgram (e1->v.touch); + PR_ExecuteProgram(e1->v.touch); } - if (e2->v.touch && e2->v.solid != SOLID_NOT) + if(e2->v.touch && e2->v.solid != SOLID_NOT) { pr_global_struct->self = EDICT_TO_PROG(e2); pr_global_struct->other = EDICT_TO_PROG(e1); - PR_ExecuteProgram (e2->v.touch); + PR_ExecuteProgram(e2->v.touch); } pr_global_struct->self = old_self; @@ -200,27 +200,27 @@ Slide off of the impacting object returns the blocked flags (1 = floor, 2 = step / wall) ================== */ -#define STOP_EPSILON 0.1 +#define STOP_EPSILON 0.1 -int32_t ClipVelocity (vec3_t in, vec3_t normal, vec3_t out, float overbounce) +int32_t ClipVelocity(vec3_t in, vec3_t normal, vec3_t out, float overbounce) { - float backoff; - float change; - int32_t i, blocked; + float backoff; + float change; + int32_t i, blocked; blocked = 0; - if (normal[2] > 0) - blocked |= 1; // floor - if (!normal[2]) - blocked |= 2; // step + if(normal[2] > 0) + blocked |= 1; // floor + if(!normal[2]) + blocked |= 2; // step - backoff = DotProduct (in, normal) * overbounce; + backoff = DotProduct(in, normal) * overbounce; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { - change = normal[i]*backoff; + change = normal[i] * backoff; out[i] = in[i] - change; - if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON) + if(out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON) out[i] = 0; } @@ -240,135 +240,140 @@ Returns the clipflags if the velocity was modified (hit something solid) If steptrace is not NULL, the trace of any vertical wall hit will be stored ============ */ -#define MAX_CLIP_PLANES 5 -int32_t SV_FlyMove (edict_t *ent, float time, trace_t *steptrace) +#define MAX_CLIP_PLANES 5 +int32_t SV_FlyMove(edict_t *ent, float time, trace_t *steptrace) { - int32_t bumpcount, numbumps; - vec3_t dir; - float d; - int32_t numplanes; - vec3_t planes[MAX_CLIP_PLANES]; - vec3_t primal_velocity, original_velocity, new_velocity; - int32_t i, j; - trace_t trace; - vec3_t end; - float time_left; - int32_t blocked; + int32_t bumpcount, numbumps; + vec3_t dir; + float d; + int32_t numplanes; + vec3_t planes[MAX_CLIP_PLANES]; + vec3_t primal_velocity, original_velocity, new_velocity; + int32_t i, j; + trace_t trace; + vec3_t end; + float time_left; + int32_t blocked; numbumps = 4; blocked = 0; - VectorCopy (ent->v.velocity, original_velocity); - VectorCopy (ent->v.velocity, primal_velocity); + VectorCopy(ent->v.velocity, original_velocity); + VectorCopy(ent->v.velocity, primal_velocity); numplanes = 0; time_left = time; - for (bumpcount=0 ; bumpcountv.velocity[0] && !ent->v.velocity[1] && !ent->v.velocity[2]) + if(!ent->v.velocity[0] && !ent->v.velocity[1] && !ent->v.velocity[2]) break; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) end[i] = ent->v.origin[i] + time_left * ent->v.velocity[i]; - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); + trace = SV_Move(ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); - if (trace.allsolid) - { // entity is trapped in another solid - VectorCopy (vec3_origin, ent->v.velocity); + if(trace.allsolid) + { + // entity is trapped in another solid + VectorCopy(vec3_origin, ent->v.velocity); return 3; } - if (trace.fraction > 0) - { // actually covered some distance - VectorCopy (trace.endpos, ent->v.origin); - VectorCopy (ent->v.velocity, original_velocity); + if(trace.fraction > 0) + { + // actually covered some distance + VectorCopy(trace.endpos, ent->v.origin); + VectorCopy(ent->v.velocity, original_velocity); numplanes = 0; } - if (trace.fraction == 1) - break; // moved the entire distance + if(trace.fraction == 1) + break; // moved the entire distance - if (!trace.ent) - Sys_Error ("SV_FlyMove: !trace.ent"); + if(!trace.ent) + Sys_Error("SV_FlyMove: !trace.ent"); - if (trace.plane.normal[2] > 0.7) + if(trace.plane.normal[2] > 0.7) { - blocked |= 1; // floor - if (trace.ent->v.solid == SOLID_BSP) + blocked |= 1; // floor + if(trace.ent->v.solid == SOLID_BSP) { - ent->v.flags = (int32_t)ent->v.flags | FL_ONGROUND; + ent->v.flags = (int32_t)ent->v.flags | FL_ONGROUND; ent->v.groundentity = EDICT_TO_PROG(trace.ent); } } - if (!trace.plane.normal[2]) + if(!trace.plane.normal[2]) { - blocked |= 2; // step - if (steptrace) - *steptrace = trace; // save for player extrafriction + blocked |= 2; // step + if(steptrace) + *steptrace = trace; // save for player extrafriction } // // run the impact function // - SV_Impact (ent, trace.ent); - if (ent->free) - break; // removed by the impact function + SV_Impact(ent, trace.ent); + if(ent->free) + break; // removed by the impact function time_left -= time_left * trace.fraction; - // cliped to another plane - if (numplanes >= MAX_CLIP_PLANES) - { // this shouldn't really happen - VectorCopy (vec3_origin, ent->v.velocity); + // cliped to another plane + if(numplanes >= MAX_CLIP_PLANES) + { + // this shouldn't really happen + VectorCopy(vec3_origin, ent->v.velocity); return 3; } - VectorCopy (trace.plane.normal, planes[numplanes]); + VectorCopy(trace.plane.normal, planes[numplanes]); numplanes++; // // modify original_velocity so it parallels all of the clip planes // - for (i=0 ; iv.velocity); + if(i != numplanes) + { + // go along this plane + VectorCopy(new_velocity, ent->v.velocity); } else - { // go along the crease - if (numplanes != 2) + { + // go along the crease + if(numplanes != 2) { // Con_Printf ("clip velocity, numplanes == %" PRIi32 "\n",numplanes); - VectorCopy (vec3_origin, ent->v.velocity); + VectorCopy(vec3_origin, ent->v.velocity); return 7; } - CrossProduct (planes[0], planes[1], dir); - d = DotProduct (dir, ent->v.velocity); - VectorScale (dir, d, ent->v.velocity); + CrossProduct(planes[0], planes[1], dir); + d = DotProduct(dir, ent->v.velocity); + VectorScale(dir, d, ent->v.velocity); } // // if original velocity is against the original velocity, stop dead // to avoid tiny occilations in sloping corners // - if (DotProduct (ent->v.velocity, primal_velocity) <= 0) + if(DotProduct(ent->v.velocity, primal_velocity) <= 0) { - VectorCopy (vec3_origin, ent->v.velocity); + VectorCopy(vec3_origin, ent->v.velocity); return blocked; } } @@ -383,13 +388,13 @@ SV_AddGravity ============ */ -void SV_AddGravity (edict_t *ent) +void SV_AddGravity(edict_t *ent) { - float ent_gravity; - eval_t *val; + float ent_gravity; + eval_t *val; val = GetEdictFieldValue(ent, "gravity"); - if (val && val->_float) + if(val && val->_float) ent_gravity = val->_float; else ent_gravity = 1.0; @@ -413,26 +418,26 @@ SV_PushEntity Does not change the entities velocity at all ============ */ -trace_t SV_PushEntity (edict_t *ent, vec3_t push) +trace_t SV_PushEntity(edict_t *ent, vec3_t push) { - trace_t trace; - vec3_t end; + trace_t trace; + vec3_t end; - VectorAdd (ent->v.origin, push, end); + VectorAdd(ent->v.origin, push, end); - if (ent->v.movetype == MOVETYPE_FLYMISSILE) - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_MISSILE, ent); - else if (ent->v.solid == SOLID_TRIGGER || ent->v.solid == SOLID_NOT) - // only clip against bmodels - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_NOMONSTERS, ent); + if(ent->v.movetype == MOVETYPE_FLYMISSILE) + trace = SV_Move(ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_MISSILE, ent); + else if(ent->v.solid == SOLID_TRIGGER || ent->v.solid == SOLID_NOT) + // only clip against bmodels + trace = SV_Move(ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_NOMONSTERS, ent); else - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_NORMAL, ent); + trace = SV_Move(ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_NORMAL, ent); - VectorCopy (trace.endpos, ent->v.origin); - SV_LinkEdict (ent, true); + VectorCopy(trace.endpos, ent->v.origin); + SV_LinkEdict(ent, true); - if (trace.ent) - SV_Impact (ent, trace.ent); + if(trace.ent) + SV_Impact(ent, trace.ent); return trace; } @@ -443,128 +448,130 @@ trace_t SV_PushEntity (edict_t *ent, vec3_t push) SV_PushMove ============ */ -void SV_PushMove (edict_t *pusher, float movetime) +void SV_PushMove(edict_t *pusher, float movetime) { - int32_t i, e; - edict_t *check, *block; - vec3_t mins, maxs, move; - vec3_t entorig, pushorig; - int32_t num_moved; - edict_t **moved_edict; //johnfitz -- dynamically allocate - vec3_t *moved_from; //johnfitz -- dynamically allocate - int32_t mark; //johnfitz + int32_t i, e; + edict_t *check, *block; + vec3_t mins, maxs, move; + vec3_t entorig, pushorig; + int32_t num_moved; + edict_t **moved_edict; //johnfitz -- dynamically allocate + vec3_t *moved_from; //johnfitz -- dynamically allocate + int32_t mark; //johnfitz - if (!pusher->v.velocity[0] && !pusher->v.velocity[1] && !pusher->v.velocity[2]) + if(!pusher->v.velocity[0] && !pusher->v.velocity[1] && !pusher->v.velocity[2]) { pusher->v.ltime += movetime; return; } - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { move[i] = pusher->v.velocity[i] * movetime; mins[i] = pusher->v.absmin[i] + move[i]; maxs[i] = pusher->v.absmax[i] + move[i]; } - VectorCopy (pusher->v.origin, pushorig); + VectorCopy(pusher->v.origin, pushorig); // move the pusher to it's final position - VectorAdd (pusher->v.origin, move, pusher->v.origin); + VectorAdd(pusher->v.origin, move, pusher->v.origin); pusher->v.ltime += movetime; - SV_LinkEdict (pusher, false); + SV_LinkEdict(pusher, false); //johnfitz -- dynamically allocate - mark = Hunk_LowMark (); - moved_edict = (edict_t **) Hunk_Alloc (sv.num_edicts*sizeof(edict_t *)); - moved_from = (vec3_t *) Hunk_Alloc (sv.num_edicts*sizeof(vec3_t)); + mark = Hunk_LowMark(); + moved_edict = (edict_t **) Hunk_Alloc(sv.num_edicts * sizeof(edict_t *)); + moved_from = (vec3_t *) Hunk_Alloc(sv.num_edicts * sizeof(vec3_t)); //johnfitz // see if any solid entities are inside the final position num_moved = 0; check = NEXT_EDICT(sv.edicts); - for (e=1 ; efree) + if(check->free) continue; - if (check->v.movetype == MOVETYPE_PUSH - || check->v.movetype == MOVETYPE_NONE - || check->v.movetype == MOVETYPE_NOCLIP) + if(check->v.movetype == MOVETYPE_PUSH + || check->v.movetype == MOVETYPE_NONE + || check->v.movetype == MOVETYPE_NOCLIP) continue; - // if the entity is standing on the pusher, it will definately be moved - if ( ! ( ((int32_t)check->v.flags & FL_ONGROUND) - && PROG_TO_EDICT(check->v.groundentity) == pusher) ) + // if the entity is standing on the pusher, it will definately be moved + if(!(((int32_t)check->v.flags & FL_ONGROUND) + && PROG_TO_EDICT(check->v.groundentity) == pusher)) { - if ( check->v.absmin[0] >= maxs[0] - || check->v.absmin[1] >= maxs[1] - || check->v.absmin[2] >= maxs[2] - || check->v.absmax[0] <= mins[0] - || check->v.absmax[1] <= mins[1] - || check->v.absmax[2] <= mins[2] ) + if(check->v.absmin[0] >= maxs[0] + || check->v.absmin[1] >= maxs[1] + || check->v.absmin[2] >= maxs[2] + || check->v.absmax[0] <= mins[0] + || check->v.absmax[1] <= mins[1] + || check->v.absmax[2] <= mins[2]) continue; - // see if the ent's bbox is inside the pusher's final position - if (!SV_TestEntityPosition (check)) + // see if the ent's bbox is inside the pusher's final position + if(!SV_TestEntityPosition(check)) continue; } - // remove the onground flag for non-players - if (check->v.movetype != MOVETYPE_WALK) + // remove the onground flag for non-players + if(check->v.movetype != MOVETYPE_WALK) check->v.flags = (int32_t)check->v.flags & ~FL_ONGROUND; - VectorCopy (check->v.origin, entorig); - VectorCopy (check->v.origin, moved_from[num_moved]); + VectorCopy(check->v.origin, entorig); + VectorCopy(check->v.origin, moved_from[num_moved]); moved_edict[num_moved] = check; num_moved++; // try moving the contacted entity pusher->v.solid = SOLID_NOT; - SV_PushEntity (check, move); + SV_PushEntity(check, move); pusher->v.solid = SOLID_BSP; - // if it is still inside the pusher, block - block = SV_TestEntityPosition (check); - if (block) - { // fail the move - if (check->v.mins[0] == check->v.maxs[0]) + // if it is still inside the pusher, block + block = SV_TestEntityPosition(check); + if(block) + { + // fail the move + if(check->v.mins[0] == check->v.maxs[0]) continue; - if (check->v.solid == SOLID_NOT || check->v.solid == SOLID_TRIGGER) - { // corpse + if(check->v.solid == SOLID_NOT || check->v.solid == SOLID_TRIGGER) + { + // corpse check->v.mins[0] = check->v.mins[1] = 0; - VectorCopy (check->v.mins, check->v.maxs); + VectorCopy(check->v.mins, check->v.maxs); continue; } - VectorCopy (entorig, check->v.origin); - SV_LinkEdict (check, true); + VectorCopy(entorig, check->v.origin); + SV_LinkEdict(check, true); - VectorCopy (pushorig, pusher->v.origin); - SV_LinkEdict (pusher, false); + VectorCopy(pushorig, pusher->v.origin); + SV_LinkEdict(pusher, false); pusher->v.ltime -= movetime; // if the pusher has a "blocked" function, call it // otherwise, just stay in place until the obstacle is gone - if (pusher->v.blocked) + if(pusher->v.blocked) { pr_global_struct->self = EDICT_TO_PROG(pusher); pr_global_struct->other = EDICT_TO_PROG(check); - PR_ExecuteProgram (pusher->v.blocked); + PR_ExecuteProgram(pusher->v.blocked); } - // move back any entities we already moved - for (i=0 ; iv.origin); - SV_LinkEdict (moved_edict[i], false); + VectorCopy(moved_from[i], moved_edict[i]->v.origin); + SV_LinkEdict(moved_edict[i], false); } - Hunk_FreeToLowMark (mark); //johnfitz + Hunk_FreeToLowMark(mark); //johnfitz return; } } - Hunk_FreeToLowMark (mark); //johnfitz + Hunk_FreeToLowMark(mark); //johnfitz } @@ -574,37 +581,37 @@ SV_Physics_Pusher ================ */ -void SV_Physics_Pusher (edict_t *ent) +void SV_Physics_Pusher(edict_t *ent) { - float thinktime; - float oldltime; - float movetime; + float thinktime; + float oldltime; + float movetime; oldltime = ent->v.ltime; thinktime = ent->v.nextthink; - if (thinktime < ent->v.ltime + host_frametime) + if(thinktime < ent->v.ltime + host_frametime) { movetime = thinktime - ent->v.ltime; - if (movetime < 0) + if(movetime < 0) movetime = 0; } else movetime = host_frametime; - if (movetime) + if(movetime) { - SV_PushMove (ent, movetime); // advances ent->v.ltime if not blocked + SV_PushMove(ent, movetime); // advances ent->v.ltime if not blocked } - if (thinktime > oldltime && thinktime <= ent->v.ltime) + if(thinktime > oldltime && thinktime <= ent->v.ltime) { ent->v.nextthink = 0; pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(ent); pr_global_struct->other = EDICT_TO_PROG(sv.edicts); - PR_ExecuteProgram (ent->v.think); - if (ent->free) + PR_ExecuteProgram(ent->v.think); + if(ent->free) return; } @@ -627,44 +634,44 @@ This is a big hack to try and fix the rare case of getting stuck in the world clipping hull. ============= */ -void SV_CheckStuck (edict_t *ent) +void SV_CheckStuck(edict_t *ent) { - int32_t i, j; - int32_t z; - vec3_t org; + int32_t i, j; + int32_t z; + vec3_t org; - if (!SV_TestEntityPosition(ent)) + if(!SV_TestEntityPosition(ent)) { - VectorCopy (ent->v.origin, ent->v.oldorigin); + VectorCopy(ent->v.origin, ent->v.oldorigin); return; } - VectorCopy (ent->v.origin, org); - VectorCopy (ent->v.oldorigin, ent->v.origin); - if (!SV_TestEntityPosition(ent)) + VectorCopy(ent->v.origin, org); + VectorCopy(ent->v.oldorigin, ent->v.origin); + if(!SV_TestEntityPosition(ent)) { - Con_DPrintf ("Unstuck.\n"); - SV_LinkEdict (ent, true); + Con_DPrintf("Unstuck.\n"); + SV_LinkEdict(ent, true); return; } - for (z=0 ; z< 18 ; z++) - for (i=-1 ; i <= 1 ; i++) - for (j=-1 ; j <= 1 ; j++) + for(z = 0 ; z < 18 ; z++) + for(i = -1 ; i <= 1 ; i++) + for(j = -1 ; j <= 1 ; j++) { ent->v.origin[0] = org[0] + i; ent->v.origin[1] = org[1] + j; ent->v.origin[2] = org[2] + z; - if (!SV_TestEntityPosition(ent)) + if(!SV_TestEntityPosition(ent)) { - Con_DPrintf ("Unstuck.\n"); - SV_LinkEdict (ent, true); + Con_DPrintf("Unstuck.\n"); + SV_LinkEdict(ent, true); return; } } - VectorCopy (org, ent->v.origin); - Con_DPrintf ("player is stuck.\n"); + VectorCopy(org, ent->v.origin); + Con_DPrintf("player is stuck.\n"); } @@ -673,10 +680,10 @@ void SV_CheckStuck (edict_t *ent) SV_CheckWater ============= */ -bool SV_CheckWater (edict_t *ent) +bool SV_CheckWater(edict_t *ent) { - vec3_t point; - int32_t cont; + vec3_t point; + int32_t cont; point[0] = ent->v.origin[0]; point[1] = ent->v.origin[1]; @@ -684,19 +691,19 @@ bool SV_CheckWater (edict_t *ent) ent->v.waterlevel = 0; ent->v.watertype = CONTENTS_EMPTY; - cont = SV_PointContents (point); - if (cont <= CONTENTS_WATER) + cont = SV_PointContents(point); + if(cont <= CONTENTS_WATER) { ent->v.watertype = cont; ent->v.waterlevel = 1; - point[2] = ent->v.origin[2] + (ent->v.mins[2] + ent->v.maxs[2])*0.5; - cont = SV_PointContents (point); - if (cont <= CONTENTS_WATER) + point[2] = ent->v.origin[2] + (ent->v.mins[2] + ent->v.maxs[2]) * 0.5; + cont = SV_PointContents(point); + if(cont <= CONTENTS_WATER) { ent->v.waterlevel = 2; point[2] = ent->v.origin[2] + ent->v.view_ofs[2]; - cont = SV_PointContents (point); - if (cont <= CONTENTS_WATER) + cont = SV_PointContents(point); + if(cont <= CONTENTS_WATER) ent->v.waterlevel = 3; } } @@ -710,23 +717,23 @@ SV_WallFriction ============ */ -void SV_WallFriction (edict_t *ent, trace_t *trace) +void SV_WallFriction(edict_t *ent, trace_t *trace) { - vec3_t forward, right, up; - float d, i; - vec3_t into, side; + vec3_t forward, right, up; + float d, i; + vec3_t into, side; - AngleVectors (ent->v.v_angle, forward, right, up); - d = DotProduct (trace->plane.normal, forward); + AngleVectors(ent->v.v_angle, forward, right, up); + d = DotProduct(trace->plane.normal, forward); d += 0.5; - if (d >= 0) + if(d >= 0) return; // cut the tangential velocity - i = DotProduct (trace->plane.normal, ent->v.velocity); - VectorScale (trace->plane.normal, i, into); - VectorSubtract (ent->v.velocity, into, side); + i = DotProduct(trace->plane.normal, ent->v.velocity); + VectorScale(trace->plane.normal, i, into); + VectorSubtract(ent->v.velocity, into, side); ent->v.velocity[0] = side[0] * (1 + d); ent->v.velocity[1] = side[1] * (1 + d); @@ -744,53 +751,77 @@ Try fixing by pushing one pixel in each direction. This is a hack, but in the interest of good gameplay... ====================== */ -int32_t SV_TryUnstick (edict_t *ent, vec3_t oldvel) +int32_t SV_TryUnstick(edict_t *ent, vec3_t oldvel) { - int32_t i; - vec3_t oldorg; - vec3_t dir; - int32_t clip; - trace_t steptrace; + int32_t i; + vec3_t oldorg; + vec3_t dir; + int32_t clip; + trace_t steptrace; - VectorCopy (ent->v.origin, oldorg); - VectorCopy (vec3_origin, dir); + VectorCopy(ent->v.origin, oldorg); + VectorCopy(vec3_origin, dir); - for (i=0 ; i<8 ; i++) + for(i = 0 ; i < 8 ; i++) { // try pushing a little in an axial direction - switch (i) + switch(i) { - case 0: dir[0] = 2; dir[1] = 0; break; - case 1: dir[0] = 0; dir[1] = 2; break; - case 2: dir[0] = -2; dir[1] = 0; break; - case 3: dir[0] = 0; dir[1] = -2; break; - case 4: dir[0] = 2; dir[1] = 2; break; - case 5: dir[0] = -2; dir[1] = 2; break; - case 6: dir[0] = 2; dir[1] = -2; break; - case 7: dir[0] = -2; dir[1] = -2; break; + case 0: + dir[0] = 2; + dir[1] = 0; + break; + case 1: + dir[0] = 0; + dir[1] = 2; + break; + case 2: + dir[0] = -2; + dir[1] = 0; + break; + case 3: + dir[0] = 0; + dir[1] = -2; + break; + case 4: + dir[0] = 2; + dir[1] = 2; + break; + case 5: + dir[0] = -2; + dir[1] = 2; + break; + case 6: + dir[0] = 2; + dir[1] = -2; + break; + case 7: + dir[0] = -2; + dir[1] = -2; + break; } - SV_PushEntity (ent, dir); + SV_PushEntity(ent, dir); // retry the original move ent->v.velocity[0] = oldvel[0]; ent->v. velocity[1] = oldvel[1]; ent->v. velocity[2] = 0; - clip = SV_FlyMove (ent, 0.1, &steptrace); + clip = SV_FlyMove(ent, 0.1, &steptrace); - if ( fabs(oldorg[1] - ent->v.origin[1]) > 4 - || fabs(oldorg[0] - ent->v.origin[0]) > 4 ) + if(fabs(oldorg[1] - ent->v.origin[1]) > 4 + || fabs(oldorg[0] - ent->v.origin[0]) > 4) { //Con_DPrintf ("unstuck!\n"); return clip; } // go back to the original pos and try again - VectorCopy (oldorg, ent->v.origin); + VectorCopy(oldorg, ent->v.origin); } - VectorCopy (vec3_origin, ent->v.velocity); - return 7; // still not moving + VectorCopy(vec3_origin, ent->v.velocity); + return 7; // still not moving } /* @@ -800,15 +831,15 @@ SV_WalkMove Only used by players ====================== */ -#define STEPSIZE 18 -void SV_WalkMove (edict_t *ent) +#define STEPSIZE 18 +void SV_WalkMove(edict_t *ent) { - vec3_t upmove, downmove; - vec3_t oldorg, oldvel; - vec3_t nosteporg, nostepvel; - int32_t clip; - int32_t oldonground; - trace_t steptrace, downtrace; + vec3_t upmove, downmove; + vec3_t oldorg, oldvel; + vec3_t nosteporg, nostepvel; + int32_t clip; + int32_t oldonground; + trace_t steptrace, downtrace; // // do a regular slide move unless it looks like you ran into a step @@ -816,71 +847,72 @@ void SV_WalkMove (edict_t *ent) oldonground = (int32_t)ent->v.flags & FL_ONGROUND; ent->v.flags = (int32_t)ent->v.flags & ~FL_ONGROUND; - VectorCopy (ent->v.origin, oldorg); - VectorCopy (ent->v.velocity, oldvel); + VectorCopy(ent->v.origin, oldorg); + VectorCopy(ent->v.velocity, oldvel); - clip = SV_FlyMove (ent, host_frametime, &steptrace); + clip = SV_FlyMove(ent, host_frametime, &steptrace); - if ( !(clip & 2) ) - return; // move didn't block on a step + if(!(clip & 2)) + return; // move didn't block on a step - if (!oldonground && ent->v.waterlevel == 0) - return; // don't stair up while jumping + if(!oldonground && ent->v.waterlevel == 0) + return; // don't stair up while jumping - if (ent->v.movetype != MOVETYPE_WALK) - return; // gibbed by a trigger + if(ent->v.movetype != MOVETYPE_WALK) + return; // gibbed by a trigger - if (sv_nostep.value) + if(sv_nostep.value) return; - if ( (int32_t)sv_player->v.flags & FL_WATERJUMP ) + if((int32_t)sv_player->v.flags & FL_WATERJUMP) return; - VectorCopy (ent->v.origin, nosteporg); - VectorCopy (ent->v.velocity, nostepvel); + VectorCopy(ent->v.origin, nosteporg); + VectorCopy(ent->v.velocity, nostepvel); // // try moving up and forward to go up a step // - VectorCopy (oldorg, ent->v.origin); // back to start pos + VectorCopy(oldorg, ent->v.origin); // back to start pos - VectorCopy (vec3_origin, upmove); - VectorCopy (vec3_origin, downmove); + VectorCopy(vec3_origin, upmove); + VectorCopy(vec3_origin, downmove); upmove[2] = STEPSIZE; - downmove[2] = -STEPSIZE + oldvel[2]*host_frametime; + downmove[2] = -STEPSIZE + oldvel[2] * host_frametime; // move up - SV_PushEntity (ent, upmove); // FIXME: don't link? + SV_PushEntity(ent, upmove); // FIXME: don't link? // move forward ent->v.velocity[0] = oldvel[0]; ent->v. velocity[1] = oldvel[1]; ent->v. velocity[2] = 0; - clip = SV_FlyMove (ent, host_frametime, &steptrace); + clip = SV_FlyMove(ent, host_frametime, &steptrace); // check for stuckness, possibly due to the limited precision of floats // in the clipping hulls - if (clip) + if(clip) { - if ( fabs(oldorg[1] - ent->v.origin[1]) < 0.03125 - && fabs(oldorg[0] - ent->v.origin[0]) < 0.03125 ) - { // stepping up didn't make any progress - clip = SV_TryUnstick (ent, oldvel); + if(fabs(oldorg[1] - ent->v.origin[1]) < 0.03125 + && fabs(oldorg[0] - ent->v.origin[0]) < 0.03125) + { + // stepping up didn't make any progress + clip = SV_TryUnstick(ent, oldvel); } } // extra friction based on view angle - if ( clip & 2 ) - SV_WallFriction (ent, &steptrace); + if(clip & 2) + SV_WallFriction(ent, &steptrace); // move down - downtrace = SV_PushEntity (ent, downmove); // FIXME: don't link? + downtrace = SV_PushEntity(ent, downmove); // FIXME: don't link? - if (downtrace.plane.normal[2] > 0.7) + if(downtrace.plane.normal[2] > 0.7) { - if (ent->v.solid == SOLID_BSP) + if(ent->v.solid == SOLID_BSP) { - ent->v.flags = (int32_t)ent->v.flags | FL_ONGROUND; + ent->v.flags = (int32_t)ent->v.flags | FL_ONGROUND; ent->v.groundentity = EDICT_TO_PROG(downtrace.ent); } } @@ -889,8 +921,8 @@ void SV_WalkMove (edict_t *ent) // if the push down didn't end up on good ground, use the move without // the step up. This happens near wall / slope combinations, and can // cause the player to hop up higher on a slope too steep to climb - VectorCopy (nosteporg, ent->v.origin); - VectorCopy (nostepvel, ent->v.velocity); + VectorCopy(nosteporg, ent->v.origin); + VectorCopy(nostepvel, ent->v.velocity); } } @@ -902,71 +934,71 @@ SV_Physics_Client Player character actions ================ */ -void SV_Physics_Client (edict_t *ent, int32_t num) +void SV_Physics_Client(edict_t *ent, int32_t num) { - if ( ! svs.clients[num-1].active ) - return; // unconnected slot + if(! svs.clients[num - 1].active) + return; // unconnected slot // // call standard client pre-think // pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(ent); - PR_ExecuteProgram (pr_global_struct->PlayerPreThink); + PR_ExecuteProgram(pr_global_struct->PlayerPreThink); // // do a move // - SV_CheckVelocity (ent); + SV_CheckVelocity(ent); // // decide which move function to call // - switch ((int32_t)ent->v.movetype) + switch((int32_t)ent->v.movetype) { case MOVETYPE_NONE: - if (!SV_RunThink (ent)) + if(!SV_RunThink(ent)) return; break; case MOVETYPE_WALK: - if (!SV_RunThink (ent)) + if(!SV_RunThink(ent)) return; - if (!SV_CheckWater (ent) && ! ((int32_t)ent->v.flags & FL_WATERJUMP) ) - SV_AddGravity (ent); - SV_CheckStuck (ent); - SV_WalkMove (ent); + if(!SV_CheckWater(ent) && !((int32_t)ent->v.flags & FL_WATERJUMP)) + SV_AddGravity(ent); + SV_CheckStuck(ent); + SV_WalkMove(ent); break; case MOVETYPE_TOSS: case MOVETYPE_BOUNCE: - SV_Physics_Toss (ent); + SV_Physics_Toss(ent); break; case MOVETYPE_FLY: - if (!SV_RunThink (ent)) + if(!SV_RunThink(ent)) return; - SV_FlyMove (ent, host_frametime, NULL); + SV_FlyMove(ent, host_frametime, NULL); break; case MOVETYPE_NOCLIP: - if (!SV_RunThink (ent)) + if(!SV_RunThink(ent)) return; - VectorMA (ent->v.origin, host_frametime, ent->v.velocity, ent->v.origin); + VectorMA(ent->v.origin, host_frametime, ent->v.velocity, ent->v.origin); break; default: - Sys_Error ("SV_Physics_client: bad movetype %" PRIi32 "", (int32_t)ent->v.movetype); + Sys_Error("SV_Physics_client: bad movetype %" PRIi32 "", (int32_t)ent->v.movetype); } // // call standard player post-think // - SV_LinkEdict (ent, true); + SV_LinkEdict(ent, true); pr_global_struct->time = sv.time; pr_global_struct->self = EDICT_TO_PROG(ent); - PR_ExecuteProgram (pr_global_struct->PlayerPostThink); + PR_ExecuteProgram(pr_global_struct->PlayerPostThink); } //============================================================================ @@ -978,10 +1010,10 @@ SV_Physics_None Non moving objects can only think ============= */ -void SV_Physics_None (edict_t *ent) +void SV_Physics_None(edict_t *ent) { // regular thinking - SV_RunThink (ent); + SV_RunThink(ent); } /* @@ -991,16 +1023,16 @@ SV_Physics_Noclip A moving object that doesn't obey physics ============= */ -void SV_Physics_Noclip (edict_t *ent) +void SV_Physics_Noclip(edict_t *ent) { // regular thinking - if (!SV_RunThink (ent)) + if(!SV_RunThink(ent)) return; - VectorMA (ent->v.angles, host_frametime, ent->v.avelocity, ent->v.angles); - VectorMA (ent->v.origin, host_frametime, ent->v.velocity, ent->v.origin); + VectorMA(ent->v.angles, host_frametime, ent->v.avelocity, ent->v.angles); + VectorMA(ent->v.origin, host_frametime, ent->v.velocity, ent->v.origin); - SV_LinkEdict (ent, false); + SV_LinkEdict(ent, false); } /* @@ -1017,33 +1049,36 @@ SV_CheckWaterTransition ============= */ -void SV_CheckWaterTransition (edict_t *ent) +void SV_CheckWaterTransition(edict_t *ent) { - int32_t cont; + int32_t cont; - cont = SV_PointContents (ent->v.origin); + cont = SV_PointContents(ent->v.origin); - if (!ent->v.watertype) - { // just spawned here + if(!ent->v.watertype) + { + // just spawned here ent->v.watertype = cont; ent->v.waterlevel = 1; return; } - if (cont <= CONTENTS_WATER) + if(cont <= CONTENTS_WATER) { - if (ent->v.watertype == CONTENTS_EMPTY) - { // just crossed into water - SV_StartSound (ent, 0, "misc/h2ohit1.wav", 255, 1); + if(ent->v.watertype == CONTENTS_EMPTY) + { + // just crossed into water + SV_StartSound(ent, 0, "misc/h2ohit1.wav", 255, 1); } ent->v.watertype = cont; ent->v.waterlevel = 1; } else { - if (ent->v.watertype != CONTENTS_EMPTY) - { // just crossed into water - SV_StartSound (ent, 0, "misc/h2ohit1.wav", 255, 1); + if(ent->v.watertype != CONTENTS_EMPTY) + { + // just crossed into water + SV_StartSound(ent, 0, "misc/h2ohit1.wav", 255, 1); } ent->v.watertype = CONTENTS_EMPTY; ent->v.waterlevel = cont; @@ -1057,59 +1092,59 @@ SV_Physics_Toss Toss, bounce, and fly movement. When onground, do nothing. ============= */ -void SV_Physics_Toss (edict_t *ent) +void SV_Physics_Toss(edict_t *ent) { - trace_t trace; - vec3_t move; - float backoff; + trace_t trace; + vec3_t move; + float backoff; // regular thinking - if (!SV_RunThink (ent)) + if(!SV_RunThink(ent)) return; // if onground, return without moving - if ( ((int32_t)ent->v.flags & FL_ONGROUND) ) + if(((int32_t)ent->v.flags & FL_ONGROUND)) return; - SV_CheckVelocity (ent); + SV_CheckVelocity(ent); // add gravity - if (ent->v.movetype != MOVETYPE_FLY - && ent->v.movetype != MOVETYPE_FLYMISSILE) - SV_AddGravity (ent); + if(ent->v.movetype != MOVETYPE_FLY + && ent->v.movetype != MOVETYPE_FLYMISSILE) + SV_AddGravity(ent); // move angles - VectorMA (ent->v.angles, host_frametime, ent->v.avelocity, ent->v.angles); + VectorMA(ent->v.angles, host_frametime, ent->v.avelocity, ent->v.angles); // move origin - VectorScale (ent->v.velocity, host_frametime, move); - trace = SV_PushEntity (ent, move); - if (trace.fraction == 1) + VectorScale(ent->v.velocity, host_frametime, move); + trace = SV_PushEntity(ent, move); + if(trace.fraction == 1) return; - if (ent->free) + if(ent->free) return; - if (ent->v.movetype == MOVETYPE_BOUNCE) + if(ent->v.movetype == MOVETYPE_BOUNCE) backoff = 1.5; else backoff = 1; - ClipVelocity (ent->v.velocity, trace.plane.normal, ent->v.velocity, backoff); + ClipVelocity(ent->v.velocity, trace.plane.normal, ent->v.velocity, backoff); // stop if on ground - if (trace.plane.normal[2] > 0.7) + if(trace.plane.normal[2] > 0.7) { - if (ent->v.velocity[2] < 60 || ent->v.movetype != MOVETYPE_BOUNCE) + if(ent->v.velocity[2] < 60 || ent->v.movetype != MOVETYPE_BOUNCE) { ent->v.flags = (int32_t)ent->v.flags | FL_ONGROUND; ent->v.groundentity = EDICT_TO_PROG(trace.ent); - VectorCopy (vec3_origin, ent->v.velocity); - VectorCopy (vec3_origin, ent->v.avelocity); + VectorCopy(vec3_origin, ent->v.velocity); + VectorCopy(vec3_origin, ent->v.avelocity); } } // check for in water - SV_CheckWaterTransition (ent); + SV_CheckWaterTransition(ent); } /* @@ -1131,34 +1166,34 @@ This is also used for objects that have become still on the ground, but will fall if the floor is pulled out from under them. ============= */ -void SV_Physics_Step (edict_t *ent) +void SV_Physics_Step(edict_t *ent) { - bool hitsound; + bool hitsound; // freefall if not onground - if ( ! ((int32_t)ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM) ) ) + if(!((int32_t)ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM))) { - if (ent->v.velocity[2] < sv_gravity.value*-0.1) + if(ent->v.velocity[2] < sv_gravity.value * -0.1) hitsound = true; else hitsound = false; - SV_AddGravity (ent); - SV_CheckVelocity (ent); - SV_FlyMove (ent, host_frametime, NULL); - SV_LinkEdict (ent, true); + SV_AddGravity(ent); + SV_CheckVelocity(ent); + SV_FlyMove(ent, host_frametime, NULL); + SV_LinkEdict(ent, true); - if ( (int32_t)ent->v.flags & FL_ONGROUND ) // just hit ground + if((int32_t)ent->v.flags & FL_ONGROUND) // just hit ground { - if (hitsound) - SV_StartSound (ent, 0, "demon/dland2.wav", 255, 1); + if(hitsound) + SV_StartSound(ent, 0, "demon/dland2.wav", 255, 1); } } // regular thinking - SV_RunThink (ent); + SV_RunThink(ent); - SV_CheckWaterTransition (ent); + SV_CheckWaterTransition(ent); } @@ -1170,17 +1205,17 @@ SV_Physics ================ */ -void SV_Physics (void) +void SV_Physics(void) { - int32_t i; - int32_t entity_cap; // For sv_freezenonclients - edict_t *ent; + int32_t i; + int32_t entity_cap; // For sv_freezenonclients + edict_t *ent; // let the progs know that a new frame has started pr_global_struct->self = EDICT_TO_PROG(sv.edicts); pr_global_struct->other = EDICT_TO_PROG(sv.edicts); pr_global_struct->time = sv.time; - PR_ExecuteProgram (pr_global_struct->StartFrame); + PR_ExecuteProgram(pr_global_struct->StartFrame); //SV_CheckAllEnts (); @@ -1189,44 +1224,44 @@ void SV_Physics (void) // ent = sv.edicts; - if (sv_freezenonclients.value) - entity_cap = svs.maxclients + 1; // Only run physics on clients and the world + if(sv_freezenonclients.value) + entity_cap = svs.maxclients + 1; // Only run physics on clients and the world else - entity_cap = sv.num_edicts; + entity_cap = sv.num_edicts; //for (i=0 ; ifree) + if(ent->free) continue; - if (pr_global_struct->force_retouch) + if(pr_global_struct->force_retouch) { - SV_LinkEdict (ent, true); // force retouch even for stationary + SV_LinkEdict(ent, true); // force retouch even for stationary } - if (i > 0 && i <= svs.maxclients) - SV_Physics_Client (ent, i); - else if (ent->v.movetype == MOVETYPE_PUSH) - SV_Physics_Pusher (ent); - else if (ent->v.movetype == MOVETYPE_NONE) - SV_Physics_None (ent); - else if (ent->v.movetype == MOVETYPE_NOCLIP) - SV_Physics_Noclip (ent); - else if (ent->v.movetype == MOVETYPE_STEP) - SV_Physics_Step (ent); - else if (ent->v.movetype == MOVETYPE_TOSS - || ent->v.movetype == MOVETYPE_BOUNCE - || ent->v.movetype == MOVETYPE_FLY - || ent->v.movetype == MOVETYPE_FLYMISSILE) - SV_Physics_Toss (ent); + if(i > 0 && i <= svs.maxclients) + SV_Physics_Client(ent, i); + else if(ent->v.movetype == MOVETYPE_PUSH) + SV_Physics_Pusher(ent); + else if(ent->v.movetype == MOVETYPE_NONE) + SV_Physics_None(ent); + else if(ent->v.movetype == MOVETYPE_NOCLIP) + SV_Physics_Noclip(ent); + else if(ent->v.movetype == MOVETYPE_STEP) + SV_Physics_Step(ent); + else if(ent->v.movetype == MOVETYPE_TOSS + || ent->v.movetype == MOVETYPE_BOUNCE + || ent->v.movetype == MOVETYPE_FLY + || ent->v.movetype == MOVETYPE_FLYMISSILE) + SV_Physics_Toss(ent); else - Sys_Error ("SV_Physics: bad movetype %" PRIi32 "", (int32_t)ent->v.movetype); + Sys_Error("SV_Physics: bad movetype %" PRIi32 "", (int32_t)ent->v.movetype); } - if (pr_global_struct->force_retouch) + if(pr_global_struct->force_retouch) pr_global_struct->force_retouch--; - if (!sv_freezenonclients.value) - sv.time += host_frametime; + if(!sv_freezenonclients.value) + sv.time += host_frametime; } diff --git a/source/sv_user.c b/source/sv_user.c index b8fb6bf..a796088 100644 --- a/source/sv_user.c +++ b/source/sv_user.c @@ -23,90 +23,90 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -edict_t *sv_player; +edict_t *sv_player; -extern cvar_t sv_friction; -cvar_t sv_edgefriction = {"edgefriction", "2", CVAR_NONE}; -extern cvar_t sv_stopspeed; +extern cvar_t sv_friction; +cvar_t sv_edgefriction = {"edgefriction", "2", CVAR_NONE}; +extern cvar_t sv_stopspeed; -static vec3_t forward, right, up; +static vec3_t forward, right, up; // world -float *angles; -float *origin; -float *velocity; +float *angles; +float *origin; +float *velocity; -bool onground; +bool onground; -usercmd_t cmd; +usercmd_t cmd; -cvar_t sv_idealpitchscale = {"sv_idealpitchscale","0.8",CVAR_NONE}; -cvar_t sv_altnoclip = {"sv_altnoclip","1",CVAR_ARCHIVE}; //johnfitz +cvar_t sv_idealpitchscale = {"sv_idealpitchscale", "0.8", CVAR_NONE}; +cvar_t sv_altnoclip = {"sv_altnoclip", "1", CVAR_ARCHIVE}; //johnfitz /* =============== SV_SetIdealPitch =============== */ -#define MAX_FORWARD 6 -void SV_SetIdealPitch (void) +#define MAX_FORWARD 6 +void SV_SetIdealPitch(void) { - float angleval, sinval, cosval; - trace_t tr; - vec3_t top, bottom; - float z[MAX_FORWARD]; - int32_t i, j; - int32_t step, dir, steps; + float angleval, sinval, cosval; + trace_t tr; + vec3_t top, bottom; + float z[MAX_FORWARD]; + int32_t i, j; + int32_t step, dir, steps; - if (!((int32_t)sv_player->v.flags & FL_ONGROUND)) + if(!((int32_t)sv_player->v.flags & FL_ONGROUND)) return; - angleval = sv_player->v.angles[YAW] * M_PI*2 / 360; + angleval = sv_player->v.angles[YAW] * M_PI * 2 / 360; sinval = sin(angleval); cosval = cos(angleval); - for (i=0 ; iv.origin[0] + cosval*(i+3)*12; - top[1] = sv_player->v.origin[1] + sinval*(i+3)*12; + top[0] = sv_player->v.origin[0] + cosval * (i + 3) * 12; + top[1] = sv_player->v.origin[1] + sinval * (i + 3) * 12; top[2] = sv_player->v.origin[2] + sv_player->v.view_ofs[2]; bottom[0] = top[0]; bottom[1] = top[1]; bottom[2] = top[2] - 160; - tr = SV_Move (top, vec3_origin, vec3_origin, bottom, 1, sv_player); - if (tr.allsolid) - return; // looking at a wall, leave ideal the way is was + tr = SV_Move(top, vec3_origin, vec3_origin, bottom, 1, sv_player); + if(tr.allsolid) + return; // looking at a wall, leave ideal the way is was - if (tr.fraction == 1) - return; // near a dropoff + if(tr.fraction == 1) + return; // near a dropoff - z[i] = top[2] + tr.fraction*(bottom[2]-top[2]); + z[i] = top[2] + tr.fraction * (bottom[2] - top[2]); } dir = 0; steps = 0; - for (j=1 ; j -ON_EPSILON && step < ON_EPSILON) + step = z[j] - z[j - 1]; + if(step > -ON_EPSILON && step < ON_EPSILON) continue; - if (dir && ( step-dir > ON_EPSILON || step-dir < -ON_EPSILON ) ) - return; // mixed changes + if(dir && (step - dir > ON_EPSILON || step - dir < -ON_EPSILON)) + return; // mixed changes steps++; dir = step; } - if (!dir) + if(!dir) { sv_player->v.idealpitch = 0; return; } - if (steps < 2) + if(steps < 2) return; sv_player->v.idealpitch = -dir * sv_idealpitchscale.value; } @@ -118,38 +118,38 @@ SV_UserFriction ================== */ -void SV_UserFriction (void) +void SV_UserFriction(void) { - float *vel; - float speed, newspeed, control; - vec3_t start, stop; - float friction; - trace_t trace; + float *vel; + float speed, newspeed, control; + vec3_t start, stop; + float friction; + trace_t trace; vel = velocity; - speed = sqrt(vel[0]*vel[0] +vel[1]*vel[1]); - if (!speed) + speed = sqrt(vel[0] * vel[0] + vel[1] * vel[1]); + if(!speed) return; // if the leading edge is over a dropoff, increase friction - start[0] = stop[0] = origin[0] + vel[0]/speed*16; - start[1] = stop[1] = origin[1] + vel[1]/speed*16; + start[0] = stop[0] = origin[0] + vel[0] / speed * 16; + start[1] = stop[1] = origin[1] + vel[1] / speed * 16; start[2] = origin[2] + sv_player->v.mins[2]; stop[2] = start[2] - 34; - trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, sv_player); + trace = SV_Move(start, vec3_origin, vec3_origin, stop, true, sv_player); - if (trace.fraction == 1.0) - friction = sv_friction.value*sv_edgefriction.value; + if(trace.fraction == 1.0) + friction = sv_friction.value * sv_edgefriction.value; else friction = sv_friction.value; // apply friction control = speed < sv_stopspeed.value ? sv_stopspeed.value : speed; - newspeed = speed - host_frametime*control*friction; + newspeed = speed - host_frametime * control * friction; - if (newspeed < 0) + if(newspeed < 0) newspeed = 0; newspeed /= speed; @@ -163,57 +163,57 @@ void SV_UserFriction (void) SV_Accelerate ============== */ -cvar_t sv_maxspeed = {"sv_maxspeed", "320", CVAR_NOTIFY|CVAR_SERVERINFO}; -cvar_t sv_accelerate = {"sv_accelerate", "10", CVAR_NONE}; -void SV_Accelerate (float wishspeed, const vec3_t wishdir) +cvar_t sv_maxspeed = {"sv_maxspeed", "320", CVAR_NOTIFY | CVAR_SERVERINFO}; +cvar_t sv_accelerate = {"sv_accelerate", "10", CVAR_NONE}; +void SV_Accelerate(float wishspeed, const vec3_t wishdir) { - int32_t i; - float addspeed, accelspeed, currentspeed; + int32_t i; + float addspeed, accelspeed, currentspeed; - currentspeed = DotProduct (velocity, wishdir); + currentspeed = DotProduct(velocity, wishdir); addspeed = wishspeed - currentspeed; - if (addspeed <= 0) + if(addspeed <= 0) return; - accelspeed = sv_accelerate.value*host_frametime*wishspeed; - if (accelspeed > addspeed) + accelspeed = sv_accelerate.value * host_frametime * wishspeed; + if(accelspeed > addspeed) accelspeed = addspeed; - for (i=0 ; i<3 ; i++) - velocity[i] += accelspeed*wishdir[i]; + for(i = 0 ; i < 3 ; i++) + velocity[i] += accelspeed * wishdir[i]; } -void SV_AirAccelerate (float wishspeed, vec3_t wishveloc) +void SV_AirAccelerate(float wishspeed, vec3_t wishveloc) { - int32_t i; - float addspeed, wishspd, accelspeed, currentspeed; + int32_t i; + float addspeed, wishspd, accelspeed, currentspeed; - wishspd = VectorNormalize (wishveloc); - if (wishspd > 30) + wishspd = VectorNormalize(wishveloc); + if(wishspd > 30) wishspd = 30; - currentspeed = DotProduct (velocity, wishveloc); + currentspeed = DotProduct(velocity, wishveloc); addspeed = wishspd - currentspeed; - if (addspeed <= 0) + if(addspeed <= 0) return; // accelspeed = sv_accelerate.value * host_frametime; - accelspeed = sv_accelerate.value*wishspeed * host_frametime; - if (accelspeed > addspeed) + accelspeed = sv_accelerate.value * wishspeed * host_frametime; + if(accelspeed > addspeed) accelspeed = addspeed; - for (i=0 ; i<3 ; i++) - velocity[i] += accelspeed*wishveloc[i]; + for(i = 0 ; i < 3 ; i++) + velocity[i] += accelspeed * wishveloc[i]; } -void DropPunchAngle (void) +void DropPunchAngle(void) { - float len; + float len; - len = VectorNormalize (sv_player->v.punchangle); + len = VectorNormalize(sv_player->v.punchangle); - len -= 10*host_frametime; - if (len < 0) + len -= 10 * host_frametime; + if(len < 0) len = 0; - VectorScale (sv_player->v.punchangle, len, sv_player->v.punchangle); + VectorScale(sv_player->v.punchangle, len, sv_player->v.punchangle); } /* @@ -222,29 +222,29 @@ SV_WaterMove =================== */ -void SV_WaterMove (void) +void SV_WaterMove(void) { - int32_t i; - vec3_t wishvel; - float speed, newspeed, wishspeed, addspeed, accelspeed; + int32_t i; + vec3_t wishvel; + float speed, newspeed, wishspeed, addspeed, accelspeed; // // user intentions // - AngleVectors (sv_player->v.v_angle, forward, right, up); + AngleVectors(sv_player->v.v_angle, forward, right, up); - for (i=0 ; i<3 ; i++) - wishvel[i] = forward[i]*cmd.forwardmove + right[i]*cmd.sidemove; + for(i = 0 ; i < 3 ; i++) + wishvel[i] = forward[i] * cmd.forwardmove + right[i] * cmd.sidemove; - if (!cmd.forwardmove && !cmd.sidemove && !cmd.upmove) - wishvel[2] -= 60; // drift towards bottom + if(!cmd.forwardmove && !cmd.sidemove && !cmd.upmove) + wishvel[2] -= 60; // drift towards bottom else wishvel[2] += cmd.upmove; wishspeed = VectorLength(wishvel); - if (wishspeed > sv_maxspeed.value) + if(wishspeed > sv_maxspeed.value) { - VectorScale (wishvel, sv_maxspeed.value/wishspeed, wishvel); + VectorScale(wishvel, sv_maxspeed.value / wishspeed, wishvel); wishspeed = sv_maxspeed.value; } wishspeed *= 0.7; @@ -252,13 +252,13 @@ void SV_WaterMove (void) // // water friction // - speed = VectorLength (velocity); - if (speed) + speed = VectorLength(velocity); + if(speed) { newspeed = speed - host_frametime * speed * sv_friction.value; - if (newspeed < 0) + if(newspeed < 0) newspeed = 0; - VectorScale (velocity, newspeed/speed, velocity); + VectorScale(velocity, newspeed / speed, velocity); } else newspeed = 0; @@ -266,26 +266,26 @@ void SV_WaterMove (void) // // water acceleration // - if (!wishspeed) + if(!wishspeed) return; addspeed = wishspeed - newspeed; - if (addspeed <= 0) + if(addspeed <= 0) return; - VectorNormalize (wishvel); + VectorNormalize(wishvel); accelspeed = sv_accelerate.value * wishspeed * host_frametime; - if (accelspeed > addspeed) + if(accelspeed > addspeed) accelspeed = addspeed; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) velocity[i] += accelspeed * wishvel[i]; } -void SV_WaterJump (void) +void SV_WaterJump(void) { - if (sv.time > sv_player->v.teleport_time - || !sv_player->v.waterlevel) + if(sv.time > sv_player->v.teleport_time + || !sv_player->v.waterlevel) { sv_player->v.flags = (int32_t)sv_player->v.flags & ~FL_WATERJUMP; sv_player->v.teleport_time = 0; @@ -301,19 +301,19 @@ SV_NoclipMove -- johnfitz new, alternate noclip. old noclip is still handled in SV_AirMove =================== */ -void SV_NoclipMove (void) +void SV_NoclipMove(void) { - AngleVectors (sv_player->v.v_angle, forward, right, up); + AngleVectors(sv_player->v.v_angle, forward, right, up); - velocity[0] = forward[0]*cmd.forwardmove + right[0]*cmd.sidemove; - velocity[1] = forward[1]*cmd.forwardmove + right[1]*cmd.sidemove; - velocity[2] = forward[2]*cmd.forwardmove + right[2]*cmd.sidemove; - velocity[2] += cmd.upmove*2; //doubled to match running speed + velocity[0] = forward[0] * cmd.forwardmove + right[0] * cmd.sidemove; + velocity[1] = forward[1] * cmd.forwardmove + right[1] * cmd.sidemove; + velocity[2] = forward[2] * cmd.forwardmove + right[2] * cmd.sidemove; + velocity[2] += cmd.upmove * 2; //doubled to match running speed - if (VectorLength (velocity) > sv_maxspeed.value) + if(VectorLength(velocity) > sv_maxspeed.value) { - VectorNormalize (velocity); - VectorScale (velocity, sv_maxspeed.value, velocity); + VectorNormalize(velocity); + VectorScale(velocity, sv_maxspeed.value, velocity); } } @@ -322,50 +322,52 @@ void SV_NoclipMove (void) SV_AirMove =================== */ -void SV_AirMove (void) +void SV_AirMove(void) { - int32_t i; - vec3_t wishvel, wishdir; - float wishspeed; - float fmove, smove; + int32_t i; + vec3_t wishvel, wishdir; + float wishspeed; + float fmove, smove; - AngleVectors (sv_player->v.angles, forward, right, up); + AngleVectors(sv_player->v.angles, forward, right, up); fmove = cmd.forwardmove; smove = cmd.sidemove; // hack to not let you back into teleporter - if (sv.time < sv_player->v.teleport_time && fmove < 0) + if(sv.time < sv_player->v.teleport_time && fmove < 0) fmove = 0; - for (i=0 ; i<3 ; i++) - wishvel[i] = forward[i]*fmove + right[i]*smove; + for(i = 0 ; i < 3 ; i++) + wishvel[i] = forward[i] * fmove + right[i] * smove; - if ( (int32_t)sv_player->v.movetype != MOVETYPE_WALK) + if((int32_t)sv_player->v.movetype != MOVETYPE_WALK) wishvel[2] = cmd.upmove; else wishvel[2] = 0; - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); - if (wishspeed > sv_maxspeed.value) + if(wishspeed > sv_maxspeed.value) { - VectorScale (wishvel, sv_maxspeed.value/wishspeed, wishvel); + VectorScale(wishvel, sv_maxspeed.value / wishspeed, wishvel); wishspeed = sv_maxspeed.value; } - if ( sv_player->v.movetype == MOVETYPE_NOCLIP) - { // noclip - VectorCopy (wishvel, velocity); - } - else if ( onground ) + if(sv_player->v.movetype == MOVETYPE_NOCLIP) { - SV_UserFriction (); - SV_Accelerate (wishspeed, wishdir); + // noclip + VectorCopy(wishvel, velocity); + } + else if(onground) + { + SV_UserFriction(); + SV_Accelerate(wishspeed, wishdir); } else - { // not on ground, so little effect on velocity - SV_AirAccelerate (wishspeed, wishvel); + { + // not on ground, so little effect on velocity + SV_AirAccelerate(wishspeed, wishvel); } } @@ -377,11 +379,11 @@ the move fields specify an intended velocity in pix/sec the angle fields specify an exact angular motion in degrees =================== */ -void SV_ClientThink (void) +void SV_ClientThink(void) { - vec3_t v_angle; + vec3_t v_angle; - if (sv_player->v.movetype == MOVETYPE_NONE) + if(sv_player->v.movetype == MOVETYPE_NONE) return; onground = (int32_t)sv_player->v.flags & FL_ONGROUND; @@ -389,12 +391,12 @@ void SV_ClientThink (void) origin = sv_player->v.origin; velocity = sv_player->v.velocity; - DropPunchAngle (); + DropPunchAngle(); // // if dead, behave differently // - if (sv_player->v.health <= 0) + if(sv_player->v.health <= 0) return; // @@ -403,29 +405,29 @@ void SV_ClientThink (void) cmd = host_client->cmd; angles = sv_player->v.angles; - VectorAdd (sv_player->v.v_angle, sv_player->v.punchangle, v_angle); - angles[ROLL] = V_CalcRoll (sv_player->v.angles, sv_player->v.velocity)*4; - if (!sv_player->v.fixangle) + VectorAdd(sv_player->v.v_angle, sv_player->v.punchangle, v_angle); + angles[ROLL] = V_CalcRoll(sv_player->v.angles, sv_player->v.velocity) * 4; + if(!sv_player->v.fixangle) { - angles[PITCH] = -v_angle[PITCH]/3; + angles[PITCH] = -v_angle[PITCH] / 3; angles[YAW] = v_angle[YAW]; } - if ( (int32_t)sv_player->v.flags & FL_WATERJUMP ) + if((int32_t)sv_player->v.flags & FL_WATERJUMP) { - SV_WaterJump (); + SV_WaterJump(); return; } // // walk // //johnfitz -- alternate noclip - if (sv_player->v.movetype == MOVETYPE_NOCLIP && sv_altnoclip.value) - SV_NoclipMove (); - else if (sv_player->v.waterlevel >= 2 && sv_player->v.movetype != MOVETYPE_NOCLIP) - SV_WaterMove (); + if(sv_player->v.movetype == MOVETYPE_NOCLIP && sv_altnoclip.value) + SV_NoclipMove(); + else if(sv_player->v.waterlevel >= 2 && sv_player->v.movetype != MOVETYPE_NOCLIP) + SV_WaterMove(); else - SV_AirMove (); + SV_AirMove(); //johnfitz } @@ -435,40 +437,40 @@ void SV_ClientThink (void) SV_ReadClientMove =================== */ -void SV_ReadClientMove (usercmd_t *move) +void SV_ReadClientMove(usercmd_t *move) { - int32_t i; - vec3_t angle; - int32_t bits; + int32_t i; + vec3_t angle; + int32_t bits; // read ping time - host_client->ping_times[host_client->num_pings%NUM_PING_TIMES] - = sv.time - MSG_ReadFloat (); + host_client->ping_times[host_client->num_pings % NUM_PING_TIMES] + = sv.time - MSG_ReadFloat(); host_client->num_pings++; // read current angles - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) //johnfitz -- 16-bit angles for PROTOCOL_FITZQUAKE - if (sv.protocol == PROTOCOL_NETQUAKE) - angle[i] = MSG_ReadAngle (sv.protocolflags); + if(sv.protocol == PROTOCOL_NETQUAKE) + angle[i] = MSG_ReadAngle(sv.protocolflags); else - angle[i] = MSG_ReadAngle16 (sv.protocolflags); - //johnfitz + angle[i] = MSG_ReadAngle16(sv.protocolflags); + //johnfitz - VectorCopy (angle, host_client->edict->v.v_angle); + VectorCopy(angle, host_client->edict->v.v_angle); // read movement - move->forwardmove = MSG_ReadShort (); - move->sidemove = MSG_ReadShort (); - move->upmove = MSG_ReadShort (); + move->forwardmove = MSG_ReadShort(); + move->sidemove = MSG_ReadShort(); + move->upmove = MSG_ReadShort(); // read buttons - bits = MSG_ReadByte (); + bits = MSG_ReadByte(); host_client->edict->v.button0 = bits & 1; - host_client->edict->v.button2 = (bits & 2)>>1; + host_client->edict->v.button2 = (bits & 2) >> 1; - i = MSG_ReadByte (); - if (i) + i = MSG_ReadByte(); + if(i) host_client->edict->v.impulse = i; } @@ -479,46 +481,46 @@ SV_ReadClientMessage Returns false if the client should be killed =================== */ -bool SV_ReadClientMessage (void) +bool SV_ReadClientMessage(void) { - int32_t ret; - int32_t ccmd; - const char *s; + int32_t ret; + int32_t ccmd; + const char *s; do { nextmsg: - ret = NET_GetMessage (host_client->netconnection); - if (ret == -1) + ret = NET_GetMessage(host_client->netconnection); + if(ret == -1) { - Sys_Printf ("SV_ReadClientMessage: NET_GetMessage failed\n"); + Sys_Printf("SV_ReadClientMessage: NET_GetMessage failed\n"); return false; } - if (!ret) + if(!ret) return true; - MSG_BeginReading (); + MSG_BeginReading(); - while (1) + while(1) { - if (!host_client->active) - return false; // a command caused an error + if(!host_client->active) + return false; // a command caused an error - if (msg_badread) + if(msg_badread) { - Sys_Printf ("SV_ReadClientMessage: badread\n"); + Sys_Printf("SV_ReadClientMessage: badread\n"); return false; } - ccmd = MSG_ReadChar (); + ccmd = MSG_ReadChar(); - switch (ccmd) + switch(ccmd) { case -1: - goto nextmsg; // end of message + goto nextmsg; // end of message default: - Sys_Printf ("SV_ReadClientMessage: unknown command char\n"); + Sys_Printf("SV_ReadClientMessage: unknown command char\n"); return false; case clc_nop: @@ -526,51 +528,51 @@ nextmsg: break; case clc_stringcmd: - s = MSG_ReadString (); + s = MSG_ReadString(); ret = 0; - if (q_strncasecmp(s, "status", 6) == 0) + if(q_strncasecmp(s, "status", 6) == 0) ret = 1; - else if (q_strncasecmp(s, "god", 3) == 0) + else if(q_strncasecmp(s, "god", 3) == 0) ret = 1; - else if (q_strncasecmp(s, "notarget", 8) == 0) + else if(q_strncasecmp(s, "notarget", 8) == 0) ret = 1; - else if (q_strncasecmp(s, "fly", 3) == 0) + else if(q_strncasecmp(s, "fly", 3) == 0) ret = 1; - else if (q_strncasecmp(s, "name", 4) == 0) + else if(q_strncasecmp(s, "name", 4) == 0) ret = 1; - else if (q_strncasecmp(s, "noclip", 6) == 0) + else if(q_strncasecmp(s, "noclip", 6) == 0) ret = 1; - else if (q_strncasecmp(s, "setpos", 6) == 0) + else if(q_strncasecmp(s, "setpos", 6) == 0) ret = 1; - else if (q_strncasecmp(s, "say", 3) == 0) + else if(q_strncasecmp(s, "say", 3) == 0) ret = 1; - else if (q_strncasecmp(s, "say_team", 8) == 0) + else if(q_strncasecmp(s, "say_team", 8) == 0) ret = 1; - else if (q_strncasecmp(s, "tell", 4) == 0) + else if(q_strncasecmp(s, "tell", 4) == 0) ret = 1; - else if (q_strncasecmp(s, "color", 5) == 0) + else if(q_strncasecmp(s, "color", 5) == 0) ret = 1; - else if (q_strncasecmp(s, "kill", 4) == 0) + else if(q_strncasecmp(s, "kill", 4) == 0) ret = 1; - else if (q_strncasecmp(s, "pause", 5) == 0) + else if(q_strncasecmp(s, "pause", 5) == 0) ret = 1; - else if (q_strncasecmp(s, "spawn", 5) == 0) + else if(q_strncasecmp(s, "spawn", 5) == 0) ret = 1; - else if (q_strncasecmp(s, "begin", 5) == 0) + else if(q_strncasecmp(s, "begin", 5) == 0) ret = 1; - else if (q_strncasecmp(s, "prespawn", 8) == 0) + else if(q_strncasecmp(s, "prespawn", 8) == 0) ret = 1; - else if (q_strncasecmp(s, "kick", 4) == 0) + else if(q_strncasecmp(s, "kick", 4) == 0) ret = 1; - else if (q_strncasecmp(s, "ping", 4) == 0) + else if(q_strncasecmp(s, "ping", 4) == 0) ret = 1; - else if (q_strncasecmp(s, "give", 4) == 0) + else if(q_strncasecmp(s, "give", 4) == 0) ret = 1; - else if (q_strncasecmp(s, "ban", 3) == 0) + else if(q_strncasecmp(s, "ban", 3) == 0) ret = 1; - if (ret == 1) - Cmd_ExecuteString (s, src_client); + if(ret == 1) + Cmd_ExecuteString(s, src_client); else Con_DPrintf("%s tried to %s\n", host_client->name, s); break; @@ -580,11 +582,12 @@ nextmsg: return false; case clc_move: - SV_ReadClientMove (&host_client->cmd); + SV_ReadClientMove(&host_client->cmd); break; } } - } while (ret == 1); + } + while(ret == 1); return true; } @@ -595,33 +598,33 @@ nextmsg: SV_RunClients ================== */ -void SV_RunClients (void) +void SV_RunClients(void) { - int32_t i; + int32_t i; - for (i=0, host_client = svs.clients ; iactive) + if(!host_client->active) continue; sv_player = host_client->edict; - if (!SV_ReadClientMessage ()) + if(!SV_ReadClientMessage()) { - SV_DropClient (false); // client misbehaved... + SV_DropClient(false); // client misbehaved... continue; } - if (!host_client->spawned) + if(!host_client->spawned) { - // clear client movement until a new packet is received - memset (&host_client->cmd, 0, sizeof(host_client->cmd)); + // clear client movement until a new packet is received + memset(&host_client->cmd, 0, sizeof(host_client->cmd)); continue; } // always pause in single player if in console or menus - if (!sv.paused && (svs.maxclients > 1 || key_dest == key_game) ) - SV_ClientThink (); + if(!sv.paused && (svs.maxclients > 1 || key_dest == key_game)) + SV_ClientThink(); } } diff --git a/source/sys.h b/source/sys.h index 20b84bd..b12cbe9 100644 --- a/source/sys.h +++ b/source/sys.h @@ -24,7 +24,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // sys.h -- non-portable functions -void Sys_Init (void); +void Sys_Init(void); // // file IO @@ -32,39 +32,39 @@ void Sys_Init (void); // returns the file size or -1 if file is not present. // the file should be in BINARY mode for stupid OSs that care -int32_t Sys_FileOpenRead (const char *path, int32_t *hndl); +int32_t Sys_FileOpenRead(const char *path, int32_t *hndl); -int32_t Sys_FileOpenWrite (const char *path); -void Sys_FileClose (int32_t handle); -void Sys_FileSeek (int32_t handle, int32_t position); -int32_t Sys_FileRead (int32_t handle, void *dest, int32_t count); -int32_t Sys_FileWrite (int32_t handle,const void *data, int32_t count); -int32_t Sys_FileTime (const char *path); -void Sys_mkdir (const char *path); +int32_t Sys_FileOpenWrite(const char *path); +void Sys_FileClose(int32_t handle); +void Sys_FileSeek(int32_t handle, int32_t position); +int32_t Sys_FileRead(int32_t handle, void *dest, int32_t count); +int32_t Sys_FileWrite(int32_t handle, const void *data, int32_t count); +int32_t Sys_FileTime(const char *path); +void Sys_mkdir(const char *path); // // system IO // -noreturn void Sys_Quit (void); -noreturn void Sys_Error (const char *error, ...) FUNC_PRINTF(1,2); +noreturn void Sys_Quit(void); +noreturn void Sys_Error(const char *error, ...) FUNC_PRINTF(1, 2); // an error will cause the entire program to exit #ifdef __WATCOMC__ #pragma aux Sys_Error aborts; #pragma aux Sys_Quit aborts; #endif -void Sys_Printf (const char *fmt, ...) FUNC_PRINTF(1,2); +void Sys_Printf(const char *fmt, ...) FUNC_PRINTF(1, 2); // send text to the console -double Sys_DoubleTime (void); +double Sys_DoubleTime(void); -const char *Sys_ConsoleInput (void); +const char *Sys_ConsoleInput(void); -void Sys_Sleep (uint32_t msecs); +void Sys_Sleep(uint32_t msecs); // yield for about 'msecs' milliseconds. -void Sys_SendKeyEvents (void); +void Sys_SendKeyEvents(void); // Perform Key_Event () callbacks until the input que is empty -#endif /* _QUAKE_SYS_H */ +#endif /* _QUAKE_SYS_H */ diff --git a/source/unix/net_bsd.c b/source/unix/net_bsd.c index 496f50d..599862b 100644 --- a/source/unix/net_bsd.c +++ b/source/unix/net_bsd.c @@ -30,7 +30,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. net_driver_t net_drivers[] = { - { "Loopback", + { + "Loopback", false, Loop_Init, Loop_Listen, @@ -46,7 +47,8 @@ net_driver_t net_drivers[] = Loop_Shutdown }, - { "Datagram", + { + "Datagram", false, Datagram_Init, Datagram_Listen, @@ -67,9 +69,10 @@ const int32_t net_numdrivers = (sizeof(net_drivers) / sizeof(net_drivers[0])); #include "net_udp.h" -net_landriver_t net_landrivers[] = +net_landriver_t net_landrivers[] = { - { "UDP", + { + "UDP", false, 0, UDP_Init, diff --git a/source/unix/net_udp.c b/source/unix/net_udp.c index 9fdf70d..90a2fca 100644 --- a/source/unix/net_udp.c +++ b/source/unix/net_udp.c @@ -26,35 +26,35 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" #include "net_defs.h" -static sys_socket_t net_acceptsocket = INVALID_SOCKET; // socket for fielding new connections +static sys_socket_t net_acceptsocket = INVALID_SOCKET; // socket for fielding new connections static sys_socket_t net_controlsocket; static sys_socket_t net_broadcastsocket = 0; static struct sockaddr_in broadcastaddr; -static in_addr_t myAddr; +static in_addr_t myAddr; #include "net_udp.h" //============================================================================= -sys_socket_t UDP_Init (void) +sys_socket_t UDP_Init(void) { - int32_t err; - char *tst; - char buff[MAXHOSTNAMELEN]; - struct hostent *local; - struct qsockaddr addr; + int32_t err; + char *tst; + char buff[MAXHOSTNAMELEN]; + struct hostent *local; + struct qsockaddr addr; - if (COM_CheckParm ("-noudp")) + if(COM_CheckParm("-noudp")) return INVALID_SOCKET; // determine my name & address myAddr = htonl(INADDR_LOOPBACK); - if (gethostname(buff, MAXHOSTNAMELEN) != 0) + if(gethostname(buff, MAXHOSTNAMELEN) != 0) { err = SOCKETERRNO; Con_SafePrintf("UDP_Init: gethostname failed (%s)\n", - socketerror(err)); + socketerror(err)); } else { @@ -64,28 +64,28 @@ sys_socket_t UDP_Init (void) // don't bother calling gethostbyname(), because it blocks for a few seconds // and then fails (on my system anyway.) tst = strstr(buff, ".local"); - if (tst && tst[6] == '\0') + if(tst && tst[6] == '\0') { Con_SafePrintf("UDP_Init: skipping gethostbyname for %s\n", buff); } else #endif - if (!(local = gethostbyname(buff))) - { - Con_SafePrintf("UDP_Init: gethostbyname failed (%s)\n", - hstrerror(h_errno)); - } - else if (local->h_addrtype != AF_INET) - { - Con_SafePrintf("UDP_Init: address from gethostbyname not IPv4\n"); - } - else - { - myAddr = *(in_addr_t *)local->h_addr_list[0]; - } + if(!(local = gethostbyname(buff))) + { + Con_SafePrintf("UDP_Init: gethostbyname failed (%s)\n", + hstrerror(h_errno)); + } + else if(local->h_addrtype != AF_INET) + { + Con_SafePrintf("UDP_Init: address from gethostbyname not IPv4\n"); + } + else + { + myAddr = *(in_addr_t *)local->h_addr_list[0]; + } } - if ((net_controlsocket = UDP_OpenSocket(0)) == INVALID_SOCKET) + if((net_controlsocket = UDP_OpenSocket(0)) == INVALID_SOCKET) { Con_SafePrintf("UDP_Init: Unable to open control socket, UDP disabled\n"); return INVALID_SOCKET; @@ -95,10 +95,10 @@ sys_socket_t UDP_Init (void) broadcastaddr.sin_addr.s_addr = INADDR_BROADCAST; broadcastaddr.sin_port = htons((uint16_t)net_hostport); - UDP_GetSocketAddr (net_controlsocket, &addr); - strcpy(my_tcpip_address, UDP_AddrToString (&addr)); + UDP_GetSocketAddr(net_controlsocket, &addr); + strcpy(my_tcpip_address, UDP_AddrToString(&addr)); tst = strrchr(my_tcpip_address, ':'); - if (tst) *tst = 0; + if(tst) *tst = 0; Con_SafePrintf("UDP Initialized\n"); tcpipAvailable = true; @@ -108,73 +108,73 @@ sys_socket_t UDP_Init (void) //============================================================================= -void UDP_Shutdown (void) +void UDP_Shutdown(void) { - UDP_Listen (false); - UDP_CloseSocket (net_controlsocket); + UDP_Listen(false); + UDP_CloseSocket(net_controlsocket); } //============================================================================= -void UDP_Listen (bool state) +void UDP_Listen(bool state) { // enable listening - if (state) + if(state) { - if (net_acceptsocket != INVALID_SOCKET) + if(net_acceptsocket != INVALID_SOCKET) return; - if ((net_acceptsocket = UDP_OpenSocket (net_hostport)) == INVALID_SOCKET) - Sys_Error ("UDP_Listen: Unable to open accept socket"); + if((net_acceptsocket = UDP_OpenSocket(net_hostport)) == INVALID_SOCKET) + Sys_Error("UDP_Listen: Unable to open accept socket"); return; } // disable listening - if (net_acceptsocket == INVALID_SOCKET) + if(net_acceptsocket == INVALID_SOCKET) return; - UDP_CloseSocket (net_acceptsocket); + UDP_CloseSocket(net_acceptsocket); net_acceptsocket = INVALID_SOCKET; } //============================================================================= -sys_socket_t UDP_OpenSocket (int32_t port) +sys_socket_t UDP_OpenSocket(int32_t port) { sys_socket_t newsocket; struct sockaddr_in address; int32_t _true = 1; int32_t err; - if ((newsocket = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) + if((newsocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) { err = SOCKETERRNO; Con_SafePrintf("UDP_OpenSocket: %s\n", socketerror(err)); return INVALID_SOCKET; } - if (ioctlsocket (newsocket, FIONBIO, &_true) == SOCKET_ERROR) + if(ioctlsocket(newsocket, FIONBIO, &_true) == SOCKET_ERROR) goto ErrorReturn; memset(&address, 0, sizeof(struct sockaddr_in)); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons((uint16_t)port); - if (bind (newsocket, (struct sockaddr *)&address, sizeof(address)) == 0) + if(bind(newsocket, (struct sockaddr *)&address, sizeof(address)) == 0) return newsocket; ErrorReturn: err = SOCKETERRNO; Con_SafePrintf("UDP_OpenSocket: %s\n", socketerror(err)); - UDP_CloseSocket (newsocket); + UDP_CloseSocket(newsocket); return INVALID_SOCKET; } //============================================================================= -int32_t UDP_CloseSocket (sys_socket_t socketid) +int32_t UDP_CloseSocket(sys_socket_t socketid) { - if (socketid == net_broadcastsocket) + if(socketid == net_broadcastsocket) net_broadcastsocket = 0; - return closesocket (socketid); + return closesocket(socketid); } //============================================================================= @@ -187,40 +187,40 @@ this lets you type only as much of the net address as required, using the local network components to fill in the rest ============ */ -static int32_t PartialIPAddress (const char *in, struct qsockaddr *hostaddr) +static int32_t PartialIPAddress(const char *in, struct qsockaddr *hostaddr) { - char buff[256]; - char *b; - int32_t addr, mask, num, port, run; + char buff[256]; + char *b; + int32_t addr, mask, num, port, run; buff[0] = '.'; b = buff; - strcpy(buff+1, in); - if (buff[1] == '.') + strcpy(buff + 1, in); + if(buff[1] == '.') b++; addr = 0; mask = -1; - while (*b == '.') + while(*b == '.') { b++; num = 0; run = 0; - while (!( *b < '0' || *b > '9')) + while(!(*b < '0' || *b > '9')) { - num = num*10 + *b++ - '0'; - if (++run > 3) + num = num * 10 + *b++ - '0'; + if(++run > 3) return -1; } - if ((*b < '0' || *b > '9') && *b != '.' && *b != ':' && *b != 0) + if((*b < '0' || *b > '9') && *b != '.' && *b != ':' && *b != 0) return -1; - if (num < 0 || num > 255) + if(num < 0 || num > 255) return -1; mask <<= 8; - addr = (addr<<8) + num; + addr = (addr << 8) + num; } - if (*b++ == ':') + if(*b++ == ':') port = atoi(b); else port = net_hostport; @@ -228,14 +228,14 @@ static int32_t PartialIPAddress (const char *in, struct qsockaddr *hostaddr) hostaddr->qsa_family = AF_INET; ((struct sockaddr_in *)hostaddr)->sin_port = htons((uint16_t)port); ((struct sockaddr_in *)hostaddr)->sin_addr.s_addr = - (myAddr & htonl(mask)) | htonl(addr); + (myAddr & htonl(mask)) | htonl(addr); return 0; } //============================================================================= -int32_t UDP_Connect (sys_socket_t socketid, struct qsockaddr *addr) +int32_t UDP_Connect(sys_socket_t socketid, struct qsockaddr *addr) { (void)socketid, (void)addr; return 0; @@ -243,58 +243,58 @@ int32_t UDP_Connect (sys_socket_t socketid, struct qsockaddr *addr) //============================================================================= -sys_socket_t UDP_CheckNewConnections (void) +sys_socket_t UDP_CheckNewConnections(void) { - int32_t available; - struct sockaddr_in from; - socklen_t fromlen; - char buff[1]; + int32_t available; + struct sockaddr_in from; + socklen_t fromlen; + char buff[1]; - if (net_acceptsocket == INVALID_SOCKET) + if(net_acceptsocket == INVALID_SOCKET) return INVALID_SOCKET; - if (ioctl (net_acceptsocket, FIONREAD, &available) == -1) + if(ioctl(net_acceptsocket, FIONREAD, &available) == -1) { int32_t err = SOCKETERRNO; - Sys_Error ("UDP: ioctlsocket (FIONREAD) failed (%s)", socketerror(err)); + Sys_Error("UDP: ioctlsocket (FIONREAD) failed (%s)", socketerror(err)); } - if (available) + if(available) return net_acceptsocket; // quietly absorb empty packets - recvfrom (net_acceptsocket, buff, 0, 0, (struct sockaddr *) &from, &fromlen); + recvfrom(net_acceptsocket, buff, 0, 0, (struct sockaddr *) &from, &fromlen); return INVALID_SOCKET; } //============================================================================= -int32_t UDP_Read (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr) +int32_t UDP_Read(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr) { socklen_t addrlen = sizeof(struct qsockaddr); int32_t ret; - ret = recvfrom (socketid, buf, len, 0, (struct sockaddr *)addr, &addrlen); - if (ret == SOCKET_ERROR) + ret = recvfrom(socketid, buf, len, 0, (struct sockaddr *)addr, &addrlen); + if(ret == SOCKET_ERROR) { int32_t err = SOCKETERRNO; - if (err == NET_EWOULDBLOCK || err == NET_ECONNREFUSED) + if(err == NET_EWOULDBLOCK || err == NET_ECONNREFUSED) return 0; - Con_SafePrintf ("UDP_Read, recvfrom: %s\n", socketerror(err)); + Con_SafePrintf("UDP_Read, recvfrom: %s\n", socketerror(err)); } return ret; } //============================================================================= -static int32_t UDP_MakeSocketBroadcastCapable (sys_socket_t socketid) +static int32_t UDP_MakeSocketBroadcastCapable(sys_socket_t socketid) { - int32_t i = 1; + int32_t i = 1; // make this socket broadcast capable - if (setsockopt(socketid, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) - == SOCKET_ERROR) + if(setsockopt(socketid, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) + == SOCKET_ERROR) { int32_t err = SOCKETERRNO; - Con_SafePrintf ("UDP, setsockopt: %s\n", socketerror(err)); + Con_SafePrintf("UDP, setsockopt: %s\n", socketerror(err)); return -1; } net_broadcastsocket = socketid; @@ -304,62 +304,62 @@ static int32_t UDP_MakeSocketBroadcastCapable (sys_socket_t socketid) //============================================================================= -int32_t UDP_Broadcast (sys_socket_t socketid, byte *buf, int32_t len) +int32_t UDP_Broadcast(sys_socket_t socketid, byte *buf, int32_t len) { - int32_t ret; + int32_t ret; - if (socketid != net_broadcastsocket) + if(socketid != net_broadcastsocket) { - if (net_broadcastsocket != 0) + if(net_broadcastsocket != 0) Sys_Error("Attempted to use multiple broadcasts sockets"); - ret = UDP_MakeSocketBroadcastCapable (socketid); - if (ret == -1) + ret = UDP_MakeSocketBroadcastCapable(socketid); + if(ret == -1) { Con_Printf("Unable to make socket broadcast capable\n"); return ret; } } - return UDP_Write (socketid, buf, len, (struct qsockaddr *)&broadcastaddr); + return UDP_Write(socketid, buf, len, (struct qsockaddr *)&broadcastaddr); } //============================================================================= -int32_t UDP_Write (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr) +int32_t UDP_Write(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr) { - int32_t ret; + int32_t ret; - ret = sendto (socketid, buf, len, 0, (struct sockaddr *)addr, - sizeof(struct qsockaddr)); - if (ret == SOCKET_ERROR) + ret = sendto(socketid, buf, len, 0, (struct sockaddr *)addr, + sizeof(struct qsockaddr)); + if(ret == SOCKET_ERROR) { int32_t err = SOCKETERRNO; - if (err == NET_EWOULDBLOCK) + if(err == NET_EWOULDBLOCK) return 0; - Con_SafePrintf ("UDP_Write, sendto: %s\n", socketerror(err)); + Con_SafePrintf("UDP_Write, sendto: %s\n", socketerror(err)); } return ret; } //============================================================================= -const char *UDP_AddrToString (struct qsockaddr *addr) +const char *UDP_AddrToString(struct qsockaddr *addr) { static char buffer[22]; - int32_t haddr; + int32_t haddr; haddr = ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr); - q_snprintf (buffer, sizeof(buffer), "%" PRIi32 ".%" PRIi32 ".%" PRIi32 ".%" PRIi32 ":%" PRIi32 "", (haddr >> 24) & 0xff, - (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff, - ntohs(((struct sockaddr_in *)addr)->sin_port)); + q_snprintf(buffer, sizeof(buffer), "%" PRIi32 ".%" PRIi32 ".%" PRIi32 ".%" PRIi32 ":%" PRIi32 "", (haddr >> 24) & 0xff, + (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff, + ntohs(((struct sockaddr_in *)addr)->sin_port)); return buffer; } //============================================================================= -int32_t UDP_StringToAddr (const char *string, struct qsockaddr *addr) +int32_t UDP_StringToAddr(const char *string, struct qsockaddr *addr) { - int32_t ha1, ha2, ha3, ha4, hp, ipaddr; + int32_t ha1, ha2, ha3, ha4, hp, ipaddr; sscanf(string, "%" PRIi32 ".%" PRIi32 ".%" PRIi32 ".%" PRIi32 ":%" PRIi32 "", &ha1, &ha2, &ha3, &ha4, &hp); ipaddr = (ha1 << 24) | (ha2 << 16) | (ha3 << 8) | ha4; @@ -372,17 +372,17 @@ int32_t UDP_StringToAddr (const char *string, struct qsockaddr *addr) //============================================================================= -int32_t UDP_GetSocketAddr (sys_socket_t socketid, struct qsockaddr *addr) +int32_t UDP_GetSocketAddr(sys_socket_t socketid, struct qsockaddr *addr) { socklen_t addrlen = sizeof(struct qsockaddr); in_addr_t a; memset(addr, 0, sizeof(struct qsockaddr)); - if (getsockname(socketid, (struct sockaddr *)addr, &addrlen) != 0) + if(getsockname(socketid, (struct sockaddr *)addr, &addrlen) != 0) return -1; a = ((struct sockaddr_in *)addr)->sin_addr.s_addr; - if (a == 0 || a == htonl(INADDR_LOOPBACK)) + if(a == 0 || a == htonl(INADDR_LOOPBACK)) ((struct sockaddr_in *)addr)->sin_addr.s_addr = myAddr; return 0; @@ -390,56 +390,56 @@ int32_t UDP_GetSocketAddr (sys_socket_t socketid, struct qsockaddr *addr) //============================================================================= -int32_t UDP_GetNameFromAddr (struct qsockaddr *addr, char *name) +int32_t UDP_GetNameFromAddr(struct qsockaddr *addr, char *name) { struct hostent *hostentry; - hostentry = gethostbyaddr ((char *)&((struct sockaddr_in *)addr)->sin_addr, - sizeof(struct in_addr), AF_INET); - if (hostentry) + hostentry = gethostbyaddr((char *) & ((struct sockaddr_in *)addr)->sin_addr, + sizeof(struct in_addr), AF_INET); + if(hostentry) { - strncpy (name, (char *)hostentry->h_name, NET_NAMELEN - 1); + strncpy(name, (char *)hostentry->h_name, NET_NAMELEN - 1); return 0; } - strcpy (name, UDP_AddrToString (addr)); + strcpy(name, UDP_AddrToString(addr)); return 0; } //============================================================================= -int32_t UDP_GetAddrFromName (const char *name, struct qsockaddr *addr) +int32_t UDP_GetAddrFromName(const char *name, struct qsockaddr *addr) { struct hostent *hostentry; - if (name[0] >= '0' && name[0] <= '9') - return PartialIPAddress (name, addr); + if(name[0] >= '0' && name[0] <= '9') + return PartialIPAddress(name, addr); - hostentry = gethostbyname (name); - if (!hostentry) + hostentry = gethostbyname(name); + if(!hostentry) return -1; addr->qsa_family = AF_INET; ((struct sockaddr_in *)addr)->sin_port = htons((uint16_t)net_hostport); ((struct sockaddr_in *)addr)->sin_addr.s_addr = - *(in_addr_t *)hostentry->h_addr_list[0]; + *(in_addr_t *)hostentry->h_addr_list[0]; return 0; } //============================================================================= -int32_t UDP_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2) +int32_t UDP_AddrCompare(struct qsockaddr *addr1, struct qsockaddr *addr2) { - if (addr1->qsa_family != addr2->qsa_family) + if(addr1->qsa_family != addr2->qsa_family) return -1; - if (((struct sockaddr_in *)addr1)->sin_addr.s_addr != - ((struct sockaddr_in *)addr2)->sin_addr.s_addr) + if(((struct sockaddr_in *)addr1)->sin_addr.s_addr != + ((struct sockaddr_in *)addr2)->sin_addr.s_addr) return -1; - if (((struct sockaddr_in *)addr1)->sin_port != - ((struct sockaddr_in *)addr2)->sin_port) + if(((struct sockaddr_in *)addr1)->sin_port != + ((struct sockaddr_in *)addr2)->sin_port) return 1; return 0; @@ -447,13 +447,13 @@ int32_t UDP_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2) //============================================================================= -int32_t UDP_GetSocketPort (struct qsockaddr *addr) +int32_t UDP_GetSocketPort(struct qsockaddr *addr) { return ntohs(((struct sockaddr_in *)addr)->sin_port); } -int32_t UDP_SetSocketPort (struct qsockaddr *addr, int32_t port) +int32_t UDP_SetSocketPort(struct qsockaddr *addr, int32_t port) { ((struct sockaddr_in *)addr)->sin_port = htons((uint16_t)port); return 0; diff --git a/source/unix/net_udp.h b/source/unix/net_udp.h index bba4f4b..8d3bc19 100644 --- a/source/unix/net_udp.h +++ b/source/unix/net_udp.h @@ -9,7 +9,7 @@ of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. @@ -22,24 +22,24 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef __net_udp_h #define __net_udp_h -sys_socket_t UDP_Init (void); -void UDP_Shutdown (void); -void UDP_Listen (bool state); -sys_socket_t UDP_OpenSocket (int32_t port); -int32_t UDP_CloseSocket (sys_socket_t socketid); -int32_t UDP_Connect (sys_socket_t socketid, struct qsockaddr *addr); -sys_socket_t UDP_CheckNewConnections (void); -int32_t UDP_Read (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); -int32_t UDP_Write (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); -int32_t UDP_Broadcast (sys_socket_t socketid, byte *buf, int32_t len); -const char *UDP_AddrToString (struct qsockaddr *addr); -int32_t UDP_StringToAddr (const char *string, struct qsockaddr *addr); -int32_t UDP_GetSocketAddr (sys_socket_t socketid, struct qsockaddr *addr); -int32_t UDP_GetNameFromAddr (struct qsockaddr *addr, char *name); -int32_t UDP_GetAddrFromName (const char *name, struct qsockaddr *addr); -int32_t UDP_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2); -int32_t UDP_GetSocketPort (struct qsockaddr *addr); -int32_t UDP_SetSocketPort (struct qsockaddr *addr, int32_t port); +sys_socket_t UDP_Init(void); +void UDP_Shutdown(void); +void UDP_Listen(bool state); +sys_socket_t UDP_OpenSocket(int32_t port); +int32_t UDP_CloseSocket(sys_socket_t socketid); +int32_t UDP_Connect(sys_socket_t socketid, struct qsockaddr *addr); +sys_socket_t UDP_CheckNewConnections(void); +int32_t UDP_Read(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); +int32_t UDP_Write(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); +int32_t UDP_Broadcast(sys_socket_t socketid, byte *buf, int32_t len); +const char *UDP_AddrToString(struct qsockaddr *addr); +int32_t UDP_StringToAddr(const char *string, struct qsockaddr *addr); +int32_t UDP_GetSocketAddr(sys_socket_t socketid, struct qsockaddr *addr); +int32_t UDP_GetNameFromAddr(struct qsockaddr *addr, char *name); +int32_t UDP_GetAddrFromName(const char *name, struct qsockaddr *addr); +int32_t UDP_AddrCompare(struct qsockaddr *addr1, struct qsockaddr *addr2); +int32_t UDP_GetSocketPort(struct qsockaddr *addr); +int32_t UDP_SetSocketPort(struct qsockaddr *addr, int32_t port); -#endif /* __net_udp_h */ +#endif /* __net_udp_h */ diff --git a/source/unix/sys_sdl_unix.c b/source/unix/sys_sdl_unix.c index 29022e1..a9b95ec 100644 --- a/source/unix/sys_sdl_unix.c +++ b/source/unix/sys_sdl_unix.c @@ -28,7 +28,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include #include #ifdef PLATFORM_OSX -#include /* dirname() and basename() */ +#include /* dirname() and basename() */ #endif #include #include @@ -38,47 +38,47 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include -bool isDedicated; -cvar_t sys_throttle = {"sys_throttle", "0.02", CVAR_ARCHIVE}; +bool isDedicated; +cvar_t sys_throttle = {"sys_throttle", "0.02", CVAR_ARCHIVE}; -#define MAX_HANDLES 32 /* johnfitz -- was 10 */ -static FILE *sys_handles[MAX_HANDLES]; +#define MAX_HANDLES 32 /* johnfitz -- was 10 */ +static FILE *sys_handles[MAX_HANDLES]; -static int32_t findhandle (void) +static int32_t findhandle(void) { int32_t i; - for (i = 1; i < MAX_HANDLES; i++) + for(i = 1; i < MAX_HANDLES; i++) { - if (!sys_handles[i]) + if(!sys_handles[i]) return i; } - Sys_Error ("out of handles"); + Sys_Error("out of handles"); return -1; } -long Sys_filelength (FILE *f) +long Sys_filelength(FILE *f) { - long pos, end; + long pos, end; - pos = ftell (f); - fseek (f, 0, SEEK_END); - end = ftell (f); - fseek (f, pos, SEEK_SET); + pos = ftell(f); + fseek(f, 0, SEEK_END); + end = ftell(f); + fseek(f, pos, SEEK_SET); return end; } -int32_t Sys_FileOpenRead (const char *path, int32_t *hndl) +int32_t Sys_FileOpenRead(const char *path, int32_t *hndl) { - FILE *f; - int32_t i, retval; + FILE *f; + int32_t i, retval; - i = findhandle (); + i = findhandle(); f = fopen(path, "rb"); - if (!f) + if(!f) { *hndl = -1; retval = -1; @@ -93,49 +93,49 @@ int32_t Sys_FileOpenRead (const char *path, int32_t *hndl) return retval; } -int32_t Sys_FileOpenWrite (const char *path) +int32_t Sys_FileOpenWrite(const char *path) { - FILE *f; - int32_t i; + FILE *f; + int32_t i; - i = findhandle (); + i = findhandle(); f = fopen(path, "wb"); - if (!f) - Sys_Error ("Error opening %s: %s", path, strerror(errno)); + if(!f) + Sys_Error("Error opening %s: %s", path, strerror(errno)); sys_handles[i] = f; return i; } -void Sys_FileClose (int32_t handle) +void Sys_FileClose(int32_t handle) { - fclose (sys_handles[handle]); + fclose(sys_handles[handle]); sys_handles[handle] = NULL; } -void Sys_FileSeek (int32_t handle, int32_t position) +void Sys_FileSeek(int32_t handle, int32_t position) { - fseek (sys_handles[handle], position, SEEK_SET); + fseek(sys_handles[handle], position, SEEK_SET); } -int32_t Sys_FileRead (int32_t handle, void *dest, int32_t count) +int32_t Sys_FileRead(int32_t handle, void *dest, int32_t count) { - return fread (dest, 1, count, sys_handles[handle]); + return fread(dest, 1, count, sys_handles[handle]); } -int32_t Sys_FileWrite (int32_t handle, const void *data, int32_t count) +int32_t Sys_FileWrite(int32_t handle, const void *data, int32_t count) { - return fwrite (data, 1, count, sys_handles[handle]); + return fwrite(data, 1, count, sys_handles[handle]); } -int32_t Sys_FileTime (const char *path) +int32_t Sys_FileTime(const char *path) { - FILE *f; + FILE *f; f = fopen(path, "rb"); - if (f) + if(f) { fclose(f); return 1; @@ -146,7 +146,7 @@ int32_t Sys_FileTime (const char *path) #if defined(__linux__) || defined(__sun) || defined(sun) || defined(_AIX) -static int32_t Sys_NumCPUs (void) +static int32_t Sys_NumCPUs(void) { int32_t numcpus = sysconf(_SC_NPROCESSORS_ONLN); return (numcpus < 1) ? 1 : numcpus; @@ -154,45 +154,45 @@ static int32_t Sys_NumCPUs (void) #elif defined(PLATFORM_OSX) #include -#if !defined(HW_AVAILCPU) /* using an ancient SDK? */ -#define HW_AVAILCPU 25 /* needs >= 10.2 */ +#if !defined(HW_AVAILCPU) /* using an ancient SDK? */ +#define HW_AVAILCPU 25 /* needs >= 10.2 */ #endif -static int32_t Sys_NumCPUs (void) +static int32_t Sys_NumCPUs(void) { int32_t numcpus; int32_t mib[2]; size_t len; -#if defined(_SC_NPROCESSORS_ONLN) /* needs >= 10.5 */ +#if defined(_SC_NPROCESSORS_ONLN) /* needs >= 10.5 */ numcpus = sysconf(_SC_NPROCESSORS_ONLN); - if (numcpus != -1) + if(numcpus != -1) return (numcpus < 1) ? 1 : numcpus; #endif len = sizeof(numcpus); mib[0] = CTL_HW; mib[1] = HW_AVAILCPU; sysctl(mib, 2, &numcpus, &len, NULL, 0); - if (sysctl(mib, 2, &numcpus, &len, NULL, 0) == -1) + if(sysctl(mib, 2, &numcpus, &len, NULL, 0) == -1) { mib[1] = HW_NCPU; - if (sysctl(mib, 2, &numcpus, &len, NULL, 0) == -1) + if(sysctl(mib, 2, &numcpus, &len, NULL, 0) == -1) return 1; } return (numcpus < 1) ? 1 : numcpus; } #elif defined(__sgi) || defined(sgi) || defined(__sgi__) /* IRIX */ -static int32_t Sys_NumCPUs (void) +static int32_t Sys_NumCPUs(void) { int32_t numcpus = sysconf(_SC_NPROC_ONLN); - if (numcpus < 1) + if(numcpus < 1) numcpus = 1; return numcpus; } #elif defined(PLATFORM_BSD) #include -static int32_t Sys_NumCPUs (void) +static int32_t Sys_NumCPUs(void) { int32_t numcpus; int32_t mib[2]; @@ -200,27 +200,27 @@ static int32_t Sys_NumCPUs (void) #if defined(_SC_NPROCESSORS_ONLN) numcpus = sysconf(_SC_NPROCESSORS_ONLN); - if (numcpus != -1) + if(numcpus != -1) return (numcpus < 1) ? 1 : numcpus; #endif len = sizeof(numcpus); mib[0] = CTL_HW; mib[1] = HW_NCPU; - if (sysctl(mib, 2, &numcpus, &len, NULL, 0) == -1) + if(sysctl(mib, 2, &numcpus, &len, NULL, 0) == -1) return 1; return (numcpus < 1) ? 1 : numcpus; } #elif defined(__hpux) || defined(__hpux__) || defined(_hpux) #include -static int32_t Sys_NumCPUs (void) +static int32_t Sys_NumCPUs(void) { int32_t numcpus = mpctl(MPC_GETNUMSPUS, NULL, NULL); return numcpus; } #else /* unknown OS */ -static int32_t Sys_NumCPUs (void) +static int32_t Sys_NumCPUs(void) { return -2; } @@ -270,68 +270,70 @@ static char const *Sys_GetUserDir(void) } #ifdef PLATFORM_OSX -static char *OSX_StripAppBundle (char *dir) -{ /* based on the ioquake3 project at icculus.org. */ - static char osx_path[MAX_OSPATH]; +static char *OSX_StripAppBundle(char *dir) +{ + /* based on the ioquake3 project at icculus.org. */ + static char osx_path[MAX_OSPATH]; - q_strlcpy (osx_path, dir, sizeof(osx_path)); - if (strcmp(basename(osx_path), "MacOS")) + q_strlcpy(osx_path, dir, sizeof(osx_path)); + if(strcmp(basename(osx_path), "MacOS")) return dir; - q_strlcpy (osx_path, dirname(osx_path), sizeof(osx_path)); - if (strcmp(basename(osx_path), "Contents")) + q_strlcpy(osx_path, dirname(osx_path), sizeof(osx_path)); + if(strcmp(basename(osx_path), "Contents")) return dir; - q_strlcpy (osx_path, dirname(osx_path), sizeof(osx_path)); - if (!strstr(basename(osx_path), ".app")) + q_strlcpy(osx_path, dirname(osx_path), sizeof(osx_path)); + if(!strstr(basename(osx_path), ".app")) return dir; - q_strlcpy (osx_path, dirname(osx_path), sizeof(osx_path)); + q_strlcpy(osx_path, dirname(osx_path), sizeof(osx_path)); return osx_path; } -static void Sys_GetBasedir (char *argv0, char *dst, size_t dstsize) +static void Sys_GetBasedir(char *argv0, char *dst, size_t dstsize) { - char *tmp; + char *tmp; - if (realpath(argv0, dst) == NULL) + if(realpath(argv0, dst) == NULL) { perror("realpath"); - if (getcwd(dst, dstsize - 1) == NULL) - _fail: Sys_Error ("Couldn't determine current directory"); + if(getcwd(dst, dstsize - 1) == NULL) +_fail: + Sys_Error("Couldn't determine current directory"); } else { /* strip off the binary name */ - if (! (tmp = strdup (dst))) goto _fail; - q_strlcpy (dst, dirname(tmp), dstsize); - free (tmp); + if(!(tmp = strdup(dst))) goto _fail; + q_strlcpy(dst, dirname(tmp), dstsize); + free(tmp); } tmp = OSX_StripAppBundle(dst); - if (tmp != dst) - q_strlcpy (dst, tmp, dstsize); + if(tmp != dst) + q_strlcpy(dst, tmp, dstsize); } #else -static void Sys_GetBasedir (char *argv0, char *dst, size_t dstsize) +static void Sys_GetBasedir(char *argv0, char *dst, size_t dstsize) { - char *tmp; + char *tmp; (void)argv0; - if (getcwd(dst, dstsize - 1) == NULL) - Sys_Error ("Couldn't determine current directory"); + if(getcwd(dst, dstsize - 1) == NULL) + Sys_Error("Couldn't determine current directory"); tmp = dst; - while (*tmp != 0) + while(*tmp != 0) tmp++; - while (*tmp == 0 && tmp != dst) + while(*tmp == 0 && tmp != dst) { --tmp; - if (tmp != dst && *tmp == '/') + if(tmp != dst && *tmp == '/') *tmp = 0; } } #endif -void Sys_Init (void) +void Sys_Init(void) { static char cwd[MAX_OSPATH]; @@ -355,16 +357,16 @@ void Sys_Init (void) Sys_Printf("Detected %" PRIi32 " CPUs.\n", host_parms->numcpus); } -void Sys_mkdir (const char *path) +void Sys_mkdir(const char *path) { - int32_t rc = mkdir (path, 0777); - if (rc != 0 && errno == EEXIST) + int32_t rc = mkdir(path, 0777); + if(rc != 0 && errno == EEXIST) { struct stat st; - if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) + if(stat(path, &st) == 0 && S_ISDIR(st.st_mode)) rc = 0; } - if (rc != 0) + if(rc != 0) { rc = errno; Sys_Error("Unable to create directory %s: %s", path, strerror(rc)); @@ -374,29 +376,29 @@ void Sys_mkdir (const char *path) static const char errortxt1[] = "\nERROR-OUT BEGIN\n\n"; static const char errortxt2[] = "\nQUAKE ERROR: "; -void Sys_Error (const char *error, ...) +void Sys_Error(const char *error, ...) { - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; host_parms->errstate++; - va_start (argptr, error); - q_vsnprintf (text, sizeof(text), error, argptr); - va_end (argptr); + va_start(argptr, error); + q_vsnprintf(text, sizeof(text), error, argptr); + va_end(argptr); - fputs (errortxt1, stderr); - Host_Shutdown (); - fputs (errortxt2, stderr); - fputs (text, stderr); - fputs ("\n\n", stderr); - if (!isDedicated) + fputs(errortxt1, stderr); + Host_Shutdown(); + fputs(errortxt2, stderr); + fputs(text, stderr); + fputs("\n\n", stderr); + if(!isDedicated) PL_ErrorDialog(text); - exit (1); + exit(1); } -void Sys_Printf (const char *fmt, ...) +void Sys_Printf(const char *fmt, ...) { va_list argptr; @@ -405,43 +407,43 @@ void Sys_Printf (const char *fmt, ...) va_end(argptr); } -void Sys_Quit (void) +void Sys_Quit(void) { Host_Shutdown(); - exit (0); + exit(0); } -double Sys_DoubleTime (void) +double Sys_DoubleTime(void) { return SDL_GetTicks() / 1000.0; } -const char *Sys_ConsoleInput (void) +const char *Sys_ConsoleInput(void) { - static char con_text[256]; - static int32_t textlen; - char c; - fd_set set; - struct timeval timeout; + static char con_text[256]; + static int32_t textlen; + char c; + fd_set set; + struct timeval timeout; - FD_ZERO (&set); - FD_SET (0, &set); // stdin + FD_ZERO(&set); + FD_SET(0, &set); // stdin timeout.tv_sec = 0; timeout.tv_usec = 0; - while (select (1, &set, NULL, NULL, &timeout)) + while(select(1, &set, NULL, NULL, &timeout)) { - read (0, &c, 1); - if (c == '\n' || c == '\r') + read(0, &c, 1); + if(c == '\n' || c == '\r') { con_text[textlen] = '\0'; textlen = 0; return con_text; } - else if (c == 8) + else if(c == 8) { - if (textlen) + if(textlen) { textlen--; con_text[textlen] = '\0'; @@ -450,11 +452,11 @@ const char *Sys_ConsoleInput (void) } con_text[textlen] = c; textlen++; - if (textlen < (int32_t) sizeof(con_text)) + if(textlen < (int32_t) sizeof(con_text)) con_text[textlen] = '\0'; else { - // buffer is full + // buffer is full textlen = 0; con_text[0] = '\0'; Sys_Printf("\nConsole input too long!\n"); @@ -465,14 +467,14 @@ const char *Sys_ConsoleInput (void) return NULL; } -void Sys_Sleep (uint32_t msecs) +void Sys_Sleep(uint32_t msecs) { SDL_Delay(msecs); } -void Sys_SendKeyEvents (void) +void Sys_SendKeyEvents(void) { - IN_Commands(); //ericw -- allow joysticks to add keys so they can be used to confirm SCR_ModalMessage + IN_Commands(); //ericw -- allow joysticks to add keys so they can be used to confirm SCR_ModalMessage IN_SendKeyEvents(); } diff --git a/source/vid.h b/source/vid.h index 0fbc9c9..908e3e3 100644 --- a/source/vid.h +++ b/source/vid.h @@ -26,68 +26,68 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // vid.h -- video driver defs -#define VID_CBITS 6 -#define VID_GRADES (1 << VID_CBITS) +#define VID_CBITS 6 +#define VID_GRADES (1 << VID_CBITS) -#define GAMMA_MAX 3.0 +#define GAMMA_MAX 3.0 // moved here for global use -- kristian typedef enum { MS_UNINIT, MS_WINDOWED, MS_FULLSCREEN } modestate_t; -extern modestate_t modestate; +extern modestate_t modestate; // a pixel can be one, two, or four bytes typedef byte pixel_t; typedef struct vrect_s { - int32_t x, y, width, height; - struct vrect_s *pnext; + int32_t x, y, width, height; + struct vrect_s *pnext; } vrect_t; typedef struct { - pixel_t *buffer; // invisible buffer - pixel_t *colormap; // 256 * VID_GRADES size - uint16_t *colormap16; // 256 * VID_GRADES size - int32_t fullbright; // index of first fullbright color - int32_t rowbytes; // may be > width if displayed in a window - int32_t width; - int32_t height; - float aspect; // width / height -- < 0 is taller than wide - int32_t numpages; - int32_t recalc_refdef; // if true, recalc vid-based stuff - pixel_t *conbuffer; - int32_t conrowbytes; - int32_t conwidth; - int32_t conheight; - int32_t maxwarpwidth; - int32_t maxwarpheight; - pixel_t *direct; // direct drawing to framebuffer, if not NULL + pixel_t *buffer; // invisible buffer + pixel_t *colormap; // 256 * VID_GRADES size + uint16_t *colormap16; // 256 * VID_GRADES size + int32_t fullbright; // index of first fullbright color + int32_t rowbytes; // may be > width if displayed in a window + int32_t width; + int32_t height; + float aspect; // width / height -- < 0 is taller than wide + int32_t numpages; + int32_t recalc_refdef; // if true, recalc vid-based stuff + pixel_t *conbuffer; + int32_t conrowbytes; + int32_t conwidth; + int32_t conheight; + int32_t maxwarpwidth; + int32_t maxwarpheight; + pixel_t *direct; // direct drawing to framebuffer, if not NULL } viddef_t; -extern viddef_t vid; // global video state +extern viddef_t vid; // global video state extern void (*vid_menudrawfn)(void); extern void (*vid_menukeyfn)(int32_t key); extern void (*vid_menucmdfn)(void); //johnfitz -void VID_Init (void); //johnfitz -- removed palette from argument list +void VID_Init(void); //johnfitz -- removed palette from argument list -void VID_Shutdown (void); +void VID_Shutdown(void); // Called at shutdown -void VID_Update (vrect_t *rects); +void VID_Update(vrect_t *rects); // flushes the given rectangles from the view buffer to the screen -void VID_SyncCvars (void); +void VID_SyncCvars(void); -void VID_Toggle (void); +void VID_Toggle(void); -void *VID_GetWindow (void); -bool VID_HasMouseOrInputFocus (void); -bool VID_IsMinimized (void); -void VID_Lock (void); +void *VID_GetWindow(void); +bool VID_HasMouseOrInputFocus(void); +bool VID_IsMinimized(void); +void VID_Lock(void); -#endif /* __VID_DEFS_H */ +#endif /* __VID_DEFS_H */ diff --git a/source/view.c b/source/view.c index 84d06bb..79469d2 100644 --- a/source/view.c +++ b/source/view.c @@ -32,46 +32,46 @@ when crossing a water boudnary. */ -cvar_t scr_ofsx = {"scr_ofsx","0", CVAR_NONE}; -cvar_t scr_ofsy = {"scr_ofsy","0", CVAR_NONE}; -cvar_t scr_ofsz = {"scr_ofsz","0", CVAR_NONE}; +cvar_t scr_ofsx = {"scr_ofsx", "0", CVAR_NONE}; +cvar_t scr_ofsy = {"scr_ofsy", "0", CVAR_NONE}; +cvar_t scr_ofsz = {"scr_ofsz", "0", CVAR_NONE}; -cvar_t cl_rollspeed = {"cl_rollspeed", "200", CVAR_NONE}; -cvar_t cl_rollangle = {"cl_rollangle", "2.0", CVAR_NONE}; +cvar_t cl_rollspeed = {"cl_rollspeed", "200", CVAR_NONE}; +cvar_t cl_rollangle = {"cl_rollangle", "2.0", CVAR_NONE}; -cvar_t cl_bob = {"cl_bob","0.02", CVAR_NONE}; -cvar_t cl_bobcycle = {"cl_bobcycle","0.6", CVAR_NONE}; -cvar_t cl_bobup = {"cl_bobup","0.5", CVAR_NONE}; +cvar_t cl_bob = {"cl_bob", "0.02", CVAR_NONE}; +cvar_t cl_bobcycle = {"cl_bobcycle", "0.6", CVAR_NONE}; +cvar_t cl_bobup = {"cl_bobup", "0.5", CVAR_NONE}; -cvar_t v_kicktime = {"v_kicktime", "0.5", CVAR_NONE}; -cvar_t v_kickroll = {"v_kickroll", "0.6", CVAR_NONE}; -cvar_t v_kickpitch = {"v_kickpitch", "0.6", CVAR_NONE}; -cvar_t v_gunkick = {"v_gunkick", "1", CVAR_NONE}; //johnfitz +cvar_t v_kicktime = {"v_kicktime", "0.5", CVAR_NONE}; +cvar_t v_kickroll = {"v_kickroll", "0.6", CVAR_NONE}; +cvar_t v_kickpitch = {"v_kickpitch", "0.6", CVAR_NONE}; +cvar_t v_gunkick = {"v_gunkick", "1", CVAR_NONE}; //johnfitz -cvar_t v_iyaw_cycle = {"v_iyaw_cycle", "2", CVAR_NONE}; -cvar_t v_iroll_cycle = {"v_iroll_cycle", "0.5", CVAR_NONE}; -cvar_t v_ipitch_cycle = {"v_ipitch_cycle", "1", CVAR_NONE}; -cvar_t v_iyaw_level = {"v_iyaw_level", "0.3", CVAR_NONE}; -cvar_t v_iroll_level = {"v_iroll_level", "0.1", CVAR_NONE}; -cvar_t v_ipitch_level = {"v_ipitch_level", "0.3", CVAR_NONE}; +cvar_t v_iyaw_cycle = {"v_iyaw_cycle", "2", CVAR_NONE}; +cvar_t v_iroll_cycle = {"v_iroll_cycle", "0.5", CVAR_NONE}; +cvar_t v_ipitch_cycle = {"v_ipitch_cycle", "1", CVAR_NONE}; +cvar_t v_iyaw_level = {"v_iyaw_level", "0.3", CVAR_NONE}; +cvar_t v_iroll_level = {"v_iroll_level", "0.1", CVAR_NONE}; +cvar_t v_ipitch_level = {"v_ipitch_level", "0.3", CVAR_NONE}; -cvar_t v_idlescale = {"v_idlescale", "0", CVAR_NONE}; +cvar_t v_idlescale = {"v_idlescale", "0", CVAR_NONE}; -cvar_t crosshair = {"crosshair", "0", CVAR_ARCHIVE}; +cvar_t crosshair = {"crosshair", "0", CVAR_ARCHIVE}; -cvar_t gl_cshiftpercent = {"gl_cshiftpercent", "100", CVAR_NONE}; -cvar_t gl_cshiftpercent_contents = {"gl_cshiftpercent_contents", "100", CVAR_NONE}; // QuakeSpasm -cvar_t gl_cshiftpercent_damage = {"gl_cshiftpercent_damage", "100", CVAR_NONE}; // QuakeSpasm -cvar_t gl_cshiftpercent_bonus = {"gl_cshiftpercent_bonus", "100", CVAR_NONE}; // QuakeSpasm -cvar_t gl_cshiftpercent_powerup = {"gl_cshiftpercent_powerup", "100", CVAR_NONE}; // QuakeSpasm +cvar_t gl_cshiftpercent = {"gl_cshiftpercent", "100", CVAR_NONE}; +cvar_t gl_cshiftpercent_contents = {"gl_cshiftpercent_contents", "100", CVAR_NONE}; // QuakeSpasm +cvar_t gl_cshiftpercent_damage = {"gl_cshiftpercent_damage", "100", CVAR_NONE}; // QuakeSpasm +cvar_t gl_cshiftpercent_bonus = {"gl_cshiftpercent_bonus", "100", CVAR_NONE}; // QuakeSpasm +cvar_t gl_cshiftpercent_powerup = {"gl_cshiftpercent_powerup", "100", CVAR_NONE}; // QuakeSpasm -cvar_t r_viewmodel_quake = {"r_viewmodel_quake", "0", CVAR_ARCHIVE}; +cvar_t r_viewmodel_quake = {"r_viewmodel_quake", "0", CVAR_ARCHIVE}; -float v_dmg_time, v_dmg_roll, v_dmg_pitch; +float v_dmg_time, v_dmg_roll, v_dmg_pitch; -extern int32_t in_forward, in_forward2, in_back; +extern int32_t in_forward, in_forward2, in_back; -vec3_t v_punchangles[2]; //johnfitz -- copied from cl.punchangle. 0 is current, 1 is previous value. never the same unless map just loaded +vec3_t v_punchangles[2]; //johnfitz -- copied from cl.punchangle. 0 is current, 1 is previous value. never the same unless map just loaded /* =============== @@ -80,15 +80,15 @@ V_CalcRoll Used by view and sv_user =============== */ -float V_CalcRoll (vec3_t angles, vec3_t velocity) +float V_CalcRoll(vec3_t angles, vec3_t velocity) { - vec3_t forward, right, up; - float sign; - float side; - float value; + vec3_t forward, right, up; + float sign; + float side; + float value; - AngleVectors (angles, forward, right, up); - side = DotProduct (velocity, right); + AngleVectors(angles, forward, right, up); + side = DotProduct(velocity, right); sign = side < 0 ? -1 : 1; side = fabs(side); @@ -96,12 +96,12 @@ float V_CalcRoll (vec3_t angles, vec3_t velocity) // if (cl.inwater) // value *= 6; - if (side < cl_rollspeed.value) + if(side < cl_rollspeed.value) side = side * value / cl_rollspeed.value; else side = value; - return side*sign; + return side * sign; } @@ -111,27 +111,27 @@ V_CalcBob =============== */ -float V_CalcBob (void) +float V_CalcBob(void) { - float bob; - float cycle; + float bob; + float cycle; - cycle = cl.time - (int32_t)(cl.time/cl_bobcycle.value)*cl_bobcycle.value; + cycle = cl.time - (int32_t)(cl.time / cl_bobcycle.value) * cl_bobcycle.value; cycle /= cl_bobcycle.value; - if (cycle < cl_bobup.value) + if(cycle < cl_bobup.value) cycle = M_PI * cycle / cl_bobup.value; else - cycle = M_PI + M_PI*(cycle-cl_bobup.value)/(1.0 - cl_bobup.value); + cycle = M_PI + M_PI * (cycle - cl_bobup.value) / (1.0 - cl_bobup.value); // bob is proportional to velocity in the xy plane // (don't count Z, or jumping messes it up) - bob = sqrt(cl.velocity[0]*cl.velocity[0] + cl.velocity[1]*cl.velocity[1]) * cl_bob.value; + bob = sqrt(cl.velocity[0] * cl.velocity[0] + cl.velocity[1] * cl.velocity[1]) * cl_bob.value; //Con_Printf ("speed: %5.1f\n", VectorLength(cl.velocity)); - bob = bob*0.3 + bob*0.7*sin(cycle); - if (bob > 4) + bob = bob * 0.3 + bob * 0.7 * sin(cycle); + if(bob > 4) bob = 4; - else if (bob < -7) + else if(bob < -7) bob = -7; return bob; } @@ -140,19 +140,19 @@ float V_CalcBob (void) //============================================================================= -cvar_t v_centermove = {"v_centermove", "0.15", CVAR_NONE}; -cvar_t v_centerspeed = {"v_centerspeed","500", CVAR_NONE}; +cvar_t v_centermove = {"v_centermove", "0.15", CVAR_NONE}; +cvar_t v_centerspeed = {"v_centerspeed", "500", CVAR_NONE}; -void V_StartPitchDrift (void) +void V_StartPitchDrift(void) { #if 1 - if (cl.laststop == cl.time) + if(cl.laststop == cl.time) { - return; // something else is keeping it from drifting + return; // something else is keeping it from drifting } #endif - if (cl.nodrift || !cl.pitchvel) + if(cl.nodrift || !cl.pitchvel) { cl.pitchvel = v_centerspeed.value; cl.nodrift = false; @@ -160,7 +160,7 @@ void V_StartPitchDrift (void) } } -void V_StopPitchDrift (void) +void V_StopPitchDrift(void) { cl.laststop = cl.time; cl.nodrift = true; @@ -180,12 +180,12 @@ Drifting is enabled when the center view key is hit, mlook is released and lookspring is non 0, or when =============== */ -void V_DriftPitch (void) +void V_DriftPitch(void) { - float delta, move; + float delta, move; - if (noclip_anglehack || !cl.onground || cls.demoplayback ) - //FIXME: noclip_anglehack is set on the server, so in a nonlocal game this won't work. + if(noclip_anglehack || !cl.onground || cls.demoplayback) + //FIXME: noclip_anglehack is set on the server, so in a nonlocal game this won't work. { cl.driftmove = 0; cl.pitchvel = 0; @@ -193,24 +193,24 @@ void V_DriftPitch (void) } // don't count small mouse motion - if (cl.nodrift) + if(cl.nodrift) { - if ( fabs(cl.cmd.forwardmove) < cl_forwardspeed.value) + if(fabs(cl.cmd.forwardmove) < cl_forwardspeed.value) cl.driftmove = 0; else cl.driftmove += host_frametime; - if ( cl.driftmove > v_centermove.value) + if(cl.driftmove > v_centermove.value) { - if (lookspring.value) - V_StartPitchDrift (); + if(lookspring.value) + V_StartPitchDrift(); } return; } delta = cl.idealpitch - cl.viewangles[PITCH]; - if (!delta) + if(!delta) { cl.pitchvel = 0; return; @@ -221,18 +221,18 @@ void V_DriftPitch (void) //Con_Printf ("move: %f (%f)\n", move, host_frametime); - if (delta > 0) + if(delta > 0) { - if (move > delta) + if(move > delta) { cl.pitchvel = 0; move = delta; } cl.viewangles[PITCH] += move; } - else if (delta < 0) + else if(delta < 0) { - if (move > -delta) + if(move > -delta) { cl.pitchvel = 0; move = -delta; @@ -244,17 +244,17 @@ void V_DriftPitch (void) /* ============================================================================== - VIEW BLENDING + VIEW BLENDING ============================================================================== */ -cshift_t cshift_empty = { {130,80,50}, 0 }; -cshift_t cshift_water = { {130,80,50}, 128 }; -cshift_t cshift_slime = { {0,25,5}, 150 }; -cshift_t cshift_lava = { {255,80,0}, 150 }; +cshift_t cshift_empty = { {130, 80, 50}, 0 }; +cshift_t cshift_water = { {130, 80, 50}, 128 }; +cshift_t cshift_slime = { {0, 25, 5}, 150 }; +cshift_t cshift_lava = { {255, 80, 0}, 150 }; -float v_blend[4]; // rgba 0.0 - 1.0 +float v_blend[4]; // rgba 0.0 - 1.0 //johnfitz -- deleted BuildGammaTable(), V_CheckGamma(), gammatable[], and ramps[][] @@ -263,40 +263,40 @@ float v_blend[4]; // rgba 0.0 - 1.0 V_ParseDamage =============== */ -void V_ParseDamage (void) +void V_ParseDamage(void) { - int32_t armor, blood; - vec3_t from; - int32_t i; - vec3_t forward, right, up; - entity_t *ent; - float side; - float count; + int32_t armor, blood; + vec3_t from; + int32_t i; + vec3_t forward, right, up; + entity_t *ent; + float side; + float count; - armor = MSG_ReadByte (); - blood = MSG_ReadByte (); - for (i=0 ; i<3 ; i++) - from[i] = MSG_ReadCoord (cl.protocolflags); + armor = MSG_ReadByte(); + blood = MSG_ReadByte(); + for(i = 0 ; i < 3 ; i++) + from[i] = MSG_ReadCoord(cl.protocolflags); - count = blood*0.5 + armor*0.5; - if (count < 10) + count = blood * 0.5 + armor * 0.5; + if(count < 10) count = 10; - cl.faceanimtime = cl.time + 0.2; // but sbar face into pain frame + cl.faceanimtime = cl.time + 0.2; // but sbar face into pain frame - cl.cshifts[CSHIFT_DAMAGE].percent += 3*count; - if (cl.cshifts[CSHIFT_DAMAGE].percent < 0) + cl.cshifts[CSHIFT_DAMAGE].percent += 3 * count; + if(cl.cshifts[CSHIFT_DAMAGE].percent < 0) cl.cshifts[CSHIFT_DAMAGE].percent = 0; - if (cl.cshifts[CSHIFT_DAMAGE].percent > 150) + if(cl.cshifts[CSHIFT_DAMAGE].percent > 150) cl.cshifts[CSHIFT_DAMAGE].percent = 150; - if (armor > blood) + if(armor > blood) { cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 200; cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 100; cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 100; } - else if (armor) + else if(armor) { cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 220; cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 50; @@ -314,16 +314,16 @@ void V_ParseDamage (void) // ent = &cl_entities[cl.viewentity]; - VectorSubtract (from, ent->origin, from); - VectorNormalize (from); + VectorSubtract(from, ent->origin, from); + VectorNormalize(from); - AngleVectors (ent->angles, forward, right, up); + AngleVectors(ent->angles, forward, right, up); - side = DotProduct (from, right); - v_dmg_roll = count*side*v_kickroll.value; + side = DotProduct(from, right); + v_dmg_roll = count * side * v_kickroll.value; - side = DotProduct (from, forward); - v_dmg_pitch = count*side*v_kickpitch.value; + side = DotProduct(from, forward); + v_dmg_pitch = count * side * v_kickpitch.value; v_dmg_time = v_kicktime.value; } @@ -334,7 +334,7 @@ void V_ParseDamage (void) V_cshift_f ================== */ -void V_cshift_f (void) +void V_cshift_f(void) { cshift_empty.destcolor[0] = atoi(Cmd_Argv(1)); cshift_empty.destcolor[1] = atoi(Cmd_Argv(2)); @@ -350,7 +350,7 @@ V_BonusFlash_f When you run over an item, the server sends this command ================== */ -void V_BonusFlash_f (void) +void V_BonusFlash_f(void) { cl.cshifts[CSHIFT_BONUS].destcolor[0] = 215; cl.cshifts[CSHIFT_BONUS].destcolor[1] = 186; @@ -365,9 +365,9 @@ V_SetContentsColor Underwater, lava, etc each has a color shift ============= */ -void V_SetContentsColor (int32_t contents) +void V_SetContentsColor(int32_t contents) { - switch (contents) + switch(contents) { case CONTENTS_EMPTY: case CONTENTS_SOLID: @@ -390,30 +390,30 @@ void V_SetContentsColor (int32_t contents) V_CalcPowerupCshift ============= */ -void V_CalcPowerupCshift (void) +void V_CalcPowerupCshift(void) { - if (cl.items & IT_QUAD) + if(cl.items & IT_QUAD) { cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 0; cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 0; cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 255; cl.cshifts[CSHIFT_POWERUP].percent = 30; } - else if (cl.items & IT_SUIT) + else if(cl.items & IT_SUIT) { cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 0; cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 255; cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 0; cl.cshifts[CSHIFT_POWERUP].percent = 20; } - else if (cl.items & IT_INVISIBILITY) + else if(cl.items & IT_INVISIBILITY) { cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 100; cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 100; cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 100; cl.cshifts[CSHIFT_POWERUP].percent = 100; } - else if (cl.items & IT_INVULNERABILITY) + else if(cl.items & IT_INVULNERABILITY) { cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 255; cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 255; @@ -429,11 +429,12 @@ void V_CalcPowerupCshift (void) V_CalcBlend ============= */ -void V_CalcBlend (void) +void V_CalcBlend(void) { - float r, g, b, a, a2; - int32_t j; - cvar_t *cshiftpercent_cvars[NUM_CSHIFTS] = { + float r, g, b, a, a2; + int32_t j; + cvar_t *cshiftpercent_cvars[NUM_CSHIFTS] = + { &gl_cshiftpercent_contents, &gl_cshiftpercent_damage, &gl_cshiftpercent_bonus, @@ -445,13 +446,13 @@ void V_CalcBlend (void) b = 0; a = 0; - for (j=0 ; jvalue / 100.0); // QuakeSpasm - if (!a2) + if(!a2) continue; - a = a + a2*(1-a); - a2 = a2/a; - r = r*(1-a2) + cl.cshifts[j].destcolor[0]*a2; - g = g*(1-a2) + cl.cshifts[j].destcolor[1]*a2; - b = b*(1-a2) + cl.cshifts[j].destcolor[2]*a2; + a = a + a2 * (1 - a); + a2 = a2 / a; + r = r * (1 - a2) + cl.cshifts[j].destcolor[0] * a2; + g = g * (1 - a2) + cl.cshifts[j].destcolor[1] * a2; + b = b * (1 - a2) + cl.cshifts[j].destcolor[2] * a2; } - v_blend[0] = r/255.0; - v_blend[1] = g/255.0; - v_blend[2] = b/255.0; + v_blend[0] = r / 255.0; + v_blend[1] = g / 255.0; + v_blend[2] = b / 255.0; v_blend[3] = a; - if (v_blend[3] > 1) + if(v_blend[3] > 1) v_blend[3] = 1; - if (v_blend[3] < 0) + if(v_blend[3] < 0) v_blend[3] = 0; } @@ -483,24 +484,24 @@ void V_CalcBlend (void) V_UpdateBlend -- johnfitz -- V_UpdatePalette cleaned up and renamed ============= */ -void V_UpdateBlend (void) +void V_UpdateBlend(void) { - int32_t i, j; - bool blend_changed; + int32_t i, j; + bool blend_changed; - V_CalcPowerupCshift (); + V_CalcPowerupCshift(); blend_changed = false; - for (i=0 ; i 180) + if(a > 180) a -= 360; return a; } @@ -580,9 +581,9 @@ float angledelta (float a) CalcGunAngle ================== */ -void CalcGunAngle (void) +void CalcGunAngle(void) { - float yaw, pitch, move; + float yaw, pitch, move; static float oldyaw = 0; static float oldpitch = 0; @@ -590,35 +591,35 @@ void CalcGunAngle (void) pitch = -r_refdef.viewangles[PITCH]; yaw = angledelta(yaw - r_refdef.viewangles[YAW]) * 0.4; - if (yaw > 10) + if(yaw > 10) yaw = 10; - if (yaw < -10) + if(yaw < -10) yaw = -10; pitch = angledelta(-pitch - r_refdef.viewangles[PITCH]) * 0.4; - if (pitch > 10) + if(pitch > 10) pitch = 10; - if (pitch < -10) + if(pitch < -10) pitch = -10; - move = host_frametime*20; - if (yaw > oldyaw) + move = host_frametime * 20; + if(yaw > oldyaw) { - if (oldyaw + move < yaw) + if(oldyaw + move < yaw) yaw = oldyaw + move; } else { - if (oldyaw - move > yaw) + if(oldyaw - move > yaw) yaw = oldyaw - move; } - if (pitch > oldpitch) + if(pitch > oldpitch) { - if (oldpitch + move < pitch) + if(oldpitch + move < pitch) pitch = oldpitch + move; } else { - if (oldpitch - move > pitch) + if(oldpitch - move > pitch) pitch = oldpitch - move; } @@ -628,9 +629,9 @@ void CalcGunAngle (void) cl.viewent.angles[YAW] = r_refdef.viewangles[YAW] + yaw; cl.viewent.angles[PITCH] = - (r_refdef.viewangles[PITCH] + pitch); - cl.viewent.angles[ROLL] -= v_idlescale.value * sin(cl.time*v_iroll_cycle.value) * v_iroll_level.value; - cl.viewent.angles[PITCH] -= v_idlescale.value * sin(cl.time*v_ipitch_cycle.value) * v_ipitch_level.value; - cl.viewent.angles[YAW] -= v_idlescale.value * sin(cl.time*v_iyaw_cycle.value) * v_iyaw_level.value; + cl.viewent.angles[ROLL] -= v_idlescale.value * sin(cl.time * v_iroll_cycle.value) * v_iroll_level.value; + cl.viewent.angles[PITCH] -= v_idlescale.value * sin(cl.time * v_ipitch_cycle.value) * v_ipitch_level.value; + cl.viewent.angles[YAW] -= v_idlescale.value * sin(cl.time * v_iyaw_cycle.value) * v_iyaw_level.value; } /* @@ -638,26 +639,26 @@ void CalcGunAngle (void) V_BoundOffsets ============== */ -void V_BoundOffsets (void) +void V_BoundOffsets(void) { - entity_t *ent; + entity_t *ent; ent = &cl_entities[cl.viewentity]; // absolutely bound refresh reletive to entity clipping hull // so the view can never be inside a solid wall - if (r_refdef.vieworg[0] < ent->origin[0] - 14) + if(r_refdef.vieworg[0] < ent->origin[0] - 14) r_refdef.vieworg[0] = ent->origin[0] - 14; - else if (r_refdef.vieworg[0] > ent->origin[0] + 14) + else if(r_refdef.vieworg[0] > ent->origin[0] + 14) r_refdef.vieworg[0] = ent->origin[0] + 14; - if (r_refdef.vieworg[1] < ent->origin[1] - 14) + if(r_refdef.vieworg[1] < ent->origin[1] - 14) r_refdef.vieworg[1] = ent->origin[1] - 14; - else if (r_refdef.vieworg[1] > ent->origin[1] + 14) + else if(r_refdef.vieworg[1] > ent->origin[1] + 14) r_refdef.vieworg[1] = ent->origin[1] + 14; - if (r_refdef.vieworg[2] < ent->origin[2] - 22) + if(r_refdef.vieworg[2] < ent->origin[2] - 22) r_refdef.vieworg[2] = ent->origin[2] - 22; - else if (r_refdef.vieworg[2] > ent->origin[2] + 30) + else if(r_refdef.vieworg[2] > ent->origin[2] + 30) r_refdef.vieworg[2] = ent->origin[2] + 30; } @@ -668,11 +669,11 @@ V_AddIdle Idle swaying ============== */ -void V_AddIdle (void) +void V_AddIdle(void) { - r_refdef.viewangles[ROLL] += v_idlescale.value * sin(cl.time*v_iroll_cycle.value) * v_iroll_level.value; - r_refdef.viewangles[PITCH] += v_idlescale.value * sin(cl.time*v_ipitch_cycle.value) * v_ipitch_level.value; - r_refdef.viewangles[YAW] += v_idlescale.value * sin(cl.time*v_iyaw_cycle.value) * v_iyaw_level.value; + r_refdef.viewangles[ROLL] += v_idlescale.value * sin(cl.time * v_iroll_cycle.value) * v_iroll_level.value; + r_refdef.viewangles[PITCH] += v_idlescale.value * sin(cl.time * v_ipitch_cycle.value) * v_ipitch_level.value; + r_refdef.viewangles[YAW] += v_idlescale.value * sin(cl.time * v_iyaw_cycle.value) * v_iyaw_level.value; } @@ -683,23 +684,23 @@ V_CalcViewRoll Roll is induced by movement and damage ============== */ -void V_CalcViewRoll (void) +void V_CalcViewRoll(void) { - float side; + float side; - side = V_CalcRoll (cl_entities[cl.viewentity].angles, cl.velocity); + side = V_CalcRoll(cl_entities[cl.viewentity].angles, cl.velocity); r_refdef.viewangles[ROLL] += side; - if (v_dmg_time > 0) + if(v_dmg_time > 0) { - r_refdef.viewangles[ROLL] += v_dmg_time/v_kicktime.value*v_dmg_roll; - r_refdef.viewangles[PITCH] += v_dmg_time/v_kicktime.value*v_dmg_pitch; + r_refdef.viewangles[ROLL] += v_dmg_time / v_kicktime.value * v_dmg_roll; + r_refdef.viewangles[PITCH] += v_dmg_time / v_kicktime.value * v_dmg_pitch; v_dmg_time -= host_frametime; } - if (cl.stats[STAT_HEALTH] <= 0) + if(cl.stats[STAT_HEALTH] <= 0) { - r_refdef.viewangles[ROLL] = 80; // dead view angle + r_refdef.viewangles[ROLL] = 80; // dead view angle return; } } @@ -710,24 +711,24 @@ V_CalcIntermissionRefdef ================== */ -void V_CalcIntermissionRefdef (void) +void V_CalcIntermissionRefdef(void) { - entity_t *ent, *view; - float old; + entity_t *ent, *view; + float old; // ent is the player model (visible when out of body) ent = &cl_entities[cl.viewentity]; // view is the weapon model (only visible from inside body) view = &cl.viewent; - VectorCopy (ent->origin, r_refdef.vieworg); - VectorCopy (ent->angles, r_refdef.viewangles); + VectorCopy(ent->origin, r_refdef.vieworg); + VectorCopy(ent->angles, r_refdef.viewangles); view->model = NULL; // allways idle in intermission old = v_idlescale.value; v_idlescale.value = 1; - V_AddIdle (); + V_AddIdle(); v_idlescale.value = old; } @@ -736,18 +737,18 @@ void V_CalcIntermissionRefdef (void) V_CalcRefdef ================== */ -void V_CalcRefdef (void) +void V_CalcRefdef(void) { - entity_t *ent, *view; - int32_t i; - vec3_t forward, right, up; - vec3_t angles; - float bob; + entity_t *ent, *view; + int32_t i; + vec3_t forward, right, up; + vec3_t angles; + float bob; static float oldz = 0; - static vec3_t punch = {0,0,0}; //johnfitz -- v_gunkick + static vec3_t punch = {0, 0, 0}; //johnfitz -- v_gunkick float delta; //johnfitz -- v_gunkick - V_DriftPitch (); + V_DriftPitch(); // ent is the player model (visible when out of body) ent = &cl_entities[cl.viewentity]; @@ -757,62 +758,62 @@ void V_CalcRefdef (void) // transform the view offset by the model's matrix to get the offset from // model origin for the view - ent->angles[YAW] = cl.viewangles[YAW]; // the model should face the view dir - ent->angles[PITCH] = -cl.viewangles[PITCH]; // the model should face the view dir + ent->angles[YAW] = cl.viewangles[YAW]; // the model should face the view dir + ent->angles[PITCH] = -cl.viewangles[PITCH]; // the model should face the view dir - bob = V_CalcBob (); + bob = V_CalcBob(); // refresh position - VectorCopy (ent->origin, r_refdef.vieworg); + VectorCopy(ent->origin, r_refdef.vieworg); r_refdef.vieworg[2] += cl.viewheight + bob; // never let it sit exactly on a node line, because a water plane can // dissapear when viewed with the eye exactly on it. // the server protocol only specifies to 1/16 pixel, so add 1/32 in each axis - r_refdef.vieworg[0] += 1.0/32; - r_refdef.vieworg[1] += 1.0/32; - r_refdef.vieworg[2] += 1.0/32; + r_refdef.vieworg[0] += 1.0 / 32; + r_refdef.vieworg[1] += 1.0 / 32; + r_refdef.vieworg[2] += 1.0 / 32; - VectorCopy (cl.viewangles, r_refdef.viewangles); - V_CalcViewRoll (); - V_AddIdle (); + VectorCopy(cl.viewangles, r_refdef.viewangles); + V_CalcViewRoll(); + V_AddIdle(); // offsets angles[PITCH] = -ent->angles[PITCH]; // because entity pitches are actually backward angles[YAW] = ent->angles[YAW]; angles[ROLL] = ent->angles[ROLL]; - AngleVectors (angles, forward, right, up); + AngleVectors(angles, forward, right, up); - if (cl.maxclients <= 1) //johnfitz -- moved cheat-protection here from V_RenderView - for (i=0 ; i<3 ; i++) - r_refdef.vieworg[i] += scr_ofsx.value*forward[i] + scr_ofsy.value*right[i] + scr_ofsz.value*up[i]; + if(cl.maxclients <= 1) //johnfitz -- moved cheat-protection here from V_RenderView + for(i = 0 ; i < 3 ; i++) + r_refdef.vieworg[i] += scr_ofsx.value * forward[i] + scr_ofsy.value * right[i] + scr_ofsz.value * up[i]; - V_BoundOffsets (); + V_BoundOffsets(); // set up gun position - VectorCopy (cl.viewangles, view->angles); + VectorCopy(cl.viewangles, view->angles); - CalcGunAngle (); + CalcGunAngle(); - VectorCopy (ent->origin, view->origin); + VectorCopy(ent->origin, view->origin); view->origin[2] += cl.viewheight; - for (i=0 ; i<3 ; i++) - view->origin[i] += forward[i]*bob*0.4; + for(i = 0 ; i < 3 ; i++) + view->origin[i] += forward[i] * bob * 0.4; view->origin[2] += bob; //johnfitz -- removed all gun position fudging code (was used to keep gun from getting covered by sbar) //MarkV -- restored this with r_viewmodel_quake cvar - if (r_viewmodel_quake.value) + if(r_viewmodel_quake.value) { - if (scr_viewsize.value == 110) + if(scr_viewsize.value == 110) view->origin[2] += 1; - else if (scr_viewsize.value == 100) + else if(scr_viewsize.value == 100) view->origin[2] += 2; - else if (scr_viewsize.value == 90) + else if(scr_viewsize.value == 90) view->origin[2] += 1; - else if (scr_viewsize.value == 80) + else if(scr_viewsize.value == 80) view->origin[2] += 0.5; } @@ -821,41 +822,41 @@ void V_CalcRefdef (void) view->colormap = vid.colormap; //johnfitz -- v_gunkick - if (v_gunkick.value == 1) //original quake kick - VectorAdd (r_refdef.viewangles, cl.punchangle, r_refdef.viewangles); - if (v_gunkick.value == 2) //lerped kick + if(v_gunkick.value == 1) //original quake kick + VectorAdd(r_refdef.viewangles, cl.punchangle, r_refdef.viewangles); + if(v_gunkick.value == 2) //lerped kick { - for (i=0; i<3; i++) - if (punch[i] != v_punchangles[0][i]) + for(i = 0; i < 3; i++) + if(punch[i] != v_punchangles[0][i]) { //speed determined by how far we need to lerp in 1/10th of a second - delta = (v_punchangles[0][i]-v_punchangles[1][i]) * host_frametime * 10; + delta = (v_punchangles[0][i] - v_punchangles[1][i]) * host_frametime * 10; - if (delta > 0) - punch[i] = q_min(punch[i]+delta, v_punchangles[0][i]); - else if (delta < 0) - punch[i] = q_max(punch[i]+delta, v_punchangles[0][i]); + if(delta > 0) + punch[i] = q_min(punch[i] + delta, v_punchangles[0][i]); + else if(delta < 0) + punch[i] = q_max(punch[i] + delta, v_punchangles[0][i]); } - VectorAdd (r_refdef.viewangles, punch, r_refdef.viewangles); + VectorAdd(r_refdef.viewangles, punch, r_refdef.viewangles); } //johnfitz // smooth out stair step ups - if (!noclip_anglehack && cl.onground && ent->origin[2] - oldz > 0) //johnfitz -- added exception for noclip - //FIXME: noclip_anglehack is set on the server, so in a nonlocal game this won't work. + if(!noclip_anglehack && cl.onground && ent->origin[2] - oldz > 0) //johnfitz -- added exception for noclip + //FIXME: noclip_anglehack is set on the server, so in a nonlocal game this won't work. { float steptime; steptime = cl.time - cl.oldtime; - if (steptime < 0) - //FIXME I_Error ("steptime < 0"); + if(steptime < 0) + //FIXME I_Error ("steptime < 0"); steptime = 0; oldz += steptime * 80; - if (oldz > ent->origin[2]) + if(oldz > ent->origin[2]) oldz = ent->origin[2]; - if (ent->origin[2] - oldz > 12) + if(ent->origin[2] - oldz > 12) oldz = ent->origin[2] - 12; r_refdef.vieworg[2] += oldz - ent->origin[2]; view->origin[2] += oldz - ent->origin[2]; @@ -863,8 +864,8 @@ void V_CalcRefdef (void) else oldz = ent->origin[2]; - if (chase_active.value) - Chase_UpdateForDrawing (); //johnfitz + if(chase_active.value) + Chase_UpdateForDrawing(); //johnfitz } /* @@ -875,29 +876,29 @@ The player's clipping box goes from (-16 -16 -24) to (16 16 32) from the entity origin, so any view position inside that will be valid ================== */ -extern vrect_t scr_vrect; +extern vrect_t scr_vrect; -void V_RenderView (void) +void V_RenderView(void) { - if (con_forcedup) + if(con_forcedup) return; - if (cl.intermission) - V_CalcIntermissionRefdef (); - else if (!cl.paused /* && (cl.maxclients > 1 || key_dest == key_game) */) - V_CalcRefdef (); + if(cl.intermission) + V_CalcIntermissionRefdef(); + else if(!cl.paused /* && (cl.maxclients > 1 || key_dest == key_game) */) + V_CalcRefdef(); //johnfitz -- removed lcd code - R_RenderView (); + R_RenderView(); - V_PolyBlend (); //johnfitz -- moved here from R_Renderview (); + V_PolyBlend(); //johnfitz -- moved here from R_Renderview (); } /* ============================================================================== - INIT + INIT ============================================================================== */ @@ -907,44 +908,44 @@ void V_RenderView (void) V_Init ============= */ -void V_Init (void) +void V_Init(void) { - Cmd_AddCommand ("v_cshift", V_cshift_f); - Cmd_AddCommand ("bf", V_BonusFlash_f); - Cmd_AddCommand ("centerview", V_StartPitchDrift); + Cmd_AddCommand("v_cshift", V_cshift_f); + Cmd_AddCommand("bf", V_BonusFlash_f); + Cmd_AddCommand("centerview", V_StartPitchDrift); - Cvar_RegisterVariable (&v_centermove); - Cvar_RegisterVariable (&v_centerspeed); + Cvar_RegisterVariable(&v_centermove); + Cvar_RegisterVariable(&v_centerspeed); - Cvar_RegisterVariable (&v_iyaw_cycle); - Cvar_RegisterVariable (&v_iroll_cycle); - Cvar_RegisterVariable (&v_ipitch_cycle); - Cvar_RegisterVariable (&v_iyaw_level); - Cvar_RegisterVariable (&v_iroll_level); - Cvar_RegisterVariable (&v_ipitch_level); + Cvar_RegisterVariable(&v_iyaw_cycle); + Cvar_RegisterVariable(&v_iroll_cycle); + Cvar_RegisterVariable(&v_ipitch_cycle); + Cvar_RegisterVariable(&v_iyaw_level); + Cvar_RegisterVariable(&v_iroll_level); + Cvar_RegisterVariable(&v_ipitch_level); - Cvar_RegisterVariable (&v_idlescale); - Cvar_RegisterVariable (&crosshair); - Cvar_RegisterVariable (&gl_cshiftpercent); - Cvar_RegisterVariable (&gl_cshiftpercent_contents); // QuakeSpasm - Cvar_RegisterVariable (&gl_cshiftpercent_damage); // QuakeSpasm - Cvar_RegisterVariable (&gl_cshiftpercent_bonus); // QuakeSpasm - Cvar_RegisterVariable (&gl_cshiftpercent_powerup); // QuakeSpasm + Cvar_RegisterVariable(&v_idlescale); + Cvar_RegisterVariable(&crosshair); + Cvar_RegisterVariable(&gl_cshiftpercent); + Cvar_RegisterVariable(&gl_cshiftpercent_contents); // QuakeSpasm + Cvar_RegisterVariable(&gl_cshiftpercent_damage); // QuakeSpasm + Cvar_RegisterVariable(&gl_cshiftpercent_bonus); // QuakeSpasm + Cvar_RegisterVariable(&gl_cshiftpercent_powerup); // QuakeSpasm - Cvar_RegisterVariable (&scr_ofsx); - Cvar_RegisterVariable (&scr_ofsy); - Cvar_RegisterVariable (&scr_ofsz); - Cvar_RegisterVariable (&cl_rollspeed); - Cvar_RegisterVariable (&cl_rollangle); - Cvar_RegisterVariable (&cl_bob); - Cvar_RegisterVariable (&cl_bobcycle); - Cvar_RegisterVariable (&cl_bobup); + Cvar_RegisterVariable(&scr_ofsx); + Cvar_RegisterVariable(&scr_ofsy); + Cvar_RegisterVariable(&scr_ofsz); + Cvar_RegisterVariable(&cl_rollspeed); + Cvar_RegisterVariable(&cl_rollangle); + Cvar_RegisterVariable(&cl_bob); + Cvar_RegisterVariable(&cl_bobcycle); + Cvar_RegisterVariable(&cl_bobup); - Cvar_RegisterVariable (&v_kicktime); - Cvar_RegisterVariable (&v_kickroll); - Cvar_RegisterVariable (&v_kickpitch); - Cvar_RegisterVariable (&v_gunkick); //johnfitz - - Cvar_RegisterVariable (&r_viewmodel_quake); //MarkV + Cvar_RegisterVariable(&v_kicktime); + Cvar_RegisterVariable(&v_kickroll); + Cvar_RegisterVariable(&v_kickpitch); + Cvar_RegisterVariable(&v_gunkick); //johnfitz + + Cvar_RegisterVariable(&r_viewmodel_quake); //MarkV } diff --git a/source/view.h b/source/view.h index af0cdf1..f34f6b6 100644 --- a/source/view.h +++ b/source/view.h @@ -23,17 +23,17 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef _QUAKE_VIEW_H #define _QUAKE_VIEW_H -extern cvar_t vid_gamma; -extern cvar_t vid_contrast; +extern cvar_t vid_gamma; +extern cvar_t vid_contrast; extern float v_blend[4]; -void V_Init (void); -void V_RenderView (void); -void V_CalcBlend (void); -void V_UpdateBlend (void); -float V_CalcRoll (vec3_t angles, vec3_t velocity); +void V_Init(void); +void V_RenderView(void); +void V_CalcBlend(void); +void V_UpdateBlend(void); +float V_CalcRoll(vec3_t angles, vec3_t velocity); //void V_UpdatePalette (void); //johnfitz -#endif /* _QUAKE_VIEW_H */ +#endif /* _QUAKE_VIEW_H */ diff --git a/source/wad.c b/source/wad.c index f75b14c..2484ad3 100644 --- a/source/wad.c +++ b/source/wad.c @@ -23,11 +23,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -int32_t wad_numlumps; -lumpinfo_t *wad_lumps; -byte *wad_base = NULL; +int32_t wad_numlumps; +lumpinfo_t *wad_lumps; +byte *wad_base = NULL; -void SwapPic (qpic_t *pic); +void SwapPic(qpic_t *pic); /* ================== @@ -40,23 +40,23 @@ Space padding is so names can be printed nicely in tables. Can safely be performed in place. ================== */ -void W_CleanupName (const char *in, char *out) +void W_CleanupName(const char *in, char *out) { - int32_t i; - int32_t c; + int32_t i; + int32_t c; - for (i=0 ; i<16 ; i++ ) + for(i = 0 ; i < 16 ; i++) { c = in[i]; - if (!c) + if(!c) break; - if (c >= 'A' && c <= 'Z') + if(c >= 'A' && c <= 'Z') c += ('a' - 'A'); out[i] = c; } - for ( ; i< 16 ; i++ ) + for(; i < 16 ; i++) out[i] = 0; } @@ -65,43 +65,43 @@ void W_CleanupName (const char *in, char *out) W_LoadWadFile ==================== */ -void W_LoadWadFile (void) //johnfitz -- filename is now hard-coded for honesty +void W_LoadWadFile(void) //johnfitz -- filename is now hard-coded for honesty { - lumpinfo_t *lump_p; - wadinfo_t *header; - int32_t i; - int32_t infotableofs; - const char *filename = WADFILENAME; + lumpinfo_t *lump_p; + wadinfo_t *header; + int32_t i; + int32_t infotableofs; + const char *filename = WADFILENAME; //johnfitz -- modified to use malloc //TODO: use cache_alloc - if (wad_base) - free (wad_base); - wad_base = COM_LoadMallocFile (filename, NULL); - if (!wad_base) - Sys_Error ("W_LoadWadFile: couldn't load %s\n\n" - "Basedir is: %s\n\n" - "Check that this has an " GAMENAME " subdirectory containing pak0.pak and pak1.pak, " - "or use the -basedir command-line option to specify another directory.", - filename, com_basedir); + if(wad_base) + free(wad_base); + wad_base = COM_LoadMallocFile(filename, NULL); + if(!wad_base) + Sys_Error("W_LoadWadFile: couldn't load %s\n\n" + "Basedir is: %s\n\n" + "Check that this has an " GAMENAME " subdirectory containing pak0.pak and pak1.pak, " + "or use the -basedir command-line option to specify another directory.", + filename, com_basedir); header = (wadinfo_t *)wad_base; - if (header->identification[0] != 'W' || header->identification[1] != 'A' - || header->identification[2] != 'D' || header->identification[3] != '2') - Sys_Error ("Wad file %s doesn't have WAD2 id\n",filename); + if(header->identification[0] != 'W' || header->identification[1] != 'A' + || header->identification[2] != 'D' || header->identification[3] != '2') + Sys_Error("Wad file %s doesn't have WAD2 id\n", filename); wad_numlumps = LittleLong(header->numlumps); infotableofs = LittleLong(header->infotableofs); wad_lumps = (lumpinfo_t *)(wad_base + infotableofs); - for (i=0, lump_p = wad_lumps ; ifilepos = LittleLong(lump_p->filepos); lump_p->size = LittleLong(lump_p->size); - W_CleanupName (lump_p->name, lump_p->name); // CAUTION: in-place editing!!! - if (lump_p->type == TYP_QPIC) - SwapPic ( (qpic_t *)(wad_base + lump_p->filepos)); + W_CleanupName(lump_p->name, lump_p->name); // CAUTION: in-place editing!!! + if(lump_p->type == TYP_QPIC) + SwapPic((qpic_t *)(wad_base + lump_p->filepos)); } } @@ -111,41 +111,41 @@ void W_LoadWadFile (void) //johnfitz -- filename is now hard-coded for honesty W_GetLumpinfo ============= */ -lumpinfo_t *W_GetLumpinfo (const char *name) +lumpinfo_t *W_GetLumpinfo(const char *name) { - int32_t i; - lumpinfo_t *lump_p; - char clean[16]; + int32_t i; + lumpinfo_t *lump_p; + char clean[16]; - W_CleanupName (name, clean); + W_CleanupName(name, clean); - for (lump_p=wad_lumps, i=0 ; iname)) + if(!strcmp(clean, lump_p->name)) return lump_p; } - Con_SafePrintf ("W_GetLumpinfo: %s not found\n", name); //johnfitz -- was Sys_Error + Con_SafePrintf("W_GetLumpinfo: %s not found\n", name); //johnfitz -- was Sys_Error return NULL; } -void *W_GetLumpName (const char *name) +void *W_GetLumpName(const char *name) { - lumpinfo_t *lump; + lumpinfo_t *lump; - lump = W_GetLumpinfo (name); + lump = W_GetLumpinfo(name); - if (!lump) return NULL; //johnfitz + if(!lump) return NULL; //johnfitz return (void *)(wad_base + lump->filepos); } -void *W_GetLumpNum (int32_t num) +void *W_GetLumpNum(int32_t num) { - lumpinfo_t *lump; + lumpinfo_t *lump; - if (num < 0 || num > wad_numlumps) - Sys_Error ("W_GetLumpNum: bad number: %" PRIi32 "", num); + if(num < 0 || num > wad_numlumps) + Sys_Error("W_GetLumpNum: bad number: %" PRIi32 "", num); lump = wad_lumps + num; @@ -160,7 +160,7 @@ automatic byte swapping ============================================================================= */ -void SwapPic (qpic_t *pic) +void SwapPic(qpic_t *pic) { pic->width = LittleLong(pic->width); pic->height = LittleLong(pic->height); diff --git a/source/wad.h b/source/wad.h index b7d35e0..d06e68a 100644 --- a/source/wad.h +++ b/source/wad.h @@ -27,56 +27,56 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // TYPES //=============== -#define CMP_NONE 0 -#define CMP_LZSS 1 +#define CMP_NONE 0 +#define CMP_LZSS 1 -#define TYP_NONE 0 -#define TYP_LABEL 1 +#define TYP_NONE 0 +#define TYP_LABEL 1 -#define TYP_LUMPY 64 // 64 + grab command number -#define TYP_PALETTE 64 -#define TYP_QTEX 65 -#define TYP_QPIC 66 -#define TYP_SOUND 67 -#define TYP_MIPTEX 68 +#define TYP_LUMPY 64 // 64 + grab command number +#define TYP_PALETTE 64 +#define TYP_QTEX 65 +#define TYP_QPIC 66 +#define TYP_SOUND 67 +#define TYP_MIPTEX 68 -#define WADFILENAME "gfx.wad" //johnfitz -- filename is now hard-coded for honesty +#define WADFILENAME "gfx.wad" //johnfitz -- filename is now hard-coded for honesty typedef struct { - int32_t width, height; - byte data[4]; // variably sized + int32_t width, height; + byte data[4]; // variably sized } qpic_t; typedef struct { - char identification[4]; // should be WAD2 or 2DAW - int32_t numlumps; - int32_t infotableofs; + char identification[4]; // should be WAD2 or 2DAW + int32_t numlumps; + int32_t infotableofs; } wadinfo_t; typedef struct { - int32_t filepos; - int32_t disksize; - int32_t size; // uncompressed - int8_t type; - int8_t compression; - uint8_t pad1, pad2; - char name[16]; // must be null terminated + int32_t filepos; + int32_t disksize; + int32_t size; // uncompressed + int8_t type; + int8_t compression; + uint8_t pad1, pad2; + char name[16]; // must be null terminated } lumpinfo_t; -extern int32_t wad_numlumps; -extern lumpinfo_t *wad_lumps; -extern byte *wad_base; +extern int32_t wad_numlumps; +extern lumpinfo_t *wad_lumps; +extern byte *wad_base; -void W_LoadWadFile (void); //johnfitz -- filename is now hard-coded for honesty -void W_CleanupName (const char *in, char *out); -lumpinfo_t *W_GetLumpinfo (const char *name); -void *W_GetLumpName (const char *name); -void *W_GetLumpNum (int32_t num); +void W_LoadWadFile(void); //johnfitz -- filename is now hard-coded for honesty +void W_CleanupName(const char *in, char *out); +lumpinfo_t *W_GetLumpinfo(const char *name); +void *W_GetLumpName(const char *name); +void *W_GetLumpNum(int32_t num); -void SwapPic (qpic_t *pic); +void SwapPic(qpic_t *pic); -#endif /* _QUAKE_WAD_H */ +#endif /* _QUAKE_WAD_H */ diff --git a/source/windows/net_win.c b/source/windows/net_win.c index 70b75b2..0f4273f 100644 --- a/source/windows/net_win.c +++ b/source/windows/net_win.c @@ -30,7 +30,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. net_driver_t net_drivers[] = { - { "Loopback", + { + "Loopback", false, Loop_Init, Loop_Listen, @@ -46,7 +47,8 @@ net_driver_t net_drivers[] = Loop_Shutdown }, - { "Datagram", + { + "Datagram", false, Datagram_Init, Datagram_Listen, @@ -69,9 +71,10 @@ const int32_t net_numdrivers = (sizeof(net_drivers) / sizeof(net_drivers[0])); #include "net_wins.h" #include "net_wipx.h" -net_landriver_t net_landrivers[] = +net_landriver_t net_landrivers[] = { - { "Winsock TCPIP", + { + "Winsock TCPIP", false, 0, WINS_Init, @@ -94,7 +97,8 @@ net_landriver_t net_landrivers[] = WINS_SetSocketPort }, - { "Winsock IPX", + { + "Winsock IPX", false, 0, WIPX_Init, diff --git a/source/windows/net_wins.c b/source/windows/net_wins.c index b5742c3..692e5ae 100644 --- a/source/windows/net_wins.c +++ b/source/windows/net_wins.c @@ -24,31 +24,31 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" #include "net_defs.h" -static sys_socket_t net_acceptsocket = INVALID_SOCKET; // socket for fielding new connections +static sys_socket_t net_acceptsocket = INVALID_SOCKET; // socket for fielding new connections static sys_socket_t net_controlsocket; static sys_socket_t net_broadcastsocket = 0; static struct sockaddr_in broadcastaddr; -static in_addr_t myAddr; +static in_addr_t myAddr; #include "net_wins.h" int32_t winsock_initialized = 0; -WSADATA winsockdata; -#define __wsaerr_static /* not static: used by net_wipx.c too */ +WSADATA winsockdata; +#define __wsaerr_static /* not static: used by net_wipx.c too */ #include "wsaerror.h" //============================================================================= #if !defined(_USE_WINSOCK2) -static double blocktime; +static double blocktime; -static INT_PTR PASCAL FAR BlockingHook (void) +static INT_PTR PASCAL FAR BlockingHook(void) { - MSG msg; - BOOL ret; + MSG msg; + BOOL ret; - if ((Sys_DoubleTime() - blocktime) > 2.0) + if((Sys_DoubleTime() - blocktime) > 2.0) { WSACancelBlockingCall(); return FALSE; @@ -58,7 +58,7 @@ static INT_PTR PASCAL FAR BlockingHook (void) ret = (BOOL) PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); /* if we got one, process it */ - if (ret) + if(ret) { TranslateMessage(&msg); DispatchMessage(&msg); @@ -67,24 +67,24 @@ static INT_PTR PASCAL FAR BlockingHook (void) /* TRUE if we got a message */ return ret; } -#endif /* ! _USE_WINSOCK2 */ +#endif /* ! _USE_WINSOCK2 */ -static void WINS_GetLocalAddress (void) +static void WINS_GetLocalAddress(void) { - struct hostent *local = NULL; - char buff[MAXHOSTNAMELEN]; - in_addr_t addr; - int32_t err; + struct hostent *local = NULL; + char buff[MAXHOSTNAMELEN]; + in_addr_t addr; + int32_t err; - if (myAddr != INADDR_ANY) + if(myAddr != INADDR_ANY) return; - if (gethostname(buff, MAXHOSTNAMELEN) == SOCKET_ERROR) + if(gethostname(buff, MAXHOSTNAMELEN) == SOCKET_ERROR) { err = SOCKETERRNO; Con_SafePrintf("WINS_GetLocalAddress: gethostname failed (%s)\n", - socketerror(err)); + socketerror(err)); return; } @@ -98,10 +98,10 @@ static void WINS_GetLocalAddress (void) #ifndef _USE_WINSOCK2 WSAUnhookBlockingHook(); #endif - if (local == NULL) + if(local == NULL) { Con_SafePrintf("WINS_GetLocalAddress: gethostbyname failed (%s)\n", - __WSAE_StrError(err)); + __WSAE_StrError(err)); return; } @@ -112,50 +112,50 @@ static void WINS_GetLocalAddress (void) } -sys_socket_t WINS_Init (void) +sys_socket_t WINS_Init(void) { - int32_t i, err; - char buff[MAXHOSTNAMELEN]; + int32_t i, err; + char buff[MAXHOSTNAMELEN]; - if (COM_CheckParm ("-noudp")) + if(COM_CheckParm("-noudp")) return -1; - if (winsock_initialized == 0) + if(winsock_initialized == 0) { - err = WSAStartup(MAKEWORD(1,1), &winsockdata); - if (err != 0) + err = WSAStartup(MAKEWORD(1, 1), &winsockdata); + if(err != 0) { Con_SafePrintf("Winsock initialization failed (%s)\n", - socketerror(err)); + socketerror(err)); return INVALID_SOCKET; } } winsock_initialized++; // determine my name & address - if (gethostname(buff, MAXHOSTNAMELEN) != 0) + if(gethostname(buff, MAXHOSTNAMELEN) != 0) { err = SOCKETERRNO; Con_SafePrintf("WINS_Init: gethostname failed (%s)\n", - socketerror(err)); + socketerror(err)); } else { buff[MAXHOSTNAMELEN - 1] = 0; } - i = COM_CheckParm ("-ip"); - if (i) + i = COM_CheckParm("-ip"); + if(i) { - if (i < com_argc-1) + if(i < com_argc - 1) { - myAddr = inet_addr(com_argv[i+1]); - if (myAddr == INADDR_NONE) - Sys_Error ("%s is not a valid IP address", com_argv[i+1]); - strcpy(my_tcpip_address, com_argv[i+1]); + myAddr = inet_addr(com_argv[i + 1]); + if(myAddr == INADDR_NONE) + Sys_Error("%s is not a valid IP address", com_argv[i + 1]); + strcpy(my_tcpip_address, com_argv[i + 1]); } else { - Sys_Error ("NET_Init: you must specify an IP address after -ip"); + Sys_Error("NET_Init: you must specify an IP address after -ip"); } } else @@ -164,11 +164,11 @@ sys_socket_t WINS_Init (void) strcpy(my_tcpip_address, "INADDR_ANY"); } - if ((net_controlsocket = WINS_OpenSocket(0)) == INVALID_SOCKET) + if((net_controlsocket = WINS_OpenSocket(0)) == INVALID_SOCKET) { Con_SafePrintf("WINS_Init: Unable to open control socket, UDP disabled\n"); - if (--winsock_initialized == 0) - WSACleanup (); + if(--winsock_initialized == 0) + WSACleanup(); return INVALID_SOCKET; } @@ -184,86 +184,86 @@ sys_socket_t WINS_Init (void) //============================================================================= -void WINS_Shutdown (void) +void WINS_Shutdown(void) { - WINS_Listen (false); - WINS_CloseSocket (net_controlsocket); - if (--winsock_initialized == 0) - WSACleanup (); + WINS_Listen(false); + WINS_CloseSocket(net_controlsocket); + if(--winsock_initialized == 0) + WSACleanup(); } //============================================================================= -void WINS_Listen (bool state) +void WINS_Listen(bool state) { // enable listening - if (state) + if(state) { - if (net_acceptsocket != INVALID_SOCKET) + if(net_acceptsocket != INVALID_SOCKET) return; WINS_GetLocalAddress(); - if ((net_acceptsocket = WINS_OpenSocket (net_hostport)) == INVALID_SOCKET) - Sys_Error ("WINS_Listen: Unable to open accept socket"); + if((net_acceptsocket = WINS_OpenSocket(net_hostport)) == INVALID_SOCKET) + Sys_Error("WINS_Listen: Unable to open accept socket"); return; } // disable listening - if (net_acceptsocket == INVALID_SOCKET) + if(net_acceptsocket == INVALID_SOCKET) return; - WINS_CloseSocket (net_acceptsocket); + WINS_CloseSocket(net_acceptsocket); net_acceptsocket = INVALID_SOCKET; } //============================================================================= -sys_socket_t WINS_OpenSocket (int32_t port) +sys_socket_t WINS_OpenSocket(int32_t port) { sys_socket_t newsocket; struct sockaddr_in address; u_long _true = 1; int32_t err; - if ((newsocket = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) + if((newsocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) { err = SOCKETERRNO; Con_SafePrintf("WINS_OpenSocket: %s\n", socketerror(err)); return INVALID_SOCKET; } - if (ioctlsocket (newsocket, FIONBIO, &_true) == SOCKET_ERROR) + if(ioctlsocket(newsocket, FIONBIO, &_true) == SOCKET_ERROR) goto ErrorReturn; memset(&address, 0, sizeof(struct sockaddr_in)); address.sin_family = AF_INET; address.sin_addr.s_addr = myAddr; address.sin_port = htons((uint16_t)port); - if (bind (newsocket, (struct sockaddr *)&address, sizeof(address)) == 0) + if(bind(newsocket, (struct sockaddr *)&address, sizeof(address)) == 0) return newsocket; - if (tcpipAvailable) + if(tcpipAvailable) { err = SOCKETERRNO; - Sys_Error ("Unable to bind to %s (%s)", - WINS_AddrToString ((struct qsockaddr *) &address), - socketerror(err)); - return INVALID_SOCKET; /* not reached */ + Sys_Error("Unable to bind to %s (%s)", + WINS_AddrToString((struct qsockaddr *) &address), + socketerror(err)); + return INVALID_SOCKET; /* not reached */ } /* else: we are still in init phase, no need to error */ ErrorReturn: err = SOCKETERRNO; Con_SafePrintf("WINS_OpenSocket: %s\n", socketerror(err)); - closesocket (newsocket); + closesocket(newsocket); return INVALID_SOCKET; } //============================================================================= -int32_t WINS_CloseSocket (sys_socket_t socketid) +int32_t WINS_CloseSocket(sys_socket_t socketid) { - if (socketid == net_broadcastsocket) + if(socketid == net_broadcastsocket) net_broadcastsocket = 0; - return closesocket (socketid); + return closesocket(socketid); } //============================================================================= @@ -276,40 +276,40 @@ this lets you type only as much of the net address as required, using the local network components to fill in the rest ============ */ -static int32_t PartialIPAddress (const char *in, struct qsockaddr *hostaddr) +static int32_t PartialIPAddress(const char *in, struct qsockaddr *hostaddr) { - char buff[256]; - char *b; - int32_t addr, mask, num, port, run; + char buff[256]; + char *b; + int32_t addr, mask, num, port, run; buff[0] = '.'; b = buff; - strcpy(buff+1, in); - if (buff[1] == '.') + strcpy(buff + 1, in); + if(buff[1] == '.') b++; addr = 0; mask = -1; - while (*b == '.') + while(*b == '.') { b++; num = 0; run = 0; - while (!( *b < '0' || *b > '9')) + while(!(*b < '0' || *b > '9')) { - num = num*10 + *b++ - '0'; - if (++run > 3) + num = num * 10 + *b++ - '0'; + if(++run > 3) return -1; } - if ((*b < '0' || *b > '9') && *b != '.' && *b != ':' && *b != 0) + if((*b < '0' || *b > '9') && *b != '.' && *b != ':' && *b != 0) return -1; - if (num < 0 || num > 255) + if(num < 0 || num > 255) return -1; mask <<= 8; - addr = (addr<<8) + num; + addr = (addr << 8) + num; } - if (*b++ == ':') + if(*b++ == ':') port = Q_atoi(b); else port = net_hostport; @@ -317,29 +317,29 @@ static int32_t PartialIPAddress (const char *in, struct qsockaddr *hostaddr) hostaddr->qsa_family = AF_INET; ((struct sockaddr_in *)hostaddr)->sin_port = htons((uint16_t)port); ((struct sockaddr_in *)hostaddr)->sin_addr.s_addr = - (myAddr & htonl(mask)) | htonl(addr); + (myAddr & htonl(mask)) | htonl(addr); return 0; } //============================================================================= -int32_t WINS_Connect (sys_socket_t socketid, struct qsockaddr *addr) +int32_t WINS_Connect(sys_socket_t socketid, struct qsockaddr *addr) { return 0; } //============================================================================= -sys_socket_t WINS_CheckNewConnections (void) +sys_socket_t WINS_CheckNewConnections(void) { - char buf[4096]; + char buf[4096]; - if (net_acceptsocket == INVALID_SOCKET) + if(net_acceptsocket == INVALID_SOCKET) return INVALID_SOCKET; - if (recvfrom (net_acceptsocket, buf, sizeof(buf), MSG_PEEK, NULL, NULL) - != SOCKET_ERROR) + if(recvfrom(net_acceptsocket, buf, sizeof(buf), MSG_PEEK, NULL, NULL) + != SOCKET_ERROR) { return net_acceptsocket; } @@ -348,34 +348,34 @@ sys_socket_t WINS_CheckNewConnections (void) //============================================================================= -int32_t WINS_Read (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr) +int32_t WINS_Read(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr) { socklen_t addrlen = sizeof(struct qsockaddr); int32_t ret; - ret = recvfrom (socketid, (char *)buf, len, 0, (struct sockaddr *)addr, &addrlen); - if (ret == SOCKET_ERROR) + ret = recvfrom(socketid, (char *)buf, len, 0, (struct sockaddr *)addr, &addrlen); + if(ret == SOCKET_ERROR) { int32_t err = SOCKETERRNO; - if (err == NET_EWOULDBLOCK || err == NET_ECONNREFUSED) + if(err == NET_EWOULDBLOCK || err == NET_ECONNREFUSED) return 0; - Con_SafePrintf ("WINS_Read, recvfrom: %s\n", socketerror(err)); + Con_SafePrintf("WINS_Read, recvfrom: %s\n", socketerror(err)); } return ret; } //============================================================================= -static int32_t WINS_MakeSocketBroadcastCapable (sys_socket_t socketid) +static int32_t WINS_MakeSocketBroadcastCapable(sys_socket_t socketid) { - int32_t i = 1; + int32_t i = 1; // make this socket broadcast capable - if (setsockopt(socketid, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) - == SOCKET_ERROR) + if(setsockopt(socketid, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) + == SOCKET_ERROR) { int32_t err = SOCKETERRNO; - Con_SafePrintf ("UDP, setsockopt: %s\n", socketerror(err)); + Con_SafePrintf("UDP, setsockopt: %s\n", socketerror(err)); return -1; } net_broadcastsocket = socketid; @@ -385,63 +385,63 @@ static int32_t WINS_MakeSocketBroadcastCapable (sys_socket_t socketid) //============================================================================= -int32_t WINS_Broadcast (sys_socket_t socketid, byte *buf, int32_t len) +int32_t WINS_Broadcast(sys_socket_t socketid, byte *buf, int32_t len) { - int32_t ret; + int32_t ret; - if (socketid != net_broadcastsocket) + if(socketid != net_broadcastsocket) { - if (net_broadcastsocket != 0) + if(net_broadcastsocket != 0) Sys_Error("Attempted to use multiple broadcasts sockets"); WINS_GetLocalAddress(); - ret = WINS_MakeSocketBroadcastCapable (socketid); - if (ret == -1) + ret = WINS_MakeSocketBroadcastCapable(socketid); + if(ret == -1) { Con_Printf("Unable to make socket broadcast capable\n"); return ret; } } - return WINS_Write (socketid, buf, len, (struct qsockaddr *)&broadcastaddr); + return WINS_Write(socketid, buf, len, (struct qsockaddr *)&broadcastaddr); } //============================================================================= -int32_t WINS_Write (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr) +int32_t WINS_Write(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr) { - int32_t ret; + int32_t ret; - ret = sendto (socketid, (char *)buf, len, 0, (struct sockaddr *)addr, - sizeof(struct qsockaddr)); - if (ret == SOCKET_ERROR) + ret = sendto(socketid, (char *)buf, len, 0, (struct sockaddr *)addr, + sizeof(struct qsockaddr)); + if(ret == SOCKET_ERROR) { int32_t err = SOCKETERRNO; - if (err == NET_EWOULDBLOCK) + if(err == NET_EWOULDBLOCK) return 0; - Con_SafePrintf ("WINS_Write, sendto: %s\n", socketerror(err)); + Con_SafePrintf("WINS_Write, sendto: %s\n", socketerror(err)); } return ret; } //============================================================================= -const char *WINS_AddrToString (struct qsockaddr *addr) +const char *WINS_AddrToString(struct qsockaddr *addr) { static char buffer[22]; - int32_t haddr; + int32_t haddr; haddr = ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr); sprintf(buffer, "%" PRIi32 ".%" PRIi32 ".%" PRIi32 ".%" PRIi32 ":%" PRIi32 "", (haddr >> 24) & 0xff, - (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff, - ntohs(((struct sockaddr_in *)addr)->sin_port)); + (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff, + ntohs(((struct sockaddr_in *)addr)->sin_port)); return buffer; } //============================================================================= -int32_t WINS_StringToAddr (const char *string, struct qsockaddr *addr) +int32_t WINS_StringToAddr(const char *string, struct qsockaddr *addr) { - int32_t ha1, ha2, ha3, ha4, hp, ipaddr; + int32_t ha1, ha2, ha3, ha4, hp, ipaddr; sscanf(string, "%" PRIi32 ".%" PRIi32 ".%" PRIi32 ".%" PRIi32 ":%" PRIi32 "", &ha1, &ha2, &ha3, &ha4, &hp); ipaddr = (ha1 << 24) | (ha2 << 16) | (ha3 << 8) | ha4; @@ -454,7 +454,7 @@ int32_t WINS_StringToAddr (const char *string, struct qsockaddr *addr) //============================================================================= -int32_t WINS_GetSocketAddr (sys_socket_t socketid, struct qsockaddr *addr) +int32_t WINS_GetSocketAddr(sys_socket_t socketid, struct qsockaddr *addr) { socklen_t addrlen = sizeof(struct qsockaddr); in_addr_t a; @@ -463,7 +463,7 @@ int32_t WINS_GetSocketAddr (sys_socket_t socketid, struct qsockaddr *addr) getsockname(socketid, (struct sockaddr *)addr, &addrlen); a = ((struct sockaddr_in *)addr)->sin_addr.s_addr; - if (a == 0 || a == htonl(INADDR_LOOPBACK)) + if(a == 0 || a == htonl(INADDR_LOOPBACK)) ((struct sockaddr_in *)addr)->sin_addr.s_addr = myAddr; return 0; @@ -471,56 +471,56 @@ int32_t WINS_GetSocketAddr (sys_socket_t socketid, struct qsockaddr *addr) //============================================================================= -int32_t WINS_GetNameFromAddr (struct qsockaddr *addr, char *name) +int32_t WINS_GetNameFromAddr(struct qsockaddr *addr, char *name) { struct hostent *hostentry; - hostentry = gethostbyaddr ((char *)&((struct sockaddr_in *)addr)->sin_addr, - sizeof(struct in_addr), AF_INET); - if (hostentry) + hostentry = gethostbyaddr((char *) & ((struct sockaddr_in *)addr)->sin_addr, + sizeof(struct in_addr), AF_INET); + if(hostentry) { - Q_strncpy (name, (char *)hostentry->h_name, NET_NAMELEN - 1); + Q_strncpy(name, (char *)hostentry->h_name, NET_NAMELEN - 1); return 0; } - Q_strcpy (name, WINS_AddrToString (addr)); + Q_strcpy(name, WINS_AddrToString(addr)); return 0; } //============================================================================= -int32_t WINS_GetAddrFromName (const char *name, struct qsockaddr *addr) +int32_t WINS_GetAddrFromName(const char *name, struct qsockaddr *addr) { struct hostent *hostentry; - if (name[0] >= '0' && name[0] <= '9') - return PartialIPAddress (name, addr); + if(name[0] >= '0' && name[0] <= '9') + return PartialIPAddress(name, addr); - hostentry = gethostbyname (name); - if (!hostentry) + hostentry = gethostbyname(name); + if(!hostentry) return -1; addr->qsa_family = AF_INET; ((struct sockaddr_in *)addr)->sin_port = htons((uint16_t)net_hostport); ((struct sockaddr_in *)addr)->sin_addr.s_addr = - *(in_addr_t *)hostentry->h_addr_list[0]; + *(in_addr_t *)hostentry->h_addr_list[0]; return 0; } //============================================================================= -int32_t WINS_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2) +int32_t WINS_AddrCompare(struct qsockaddr *addr1, struct qsockaddr *addr2) { - if (addr1->qsa_family != addr2->qsa_family) + if(addr1->qsa_family != addr2->qsa_family) return -1; - if (((struct sockaddr_in *)addr1)->sin_addr.s_addr != - ((struct sockaddr_in *)addr2)->sin_addr.s_addr) + if(((struct sockaddr_in *)addr1)->sin_addr.s_addr != + ((struct sockaddr_in *)addr2)->sin_addr.s_addr) return -1; - if (((struct sockaddr_in *)addr1)->sin_port != - ((struct sockaddr_in *)addr2)->sin_port) + if(((struct sockaddr_in *)addr1)->sin_port != + ((struct sockaddr_in *)addr2)->sin_port) return 1; return 0; @@ -528,13 +528,13 @@ int32_t WINS_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2) //============================================================================= -int32_t WINS_GetSocketPort (struct qsockaddr *addr) +int32_t WINS_GetSocketPort(struct qsockaddr *addr) { return ntohs(((struct sockaddr_in *)addr)->sin_port); } -int32_t WINS_SetSocketPort (struct qsockaddr *addr, int32_t port) +int32_t WINS_SetSocketPort(struct qsockaddr *addr, int32_t port) { ((struct sockaddr_in *)addr)->sin_port = htons((uint16_t)port); return 0; diff --git a/source/windows/net_wins.h b/source/windows/net_wins.h index 39e2535..172a40d 100644 --- a/source/windows/net_wins.h +++ b/source/windows/net_wins.h @@ -22,24 +22,24 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef __NET_WINSOCK_H #define __NET_WINSOCK_H -sys_socket_t WINS_Init (void); -void WINS_Shutdown (void); -void WINS_Listen (bool state); -sys_socket_t WINS_OpenSocket (int32_t port); -int32_t WINS_CloseSocket (sys_socket_t socketid); -int32_t WINS_Connect (sys_socket_t socketid, struct qsockaddr *addr); -sys_socket_t WINS_CheckNewConnections (void); -int32_t WINS_Read (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); -int32_t WINS_Write (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); -int32_t WINS_Broadcast (sys_socket_t socketid, byte *buf, int32_t len); -const char *WINS_AddrToString (struct qsockaddr *addr); -int32_t WINS_StringToAddr (const char *string, struct qsockaddr *addr); -int32_t WINS_GetSocketAddr (sys_socket_t socketid, struct qsockaddr *addr); -int32_t WINS_GetNameFromAddr (struct qsockaddr *addr, char *name); -int32_t WINS_GetAddrFromName (const char *name, struct qsockaddr *addr); -int32_t WINS_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2); -int32_t WINS_GetSocketPort (struct qsockaddr *addr); -int32_t WINS_SetSocketPort (struct qsockaddr *addr, int32_t port); +sys_socket_t WINS_Init(void); +void WINS_Shutdown(void); +void WINS_Listen(bool state); +sys_socket_t WINS_OpenSocket(int32_t port); +int32_t WINS_CloseSocket(sys_socket_t socketid); +int32_t WINS_Connect(sys_socket_t socketid, struct qsockaddr *addr); +sys_socket_t WINS_CheckNewConnections(void); +int32_t WINS_Read(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); +int32_t WINS_Write(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); +int32_t WINS_Broadcast(sys_socket_t socketid, byte *buf, int32_t len); +const char *WINS_AddrToString(struct qsockaddr *addr); +int32_t WINS_StringToAddr(const char *string, struct qsockaddr *addr); +int32_t WINS_GetSocketAddr(sys_socket_t socketid, struct qsockaddr *addr); +int32_t WINS_GetNameFromAddr(struct qsockaddr *addr, char *name); +int32_t WINS_GetAddrFromName(const char *name, struct qsockaddr *addr); +int32_t WINS_AddrCompare(struct qsockaddr *addr1, struct qsockaddr *addr2); +int32_t WINS_GetSocketPort(struct qsockaddr *addr); +int32_t WINS_SetSocketPort(struct qsockaddr *addr, int32_t port); -#endif /* __NET_WINSOCK_H */ +#endif /* __NET_WINSOCK_H */ diff --git a/source/windows/net_wipx.c b/source/windows/net_wipx.c index 14e0211..86e6e79 100644 --- a/source/windows/net_wipx.c +++ b/source/windows/net_wipx.c @@ -31,14 +31,14 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. extern cvar_t hostname; -static sys_socket_t net_acceptsocket = INVALID_SOCKET; // socket for fielding new connections +static sys_socket_t net_acceptsocket = INVALID_SOCKET; // socket for fielding new connections static sys_socket_t net_controlsocket; static struct sockaddr_ipx broadcastaddr; /* externs from net_wins.c: */ extern bool winsock_initialized; -extern WSADATA winsockdata; -extern const char *__WSAE_StrError (int32_t); +extern WSADATA winsockdata; +extern const char *__WSAE_StrError(int32_t); #define IPXSOCKETS 18 static sys_socket_t ipxsocket[IPXSOCKETS]; @@ -46,48 +46,48 @@ static int32_t sequence[IPXSOCKETS]; //============================================================================= -sys_socket_t WIPX_Init (void) +sys_socket_t WIPX_Init(void) { - int32_t i, err; - char *colon; - char buff[MAXHOSTNAMELEN]; - struct qsockaddr addr; + int32_t i, err; + char *colon; + char buff[MAXHOSTNAMELEN]; + struct qsockaddr addr; - if (COM_CheckParm ("-noipx")) + if(COM_CheckParm("-noipx")) return INVALID_SOCKET; - if (winsock_initialized == 0) + if(winsock_initialized == 0) { - err = WSAStartup(MAKEWORD(1,1), &winsockdata); - if (err != 0) + err = WSAStartup(MAKEWORD(1, 1), &winsockdata); + if(err != 0) { Con_SafePrintf("Winsock initialization failed (%s)\n", - socketerror(err)); + socketerror(err)); return INVALID_SOCKET; } } winsock_initialized++; - for (i = 0; i < IPXSOCKETS; i++) + for(i = 0; i < IPXSOCKETS; i++) ipxsocket[i] = 0; // determine my name & address - if (gethostname(buff, MAXHOSTNAMELEN) != 0) + if(gethostname(buff, MAXHOSTNAMELEN) != 0) { err = SOCKETERRNO; Con_SafePrintf("WIPX_Init: gethostname failed (%s)\n", - socketerror(err)); + socketerror(err)); } else { buff[MAXHOSTNAMELEN - 1] = 0; } - if ((net_controlsocket = WIPX_OpenSocket(0)) == INVALID_SOCKET) + if((net_controlsocket = WIPX_OpenSocket(0)) == INVALID_SOCKET) { Con_SafePrintf("WIPX_Init: Unable to open control socket, IPX disabled\n"); - if (--winsock_initialized == 0) - WSACleanup (); + if(--winsock_initialized == 0) + WSACleanup(); return INVALID_SOCKET; } @@ -96,10 +96,10 @@ sys_socket_t WIPX_Init (void) memset(broadcastaddr.sa_nodenum, 0xff, 6); broadcastaddr.sa_socket = htons((uint16_t)net_hostport); - WIPX_GetSocketAddr (net_controlsocket, &addr); - Q_strcpy(my_ipx_address, WIPX_AddrToString (&addr)); - colon = Q_strrchr (my_ipx_address, ':'); - if (colon) + WIPX_GetSocketAddr(net_controlsocket, &addr); + Q_strcpy(my_ipx_address, WIPX_AddrToString(&addr)); + colon = Q_strrchr(my_ipx_address, ':'); + if(colon) *colon = 0; Con_SafePrintf("IPX Initialized\n"); @@ -110,129 +110,129 @@ sys_socket_t WIPX_Init (void) //============================================================================= -void WIPX_Shutdown (void) +void WIPX_Shutdown(void) { - WIPX_Listen (false); - WIPX_CloseSocket (net_controlsocket); - if (--winsock_initialized == 0) - WSACleanup (); + WIPX_Listen(false); + WIPX_CloseSocket(net_controlsocket); + if(--winsock_initialized == 0) + WSACleanup(); } //============================================================================= -void WIPX_Listen (bool state) +void WIPX_Listen(bool state) { // enable listening - if (state) + if(state) { - if (net_acceptsocket != INVALID_SOCKET) + if(net_acceptsocket != INVALID_SOCKET) return; - if ((net_acceptsocket = WIPX_OpenSocket (net_hostport)) == INVALID_SOCKET) - Sys_Error ("WIPX_Listen: Unable to open accept socket"); + if((net_acceptsocket = WIPX_OpenSocket(net_hostport)) == INVALID_SOCKET) + Sys_Error("WIPX_Listen: Unable to open accept socket"); return; } // disable listening - if (net_acceptsocket == INVALID_SOCKET) + if(net_acceptsocket == INVALID_SOCKET) return; - WIPX_CloseSocket (net_acceptsocket); + WIPX_CloseSocket(net_acceptsocket); net_acceptsocket = INVALID_SOCKET; } //============================================================================= -sys_socket_t WIPX_OpenSocket (int32_t port) +sys_socket_t WIPX_OpenSocket(int32_t port) { - int32_t err; - sys_socket_t handle, newsocket; + int32_t err; + sys_socket_t handle, newsocket; struct sockaddr_ipx address; u_long _true = 1; - for (handle = 0; handle < IPXSOCKETS; handle++) + for(handle = 0; handle < IPXSOCKETS; handle++) { - if (ipxsocket[handle] == 0) + if(ipxsocket[handle] == 0) break; } - if (handle == IPXSOCKETS) + if(handle == IPXSOCKETS) { Con_SafePrintf("WIPX_OpenSocket: Out of free IPX handles.\n"); return INVALID_SOCKET; } - if ((newsocket = socket (AF_IPX, SOCK_DGRAM, NSPROTO_IPX)) == INVALID_SOCKET) + if((newsocket = socket(AF_IPX, SOCK_DGRAM, NSPROTO_IPX)) == INVALID_SOCKET) { err = SOCKETERRNO; Con_SafePrintf("WIPX_OpenSocket: %s\n", socketerror(err)); return INVALID_SOCKET; } - if (ioctlsocket (newsocket, FIONBIO, &_true) == SOCKET_ERROR) + if(ioctlsocket(newsocket, FIONBIO, &_true) == SOCKET_ERROR) goto ErrorReturn; - if (setsockopt(newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&_true, sizeof(_true)) - == SOCKET_ERROR) + if(setsockopt(newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&_true, sizeof(_true)) + == SOCKET_ERROR) goto ErrorReturn; address.sa_family = AF_IPX; memset(address.sa_netnum, 0, 4); memset(address.sa_nodenum, 0, 6);; address.sa_socket = htons((uint16_t)port); - if (bind (newsocket, (struct sockaddr *)&address, sizeof(address)) == 0) + if(bind(newsocket, (struct sockaddr *)&address, sizeof(address)) == 0) { ipxsocket[handle] = newsocket; sequence[handle] = 0; return handle; } - if (ipxAvailable) + if(ipxAvailable) { err = SOCKETERRNO; - Sys_Error ("IPX bind failed (%s)", socketerror(err)); - return INVALID_SOCKET; /* not reached */ + Sys_Error("IPX bind failed (%s)", socketerror(err)); + return INVALID_SOCKET; /* not reached */ } /* else: we are still in init phase, no need to error */ ErrorReturn: err = SOCKETERRNO; Con_SafePrintf("WIPX_OpenSocket: %s\n", socketerror(err)); - closesocket (newsocket); + closesocket(newsocket); return INVALID_SOCKET; } //============================================================================= -int32_t WIPX_CloseSocket (sys_socket_t handle) +int32_t WIPX_CloseSocket(sys_socket_t handle) { sys_socket_t socketid = ipxsocket[handle]; int32_t ret; - ret = closesocket (socketid); + ret = closesocket(socketid); ipxsocket[handle] = 0; return ret; } //============================================================================= -int32_t WIPX_Connect (sys_socket_t handle, struct qsockaddr *addr) +int32_t WIPX_Connect(sys_socket_t handle, struct qsockaddr *addr) { return 0; } //============================================================================= -sys_socket_t WIPX_CheckNewConnections (void) +sys_socket_t WIPX_CheckNewConnections(void) { - u_long available; + u_long available; - if (net_acceptsocket == INVALID_SOCKET) + if(net_acceptsocket == INVALID_SOCKET) return INVALID_SOCKET; - if (ioctlsocket (ipxsocket[net_acceptsocket], FIONREAD, &available) == SOCKET_ERROR) + if(ioctlsocket(ipxsocket[net_acceptsocket], FIONREAD, &available) == SOCKET_ERROR) { int32_t err = SOCKETERRNO; - Sys_Error ("WIPX: ioctlsocket (FIONREAD) failed (%s)", socketerror(err)); + Sys_Error("WIPX: ioctlsocket (FIONREAD) failed (%s)", socketerror(err)); } - if (available) + if(available) return net_acceptsocket; return INVALID_SOCKET; } @@ -241,41 +241,41 @@ sys_socket_t WIPX_CheckNewConnections (void) static byte netpacketBuffer[NET_DATAGRAMSIZE + 4]; -int32_t WIPX_Read (sys_socket_t handle, byte *buf, int32_t len, struct qsockaddr *addr) +int32_t WIPX_Read(sys_socket_t handle, byte *buf, int32_t len, struct qsockaddr *addr) { socklen_t addrlen = sizeof(struct qsockaddr); sys_socket_t socketid = ipxsocket[handle]; int32_t ret; - ret = recvfrom (socketid, (char *)netpacketBuffer, len+4, 0, (struct sockaddr *)addr, &addrlen); - if (ret == SOCKET_ERROR) + ret = recvfrom(socketid, (char *)netpacketBuffer, len + 4, 0, (struct sockaddr *)addr, &addrlen); + if(ret == SOCKET_ERROR) { int32_t err = SOCKETERRNO; - if (err == NET_EWOULDBLOCK || err == NET_ECONNREFUSED) + if(err == NET_EWOULDBLOCK || err == NET_ECONNREFUSED) return 0; - Con_SafePrintf ("WIPX_Read, recvfrom: %s\n", socketerror(err)); + Con_SafePrintf("WIPX_Read, recvfrom: %s\n", socketerror(err)); } - if (ret < 4) + if(ret < 4) return 0; // remove sequence number, it's only needed for DOS IPX ret -= 4; - memcpy(buf, netpacketBuffer+4, ret); + memcpy(buf, netpacketBuffer + 4, ret); return ret; } //============================================================================= -int32_t WIPX_Broadcast (sys_socket_t handle, byte *buf, int32_t len) +int32_t WIPX_Broadcast(sys_socket_t handle, byte *buf, int32_t len) { - return WIPX_Write (handle, buf, len, (struct qsockaddr *)&broadcastaddr); + return WIPX_Write(handle, buf, len, (struct qsockaddr *)&broadcastaddr); } //============================================================================= -int32_t WIPX_Write (sys_socket_t handle, byte *buf, int32_t len, struct qsockaddr *addr) +int32_t WIPX_Write(sys_socket_t handle, byte *buf, int32_t len, struct qsockaddr *addr) { sys_socket_t socketid = ipxsocket[handle]; int32_t ret; @@ -286,13 +286,13 @@ int32_t WIPX_Write (sys_socket_t handle, byte *buf, int32_t len, struct qsockadd memcpy(&netpacketBuffer[4], buf, len); len += 4; - ret = sendto (socketid, (char *)netpacketBuffer, len, 0, (struct sockaddr *)addr, sizeof(struct qsockaddr)); - if (ret == SOCKET_ERROR) + ret = sendto(socketid, (char *)netpacketBuffer, len, 0, (struct sockaddr *)addr, sizeof(struct qsockaddr)); + if(ret == SOCKET_ERROR) { int32_t err = SOCKETERRNO; - if (err == NET_EWOULDBLOCK) + if(err == NET_EWOULDBLOCK) return 0; - Con_SafePrintf ("WIPX_Write, sendto: %s\n", socketerror(err)); + Con_SafePrintf("WIPX_Write, sendto: %s\n", socketerror(err)); } return ret; @@ -300,43 +300,43 @@ int32_t WIPX_Write (sys_socket_t handle, byte *buf, int32_t len, struct qsockadd //============================================================================= -const char *WIPX_AddrToString (struct qsockaddr *addr) +const char *WIPX_AddrToString(struct qsockaddr *addr) { static char buf[28]; sprintf(buf, "%02x%02x%02x%02x:%02x%02x%02x%02x%02x%02x:%" PRIu32 "", - ((struct sockaddr_ipx *)addr)->sa_netnum[0] & 0xff, - ((struct sockaddr_ipx *)addr)->sa_netnum[1] & 0xff, - ((struct sockaddr_ipx *)addr)->sa_netnum[2] & 0xff, - ((struct sockaddr_ipx *)addr)->sa_netnum[3] & 0xff, - ((struct sockaddr_ipx *)addr)->sa_nodenum[0] & 0xff, - ((struct sockaddr_ipx *)addr)->sa_nodenum[1] & 0xff, - ((struct sockaddr_ipx *)addr)->sa_nodenum[2] & 0xff, - ((struct sockaddr_ipx *)addr)->sa_nodenum[3] & 0xff, - ((struct sockaddr_ipx *)addr)->sa_nodenum[4] & 0xff, - ((struct sockaddr_ipx *)addr)->sa_nodenum[5] & 0xff, - ntohs(((struct sockaddr_ipx *)addr)->sa_socket) - ); + ((struct sockaddr_ipx *)addr)->sa_netnum[0] & 0xff, + ((struct sockaddr_ipx *)addr)->sa_netnum[1] & 0xff, + ((struct sockaddr_ipx *)addr)->sa_netnum[2] & 0xff, + ((struct sockaddr_ipx *)addr)->sa_netnum[3] & 0xff, + ((struct sockaddr_ipx *)addr)->sa_nodenum[0] & 0xff, + ((struct sockaddr_ipx *)addr)->sa_nodenum[1] & 0xff, + ((struct sockaddr_ipx *)addr)->sa_nodenum[2] & 0xff, + ((struct sockaddr_ipx *)addr)->sa_nodenum[3] & 0xff, + ((struct sockaddr_ipx *)addr)->sa_nodenum[4] & 0xff, + ((struct sockaddr_ipx *)addr)->sa_nodenum[5] & 0xff, + ntohs(((struct sockaddr_ipx *)addr)->sa_socket) + ); return buf; } //============================================================================= -int32_t WIPX_StringToAddr (const char *string, struct qsockaddr *addr) +int32_t WIPX_StringToAddr(const char *string, struct qsockaddr *addr) { - int32_t val; - char buf[3]; + int32_t val; + char buf[3]; buf[2] = 0; Q_memset(addr, 0, sizeof(struct qsockaddr)); addr->qsa_family = AF_IPX; -#define DO(src,dest) do { \ - buf[0] = string[src]; \ - buf[1] = string[src + 1]; \ - if (sscanf (buf, "%x", &val) != 1) \ - return -1; \ - ((struct sockaddr_ipx *)addr)->dest = val; \ +#define DO(src,dest) do { \ + buf[0] = string[src]; \ + buf[1] = string[src + 1]; \ + if (sscanf (buf, "%x", &val) != 1) \ + return -1; \ + ((struct sockaddr_ipx *)addr)->dest = val; \ } while (0) DO(0, sa_netnum[0]); @@ -351,7 +351,7 @@ int32_t WIPX_StringToAddr (const char *string, struct qsockaddr *addr) DO(19, sa_nodenum[5]); #undef DO - sscanf (&string[22], "%" PRIu32 "", &val); + sscanf(&string[22], "%" PRIu32 "", &val); ((struct sockaddr_ipx *)addr)->sa_socket = htons((uint16_t)val); return 0; @@ -359,17 +359,17 @@ int32_t WIPX_StringToAddr (const char *string, struct qsockaddr *addr) //============================================================================= -int32_t WIPX_GetSocketAddr (sys_socket_t handle, struct qsockaddr *addr) +int32_t WIPX_GetSocketAddr(sys_socket_t handle, struct qsockaddr *addr) { sys_socket_t socketid = ipxsocket[handle]; socklen_t addrlen = sizeof(struct qsockaddr); Q_memset(addr, 0, sizeof(struct qsockaddr)); - if (getsockname(socketid, (struct sockaddr *)addr, &addrlen) != 0) + if(getsockname(socketid, (struct sockaddr *)addr, &addrlen) != 0) { int32_t err = SOCKETERRNO; /* FIXME: what action should be taken?... */ - Con_SafePrintf ("WIPX, getsockname: %s\n", socketerror(err)); + Con_SafePrintf("WIPX, getsockname: %s\n", socketerror(err)); } return 0; @@ -377,7 +377,7 @@ int32_t WIPX_GetSocketAddr (sys_socket_t handle, struct qsockaddr *addr) //============================================================================= -int32_t WIPX_GetNameFromAddr (struct qsockaddr *addr, char *name) +int32_t WIPX_GetNameFromAddr(struct qsockaddr *addr, char *name) { Q_strcpy(name, WIPX_AddrToString(addr)); return 0; @@ -385,60 +385,60 @@ int32_t WIPX_GetNameFromAddr (struct qsockaddr *addr, char *name) //============================================================================= -int32_t WIPX_GetAddrFromName (const char *name, struct qsockaddr *addr) +int32_t WIPX_GetAddrFromName(const char *name, struct qsockaddr *addr) { - int32_t n; - char buf[32]; + int32_t n; + char buf[32]; n = Q_strlen(name); - if (n == 12) + if(n == 12) { sprintf(buf, "00000000:%s:%" PRIu32 "", name, net_hostport); - return WIPX_StringToAddr (buf, addr); + return WIPX_StringToAddr(buf, addr); } - if (n == 21) + if(n == 21) { sprintf(buf, "%s:%" PRIu32 "", name, net_hostport); - return WIPX_StringToAddr (buf, addr); + return WIPX_StringToAddr(buf, addr); } - if (n > 21 && n <= 27) - return WIPX_StringToAddr (name, addr); + if(n > 21 && n <= 27) + return WIPX_StringToAddr(name, addr); return -1; } //============================================================================= -int32_t WIPX_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2) +int32_t WIPX_AddrCompare(struct qsockaddr *addr1, struct qsockaddr *addr2) { - if (addr1->qsa_family != addr2->qsa_family) + if(addr1->qsa_family != addr2->qsa_family) return -1; - if (*((struct sockaddr_ipx *)addr1)->sa_netnum && *((struct sockaddr_ipx *)addr2)->sa_netnum) + if(*((struct sockaddr_ipx *)addr1)->sa_netnum && *((struct sockaddr_ipx *)addr2)->sa_netnum) { - if (memcmp(((struct sockaddr_ipx *)addr1)->sa_netnum, ((struct sockaddr_ipx *)addr2)->sa_netnum, 4) != 0) + if(memcmp(((struct sockaddr_ipx *)addr1)->sa_netnum, ((struct sockaddr_ipx *)addr2)->sa_netnum, 4) != 0) return -1; } - if (memcmp(((struct sockaddr_ipx *)addr1)->sa_nodenum, ((struct sockaddr_ipx *)addr2)->sa_nodenum, 6) != 0) + if(memcmp(((struct sockaddr_ipx *)addr1)->sa_nodenum, ((struct sockaddr_ipx *)addr2)->sa_nodenum, 6) != 0) return -1; - if (((struct sockaddr_ipx *)addr1)->sa_socket != ((struct sockaddr_ipx *)addr2)->sa_socket) - return 1; + if(((struct sockaddr_ipx *)addr1)->sa_socket != ((struct sockaddr_ipx *)addr2)->sa_socket) + return 1; return 0; } //============================================================================= -int32_t WIPX_GetSocketPort (struct qsockaddr *addr) +int32_t WIPX_GetSocketPort(struct qsockaddr *addr) { return ntohs(((struct sockaddr_ipx *)addr)->sa_socket); } -int32_t WIPX_SetSocketPort (struct qsockaddr *addr, int32_t port) +int32_t WIPX_SetSocketPort(struct qsockaddr *addr, int32_t port) { ((struct sockaddr_ipx *)addr)->sa_socket = htons((uint16_t)port); return 0; diff --git a/source/windows/net_wipx.h b/source/windows/net_wipx.h index ae3fa49..23522fd 100644 --- a/source/windows/net_wipx.h +++ b/source/windows/net_wipx.h @@ -22,24 +22,24 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef __NET_WINIPX_H #define __NET_WINIPX_H -sys_socket_t WIPX_Init (void); -void WIPX_Shutdown (void); -void WIPX_Listen (bool state); -sys_socket_t WIPX_OpenSocket (int32_t port); -int32_t WIPX_CloseSocket (sys_socket_t socketid); -int32_t WIPX_Connect (sys_socket_t socketid, struct qsockaddr *addr); -sys_socket_t WIPX_CheckNewConnections (void); -int32_t WIPX_Read (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); -int32_t WIPX_Write (sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); -int32_t WIPX_Broadcast (sys_socket_t socketid, byte *buf, int32_t len); -const char *WIPX_AddrToString (struct qsockaddr *addr); -int32_t WIPX_StringToAddr (const char *string, struct qsockaddr *addr); -int32_t WIPX_GetSocketAddr (sys_socket_t socketid, struct qsockaddr *addr); -int32_t WIPX_GetNameFromAddr (struct qsockaddr *addr, char *name); -int32_t WIPX_GetAddrFromName (const char *name, struct qsockaddr *addr); -int32_t WIPX_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2); -int32_t WIPX_GetSocketPort (struct qsockaddr *addr); -int32_t WIPX_SetSocketPort (struct qsockaddr *addr, int32_t port); +sys_socket_t WIPX_Init(void); +void WIPX_Shutdown(void); +void WIPX_Listen(bool state); +sys_socket_t WIPX_OpenSocket(int32_t port); +int32_t WIPX_CloseSocket(sys_socket_t socketid); +int32_t WIPX_Connect(sys_socket_t socketid, struct qsockaddr *addr); +sys_socket_t WIPX_CheckNewConnections(void); +int32_t WIPX_Read(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); +int32_t WIPX_Write(sys_socket_t socketid, byte *buf, int32_t len, struct qsockaddr *addr); +int32_t WIPX_Broadcast(sys_socket_t socketid, byte *buf, int32_t len); +const char *WIPX_AddrToString(struct qsockaddr *addr); +int32_t WIPX_StringToAddr(const char *string, struct qsockaddr *addr); +int32_t WIPX_GetSocketAddr(sys_socket_t socketid, struct qsockaddr *addr); +int32_t WIPX_GetNameFromAddr(struct qsockaddr *addr, char *name); +int32_t WIPX_GetAddrFromName(const char *name, struct qsockaddr *addr); +int32_t WIPX_AddrCompare(struct qsockaddr *addr1, struct qsockaddr *addr2); +int32_t WIPX_GetSocketPort(struct qsockaddr *addr); +int32_t WIPX_SetSocketPort(struct qsockaddr *addr, int32_t port); -#endif /* __NET_WINIPX_H */ +#endif /* __NET_WINIPX_H */ diff --git a/source/windows/pl_win.c b/source/windows/pl_win.c index 0241743..c9c7654 100644 --- a/source/windows/pl_win.c +++ b/source/windows/pl_win.c @@ -28,7 +28,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. static HICON icon; -void PL_SetWindowIcon (void) +void PL_SetWindowIcon(void) { HINSTANCE handle; SDL_SysWMinfo wminfo; @@ -37,13 +37,13 @@ void PL_SetWindowIcon (void) handle = GetModuleHandle(NULL); icon = LoadIcon(handle, "icon"); - if (!icon) - return; /* no icon in the exe */ + if(!icon) + return; /* no icon in the exe */ SDL_VERSION(&wminfo.version); - if (SDL_GetWindowWMInfo((SDL_Window*) VID_GetWindow(), &wminfo) != SDL_TRUE) - return; /* wrong SDL version */ + if(SDL_GetWindowWMInfo((SDL_Window*) VID_GetWindow(), &wminfo) != SDL_TRUE) + return; /* wrong SDL version */ hwnd = wminfo.info.win.window; #ifdef _WIN64 @@ -53,45 +53,45 @@ void PL_SetWindowIcon (void) #endif } -void PL_VID_Shutdown (void) +void PL_VID_Shutdown(void) { DestroyIcon(icon); } -#define MAX_CLIPBOARDTXT MAXCMDLINE /* 256 */ -char *PL_GetClipboardData (void) +#define MAX_CLIPBOARDTXT MAXCMDLINE /* 256 */ +char *PL_GetClipboardData(void) { char *data = NULL; char *cliptext; - if (OpenClipboard(NULL) != 0) + if(OpenClipboard(NULL) != 0) { HANDLE hClipboardData; - if ((hClipboardData = GetClipboardData(CF_TEXT)) != NULL) + if((hClipboardData = GetClipboardData(CF_TEXT)) != NULL) { cliptext = (char *) GlobalLock(hClipboardData); - if (cliptext != NULL) + if(cliptext != NULL) { size_t size = GlobalSize(hClipboardData) + 1; - /* this is intended for simple small text copies - * such as an ip address, etc: do chop the size - * here, otherwise we may experience Z_Malloc() - * failures and all other not-oh-so-fun stuff. */ + /* this is intended for simple small text copies + * such as an ip address, etc: do chop the size + * here, otherwise we may experience Z_Malloc() + * failures and all other not-oh-so-fun stuff. */ size = q_min(MAX_CLIPBOARDTXT, size); data = (char *) Z_Malloc(size); - q_strlcpy (data, cliptext, size); - GlobalUnlock (hClipboardData); + q_strlcpy(data, cliptext, size); + GlobalUnlock(hClipboardData); } } - CloseClipboard (); + CloseClipboard(); } return data; } void PL_ErrorDialog(const char *errorMsg) { - MessageBox (NULL, errorMsg, "Quake Error", - MB_OK | MB_SETFOREGROUND | MB_ICONSTOP); + MessageBox(NULL, errorMsg, "Quake Error", + MB_OK | MB_SETFOREGROUND | MB_ICONSTOP); } diff --git a/source/windows/sys_sdl_win.c b/source/windows/sys_sdl_win.c index 6d4024d..2c029f5 100644 --- a/source/windows/sys_sdl_win.c +++ b/source/windows/sys_sdl_win.c @@ -36,50 +36,50 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include -bool isDedicated; -bool Win95, Win95old, WinNT, WinVista; -cvar_t sys_throttle = {"sys_throttle", "0.02", CVAR_ARCHIVE}; +bool isDedicated; +bool Win95, Win95old, WinNT, WinVista; +cvar_t sys_throttle = {"sys_throttle", "0.02", CVAR_ARCHIVE}; -static HANDLE hinput, houtput; +static HANDLE hinput, houtput; -#define MAX_HANDLES 32 /* johnfitz -- was 10 */ -static FILE *sys_handles[MAX_HANDLES]; +#define MAX_HANDLES 32 /* johnfitz -- was 10 */ +static FILE *sys_handles[MAX_HANDLES]; -static int32_t findhandle (void) +static int32_t findhandle(void) { int32_t i; - for (i = 1; i < MAX_HANDLES; i++) + for(i = 1; i < MAX_HANDLES; i++) { - if (!sys_handles[i]) + if(!sys_handles[i]) return i; } - Sys_Error ("out of handles"); + Sys_Error("out of handles"); return -1; } -long Sys_filelength (FILE *f) +long Sys_filelength(FILE *f) { - long pos, end; + long pos, end; - pos = ftell (f); - fseek (f, 0, SEEK_END); - end = ftell (f); - fseek (f, pos, SEEK_SET); + pos = ftell(f); + fseek(f, 0, SEEK_END); + end = ftell(f); + fseek(f, pos, SEEK_SET); return end; } -int32_t Sys_FileOpenRead (const char *path, int32_t *hndl) +int32_t Sys_FileOpenRead(const char *path, int32_t *hndl) { - FILE *f; - int32_t i, retval; + FILE *f; + int32_t i, retval; - i = findhandle (); + i = findhandle(); f = fopen(path, "rb"); - if (!f) + if(!f) { *hndl = -1; retval = -1; @@ -94,49 +94,49 @@ int32_t Sys_FileOpenRead (const char *path, int32_t *hndl) return retval; } -int32_t Sys_FileOpenWrite (const char *path) +int32_t Sys_FileOpenWrite(const char *path) { - FILE *f; - int32_t i; + FILE *f; + int32_t i; - i = findhandle (); + i = findhandle(); f = fopen(path, "wb"); - if (!f) - Sys_Error ("Error opening %s: %s", path, strerror(errno)); + if(!f) + Sys_Error("Error opening %s: %s", path, strerror(errno)); sys_handles[i] = f; return i; } -void Sys_FileClose (int32_t handle) +void Sys_FileClose(int32_t handle) { - fclose (sys_handles[handle]); + fclose(sys_handles[handle]); sys_handles[handle] = NULL; } -void Sys_FileSeek (int32_t handle, int32_t position) +void Sys_FileSeek(int32_t handle, int32_t position) { - fseek (sys_handles[handle], position, SEEK_SET); + fseek(sys_handles[handle], position, SEEK_SET); } -int32_t Sys_FileRead (int32_t handle, void *dest, int32_t count) +int32_t Sys_FileRead(int32_t handle, void *dest, int32_t count) { - return fread (dest, 1, count, sys_handles[handle]); + return fread(dest, 1, count, sys_handles[handle]); } -int32_t Sys_FileWrite (int32_t handle, const void *data, int32_t count) +int32_t Sys_FileWrite(int32_t handle, const void *data, int32_t count) { - return fwrite (data, 1, count, sys_handles[handle]); + return fwrite(data, 1, count, sys_handles[handle]); } -int32_t Sys_FileTime (const char *path) +int32_t Sys_FileTime(const char *path) { - FILE *f; + FILE *f; f = fopen(path, "rb"); - if (f) + if(f) { fclose(f); return 1; @@ -145,33 +145,33 @@ int32_t Sys_FileTime (const char *path) return -1; } -static char cwd[1024]; +static char cwd[1024]; -static void Sys_GetBasedir (char *argv0, char *dst, size_t dstsize) +static void Sys_GetBasedir(char *argv0, char *dst, size_t dstsize) { char *tmp; size_t rc; rc = GetCurrentDirectory(dstsize, dst); - if (rc == 0 || rc > dstsize) - Sys_Error ("Couldn't determine current directory"); + if(rc == 0 || rc > dstsize) + Sys_Error("Couldn't determine current directory"); tmp = dst; - while (*tmp != 0) + while(*tmp != 0) tmp++; - while (*tmp == 0 && tmp != dst) + while(*tmp == 0 && tmp != dst) { --tmp; - if (tmp != dst && (*tmp == '/' || *tmp == '\\')) + if(tmp != dst && (*tmp == '/' || *tmp == '\\')) *tmp = 0; } } typedef enum { dpi_unaware = 0, dpi_system_aware = 1, dpi_monitor_aware = 2 } dpi_awareness; typedef BOOL (WINAPI *SetProcessDPIAwareFunc)(); -typedef HRESULT (WINAPI *SetProcessDPIAwarenessFunc)(dpi_awareness value); +typedef HRESULT(WINAPI *SetProcessDPIAwarenessFunc)(dpi_awareness value); -static void Sys_SetDPIAware (void) +static void Sys_SetDPIAware(void) { HMODULE hUser32, hShcore; SetProcessDPIAwarenessFunc setDPIAwareness; @@ -182,20 +182,20 @@ static void Sys_SetDPIAware (void) Call SetProcessDpiAwareness/SetProcessDPIAware to opt out of scaling. */ - hShcore = LoadLibraryA ("Shcore.dll"); - hUser32 = LoadLibraryA ("user32.dll"); - setDPIAwareness = (SetProcessDPIAwarenessFunc) (hShcore ? GetProcAddress (hShcore, "SetProcessDpiAwareness") : NULL); - setDPIAware = (SetProcessDPIAwareFunc) (hUser32 ? GetProcAddress (hUser32, "SetProcessDPIAware") : NULL); + hShcore = LoadLibraryA("Shcore.dll"); + hUser32 = LoadLibraryA("user32.dll"); + setDPIAwareness = (SetProcessDPIAwarenessFunc)(hShcore ? GetProcAddress(hShcore, "SetProcessDpiAwareness") : NULL); + setDPIAware = (SetProcessDPIAwareFunc)(hUser32 ? GetProcAddress(hUser32, "SetProcessDPIAware") : NULL); - if (setDPIAwareness) /* Windows 8.1+ */ - setDPIAwareness (dpi_monitor_aware); - else if (setDPIAware) /* Windows Vista-8.0 */ - setDPIAware (); + if(setDPIAwareness) /* Windows 8.1+ */ + setDPIAwareness(dpi_monitor_aware); + else if(setDPIAware) /* Windows Vista-8.0 */ + setDPIAware(); - if (hShcore) - FreeLibrary (hShcore); - if (hUser32) - FreeLibrary (hUser32); + if(hShcore) + FreeLibrary(hShcore); + if(hUser32) + FreeLibrary(hUser32); } static void Sys_SetTimerResolution(void) @@ -205,17 +205,17 @@ static void Sys_SetTimerResolution(void) will make Sleep()/SDL_Dleay() accurate to 1ms which should help framerate stability. */ - timeBeginPeriod (1); + timeBeginPeriod(1); } -void Sys_Init (void) +void Sys_Init(void) { - OSVERSIONINFO vinfo; + OSVERSIONINFO vinfo; - Sys_SetTimerResolution (); - Sys_SetDPIAware (); + Sys_SetTimerResolution(); + Sys_SetDPIAware(); - memset (cwd, 0, sizeof(cwd)); + memset(cwd, 0, sizeof(cwd)); Sys_GetBasedir(NULL, cwd, sizeof(cwd)); host_parms->basedir = cwd; @@ -225,209 +225,209 @@ void Sys_Init (void) vinfo.dwOSVersionInfoSize = sizeof(vinfo); - if (!GetVersionEx (&vinfo)) - Sys_Error ("Couldn't get OS info"); + if(!GetVersionEx(&vinfo)) + Sys_Error("Couldn't get OS info"); - if ((vinfo.dwMajorVersion < 4) || - (vinfo.dwPlatformId == VER_PLATFORM_WIN32s)) + if((vinfo.dwMajorVersion < 4) || + (vinfo.dwPlatformId == VER_PLATFORM_WIN32s)) { - Sys_Error ("QuakeSpasm requires at least Win95 or NT 4.0"); + Sys_Error("QuakeSpasm requires at least Win95 or NT 4.0"); } - if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) + if(vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { SYSTEM_INFO info; WinNT = true; - if (vinfo.dwMajorVersion >= 6) + if(vinfo.dwMajorVersion >= 6) WinVista = true; GetSystemInfo(&info); host_parms->numcpus = info.dwNumberOfProcessors; - if (host_parms->numcpus < 1) + if(host_parms->numcpus < 1) host_parms->numcpus = 1; } else { WinNT = false; /* Win9x or WinME */ host_parms->numcpus = 1; - if ((vinfo.dwMajorVersion == 4) && (vinfo.dwMinorVersion == 0)) + if((vinfo.dwMajorVersion == 4) && (vinfo.dwMinorVersion == 0)) { Win95 = true; /* Win95-gold or Win95A can't switch bpp automatically */ - if (vinfo.szCSDVersion[1] != 'C' && vinfo.szCSDVersion[1] != 'B') + if(vinfo.szCSDVersion[1] != 'C' && vinfo.szCSDVersion[1] != 'B') Win95old = true; } } Sys_Printf("Detected %" PRIi32 " CPUs.\n", host_parms->numcpus); - if (isDedicated) + if(isDedicated) { - if (!AllocConsole ()) + if(!AllocConsole()) { - isDedicated = false; /* so that we have a graphical error dialog */ - Sys_Error ("Couldn't create dedicated server console"); + isDedicated = false; /* so that we have a graphical error dialog */ + Sys_Error("Couldn't create dedicated server console"); } - hinput = GetStdHandle (STD_INPUT_HANDLE); - houtput = GetStdHandle (STD_OUTPUT_HANDLE); + hinput = GetStdHandle(STD_INPUT_HANDLE); + houtput = GetStdHandle(STD_OUTPUT_HANDLE); } } -void Sys_mkdir (const char *path) +void Sys_mkdir(const char *path) { - if (CreateDirectory(path, NULL) != 0) + if(CreateDirectory(path, NULL) != 0) return; - if (GetLastError() != ERROR_ALREADY_EXISTS) + if(GetLastError() != ERROR_ALREADY_EXISTS) Sys_Error("Unable to create directory %s", path); } static const char errortxt1[] = "\nERROR-OUT BEGIN\n\n"; static const char errortxt2[] = "\nQUAKE ERROR: "; -void Sys_Error (const char *error, ...) +void Sys_Error(const char *error, ...) { - va_list argptr; - char text[1024]; - DWORD dummy; + va_list argptr; + char text[1024]; + DWORD dummy; host_parms->errstate++; - va_start (argptr, error); - q_vsnprintf (text, sizeof(text), error, argptr); - va_end (argptr); + va_start(argptr, error); + q_vsnprintf(text, sizeof(text), error, argptr); + va_end(argptr); - if (isDedicated) - WriteFile (houtput, errortxt1, strlen(errortxt1), &dummy, NULL); + if(isDedicated) + WriteFile(houtput, errortxt1, strlen(errortxt1), &dummy, NULL); /* SDL will put these into its own stderr log, so print to stderr even in graphical mode. */ - fputs (errortxt1, stderr); - Host_Shutdown (); - fputs (errortxt2, stderr); - fputs (text, stderr); - fputs ("\n\n", stderr); - if (!isDedicated) + fputs(errortxt1, stderr); + Host_Shutdown(); + fputs(errortxt2, stderr); + fputs(text, stderr); + fputs("\n\n", stderr); + if(!isDedicated) PL_ErrorDialog(text); else { - WriteFile (houtput, errortxt2, strlen(errortxt2), &dummy, NULL); - WriteFile (houtput, text, strlen(text), &dummy, NULL); - WriteFile (houtput, "\r\n", 2, &dummy, NULL); - SDL_Delay (3000); /* show the console 3 more seconds */ + WriteFile(houtput, errortxt2, strlen(errortxt2), &dummy, NULL); + WriteFile(houtput, text, strlen(text), &dummy, NULL); + WriteFile(houtput, "\r\n", 2, &dummy, NULL); + SDL_Delay(3000); /* show the console 3 more seconds */ } - exit (1); + exit(1); } -void Sys_Printf (const char *fmt, ...) +void Sys_Printf(const char *fmt, ...) { - va_list argptr; - char text[1024]; - DWORD dummy; + va_list argptr; + char text[1024]; + DWORD dummy; - va_start (argptr,fmt); - q_vsnprintf (text, sizeof(text), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + q_vsnprintf(text, sizeof(text), fmt, argptr); + va_end(argptr); - if (isDedicated) + if(isDedicated) { WriteFile(houtput, text, strlen(text), &dummy, NULL); } else { - /* SDL will put these into its own stdout log, - so print to stdout even in graphical mode. */ - fputs (text, stdout); + /* SDL will put these into its own stdout log, + so print to stdout even in graphical mode. */ + fputs(text, stdout); } } -void Sys_Quit (void) +void Sys_Quit(void) { Host_Shutdown(); - if (isDedicated) - FreeConsole (); + if(isDedicated) + FreeConsole(); - exit (0); + exit(0); } -double Sys_DoubleTime (void) +double Sys_DoubleTime(void) { return SDL_GetTicks() / 1000.0; } -const char *Sys_ConsoleInput (void) +const char *Sys_ConsoleInput(void) { - static char con_text[256]; - static int32_t textlen; - INPUT_RECORD recs[1024]; - int32_t ch; - DWORD dummy, numread, numevents; + static char con_text[256]; + static int32_t textlen; + INPUT_RECORD recs[1024]; + int32_t ch; + DWORD dummy, numread, numevents; - for ( ;; ) + for(;;) { - if (GetNumberOfConsoleInputEvents(hinput, &numevents) == 0) - Sys_Error ("Error getting # of console events"); + if(GetNumberOfConsoleInputEvents(hinput, &numevents) == 0) + Sys_Error("Error getting # of console events"); - if (! numevents) + if(! numevents) break; - if (ReadConsoleInput(hinput, recs, 1, &numread) == 0) - Sys_Error ("Error reading console input"); + if(ReadConsoleInput(hinput, recs, 1, &numread) == 0) + Sys_Error("Error reading console input"); - if (numread != 1) - Sys_Error ("Couldn't read console input"); + if(numread != 1) + Sys_Error("Couldn't read console input"); - if (recs[0].EventType == KEY_EVENT) + if(recs[0].EventType == KEY_EVENT) { - if (recs[0].Event.KeyEvent.bKeyDown == FALSE) - { - ch = recs[0].Event.KeyEvent.uChar.AsciiChar; - - switch (ch) + if(recs[0].Event.KeyEvent.bKeyDown == FALSE) { - case '\r': - WriteFile(houtput, "\r\n", 2, &dummy, NULL); + ch = recs[0].Event.KeyEvent.uChar.AsciiChar; - if (textlen != 0) + switch(ch) { - con_text[textlen] = 0; - textlen = 0; - return con_text; + case '\r': + WriteFile(houtput, "\r\n", 2, &dummy, NULL); + + if(textlen != 0) + { + con_text[textlen] = 0; + textlen = 0; + return con_text; + } + + break; + + case '\b': + WriteFile(houtput, "\b \b", 3, &dummy, NULL); + if(textlen != 0) + textlen--; + + break; + + default: + if(ch >= ' ') + { + WriteFile(houtput, &ch, 1, &dummy, NULL); + con_text[textlen] = ch; + textlen = (textlen + 1) & 0xff; + } + + break; } - - break; - - case '\b': - WriteFile(houtput, "\b \b", 3, &dummy, NULL); - if (textlen != 0) - textlen--; - - break; - - default: - if (ch >= ' ') - { - WriteFile(houtput, &ch, 1, &dummy, NULL); - con_text[textlen] = ch; - textlen = (textlen + 1) & 0xff; - } - - break; } - } } } return NULL; } -void Sys_Sleep (uint32_t msecs) +void Sys_Sleep(uint32_t msecs) { SDL_Delay(msecs); } -void Sys_SendKeyEvents (void) +void Sys_SendKeyEvents(void) { - IN_Commands(); //ericw -- allow joysticks to add keys so they can be used to confirm SCR_ModalMessage + IN_Commands(); //ericw -- allow joysticks to add keys so they can be used to confirm SCR_ModalMessage IN_SendKeyEvents(); } diff --git a/source/windows/wsaerror.h b/source/windows/wsaerror.h index b52e1c2..1fc24b2 100644 --- a/source/windows/wsaerror.h +++ b/source/windows/wsaerror.h @@ -8,84 +8,147 @@ #ifndef __wsaerr_static #define __wsaerr_static static -#endif /* static */ +#endif /* static */ -__wsaerr_static const char *__WSAE_StrError (int32_t err) +__wsaerr_static const char *__WSAE_StrError(int32_t err) { - switch (err) + switch(err) { - case 0: return "No error"; - case WSAEINTR: return "Interrupted system call"; /* 10004 */ - case WSAEBADF: return "Bad file number"; /* 10009 */ - case WSAEACCES: return "Permission denied"; /* 10013 */ - case WSAEFAULT: return "Bad address"; /* 10014 */ - case WSAEINVAL: return "Invalid argument (not bind)"; /* 10022 */ - case WSAEMFILE: return "Too many open files"; /* 10024 */ - case WSAEWOULDBLOCK: return "Operation would block"; /* 10035 */ - case WSAEINPROGRESS: return "Operation now in progress"; /* 10036 */ - case WSAEALREADY: return "Operation already in progress"; /* 10037 */ - case WSAENOTSOCK: return "Socket operation on non-socket"; /* 10038 */ - case WSAEDESTADDRREQ: return "Destination address required"; /* 10039 */ - case WSAEMSGSIZE: return "Message too long"; /* 10040 */ - case WSAEPROTOTYPE: return "Protocol wrong type for socket"; /* 10041 */ - case WSAENOPROTOOPT: return "Bad protocol option"; /* 10042 */ - case WSAEPROTONOSUPPORT: return "Protocol not supported"; /* 10043 */ - case WSAESOCKTNOSUPPORT: return "Socket type not supported"; /* 10044 */ - case WSAEOPNOTSUPP: return "Operation not supported on socket"; /* 10045 */ - case WSAEPFNOSUPPORT: return "Protocol family not supported"; /* 10046 */ - case WSAEAFNOSUPPORT: return "Address family not supported by protocol family"; /* 10047 */ - case WSAEADDRINUSE: return "Address already in use"; /* 10048 */ - case WSAEADDRNOTAVAIL: return "Can't assign requested address"; /* 10049 */ - case WSAENETDOWN: return "Network is down"; /* 10050 */ - case WSAENETUNREACH: return "Network is unreachable"; /* 10051 */ - case WSAENETRESET: return "Net dropped connection or reset"; /* 10052 */ - case WSAECONNABORTED: return "Software caused connection abort"; /* 10053 */ - case WSAECONNRESET: return "Connection reset by peer"; /* 10054 */ - case WSAENOBUFS: return "No buffer space available"; /* 10055 */ - case WSAEISCONN: return "Socket is already connected"; /* 10056 */ - case WSAENOTCONN: return "Socket is not connected"; /* 10057 */ - case WSAESHUTDOWN: return "Can't send after socket shutdown"; /* 10058 */ - case WSAETOOMANYREFS: return "Too many references, can't splice"; /* 10059 */ - case WSAETIMEDOUT: return "Connection timed out"; /* 10060 */ - case WSAECONNREFUSED: return "Connection refused"; /* 10061 */ - case WSAELOOP: return "Too many levels of symbolic links"; /* 10062 */ - case WSAENAMETOOLONG: return "File name too long"; /* 10063 */ - case WSAEHOSTDOWN: return "Host is down"; /* 10064 */ - case WSAEHOSTUNREACH: return "No Route to Host"; /* 10065 */ - case WSAENOTEMPTY: return "Directory not empty"; /* 10066 */ - case WSAEPROCLIM: return "Too many processes"; /* 10067 */ - case WSAEUSERS: return "Too many users"; /* 10068 */ - case WSAEDQUOT: return "Disc Quota Exceeded"; /* 10069 */ - case WSAESTALE: return "Stale NFS file handle"; /* 10070 */ - case WSAEREMOTE: return "Too many levels of remote in path"; /* 10071 */ - case WSAEDISCON: return "Graceful shutdown in progress"; /* 10101 */ + case 0: + return "No error"; + case WSAEINTR: + return "Interrupted system call"; /* 10004 */ + case WSAEBADF: + return "Bad file number"; /* 10009 */ + case WSAEACCES: + return "Permission denied"; /* 10013 */ + case WSAEFAULT: + return "Bad address"; /* 10014 */ + case WSAEINVAL: + return "Invalid argument (not bind)"; /* 10022 */ + case WSAEMFILE: + return "Too many open files"; /* 10024 */ + case WSAEWOULDBLOCK: + return "Operation would block"; /* 10035 */ + case WSAEINPROGRESS: + return "Operation now in progress"; /* 10036 */ + case WSAEALREADY: + return "Operation already in progress"; /* 10037 */ + case WSAENOTSOCK: + return "Socket operation on non-socket"; /* 10038 */ + case WSAEDESTADDRREQ: + return "Destination address required"; /* 10039 */ + case WSAEMSGSIZE: + return "Message too long"; /* 10040 */ + case WSAEPROTOTYPE: + return "Protocol wrong type for socket"; /* 10041 */ + case WSAENOPROTOOPT: + return "Bad protocol option"; /* 10042 */ + case WSAEPROTONOSUPPORT: + return "Protocol not supported"; /* 10043 */ + case WSAESOCKTNOSUPPORT: + return "Socket type not supported"; /* 10044 */ + case WSAEOPNOTSUPP: + return "Operation not supported on socket"; /* 10045 */ + case WSAEPFNOSUPPORT: + return "Protocol family not supported"; /* 10046 */ + case WSAEAFNOSUPPORT: + return "Address family not supported by protocol family"; /* 10047 */ + case WSAEADDRINUSE: + return "Address already in use"; /* 10048 */ + case WSAEADDRNOTAVAIL: + return "Can't assign requested address"; /* 10049 */ + case WSAENETDOWN: + return "Network is down"; /* 10050 */ + case WSAENETUNREACH: + return "Network is unreachable"; /* 10051 */ + case WSAENETRESET: + return "Net dropped connection or reset"; /* 10052 */ + case WSAECONNABORTED: + return "Software caused connection abort"; /* 10053 */ + case WSAECONNRESET: + return "Connection reset by peer"; /* 10054 */ + case WSAENOBUFS: + return "No buffer space available"; /* 10055 */ + case WSAEISCONN: + return "Socket is already connected"; /* 10056 */ + case WSAENOTCONN: + return "Socket is not connected"; /* 10057 */ + case WSAESHUTDOWN: + return "Can't send after socket shutdown"; /* 10058 */ + case WSAETOOMANYREFS: + return "Too many references, can't splice"; /* 10059 */ + case WSAETIMEDOUT: + return "Connection timed out"; /* 10060 */ + case WSAECONNREFUSED: + return "Connection refused"; /* 10061 */ + case WSAELOOP: + return "Too many levels of symbolic links"; /* 10062 */ + case WSAENAMETOOLONG: + return "File name too long"; /* 10063 */ + case WSAEHOSTDOWN: + return "Host is down"; /* 10064 */ + case WSAEHOSTUNREACH: + return "No Route to Host"; /* 10065 */ + case WSAENOTEMPTY: + return "Directory not empty"; /* 10066 */ + case WSAEPROCLIM: + return "Too many processes"; /* 10067 */ + case WSAEUSERS: + return "Too many users"; /* 10068 */ + case WSAEDQUOT: + return "Disc Quota Exceeded"; /* 10069 */ + case WSAESTALE: + return "Stale NFS file handle"; /* 10070 */ + case WSAEREMOTE: + return "Too many levels of remote in path"; /* 10071 */ + case WSAEDISCON: + return "Graceful shutdown in progress"; /* 10101 */ - case WSASYSNOTREADY: return "Network SubSystem is unavailable"; /* 10091 */ - case WSAVERNOTSUPPORTED: return "WINSOCK DLL Version out of range"; /* 10092 */ - case WSANOTINITIALISED: return "Successful WSASTARTUP not yet performed"; /* 10093 */ - case WSAHOST_NOT_FOUND: return "Authoritative answer: Host not found"; /* 11001 */ - case WSATRY_AGAIN: return "Non-Authoritative: Host not found or SERVERFAIL"; /* 11002 */ - case WSANO_RECOVERY: return "Non-Recoverable errors, FORMERR, REFUSED, NOTIMP"; /* 11003 */ - case WSANO_DATA: return "Valid name, no data record of requested type"; /* 11004 */ + case WSASYSNOTREADY: + return "Network SubSystem is unavailable"; /* 10091 */ + case WSAVERNOTSUPPORTED: + return "WINSOCK DLL Version out of range"; /* 10092 */ + case WSANOTINITIALISED: + return "Successful WSASTARTUP not yet performed"; /* 10093 */ + case WSAHOST_NOT_FOUND: + return "Authoritative answer: Host not found"; /* 11001 */ + case WSATRY_AGAIN: + return "Non-Authoritative: Host not found or SERVERFAIL"; /* 11002 */ + case WSANO_RECOVERY: + return "Non-Recoverable errors, FORMERR, REFUSED, NOTIMP"; /* 11003 */ + case WSANO_DATA: + return "Valid name, no data record of requested type"; /* 11004 */ - case WSAENOMORE: return "10102: No more results"; /* 10102 */ - case WSAECANCELLED: return "10103: Call has been canceled"; /* 10103 */ - case WSAEINVALIDPROCTABLE: return "Procedure call table is invalid"; /* 10104 */ - case WSAEINVALIDPROVIDER: return "Service provider is invalid"; /* 10105 */ - case WSAEPROVIDERFAILEDINIT: return "Service provider failed to initialize"; /* 10106 */ - case WSASYSCALLFAILURE: return "System call failure"; /* 10107 */ - case WSASERVICE_NOT_FOUND: return "Service not found"; /* 10108 */ - case WSATYPE_NOT_FOUND: return "Class type not found"; /* 10109 */ - case WSA_E_NO_MORE: return "10110: No more results"; /* 10110 */ - case WSA_E_CANCELLED: return "10111: Call was canceled"; /* 10111 */ - case WSAEREFUSED: return "Database query was refused"; /* 10112 */ + case WSAENOMORE: + return "10102: No more results"; /* 10102 */ + case WSAECANCELLED: + return "10103: Call has been canceled"; /* 10103 */ + case WSAEINVALIDPROCTABLE: + return "Procedure call table is invalid"; /* 10104 */ + case WSAEINVALIDPROVIDER: + return "Service provider is invalid"; /* 10105 */ + case WSAEPROVIDERFAILEDINIT: + return "Service provider failed to initialize"; /* 10106 */ + case WSASYSCALLFAILURE: + return "System call failure"; /* 10107 */ + case WSASERVICE_NOT_FOUND: + return "Service not found"; /* 10108 */ + case WSATYPE_NOT_FOUND: + return "Class type not found"; /* 10109 */ + case WSA_E_NO_MORE: + return "10110: No more results"; /* 10110 */ + case WSA_E_CANCELLED: + return "10111: Call was canceled"; /* 10111 */ + case WSAEREFUSED: + return "Database query was refused"; /* 10112 */ default: - { - static char _err_unknown[64]; - sprintf(_err_unknown, "Unknown WSAE error (%" PRIi32 ")", err); - return _err_unknown; - } + { + static char _err_unknown[64]; + sprintf(_err_unknown, "Unknown WSAE error (%" PRIi32 ")", err); + return _err_unknown; + } } } diff --git a/source/world.c b/source/world.c index 33f4d11..3a6f474 100644 --- a/source/world.c +++ b/source/world.c @@ -35,17 +35,17 @@ line of sight checks trace->crosscontent, but bullets don't typedef struct { - vec3_t boxmins, boxmaxs;// enclose the test object along entire move - float *mins, *maxs; // size of the moving object - vec3_t mins2, maxs2; // size when clipping against mosnters - float *start, *end; - trace_t trace; - int32_t type; - edict_t *passedict; + vec3_t boxmins, boxmaxs;// enclose the test object along entire move + float *mins, *maxs; // size of the moving object + vec3_t mins2, maxs2; // size when clipping against mosnters + float *start, *end; + trace_t trace; + int32_t type; + edict_t *passedict; } moveclip_t; -int32_t SV_HullPointContents (hull_t *hull, int32_t num, vec3_t p); +int32_t SV_HullPointContents(hull_t *hull, int32_t num, vec3_t p); /* =============================================================================== @@ -56,9 +56,9 @@ HULL BOXES */ -static hull_t box_hull; -static mclipnode_t box_clipnodes[6]; //johnfitz -- was dclipnode_t -static mplane_t box_planes[6]; +static hull_t box_hull; +static mclipnode_t box_clipnodes[6]; //johnfitz -- was dclipnode_t +static mplane_t box_planes[6]; /* =================== @@ -68,30 +68,30 @@ Set up the planes and clipnodes so that the six floats of a bounding box can just be stored out and get a proper hull_t structure. =================== */ -void SV_InitBoxHull (void) +void SV_InitBoxHull(void) { - int32_t i; - int32_t side; + int32_t i; + int32_t side; box_hull.clipnodes = box_clipnodes; box_hull.planes = box_planes; box_hull.firstclipnode = 0; box_hull.lastclipnode = 5; - for (i=0 ; i<6 ; i++) + for(i = 0 ; i < 6 ; i++) { box_clipnodes[i].planenum = i; - side = i&1; + side = i & 1; box_clipnodes[i].children[side] = CONTENTS_EMPTY; - if (i != 5) - box_clipnodes[i].children[side^1] = i + 1; + if(i != 5) + box_clipnodes[i].children[side ^ 1] = i + 1; else - box_clipnodes[i].children[side^1] = CONTENTS_SOLID; + box_clipnodes[i].children[side ^ 1] = CONTENTS_SOLID; - box_planes[i].type = i>>1; - box_planes[i].normal[i>>1] = 1; + box_planes[i].type = i >> 1; + box_planes[i].normal[i >> 1] = 1; } } @@ -105,7 +105,7 @@ To keep everything totally uniform, bounding boxes are turned into small BSP trees instead of being compared directly. =================== */ -hull_t *SV_HullForBox (vec3_t mins, vec3_t maxs) +hull_t *SV_HullForBox(vec3_t mins, vec3_t maxs) { box_planes[0].dist = maxs[0]; box_planes[1].dist = mins[0]; @@ -129,46 +129,48 @@ Offset is filled in to contain the adjustment that must be added to the testing object's origin to get a point to use with the returned hull. ================ */ -hull_t *SV_HullForEntity (edict_t *ent, vec3_t mins, vec3_t maxs, vec3_t offset) +hull_t *SV_HullForEntity(edict_t *ent, vec3_t mins, vec3_t maxs, vec3_t offset) { - qmodel_t *model; - vec3_t size; - vec3_t hullmins, hullmaxs; - hull_t *hull; + qmodel_t *model; + vec3_t size; + vec3_t hullmins, hullmaxs; + hull_t *hull; // decide which clipping hull to use, based on the size - if (ent->v.solid == SOLID_BSP) - { // explicit hulls in the BSP model - if (ent->v.movetype != MOVETYPE_PUSH) - Host_Error ("SOLID_BSP without MOVETYPE_PUSH (%s at %f %f %f)", - PR_GetString(ent->v.classname), ent->v.origin[0], ent->v.origin[1], ent->v.origin[2]); + if(ent->v.solid == SOLID_BSP) + { + // explicit hulls in the BSP model + if(ent->v.movetype != MOVETYPE_PUSH) + Host_Error("SOLID_BSP without MOVETYPE_PUSH (%s at %f %f %f)", + PR_GetString(ent->v.classname), ent->v.origin[0], ent->v.origin[1], ent->v.origin[2]); - model = sv.models[ (int32_t)ent->v.modelindex ]; + model = sv.models[(int32_t)ent->v.modelindex ]; - if (!model || model->type != mod_brush) - Host_Error ("SOLID_BSP with a non bsp model (%s at %f %f %f)", - PR_GetString(ent->v.classname), ent->v.origin[0], ent->v.origin[1], ent->v.origin[2]); + if(!model || model->type != mod_brush) + Host_Error("SOLID_BSP with a non bsp model (%s at %f %f %f)", + PR_GetString(ent->v.classname), ent->v.origin[0], ent->v.origin[1], ent->v.origin[2]); - VectorSubtract (maxs, mins, size); - if (size[0] < 3) + VectorSubtract(maxs, mins, size); + if(size[0] < 3) hull = &model->hulls[0]; - else if (size[0] <= 32) + else if(size[0] <= 32) hull = &model->hulls[1]; else hull = &model->hulls[2]; // calculate an offset value to center the origin - VectorSubtract (hull->clip_mins, mins, offset); - VectorAdd (offset, ent->v.origin, offset); + VectorSubtract(hull->clip_mins, mins, offset); + VectorAdd(offset, ent->v.origin, offset); } else - { // create a temp hull from bounding box sizes + { + // create a temp hull from bounding box sizes - VectorSubtract (ent->v.mins, maxs, hullmins); - VectorSubtract (ent->v.maxs, mins, hullmaxs); - hull = SV_HullForBox (hullmins, hullmaxs); + VectorSubtract(ent->v.mins, maxs, hullmins); + VectorSubtract(ent->v.maxs, mins, hullmaxs); + hull = SV_HullForBox(hullmins, hullmaxs); - VectorCopy (ent->v.origin, offset); + VectorCopy(ent->v.origin, offset); } @@ -185,18 +187,18 @@ ENTITY AREA CHECKING typedef struct areanode_s { - int32_t axis; // -1 = leaf node - float dist; - struct areanode_s *children[2]; - link_t trigger_edicts; - link_t solid_edicts; + int32_t axis; // -1 = leaf node + float dist; + struct areanode_s *children[2]; + link_t trigger_edicts; + link_t solid_edicts; } areanode_t; -#define AREA_DEPTH 4 -#define AREA_NODES 32 +#define AREA_DEPTH 4 +#define AREA_NODES 32 -static areanode_t sv_areanodes[AREA_NODES]; -static int32_t sv_numareanodes; +static areanode_t sv_areanodes[AREA_NODES]; +static int32_t sv_numareanodes; /* =============== @@ -204,41 +206,41 @@ SV_CreateAreaNode =============== */ -areanode_t *SV_CreateAreaNode (int32_t depth, vec3_t mins, vec3_t maxs) +areanode_t *SV_CreateAreaNode(int32_t depth, vec3_t mins, vec3_t maxs) { - areanode_t *anode; - vec3_t size; - vec3_t mins1, maxs1, mins2, maxs2; + areanode_t *anode; + vec3_t size; + vec3_t mins1, maxs1, mins2, maxs2; anode = &sv_areanodes[sv_numareanodes]; sv_numareanodes++; - ClearLink (&anode->trigger_edicts); - ClearLink (&anode->solid_edicts); + ClearLink(&anode->trigger_edicts); + ClearLink(&anode->solid_edicts); - if (depth == AREA_DEPTH) + if(depth == AREA_DEPTH) { anode->axis = -1; anode->children[0] = anode->children[1] = NULL; return anode; } - VectorSubtract (maxs, mins, size); - if (size[0] > size[1]) + VectorSubtract(maxs, mins, size); + if(size[0] > size[1]) anode->axis = 0; else anode->axis = 1; anode->dist = 0.5 * (maxs[anode->axis] + mins[anode->axis]); - VectorCopy (mins, mins1); - VectorCopy (mins, mins2); - VectorCopy (maxs, maxs1); - VectorCopy (maxs, maxs2); + VectorCopy(mins, mins1); + VectorCopy(mins, mins2); + VectorCopy(maxs, maxs1); + VectorCopy(maxs, maxs2); maxs1[anode->axis] = mins2[anode->axis] = anode->dist; - anode->children[0] = SV_CreateAreaNode (depth+1, mins2, maxs2); - anode->children[1] = SV_CreateAreaNode (depth+1, mins1, maxs1); + anode->children[0] = SV_CreateAreaNode(depth + 1, mins2, maxs2); + anode->children[1] = SV_CreateAreaNode(depth + 1, mins1, maxs1); return anode; } @@ -249,13 +251,13 @@ SV_ClearWorld =============== */ -void SV_ClearWorld (void) +void SV_ClearWorld(void) { - SV_InitBoxHull (); + SV_InitBoxHull(); - memset (sv_areanodes, 0, sizeof(sv_areanodes)); + memset(sv_areanodes, 0, sizeof(sv_areanodes)); sv_numareanodes = 0; - SV_CreateAreaNode (0, sv.worldmodel->mins, sv.worldmodel->maxs); + SV_CreateAreaNode(0, sv.worldmodel->mins, sv.worldmodel->maxs); } @@ -265,11 +267,11 @@ SV_UnlinkEdict =============== */ -void SV_UnlinkEdict (edict_t *ent) +void SV_UnlinkEdict(edict_t *ent) { - if (!ent->area.prev) - return; // not linked in anywhere - RemoveLink (&ent->area); + if(!ent->area.prev) + return; // not linked in anywhere + RemoveLink(&ent->area); ent->area.prev = ent->area.next = NULL; } @@ -283,29 +285,29 @@ them and risking the list getting corrupt. ==================== */ static void -SV_AreaTriggerEdicts ( edict_t *ent, areanode_t *node, edict_t **list, int32_t *listcount, const int32_t listspace ) +SV_AreaTriggerEdicts(edict_t *ent, areanode_t *node, edict_t **list, int32_t *listcount, const int32_t listspace) { - link_t *l, *next; - edict_t *touch; + link_t *l, *next; + edict_t *touch; // touch linked edicts - for (l = node->trigger_edicts.next ; l != &node->trigger_edicts ; l = next) + for(l = node->trigger_edicts.next ; l != &node->trigger_edicts ; l = next) { next = l->next; touch = EDICT_FROM_AREA(l); - if (touch == ent) + if(touch == ent) continue; - if (!touch->v.touch || touch->v.solid != SOLID_TRIGGER) + if(!touch->v.touch || touch->v.solid != SOLID_TRIGGER) continue; - if (ent->v.absmin[0] > touch->v.absmax[0] - || ent->v.absmin[1] > touch->v.absmax[1] - || ent->v.absmin[2] > touch->v.absmax[2] - || ent->v.absmax[0] < touch->v.absmin[0] - || ent->v.absmax[1] < touch->v.absmin[1] - || ent->v.absmax[2] < touch->v.absmin[2] ) + if(ent->v.absmin[0] > touch->v.absmax[0] + || ent->v.absmin[1] > touch->v.absmax[1] + || ent->v.absmin[2] > touch->v.absmax[2] + || ent->v.absmax[0] < touch->v.absmin[0] + || ent->v.absmax[1] < touch->v.absmin[1] + || ent->v.absmax[2] < touch->v.absmin[2]) continue; - if (*listcount == listspace) + if(*listcount == listspace) return; // should never happen list[*listcount] = touch; @@ -313,13 +315,13 @@ SV_AreaTriggerEdicts ( edict_t *ent, areanode_t *node, edict_t **list, int32_t * } // recurse down both sides - if (node->axis == -1) + if(node->axis == -1) return; - if ( ent->v.absmax[node->axis] > node->dist ) - SV_AreaTriggerEdicts ( ent, node->children[0], list, listcount, listspace ); - if ( ent->v.absmin[node->axis] < node->dist ) - SV_AreaTriggerEdicts ( ent, node->children[1], list, listcount, listspace ); + if(ent->v.absmax[node->axis] > node->dist) + SV_AreaTriggerEdicts(ent, node->children[0], list, listcount, listspace); + if(ent->v.absmin[node->axis] < node->dist) + SV_AreaTriggerEdicts(ent, node->children[1], list, listcount, listspace); } /* @@ -332,35 +334,35 @@ which could potentially corrupt the list while it's being iterated. Based on code from Spike. ==================== */ -void SV_TouchLinks (edict_t *ent) +void SV_TouchLinks(edict_t *ent) { - edict_t **list; - edict_t *touch; - int32_t old_self, old_other; - int32_t i, listcount; - int32_t mark; - - mark = Hunk_LowMark (); - list = (edict_t **) Hunk_Alloc (sv.num_edicts*sizeof(edict_t *)); - - listcount = 0; - SV_AreaTriggerEdicts (ent, sv_areanodes, list, &listcount, sv.num_edicts); + edict_t **list; + edict_t *touch; + int32_t old_self, old_other; + int32_t i, listcount; + int32_t mark; - for (i = 0; i < listcount; i++) + mark = Hunk_LowMark(); + list = (edict_t **) Hunk_Alloc(sv.num_edicts * sizeof(edict_t *)); + + listcount = 0; + SV_AreaTriggerEdicts(ent, sv_areanodes, list, &listcount, sv.num_edicts); + + for(i = 0; i < listcount; i++) { touch = list[i]; - // re-validate in case of PR_ExecuteProgram having side effects that make - // edicts later in the list no longer touch - if (touch == ent) + // re-validate in case of PR_ExecuteProgram having side effects that make + // edicts later in the list no longer touch + if(touch == ent) continue; - if (!touch->v.touch || touch->v.solid != SOLID_TRIGGER) + if(!touch->v.touch || touch->v.solid != SOLID_TRIGGER) continue; - if (ent->v.absmin[0] > touch->v.absmax[0] - || ent->v.absmin[1] > touch->v.absmax[1] - || ent->v.absmin[2] > touch->v.absmax[2] - || ent->v.absmax[0] < touch->v.absmin[0] - || ent->v.absmax[1] < touch->v.absmin[1] - || ent->v.absmax[2] < touch->v.absmin[2] ) + if(ent->v.absmin[0] > touch->v.absmax[0] + || ent->v.absmin[1] > touch->v.absmax[1] + || ent->v.absmin[2] > touch->v.absmax[2] + || ent->v.absmax[0] < touch->v.absmin[0] + || ent->v.absmax[1] < touch->v.absmin[1] + || ent->v.absmax[2] < touch->v.absmin[2]) continue; old_self = pr_global_struct->self; old_other = pr_global_struct->other; @@ -368,14 +370,14 @@ void SV_TouchLinks (edict_t *ent) pr_global_struct->self = EDICT_TO_PROG(touch); pr_global_struct->other = EDICT_TO_PROG(ent); pr_global_struct->time = sv.time; - PR_ExecuteProgram (touch->v.touch); + PR_ExecuteProgram(touch->v.touch); pr_global_struct->self = old_self; pr_global_struct->other = old_other; } // free hunk-allocated edicts array - Hunk_FreeToLowMark (mark); + Hunk_FreeToLowMark(mark); } @@ -385,21 +387,21 @@ SV_FindTouchedLeafs =============== */ -void SV_FindTouchedLeafs (edict_t *ent, mnode_t *node) +void SV_FindTouchedLeafs(edict_t *ent, mnode_t *node) { - mplane_t *splitplane; - mleaf_t *leaf; - int32_t sides; - int32_t leafnum; + mplane_t *splitplane; + mleaf_t *leaf; + int32_t sides; + int32_t leafnum; - if (node->contents == CONTENTS_SOLID) + if(node->contents == CONTENTS_SOLID) return; // add an efrag if the node is a leaf - if ( node->contents < 0) + if(node->contents < 0) { - if (ent->num_leafs == MAX_ENT_LEAFS) + if(ent->num_leafs == MAX_ENT_LEAFS) return; leaf = (mleaf_t *)node; @@ -416,11 +418,11 @@ void SV_FindTouchedLeafs (edict_t *ent, mnode_t *node) sides = BOX_ON_PLANE_SIDE(ent->v.absmin, ent->v.absmax, splitplane); // recurse down the contacted sides - if (sides & 1) - SV_FindTouchedLeafs (ent, node->children[0]); + if(sides & 1) + SV_FindTouchedLeafs(ent, node->children[0]); - if (sides & 2) - SV_FindTouchedLeafs (ent, node->children[1]); + if(sides & 2) + SV_FindTouchedLeafs(ent, node->children[1]); } /* @@ -429,28 +431,28 @@ SV_LinkEdict =============== */ -void SV_LinkEdict (edict_t *ent, bool touch_triggers) +void SV_LinkEdict(edict_t *ent, bool touch_triggers) { - areanode_t *node; + areanode_t *node; - if (ent->area.prev) - SV_UnlinkEdict (ent); // unlink from old position + if(ent->area.prev) + SV_UnlinkEdict(ent); // unlink from old position - if (ent == sv.edicts) - return; // don't add the world + if(ent == sv.edicts) + return; // don't add the world - if (ent->free) + if(ent->free) return; // set the abs box - VectorAdd (ent->v.origin, ent->v.mins, ent->v.absmin); - VectorAdd (ent->v.origin, ent->v.maxs, ent->v.absmax); + VectorAdd(ent->v.origin, ent->v.mins, ent->v.absmin); + VectorAdd(ent->v.origin, ent->v.maxs, ent->v.absmax); // // to make items easier to pick up and allow them to be grabbed off // of shelves, the abs sizes are expanded // - if ((int32_t)ent->v.flags & FL_ITEM) + if((int32_t)ent->v.flags & FL_ITEM) { ent->v.absmin[0] -= 15; ent->v.absmin[1] -= 15; @@ -458,7 +460,8 @@ void SV_LinkEdict (edict_t *ent, bool touch_triggers) ent->v.absmax[1] += 15; } else - { // because movement is clipped an epsilon away from an actual edge, + { + // because movement is clipped an epsilon away from an actual edge, // we must fully check even when bounding boxes don't quite touch ent->v.absmin[0] -= 1; ent->v.absmin[1] -= 1; @@ -470,36 +473,36 @@ void SV_LinkEdict (edict_t *ent, bool touch_triggers) // link to PVS leafs ent->num_leafs = 0; - if (ent->v.modelindex) - SV_FindTouchedLeafs (ent, sv.worldmodel->nodes); + if(ent->v.modelindex) + SV_FindTouchedLeafs(ent, sv.worldmodel->nodes); - if (ent->v.solid == SOLID_NOT) + if(ent->v.solid == SOLID_NOT) return; // find the first node that the ent's box crosses node = sv_areanodes; - while (1) + while(1) { - if (node->axis == -1) + if(node->axis == -1) break; - if (ent->v.absmin[node->axis] > node->dist) + if(ent->v.absmin[node->axis] > node->dist) node = node->children[0]; - else if (ent->v.absmax[node->axis] < node->dist) + else if(ent->v.absmax[node->axis] < node->dist) node = node->children[1]; else - break; // crosses the node + break; // crosses the node } // link it in - if (ent->v.solid == SOLID_TRIGGER) - InsertLinkBefore (&ent->area, &node->trigger_edicts); + if(ent->v.solid == SOLID_TRIGGER) + InsertLinkBefore(&ent->area, &node->trigger_edicts); else - InsertLinkBefore (&ent->area, &node->solid_edicts); + InsertLinkBefore(&ent->area, &node->solid_edicts); // if touch_triggers, touch all entities at this node and decend for more - if (touch_triggers) - SV_TouchLinks ( ent ); + if(touch_triggers) + SV_TouchLinks(ent); } @@ -518,25 +521,25 @@ SV_HullPointContents ================== */ -int32_t SV_HullPointContents (hull_t *hull, int32_t num, vec3_t p) +int32_t SV_HullPointContents(hull_t *hull, int32_t num, vec3_t p) { - float d; - mclipnode_t *node; //johnfitz -- was dclipnode_t - mplane_t *plane; + float d; + mclipnode_t *node; //johnfitz -- was dclipnode_t + mplane_t *plane; - while (num >= 0) + while(num >= 0) { - if (num < hull->firstclipnode || num > hull->lastclipnode) - Sys_Error ("SV_HullPointContents: bad node number"); + if(num < hull->firstclipnode || num > hull->lastclipnode) + Sys_Error("SV_HullPointContents: bad node number"); node = hull->clipnodes + num; plane = hull->planes + node->planenum; - if (plane->type < 3) + if(plane->type < 3) d = p[plane->type] - plane->dist; else - d = DoublePrecisionDotProduct (plane->normal, p) - plane->dist; - if (d < 0) + d = DoublePrecisionDotProduct(plane->normal, p) - plane->dist; + if(d < 0) num = node->children[1]; else num = node->children[0]; @@ -552,19 +555,19 @@ SV_PointContents ================== */ -int32_t SV_PointContents (vec3_t p) +int32_t SV_PointContents(vec3_t p) { - int32_t cont; + int32_t cont; - cont = SV_HullPointContents (&sv.worldmodel->hulls[0], 0, p); - if (cont <= CONTENTS_CURRENT_0 && cont >= CONTENTS_CURRENT_DOWN) + cont = SV_HullPointContents(&sv.worldmodel->hulls[0], 0, p); + if(cont <= CONTENTS_CURRENT_0 && cont >= CONTENTS_CURRENT_DOWN) cont = CONTENTS_WATER; return cont; } -int32_t SV_TruePointContents (vec3_t p) +int32_t SV_TruePointContents(vec3_t p) { - return SV_HullPointContents (&sv.worldmodel->hulls[0], 0, p); + return SV_HullPointContents(&sv.worldmodel->hulls[0], 0, p); } //=========================================================================== @@ -576,13 +579,13 @@ SV_TestEntityPosition This could be a lot more efficient... ============ */ -edict_t *SV_TestEntityPosition (edict_t *ent) +edict_t *SV_TestEntityPosition(edict_t *ent) { - trace_t trace; + trace_t trace; - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, ent->v.origin, 0, ent); + trace = SV_Move(ent->v.origin, ent->v.mins, ent->v.maxs, ent->v.origin, 0, ent); - if (trace.startsolid) + if(trace.startsolid) return sv.edicts; return NULL; @@ -603,35 +606,35 @@ SV_RecursiveHullCheck ================== */ -bool SV_RecursiveHullCheck (hull_t *hull, int32_t num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace) +bool SV_RecursiveHullCheck(hull_t *hull, int32_t num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace) { - mclipnode_t *node; //johnfitz -- was dclipnode_t - mplane_t *plane; - float t1, t2; - float frac; - int32_t i; - vec3_t mid; - int32_t side; - float midf; + mclipnode_t *node; //johnfitz -- was dclipnode_t + mplane_t *plane; + float t1, t2; + float frac; + int32_t i; + vec3_t mid; + int32_t side; + float midf; // check for empty - if (num < 0) + if(num < 0) { - if (num != CONTENTS_SOLID) + if(num != CONTENTS_SOLID) { trace->allsolid = false; - if (num == CONTENTS_EMPTY) + if(num == CONTENTS_EMPTY) trace->inopen = true; else trace->inwater = true; } else trace->startsolid = true; - return true; // empty + return true; // empty } - if (num < hull->firstclipnode || num > hull->lastclipnode) - Sys_Error ("SV_RecursiveHullCheck: bad node number"); + if(num < hull->firstclipnode || num > hull->lastclipnode) + Sys_Error("SV_RecursiveHullCheck: bad node number"); // // find the point distances @@ -639,98 +642,99 @@ bool SV_RecursiveHullCheck (hull_t *hull, int32_t num, float p1f, float p2f, vec node = hull->clipnodes + num; plane = hull->planes + node->planenum; - if (plane->type < 3) + if(plane->type < 3) { t1 = p1[plane->type] - plane->dist; t2 = p2[plane->type] - plane->dist; } else { - t1 = DoublePrecisionDotProduct (plane->normal, p1) - plane->dist; - t2 = DoublePrecisionDotProduct (plane->normal, p2) - plane->dist; + t1 = DoublePrecisionDotProduct(plane->normal, p1) - plane->dist; + t2 = DoublePrecisionDotProduct(plane->normal, p2) - plane->dist; } #if 1 - if (t1 >= 0 && t2 >= 0) - return SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace); - if (t1 < 0 && t2 < 0) - return SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace); + if(t1 >= 0 && t2 >= 0) + return SV_RecursiveHullCheck(hull, node->children[0], p1f, p2f, p1, p2, trace); + if(t1 < 0 && t2 < 0) + return SV_RecursiveHullCheck(hull, node->children[1], p1f, p2f, p1, p2, trace); #else - if ( (t1 >= DIST_EPSILON && t2 >= DIST_EPSILON) || (t2 > t1 && t1 >= 0) ) - return SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace); - if ( (t1 <= -DIST_EPSILON && t2 <= -DIST_EPSILON) || (t2 < t1 && t1 <= 0) ) - return SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace); + if((t1 >= DIST_EPSILON && t2 >= DIST_EPSILON) || (t2 > t1 && t1 >= 0)) + return SV_RecursiveHullCheck(hull, node->children[0], p1f, p2f, p1, p2, trace); + if((t1 <= -DIST_EPSILON && t2 <= -DIST_EPSILON) || (t2 < t1 && t1 <= 0)) + return SV_RecursiveHullCheck(hull, node->children[1], p1f, p2f, p1, p2, trace); #endif // put the crosspoint DIST_EPSILON pixels on the near side - if (t1 < 0) - frac = (t1 + DIST_EPSILON)/(t1-t2); + if(t1 < 0) + frac = (t1 + DIST_EPSILON) / (t1 - t2); else - frac = (t1 - DIST_EPSILON)/(t1-t2); - if (frac < 0) + frac = (t1 - DIST_EPSILON) / (t1 - t2); + if(frac < 0) frac = 0; - if (frac > 1) + if(frac > 1) frac = 1; - midf = p1f + (p2f - p1f)*frac; - for (i=0 ; i<3 ; i++) - mid[i] = p1[i] + frac*(p2[i] - p1[i]); + midf = p1f + (p2f - p1f) * frac; + for(i = 0 ; i < 3 ; i++) + mid[i] = p1[i] + frac * (p2[i] - p1[i]); side = (t1 < 0); // move up to the node - if (!SV_RecursiveHullCheck (hull, node->children[side], p1f, midf, p1, mid, trace) ) + if(!SV_RecursiveHullCheck(hull, node->children[side], p1f, midf, p1, mid, trace)) return false; #ifdef PARANOID - if (SV_HullPointContents (sv_hullmodel, mid, node->children[side]) - == CONTENTS_SOLID) + if(SV_HullPointContents(sv_hullmodel, mid, node->children[side]) + == CONTENTS_SOLID) { - Con_Printf ("mid PointInHullSolid\n"); + Con_Printf("mid PointInHullSolid\n"); return false; } #endif - if (SV_HullPointContents (hull, node->children[side^1], mid) - != CONTENTS_SOLID) + if(SV_HullPointContents(hull, node->children[side ^ 1], mid) + != CONTENTS_SOLID) // go past the node - return SV_RecursiveHullCheck (hull, node->children[side^1], midf, p2f, mid, p2, trace); + return SV_RecursiveHullCheck(hull, node->children[side ^ 1], midf, p2f, mid, p2, trace); - if (trace->allsolid) - return false; // never got out of the solid area + if(trace->allsolid) + return false; // never got out of the solid area //================== // the other side of the node is solid, this is the impact point //================== - if (!side) + if(!side) { - VectorCopy (plane->normal, trace->plane.normal); + VectorCopy(plane->normal, trace->plane.normal); trace->plane.dist = plane->dist; } else { - VectorSubtract (vec3_origin, plane->normal, trace->plane.normal); + VectorSubtract(vec3_origin, plane->normal, trace->plane.normal); trace->plane.dist = -plane->dist; } - while (SV_HullPointContents (hull, hull->firstclipnode, mid) - == CONTENTS_SOLID) - { // shouldn't really happen, but does occasionally + while(SV_HullPointContents(hull, hull->firstclipnode, mid) + == CONTENTS_SOLID) + { + // shouldn't really happen, but does occasionally frac -= 0.1; - if (frac < 0) + if(frac < 0) { trace->fraction = midf; - VectorCopy (mid, trace->endpos); - Con_DPrintf ("backup past 0\n"); + VectorCopy(mid, trace->endpos); + Con_DPrintf("backup past 0\n"); return false; } - midf = p1f + (p2f - p1f)*frac; - for (i=0 ; i<3 ; i++) - mid[i] = p1[i] + frac*(p2[i] - p1[i]); + midf = p1f + (p2f - p1f) * frac; + for(i = 0 ; i < 3 ; i++) + mid[i] = p1[i] + frac * (p2[i] - p1[i]); } trace->fraction = midf; - VectorCopy (mid, trace->endpos); + VectorCopy(mid, trace->endpos); return false; } @@ -744,34 +748,34 @@ Handles selection or creation of a clipping hull, and offseting (and eventually rotation) of the end points ================== */ -trace_t SV_ClipMoveToEntity (edict_t *ent, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end) +trace_t SV_ClipMoveToEntity(edict_t *ent, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end) { - trace_t trace; - vec3_t offset; - vec3_t start_l, end_l; - hull_t *hull; + trace_t trace; + vec3_t offset; + vec3_t start_l, end_l; + hull_t *hull; // fill in a default trace - memset (&trace, 0, sizeof(trace_t)); + memset(&trace, 0, sizeof(trace_t)); trace.fraction = 1; trace.allsolid = true; - VectorCopy (end, trace.endpos); + VectorCopy(end, trace.endpos); // get the clipping hull - hull = SV_HullForEntity (ent, mins, maxs, offset); + hull = SV_HullForEntity(ent, mins, maxs, offset); - VectorSubtract (start, offset, start_l); - VectorSubtract (end, offset, end_l); + VectorSubtract(start, offset, start_l); + VectorSubtract(end, offset, end_l); // trace a line through the apropriate clipping hull - SV_RecursiveHullCheck (hull, hull->firstclipnode, 0, 1, start_l, end_l, &trace); + SV_RecursiveHullCheck(hull, hull->firstclipnode, 0, 1, start_l, end_l, &trace); // fix trace up by the offset - if (trace.fraction != 1) - VectorAdd (trace.endpos, offset, trace.endpos); + if(trace.fraction != 1) + VectorAdd(trace.endpos, offset, trace.endpos); // did we clip the move? - if (trace.fraction < 1 || trace.startsolid ) + if(trace.fraction < 1 || trace.startsolid) trace.ent = ent; return trace; @@ -786,58 +790,58 @@ SV_ClipToLinks Mins and maxs enclose the entire area swept by the move ==================== */ -void SV_ClipToLinks ( areanode_t *node, moveclip_t *clip ) +void SV_ClipToLinks(areanode_t *node, moveclip_t *clip) { - link_t *l, *next; - edict_t *touch; - trace_t trace; + link_t *l, *next; + edict_t *touch; + trace_t trace; // touch linked edicts - for (l = node->solid_edicts.next ; l != &node->solid_edicts ; l = next) + for(l = node->solid_edicts.next ; l != &node->solid_edicts ; l = next) { next = l->next; touch = EDICT_FROM_AREA(l); - if (touch->v.solid == SOLID_NOT) + if(touch->v.solid == SOLID_NOT) continue; - if (touch == clip->passedict) + if(touch == clip->passedict) continue; - if (touch->v.solid == SOLID_TRIGGER) - Sys_Error ("Trigger in clipping list"); + if(touch->v.solid == SOLID_TRIGGER) + Sys_Error("Trigger in clipping list"); - if (clip->type == MOVE_NOMONSTERS && touch->v.solid != SOLID_BSP) + if(clip->type == MOVE_NOMONSTERS && touch->v.solid != SOLID_BSP) continue; - if (clip->boxmins[0] > touch->v.absmax[0] - || clip->boxmins[1] > touch->v.absmax[1] - || clip->boxmins[2] > touch->v.absmax[2] - || clip->boxmaxs[0] < touch->v.absmin[0] - || clip->boxmaxs[1] < touch->v.absmin[1] - || clip->boxmaxs[2] < touch->v.absmin[2] ) + if(clip->boxmins[0] > touch->v.absmax[0] + || clip->boxmins[1] > touch->v.absmax[1] + || clip->boxmins[2] > touch->v.absmax[2] + || clip->boxmaxs[0] < touch->v.absmin[0] + || clip->boxmaxs[1] < touch->v.absmin[1] + || clip->boxmaxs[2] < touch->v.absmin[2]) continue; - if (clip->passedict && clip->passedict->v.size[0] && !touch->v.size[0]) - continue; // points never interact + if(clip->passedict && clip->passedict->v.size[0] && !touch->v.size[0]) + continue; // points never interact - // might intersect, so do an exact clip - if (clip->trace.allsolid) + // might intersect, so do an exact clip + if(clip->trace.allsolid) return; - if (clip->passedict) + if(clip->passedict) { - if (PROG_TO_EDICT(touch->v.owner) == clip->passedict) - continue; // don't clip against own missiles - if (PROG_TO_EDICT(clip->passedict->v.owner) == touch) - continue; // don't clip against owner + if(PROG_TO_EDICT(touch->v.owner) == clip->passedict) + continue; // don't clip against own missiles + if(PROG_TO_EDICT(clip->passedict->v.owner) == touch) + continue; // don't clip against owner } - if ((int32_t)touch->v.flags & FL_MONSTER) - trace = SV_ClipMoveToEntity (touch, clip->start, clip->mins2, clip->maxs2, clip->end); + if((int32_t)touch->v.flags & FL_MONSTER) + trace = SV_ClipMoveToEntity(touch, clip->start, clip->mins2, clip->maxs2, clip->end); else - trace = SV_ClipMoveToEntity (touch, clip->start, clip->mins, clip->maxs, clip->end); - if (trace.allsolid || trace.startsolid || - trace.fraction < clip->trace.fraction) + trace = SV_ClipMoveToEntity(touch, clip->start, clip->mins, clip->maxs, clip->end); + if(trace.allsolid || trace.startsolid || + trace.fraction < clip->trace.fraction) { trace.ent = touch; - if (clip->trace.startsolid) + if(clip->trace.startsolid) { clip->trace = trace; clip->trace.startsolid = true; @@ -845,18 +849,18 @@ void SV_ClipToLinks ( areanode_t *node, moveclip_t *clip ) else clip->trace = trace; } - else if (trace.startsolid) + else if(trace.startsolid) clip->trace.startsolid = true; } // recurse down both sides - if (node->axis == -1) + if(node->axis == -1) return; - if ( clip->boxmaxs[node->axis] > node->dist ) - SV_ClipToLinks ( node->children[0], clip ); - if ( clip->boxmins[node->axis] < node->dist ) - SV_ClipToLinks ( node->children[1], clip ); + if(clip->boxmaxs[node->axis] > node->dist) + SV_ClipToLinks(node->children[0], clip); + if(clip->boxmins[node->axis] < node->dist) + SV_ClipToLinks(node->children[1], clip); } @@ -865,18 +869,18 @@ void SV_ClipToLinks ( areanode_t *node, moveclip_t *clip ) SV_MoveBounds ================== */ -void SV_MoveBounds (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, vec3_t boxmins, vec3_t boxmaxs) +void SV_MoveBounds(vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, vec3_t boxmins, vec3_t boxmaxs) { #if 0 // debug to test against everything -boxmins[0] = boxmins[1] = boxmins[2] = -9999; -boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999; + boxmins[0] = boxmins[1] = boxmins[2] = -9999; + boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999; #else - int32_t i; + int32_t i; - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { - if (end[i] > start[i]) + if(end[i] > start[i]) { boxmins[i] = start[i] + mins[i] - 1; boxmaxs[i] = end[i] + maxs[i] + 1; @@ -895,15 +899,15 @@ boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999; SV_Move ================== */ -trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int32_t type, edict_t *passedict) +trace_t SV_Move(vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int32_t type, edict_t *passedict) { - moveclip_t clip; - int32_t i; + moveclip_t clip; + int32_t i; - memset ( &clip, 0, sizeof ( moveclip_t ) ); + memset(&clip, 0, sizeof(moveclip_t)); // clip to world - clip.trace = SV_ClipMoveToEntity ( sv.edicts, start, mins, maxs, end ); + clip.trace = SV_ClipMoveToEntity(sv.edicts, start, mins, maxs, end); clip.start = start; clip.end = end; @@ -912,9 +916,9 @@ trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int32_t typ clip.type = type; clip.passedict = passedict; - if (type == MOVE_MISSILE) + if(type == MOVE_MISSILE) { - for (i=0 ; i<3 ; i++) + for(i = 0 ; i < 3 ; i++) { clip.mins2[i] = -15; clip.maxs2[i] = 15; @@ -922,15 +926,15 @@ trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int32_t typ } else { - VectorCopy (mins, clip.mins2); - VectorCopy (maxs, clip.maxs2); + VectorCopy(mins, clip.mins2); + VectorCopy(maxs, clip.maxs2); } // create the bounding box of the entire move - SV_MoveBounds ( start, clip.mins2, clip.maxs2, end, clip.boxmins, clip.boxmaxs ); + SV_MoveBounds(start, clip.mins2, clip.maxs2, end, clip.boxmins, clip.boxmaxs); // clip to entities - SV_ClipToLinks ( sv_areanodes, &clip ); + SV_ClipToLinks(sv_areanodes, &clip); return clip.trace; } diff --git a/source/world.h b/source/world.h index 511e060..dea0d23 100644 --- a/source/world.h +++ b/source/world.h @@ -25,50 +25,50 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. typedef struct { - vec3_t normal; - float dist; + vec3_t normal; + float dist; } plane_t; typedef struct { - bool allsolid; // if true, plane is not valid - bool startsolid; // if true, the initial point was in a solid area - bool inopen, inwater; - float fraction; // time completed, 1.0 = didn't hit anything - vec3_t endpos; // final position - plane_t plane; // surface normal at impact - edict_t *ent; // entity the surface is on + bool allsolid; // if true, plane is not valid + bool startsolid; // if true, the initial point was in a solid area + bool inopen, inwater; + float fraction; // time completed, 1.0 = didn't hit anything + vec3_t endpos; // final position + plane_t plane; // surface normal at impact + edict_t *ent; // entity the surface is on } trace_t; -#define MOVE_NORMAL 0 -#define MOVE_NOMONSTERS 1 -#define MOVE_MISSILE 2 +#define MOVE_NORMAL 0 +#define MOVE_NOMONSTERS 1 +#define MOVE_MISSILE 2 -void SV_ClearWorld (void); +void SV_ClearWorld(void); // called after the world model has been loaded, before linking any entities -void SV_UnlinkEdict (edict_t *ent); +void SV_UnlinkEdict(edict_t *ent); // call before removing an entity, and before trying to move one, // so it doesn't clip against itself // flags ent->v.modified -void SV_LinkEdict (edict_t *ent, bool touch_triggers); +void SV_LinkEdict(edict_t *ent, bool touch_triggers); // Needs to be called any time an entity changes origin, mins, maxs, or solid // flags ent->v.modified // sets ent->v.absmin and ent->v.absmax // if touchtriggers, calls prog functions for the intersected triggers -int32_t SV_PointContents (vec3_t p); -int32_t SV_TruePointContents (vec3_t p); +int32_t SV_PointContents(vec3_t p); +int32_t SV_TruePointContents(vec3_t p); // returns the CONTENTS_* value from the world at the given point. // does not check any entities at all // the non-true version remaps the water current contents to content_water -edict_t *SV_TestEntityPosition (edict_t *ent); +edict_t *SV_TestEntityPosition(edict_t *ent); -trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int32_t type, edict_t *passedict); +trace_t SV_Move(vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int32_t type, edict_t *passedict); // mins and maxs are reletive // if the entire move stays in a solid volume, trace.allsolid will be set @@ -81,7 +81,7 @@ trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int32_t typ // passedict is explicitly excluded from clipping checks (normally NULL) -bool SV_RecursiveHullCheck (hull_t *hull, int32_t num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace); +bool SV_RecursiveHullCheck(hull_t *hull, int32_t num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace); -#endif /* _QUAKE_WORLD_H */ +#endif /* _QUAKE_WORLD_H */ diff --git a/source/zone.c b/source/zone.c index e5ee78a..556da0c 100644 --- a/source/zone.c +++ b/source/zone.c @@ -23,35 +23,35 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" -#define DYNAMIC_SIZE (4 * 1024 * 1024) // ericw -- was 512KB (64-bit) / 384KB (32-bit) +#define DYNAMIC_SIZE (4 * 1024 * 1024) // ericw -- was 512KB (64-bit) / 384KB (32-bit) -#define ZONEID 0x1d4a11 -#define MINFRAGMENT 64 +#define ZONEID 0x1d4a11 +#define MINFRAGMENT 64 typedef struct memblock_s { - int32_t size; // including the header and possibly tiny fragments - int32_t tag; // a tag of 0 is a free block - int32_t id; // should be ZONEID - int32_t pad; // pad to 64 bit boundary - struct memblock_s *next, *prev; + int32_t size; // including the header and possibly tiny fragments + int32_t tag; // a tag of 0 is a free block + int32_t id; // should be ZONEID + int32_t pad; // pad to 64 bit boundary + struct memblock_s *next, *prev; } memblock_t; typedef struct { - int32_t size; // total bytes malloced, including header - memblock_t blocklist; // start / end cap for linked list - memblock_t *rover; + int32_t size; // total bytes malloced, including header + memblock_t blocklist; // start / end cap for linked list + memblock_t *rover; } memzone_t; -void Cache_FreeLow (int32_t new_low_hunk); -void Cache_FreeHigh (int32_t new_high_hunk); +void Cache_FreeLow(int32_t new_low_hunk); +void Cache_FreeHigh(int32_t new_high_hunk); /* ============================================================================== - ZONE MEMORY ALLOCATION + ZONE MEMORY ALLOCATION There is never any space between memblocks, and there will never be two contiguous free memblocks. @@ -63,7 +63,7 @@ all big things are allocated on the hunk. ============================================================================== */ -static memzone_t *mainzone; +static memzone_t *mainzone; /* @@ -71,82 +71,86 @@ static memzone_t *mainzone; Z_Free ======================== */ -void Z_Free (void *ptr) +void Z_Free(void *ptr) { - memblock_t *block, *other; + memblock_t *block, *other; - if (!ptr) - Sys_Error ("Z_Free: NULL pointer"); + if(!ptr) + Sys_Error("Z_Free: NULL pointer"); - block = (memblock_t *) ( (byte *)ptr - sizeof(memblock_t)); - if (block->id != ZONEID) - Sys_Error ("Z_Free: freed a pointer without ZONEID"); - if (block->tag == 0) - Sys_Error ("Z_Free: freed a freed pointer"); + block = (memblock_t *)((byte *)ptr - sizeof(memblock_t)); + if(block->id != ZONEID) + Sys_Error("Z_Free: freed a pointer without ZONEID"); + if(block->tag == 0) + Sys_Error("Z_Free: freed a freed pointer"); - block->tag = 0; // mark as free + block->tag = 0; // mark as free other = block->prev; - if (!other->tag) - { // merge with previous free block + if(!other->tag) + { + // merge with previous free block other->size += block->size; other->next = block->next; other->next->prev = other; - if (block == mainzone->rover) + if(block == mainzone->rover) mainzone->rover = other; block = other; } other = block->next; - if (!other->tag) - { // merge the next free block onto the end + if(!other->tag) + { + // merge the next free block onto the end block->size += other->size; block->next = other->next; block->next->prev = block; - if (other == mainzone->rover) + if(other == mainzone->rover) mainzone->rover = block; } } -static void *Z_TagMalloc (int32_t size, int32_t tag) +static void *Z_TagMalloc(int32_t size, int32_t tag) { - int32_t extra; - memblock_t *start, *rover, *newblock, *base; + int32_t extra; + memblock_t *start, *rover, *newblock, *base; - if (!tag) - Sys_Error ("Z_TagMalloc: tried to use a 0 tag"); + if(!tag) + Sys_Error("Z_TagMalloc: tried to use a 0 tag"); // // scan through the block list looking for the first free block // of sufficient size // - size += sizeof(memblock_t); // account for size of block header - size += 4; // space for memory trash tester - size = (size + 7) & ~7; // align to 8-byte boundary + size += sizeof(memblock_t); // account for size of block header + size += 4; // space for memory trash tester + size = (size + 7) & ~7; // align to 8-byte boundary base = rover = mainzone->rover; start = base->prev; do { - if (rover == start) // scaned all the way around the list + if(rover == start) // scaned all the way around the list return NULL; - if (rover->tag) + if(rover->tag) base = rover = rover->next; else rover = rover->next; - } while (base->tag || base->size < size); + } + while(base->tag || base->size < size); // // found a block big enough // extra = base->size - size; - if (extra > MINFRAGMENT) - { // there will be a free fragment after the allocated block - newblock = (memblock_t *) ((byte *)base + size ); + if(extra > MINFRAGMENT) + { + // there will be a free fragment after the allocated block + newblock = (memblock_t *)((byte *)base + size); newblock->size = extra; - newblock->tag = 0; // free block + newblock->tag = 0; // free block newblock->prev = base; newblock->id = ZONEID; newblock->next = base->next; @@ -155,16 +159,16 @@ static void *Z_TagMalloc (int32_t size, int32_t tag) base->size = size; } - base->tag = tag; // no longer a free block + base->tag = tag; // no longer a free block - mainzone->rover = base->next; // next allocation will start looking here + mainzone->rover = base->next; // next allocation will start looking here base->id = ZONEID; // marker for memory trash testing *(int32_t *)((byte *)base + base->size - 4) = ZONEID; - return (void *) ((byte *)base + sizeof(memblock_t)); + return (void *)((byte *)base + sizeof(memblock_t)); } /* @@ -172,20 +176,20 @@ static void *Z_TagMalloc (int32_t size, int32_t tag) Z_CheckHeap ======================== */ -static void Z_CheckHeap (void) +static void Z_CheckHeap(void) { - memblock_t *block; + memblock_t *block; - for (block = mainzone->blocklist.next ; ; block = block->next) + for(block = mainzone->blocklist.next ; ; block = block->next) { - if (block->next == &mainzone->blocklist) - break; // all blocks have been hit - if ( (byte *)block + block->size != (byte *)block->next) - Sys_Error ("Z_CheckHeap: block size does not touch the next block\n"); - if ( block->next->prev != block) - Sys_Error ("Z_CheckHeap: next block doesn't have proper back link\n"); - if (!block->tag && !block->next->tag) - Sys_Error ("Z_CheckHeap: two consecutive free blocks\n"); + if(block->next == &mainzone->blocklist) + break; // all blocks have been hit + if((byte *)block + block->size != (byte *)block->next) + Sys_Error("Z_CheckHeap: block size does not touch the next block\n"); + if(block->next->prev != block) + Sys_Error("Z_CheckHeap: next block doesn't have proper back link\n"); + if(!block->tag && !block->next->tag) + Sys_Error("Z_CheckHeap: two consecutive free blocks\n"); } } @@ -195,15 +199,15 @@ static void Z_CheckHeap (void) Z_Malloc ======================== */ -void *Z_Malloc (int32_t size) +void *Z_Malloc(int32_t size) { - void *buf; + void *buf; - Z_CheckHeap (); // DEBUG - buf = Z_TagMalloc (size, 1); - if (!buf) - Sys_Error ("Z_Malloc: failed on allocation of %" PRIi32 " bytes",size); - Q_memset (buf, 0, size); + Z_CheckHeap(); // DEBUG + buf = Z_TagMalloc(size, 1); + if(!buf) + Sys_Error("Z_Malloc: failed on allocation of %" PRIi32 " bytes", size); + Q_memset(buf, 0, size); return buf; } @@ -219,37 +223,37 @@ void *Z_Realloc(void *ptr, int32_t size) void *old_ptr; memblock_t *block; - if (!ptr) - return Z_Malloc (size); + if(!ptr) + return Z_Malloc(size); - block = (memblock_t *) ((byte *) ptr - sizeof (memblock_t)); - if (block->id != ZONEID) - Sys_Error ("Z_Realloc: realloced a pointer without ZONEID"); - if (block->tag == 0) - Sys_Error ("Z_Realloc: realloced a freed pointer"); + block = (memblock_t *)((byte *) ptr - sizeof(memblock_t)); + if(block->id != ZONEID) + Sys_Error("Z_Realloc: realloced a pointer without ZONEID"); + if(block->tag == 0) + Sys_Error("Z_Realloc: realloced a freed pointer"); old_size = block->size; - old_size -= (4 + (int32_t)sizeof(memblock_t)); /* see Z_TagMalloc() */ + old_size -= (4 + (int32_t)sizeof(memblock_t)); /* see Z_TagMalloc() */ old_ptr = ptr; - Z_Free (ptr); - ptr = Z_TagMalloc (size, 1); - if (!ptr) - Sys_Error ("Z_Realloc: failed on allocation of %" PRIi32 " bytes", size); + Z_Free(ptr); + ptr = Z_TagMalloc(size, 1); + if(!ptr) + Sys_Error("Z_Realloc: failed on allocation of %" PRIi32 " bytes", size); - if (ptr != old_ptr) - memmove (ptr, old_ptr, q_min(old_size, size)); - if (old_size < size) - memset ((byte *)ptr + old_size, 0, size - old_size); + if(ptr != old_ptr) + memmove(ptr, old_ptr, q_min(old_size, size)); + if(old_size < size) + memset((byte *)ptr + old_size, 0, size - old_size); return ptr; } -char *Z_Strdup (const char *s) +char *Z_Strdup(const char *s) { size_t sz = strlen(s) + 1; - char *ptr = (char *) Z_Malloc (sz); - memcpy (ptr, s, sz); + char *ptr = (char *) Z_Malloc(sz); + memcpy(ptr, s, sz); return ptr; } @@ -259,49 +263,49 @@ char *Z_Strdup (const char *s) Z_Print ======================== */ -void Z_Print (memzone_t *zone) +void Z_Print(memzone_t *zone) { - memblock_t *block; + memblock_t *block; - Con_Printf ("zone size: %" PRIi32 " location: %p\n",mainzone->size,mainzone); + Con_Printf("zone size: %" PRIi32 " location: %p\n", mainzone->size, mainzone); - for (block = zone->blocklist.next ; ; block = block->next) + for(block = zone->blocklist.next ; ; block = block->next) { - Con_Printf ("block:%p size:%7" PRIi32 " tag:%3" PRIi32 "\n", - block, block->size, block->tag); + Con_Printf("block:%p size:%7" PRIi32 " tag:%3" PRIi32 "\n", + block, block->size, block->tag); - if (block->next == &zone->blocklist) - break; // all blocks have been hit - if ( (byte *)block + block->size != (byte *)block->next) - Con_Printf ("ERROR: block size does not touch the next block\n"); - if ( block->next->prev != block) - Con_Printf ("ERROR: next block doesn't have proper back link\n"); - if (!block->tag && !block->next->tag) - Con_Printf ("ERROR: two consecutive free blocks\n"); + if(block->next == &zone->blocklist) + break; // all blocks have been hit + if((byte *)block + block->size != (byte *)block->next) + Con_Printf("ERROR: block size does not touch the next block\n"); + if(block->next->prev != block) + Con_Printf("ERROR: next block doesn't have proper back link\n"); + if(!block->tag && !block->next->tag) + Con_Printf("ERROR: two consecutive free blocks\n"); } } //============================================================================ -#define HUNK_SENTINAL 0x1df001ed +#define HUNK_SENTINAL 0x1df001ed -#define HUNKNAME_LEN 24 +#define HUNKNAME_LEN 24 typedef struct { - int32_t sentinal; - int32_t size; // including sizeof(hunk_t), -1 = not allocated - char name[HUNKNAME_LEN]; + int32_t sentinal; + int32_t size; // including sizeof(hunk_t), -1 = not allocated + char name[HUNKNAME_LEN]; } hunk_t; -byte *hunk_base; -int32_t hunk_size; +byte *hunk_base; +int32_t hunk_size; -int32_t hunk_low_used; -int32_t hunk_high_used; +int32_t hunk_low_used; +int32_t hunk_high_used; -bool hunk_tempactive; -int32_t hunk_tempmark; +bool hunk_tempactive; +int32_t hunk_tempmark; /* ============== @@ -310,17 +314,17 @@ Hunk_Check Run consistancy and sentinal trahing checks ============== */ -void Hunk_Check (void) +void Hunk_Check(void) { - hunk_t *h; + hunk_t *h; - for (h = (hunk_t *)hunk_base ; (byte *)h != hunk_base + hunk_low_used ; ) + for(h = (hunk_t *)hunk_base ; (byte *)h != hunk_base + hunk_low_used ;) { - if (h->sentinal != HUNK_SENTINAL) - Sys_Error ("Hunk_Check: trahsed sentinal"); - if (h->size < (int32_t) sizeof(hunk_t) || h->size + (byte *)h - hunk_base > hunk_size) - Sys_Error ("Hunk_Check: bad size"); - h = (hunk_t *)((byte *)h+h->size); + if(h->sentinal != HUNK_SENTINAL) + Sys_Error("Hunk_Check: trahsed sentinal"); + if(h->size < (int32_t) sizeof(hunk_t) || h->size + (byte *)h - hunk_base > hunk_size) + Sys_Error("Hunk_Check: bad size"); + h = (hunk_t *)((byte *)h + h->size); } } @@ -332,12 +336,12 @@ If "all" is specified, every single allocation is printed. Otherwise, allocations with the same name will be totaled up before printing. ============== */ -void Hunk_Print (bool all) +void Hunk_Print(bool all) { - hunk_t *h, *next, *endlow, *starthigh, *endhigh; - int32_t count, sum; - int32_t totalblocks; - char name[HUNKNAME_LEN]; + hunk_t *h, *next, *endlow, *starthigh, *endhigh; + int32_t count, sum; + int32_t totalblocks; + char name[HUNKNAME_LEN]; count = 0; sum = 0; @@ -348,56 +352,56 @@ void Hunk_Print (bool all) starthigh = (hunk_t *)(hunk_base + hunk_size - hunk_high_used); endhigh = (hunk_t *)(hunk_base + hunk_size); - Con_Printf (" :%8" PRIi32 " total hunk size\n", hunk_size); - Con_Printf ("-------------------------\n"); + Con_Printf(" :%8" PRIi32 " total hunk size\n", hunk_size); + Con_Printf("-------------------------\n"); - while (1) + while(1) { - // - // skip to the high hunk if done with low hunk - // - if ( h == endlow ) + // + // skip to the high hunk if done with low hunk + // + if(h == endlow) { - Con_Printf ("-------------------------\n"); - Con_Printf (" :%8" PRIi32 " REMAINING\n", hunk_size - hunk_low_used - hunk_high_used); - Con_Printf ("-------------------------\n"); + Con_Printf("-------------------------\n"); + Con_Printf(" :%8" PRIi32 " REMAINING\n", hunk_size - hunk_low_used - hunk_high_used); + Con_Printf("-------------------------\n"); h = starthigh; } - // - // if totally done, break - // - if ( h == endhigh ) + // + // if totally done, break + // + if(h == endhigh) break; - // - // run consistancy checks - // - if (h->sentinal != HUNK_SENTINAL) - Sys_Error ("Hunk_Check: trahsed sentinal"); - if (h->size < (int32_t) sizeof(hunk_t) || h->size + (byte *)h - hunk_base > hunk_size) - Sys_Error ("Hunk_Check: bad size"); + // + // run consistancy checks + // + if(h->sentinal != HUNK_SENTINAL) + Sys_Error("Hunk_Check: trahsed sentinal"); + if(h->size < (int32_t) sizeof(hunk_t) || h->size + (byte *)h - hunk_base > hunk_size) + Sys_Error("Hunk_Check: bad size"); - next = (hunk_t *)((byte *)h+h->size); + next = (hunk_t *)((byte *)h + h->size); count++; totalblocks++; sum += h->size; - // - // print the single block - // - memcpy (name, h->name, HUNKNAME_LEN); - if (all) - Con_Printf ("%8p :%8" PRIi32 " %8s\n",h, h->size, name); + // + // print the single block + // + memcpy(name, h->name, HUNKNAME_LEN); + if(all) + Con_Printf("%8p :%8" PRIi32 " %8s\n", h, h->size, name); - // - // print the total - // - if (next == endlow || next == endhigh || - strncmp (h->name, next->name, HUNKNAME_LEN - 1)) + // + // print the total + // + if(next == endlow || next == endhigh || + strncmp(h->name, next->name, HUNKNAME_LEN - 1)) { - if (!all) - Con_Printf (" :%8" PRIi32 " %8s (TOTAL)\n",sum, name); + if(!all) + Con_Printf(" :%8" PRIi32 " %8s (TOTAL)\n", sum, name); count = 0; sum = 0; } @@ -405,8 +409,8 @@ void Hunk_Print (bool all) h = next; } - Con_Printf ("-------------------------\n"); - Con_Printf ("%8" PRIi32 " total blocks\n", totalblocks); + Con_Printf("-------------------------\n"); + Con_Printf("%8" PRIi32 " total blocks\n", totalblocks); } @@ -415,9 +419,9 @@ void Hunk_Print (bool all) Hunk_Print_f -- johnfitz -- console command to call hunk_print =================== */ -void Hunk_Print_f (void) +void Hunk_Print_f(void) { - Hunk_Print (false); + Hunk_Print(false); } /* @@ -425,34 +429,34 @@ void Hunk_Print_f (void) Hunk_AllocName =================== */ -void *Hunk_AllocName (int32_t size, const char *name) +void *Hunk_AllocName(int32_t size, const char *name) { - hunk_t *h; + hunk_t *h; #ifdef PARANOID - Hunk_Check (); + Hunk_Check(); #endif - if (size < 0) - Sys_Error ("Hunk_Alloc: bad size: %" PRIi32 "", size); + if(size < 0) + Sys_Error("Hunk_Alloc: bad size: %" PRIi32 "", size); - size = sizeof(hunk_t) + ((size+15)&~15); + size = sizeof(hunk_t) + ((size + 15) & ~15); - if (hunk_size - hunk_low_used - hunk_high_used < size) - Sys_Error ("Hunk_Alloc: failed on %" PRIi32 " bytes",size); + if(hunk_size - hunk_low_used - hunk_high_used < size) + Sys_Error("Hunk_Alloc: failed on %" PRIi32 " bytes", size); h = (hunk_t *)(hunk_base + hunk_low_used); hunk_low_used += size; - Cache_FreeLow (hunk_low_used); + Cache_FreeLow(hunk_low_used); - memset (h, 0, size); + memset(h, 0, size); h->size = size; h->sentinal = HUNK_SENTINAL; - q_strlcpy (h->name, name, HUNKNAME_LEN); + q_strlcpy(h->name, name, HUNKNAME_LEN); - return (void *)(h+1); + return (void *)(h + 1); } /* @@ -460,45 +464,45 @@ void *Hunk_AllocName (int32_t size, const char *name) Hunk_Alloc =================== */ -void *Hunk_Alloc (int32_t size) +void *Hunk_Alloc(int32_t size) { - return Hunk_AllocName (size, "unknown"); + return Hunk_AllocName(size, "unknown"); } -int32_t Hunk_LowMark (void) +int32_t Hunk_LowMark(void) { return hunk_low_used; } -void Hunk_FreeToLowMark (int32_t mark) +void Hunk_FreeToLowMark(int32_t mark) { - if (mark < 0 || mark > hunk_low_used) - Sys_Error ("Hunk_FreeToLowMark: bad mark %" PRIi32 "", mark); - memset (hunk_base + mark, 0, hunk_low_used - mark); + if(mark < 0 || mark > hunk_low_used) + Sys_Error("Hunk_FreeToLowMark: bad mark %" PRIi32 "", mark); + memset(hunk_base + mark, 0, hunk_low_used - mark); hunk_low_used = mark; } -int32_t Hunk_HighMark (void) +int32_t Hunk_HighMark(void) { - if (hunk_tempactive) + if(hunk_tempactive) { hunk_tempactive = false; - Hunk_FreeToHighMark (hunk_tempmark); + Hunk_FreeToHighMark(hunk_tempmark); } return hunk_high_used; } -void Hunk_FreeToHighMark (int32_t mark) +void Hunk_FreeToHighMark(int32_t mark) { - if (hunk_tempactive) + if(hunk_tempactive) { hunk_tempactive = false; - Hunk_FreeToHighMark (hunk_tempmark); + Hunk_FreeToHighMark(hunk_tempmark); } - if (mark < 0 || mark > hunk_high_used) - Sys_Error ("Hunk_FreeToHighMark: bad mark %" PRIi32 "", mark); - memset (hunk_base + hunk_size - hunk_high_used, 0, hunk_high_used - mark); + if(mark < 0 || mark > hunk_high_used) + Sys_Error("Hunk_FreeToHighMark: bad mark %" PRIi32 "", mark); + memset(hunk_base + hunk_size - hunk_high_used, 0, hunk_high_used - mark); hunk_high_used = mark; } @@ -508,42 +512,42 @@ void Hunk_FreeToHighMark (int32_t mark) Hunk_HighAllocName =================== */ -void *Hunk_HighAllocName (int32_t size, const char *name) +void *Hunk_HighAllocName(int32_t size, const char *name) { - hunk_t *h; + hunk_t *h; - if (size < 0) - Sys_Error ("Hunk_HighAllocName: bad size: %" PRIi32 "", size); + if(size < 0) + Sys_Error("Hunk_HighAllocName: bad size: %" PRIi32 "", size); - if (hunk_tempactive) + if(hunk_tempactive) { - Hunk_FreeToHighMark (hunk_tempmark); + Hunk_FreeToHighMark(hunk_tempmark); hunk_tempactive = false; } #ifdef PARANOID - Hunk_Check (); + Hunk_Check(); #endif - size = sizeof(hunk_t) + ((size+15)&~15); + size = sizeof(hunk_t) + ((size + 15) & ~15); - if (hunk_size - hunk_low_used - hunk_high_used < size) + if(hunk_size - hunk_low_used - hunk_high_used < size) { - Con_Printf ("Hunk_HighAlloc: failed on %" PRIi32 " bytes\n",size); + Con_Printf("Hunk_HighAlloc: failed on %" PRIi32 " bytes\n", size); return NULL; } hunk_high_used += size; - Cache_FreeHigh (hunk_high_used); + Cache_FreeHigh(hunk_high_used); h = (hunk_t *)(hunk_base + hunk_size - hunk_high_used); - memset (h, 0, size); + memset(h, 0, size); h->size = size; h->sentinal = HUNK_SENTINAL; - q_strlcpy (h->name, name, HUNKNAME_LEN); + q_strlcpy(h->name, name, HUNKNAME_LEN); - return (void *)(h+1); + return (void *)(h + 1); } @@ -554,32 +558,32 @@ Hunk_TempAlloc Return space from the top of the hunk ================= */ -void *Hunk_TempAlloc (int32_t size) +void *Hunk_TempAlloc(int32_t size) { - void *buf; + void *buf; - size = (size+15)&~15; + size = (size + 15) & ~15; - if (hunk_tempactive) + if(hunk_tempactive) { - Hunk_FreeToHighMark (hunk_tempmark); + Hunk_FreeToHighMark(hunk_tempmark); hunk_tempactive = false; } - hunk_tempmark = Hunk_HighMark (); + hunk_tempmark = Hunk_HighMark(); - buf = Hunk_HighAllocName (size, "temp"); + buf = Hunk_HighAllocName(size, "temp"); hunk_tempactive = true; return buf; } -char *Hunk_Strdup (const char *s, const char *name) +char *Hunk_Strdup(const char *s, const char *name) { size_t sz = strlen(s) + 1; - char *ptr = (char *) Hunk_AllocName (sz, name); - memcpy (ptr, s, sz); + char *ptr = (char *) Hunk_AllocName(sz, name); + memcpy(ptr, s, sz); return ptr; } @@ -591,46 +595,46 @@ CACHE MEMORY =============================================================================== */ -#define CACHENAME_LEN 32 +#define CACHENAME_LEN 32 typedef struct cache_system_s { - int32_t size; // including this header - cache_user_t *user; - char name[CACHENAME_LEN]; - struct cache_system_s *prev, *next; - struct cache_system_s *lru_prev, *lru_next; // for LRU flushing + int32_t size; // including this header + cache_user_t *user; + char name[CACHENAME_LEN]; + struct cache_system_s *prev, *next; + struct cache_system_s *lru_prev, *lru_next; // for LRU flushing } cache_system_t; -cache_system_t *Cache_TryAlloc (int32_t size, bool nobottom); +cache_system_t *Cache_TryAlloc(int32_t size, bool nobottom); -cache_system_t cache_head; +cache_system_t cache_head; /* =========== Cache_Move =========== */ -void Cache_Move ( cache_system_t *c) +void Cache_Move(cache_system_t *c) { - cache_system_t *new_cs; + cache_system_t *new_cs; // we are clearing up space at the bottom, so only allocate it late - new_cs = Cache_TryAlloc (c->size, true); - if (new_cs) + new_cs = Cache_TryAlloc(c->size, true); + if(new_cs) { // Con_Printf ("cache_move ok\n"); - Q_memcpy ( new_cs+1, c+1, c->size - sizeof(cache_system_t) ); + Q_memcpy(new_cs + 1, c + 1, c->size - sizeof(cache_system_t)); new_cs->user = c->user; - Q_memcpy (new_cs->name, c->name, sizeof(new_cs->name)); - Cache_Free (c->user, false); //johnfitz -- added second argument - new_cs->user->data = (void *)(new_cs+1); + Q_memcpy(new_cs->name, c->name, sizeof(new_cs->name)); + Cache_Free(c->user, false); //johnfitz -- added second argument + new_cs->user->data = (void *)(new_cs + 1); } else { // Con_Printf ("cache_move failed\n"); - Cache_Free (c->user, true); // tough luck... //johnfitz -- added second argument + Cache_Free(c->user, true); // tough luck... //johnfitz -- added second argument } } @@ -641,18 +645,18 @@ Cache_FreeLow Throw things out until the hunk can be expanded to the given point ============ */ -void Cache_FreeLow (int32_t new_low_hunk) +void Cache_FreeLow(int32_t new_low_hunk) { - cache_system_t *c; + cache_system_t *c; - while (1) + while(1) { c = cache_head.next; - if (c == &cache_head) - return; // nothing in cache at all - if ((byte *)c >= hunk_base + new_low_hunk) - return; // there is space to grow the hunk - Cache_Move ( c ); // reclaim the space + if(c == &cache_head) + return; // nothing in cache at all + if((byte *)c >= hunk_base + new_low_hunk) + return; // there is space to grow the hunk + Cache_Move(c); // reclaim the space } } @@ -663,32 +667,32 @@ Cache_FreeHigh Throw things out until the hunk can be expanded to the given point ============ */ -void Cache_FreeHigh (int32_t new_high_hunk) +void Cache_FreeHigh(int32_t new_high_hunk) { - cache_system_t *c, *prev; + cache_system_t *c, *prev; prev = NULL; - while (1) + while(1) { c = cache_head.prev; - if (c == &cache_head) - return; // nothing in cache at all - if ( (byte *)c + c->size <= hunk_base + hunk_size - new_high_hunk) - return; // there is space to grow the hunk - if (c == prev) - Cache_Free (c->user, true); // didn't move out of the way //johnfitz -- added second argument + if(c == &cache_head) + return; // nothing in cache at all + if((byte *)c + c->size <= hunk_base + hunk_size - new_high_hunk) + return; // there is space to grow the hunk + if(c == prev) + Cache_Free(c->user, true); // didn't move out of the way //johnfitz -- added second argument else { - Cache_Move (c); // try to move it + Cache_Move(c); // try to move it prev = c; } } } -void Cache_UnlinkLRU (cache_system_t *cs) +void Cache_UnlinkLRU(cache_system_t *cs) { - if (!cs->lru_next || !cs->lru_prev) - Sys_Error ("Cache_UnlinkLRU: NULL link"); + if(!cs->lru_next || !cs->lru_prev) + Sys_Error("Cache_UnlinkLRU: NULL link"); cs->lru_next->lru_prev = cs->lru_prev; cs->lru_prev->lru_next = cs->lru_next; @@ -696,10 +700,10 @@ void Cache_UnlinkLRU (cache_system_t *cs) cs->lru_prev = cs->lru_next = NULL; } -void Cache_MakeLRU (cache_system_t *cs) +void Cache_MakeLRU(cache_system_t *cs) { - if (cs->lru_next || cs->lru_prev) - Sys_Error ("Cache_MakeLRU: active link"); + if(cs->lru_next || cs->lru_prev) + Sys_Error("Cache_MakeLRU: active link"); cache_head.lru_next->lru_prev = cs; cs->lru_next = cache_head.lru_next; @@ -715,40 +719,41 @@ Looks for a free block of memory between the high and low hunk marks Size should already include the header and padding ============ */ -cache_system_t *Cache_TryAlloc (int32_t size, bool nobottom) +cache_system_t *Cache_TryAlloc(int32_t size, bool nobottom) { - cache_system_t *cs, *new_cs; + cache_system_t *cs, *new_cs; // is the cache completely empty? - if (!nobottom && cache_head.prev == &cache_head) + if(!nobottom && cache_head.prev == &cache_head) { - if (hunk_size - hunk_high_used - hunk_low_used < size) - Sys_Error ("Cache_TryAlloc: %" PRIi32 " is greater then free hunk", size); + if(hunk_size - hunk_high_used - hunk_low_used < size) + Sys_Error("Cache_TryAlloc: %" PRIi32 " is greater then free hunk", size); - new_cs = (cache_system_t *) (hunk_base + hunk_low_used); - memset (new_cs, 0, sizeof(*new_cs)); + new_cs = (cache_system_t *)(hunk_base + hunk_low_used); + memset(new_cs, 0, sizeof(*new_cs)); new_cs->size = size; cache_head.prev = cache_head.next = new_cs; new_cs->prev = new_cs->next = &cache_head; - Cache_MakeLRU (new_cs); + Cache_MakeLRU(new_cs); return new_cs; } // search from the bottom up for space - new_cs = (cache_system_t *) (hunk_base + hunk_low_used); + new_cs = (cache_system_t *)(hunk_base + hunk_low_used); cs = cache_head.next; do { - if (!nobottom || cs != cache_head.next) + if(!nobottom || cs != cache_head.next) { - if ( (byte *)cs - (byte *)new_cs >= size) - { // found space - memset (new_cs, 0, sizeof(*new_cs)); + if((byte *)cs - (byte *)new_cs >= size) + { + // found space + memset(new_cs, 0, sizeof(*new_cs)); new_cs->size = size; new_cs->next = cs; @@ -756,22 +761,23 @@ cache_system_t *Cache_TryAlloc (int32_t size, bool nobottom) cs->prev->next = new_cs; cs->prev = new_cs; - Cache_MakeLRU (new_cs); + Cache_MakeLRU(new_cs); return new_cs; } } - // continue looking + // continue looking new_cs = (cache_system_t *)((byte *)cs + cs->size); cs = cs->next; - } while (cs != &cache_head); + } + while(cs != &cache_head); // try to allocate one at the very end - if ( hunk_base + hunk_size - hunk_high_used - (byte *)new_cs >= size) + if(hunk_base + hunk_size - hunk_high_used - (byte *)new_cs >= size) { - memset (new_cs, 0, sizeof(*new_cs)); + memset(new_cs, 0, sizeof(*new_cs)); new_cs->size = size; new_cs->next = &cache_head; @@ -779,12 +785,12 @@ cache_system_t *Cache_TryAlloc (int32_t size, bool nobottom) cache_head.prev->next = new_cs; cache_head.prev = new_cs; - Cache_MakeLRU (new_cs); + Cache_MakeLRU(new_cs); return new_cs; } - return NULL; // couldn't allocate + return NULL; // couldn't allocate } /* @@ -794,10 +800,10 @@ Cache_Flush Throw everything out, so new data will be demand cached ============ */ -void Cache_Flush (void) +void Cache_Flush(void) { - while (cache_head.next != &cache_head) - Cache_Free ( cache_head.next->user, true); // reclaim the space //johnfitz -- added second argument + while(cache_head.next != &cache_head) + Cache_Free(cache_head.next->user, true); // reclaim the space //johnfitz -- added second argument } /* @@ -806,13 +812,13 @@ Cache_Print ============ */ -void Cache_Print (void) +void Cache_Print(void) { - cache_system_t *cd; + cache_system_t *cd; - for (cd = cache_head.next ; cd != &cache_head ; cd = cd->next) + for(cd = cache_head.next ; cd != &cache_head ; cd = cd->next) { - Con_Printf ("%8" PRIi32 " : %s\n", cd->size, cd->name); + Con_Printf("%8" PRIi32 " : %s\n", cd->size, cd->name); } } @@ -822,9 +828,9 @@ Cache_Report ============ */ -void Cache_Report (void) +void Cache_Report(void) { - Con_DPrintf ("%4.1f megabyte data cache\n", (hunk_size - hunk_high_used - hunk_low_used) / (float)(1024*1024) ); + Con_DPrintf("%4.1f megabyte data cache\n", (hunk_size - hunk_high_used - hunk_low_used) / (float)(1024 * 1024)); } /* @@ -833,12 +839,12 @@ Cache_Init ============ */ -void Cache_Init (void) +void Cache_Init(void) { cache_head.next = cache_head.prev = &cache_head; cache_head.lru_next = cache_head.lru_prev = &cache_head; - Cmd_AddCommand ("flush", Cache_Flush); + Cmd_AddCommand("flush", Cache_Flush); } /* @@ -848,12 +854,12 @@ Cache_Free Frees the memory and removes it from the LRU list ============== */ -void Cache_Free (cache_user_t *c, bool freetextures) //johnfitz -- added second argument +void Cache_Free(cache_user_t *c, bool freetextures) //johnfitz -- added second argument { - cache_system_t *cs; + cache_system_t *cs; - if (!c->data) - Sys_Error ("Cache_Free: not allocated"); + if(!c->data) + Sys_Error("Cache_Free: not allocated"); cs = ((cache_system_t *)c->data) - 1; @@ -863,13 +869,13 @@ void Cache_Free (cache_user_t *c, bool freetextures) //johnfitz -- added second c->data = NULL; - Cache_UnlinkLRU (cs); + Cache_UnlinkLRU(cs); //johnfitz -- if a model becomes uncached, free the gltextures. This only works //becuase the cache_user_t is the last component of the qmodel_t struct. Should //fail harmlessly if *c is actually part of an sfx_t struct. I FEEL DIRTY - if (freetextures) - TexMgr_FreeTexturesForOwner ((qmodel_t *)(c + 1) - 1); + if(freetextures) + TexMgr_FreeTexturesForOwner((qmodel_t *)(c + 1) - 1); } @@ -879,18 +885,18 @@ void Cache_Free (cache_user_t *c, bool freetextures) //johnfitz -- added second Cache_Check ============== */ -void *Cache_Check (cache_user_t *c) +void *Cache_Check(cache_user_t *c) { - cache_system_t *cs; + cache_system_t *cs; - if (!c->data) + if(!c->data) return NULL; cs = ((cache_system_t *)c->data) - 1; // move to head of LRU - Cache_UnlinkLRU (cs); - Cache_MakeLRU (cs); + Cache_UnlinkLRU(cs); + Cache_MakeLRU(cs); return c->data; } @@ -901,58 +907,58 @@ void *Cache_Check (cache_user_t *c) Cache_Alloc ============== */ -void *Cache_Alloc (cache_user_t *c, int32_t size, const char *name) +void *Cache_Alloc(cache_user_t *c, int32_t size, const char *name) { - cache_system_t *cs; + cache_system_t *cs; - if (c->data) - Sys_Error ("Cache_Alloc: allready allocated"); + if(c->data) + Sys_Error("Cache_Alloc: allready allocated"); - if (size <= 0) - Sys_Error ("Cache_Alloc: size %" PRIi32 "", size); + if(size <= 0) + Sys_Error("Cache_Alloc: size %" PRIi32 "", size); size = (size + sizeof(cache_system_t) + 15) & ~15; // find memory for it - while (1) + while(1) { - cs = Cache_TryAlloc (size, false); - if (cs) + cs = Cache_TryAlloc(size, false); + if(cs) { - q_strlcpy (cs->name, name, CACHENAME_LEN); - c->data = (void *)(cs+1); + q_strlcpy(cs->name, name, CACHENAME_LEN); + c->data = (void *)(cs + 1); cs->user = c; break; } - // free the least recently used cahedat - if (cache_head.lru_prev == &cache_head) - Sys_Error ("Cache_Alloc: out of memory"); // not enough memory at all + // free the least recently used cahedat + if(cache_head.lru_prev == &cache_head) + Sys_Error("Cache_Alloc: out of memory"); // not enough memory at all - Cache_Free (cache_head.lru_prev->user, true); //johnfitz -- added second argument + Cache_Free(cache_head.lru_prev->user, true); //johnfitz -- added second argument } - return Cache_Check (c); + return Cache_Check(c); } //============================================================================ -static void Memory_InitZone (memzone_t *zone, int32_t size) +static void Memory_InitZone(memzone_t *zone, int32_t size) { - memblock_t *block; + memblock_t *block; // set the entire zone to one free block zone->blocklist.next = zone->blocklist.prev = block = - (memblock_t *)( (byte *)zone + sizeof(memzone_t) ); - zone->blocklist.tag = 1; // in use block + (memblock_t *)((byte *)zone + sizeof(memzone_t)); + zone->blocklist.tag = 1; // in use block zone->blocklist.id = 0; zone->blocklist.size = 0; zone->rover = block; block->prev = block->next = &zone->blocklist; - block->tag = 0; // free block + block->tag = 0; // free block block->id = ZONEID; block->size = size - sizeof(memzone_t); } @@ -962,7 +968,7 @@ static void Memory_InitZone (memzone_t *zone, int32_t size) Memory_Init ======================== */ -void Memory_Init (void *buf, int32_t size) +void Memory_Init(void *buf, int32_t size) { int32_t p; int32_t zonesize = DYNAMIC_SIZE; @@ -972,18 +978,18 @@ void Memory_Init (void *buf, int32_t size) hunk_low_used = 0; hunk_high_used = 0; - Cache_Init (); - p = COM_CheckParm ("-zone"); - if (p) + Cache_Init(); + p = COM_CheckParm("-zone"); + if(p) { - if (p < com_argc-1) - zonesize = Q_atoi (com_argv[p+1]) * 1024; + if(p < com_argc - 1) + zonesize = Q_atoi(com_argv[p + 1]) * 1024; else - Sys_Error ("Memory_Init: you must specify a size in KB after -zone"); + Sys_Error("Memory_Init: you must specify a size in KB after -zone"); } - mainzone = (memzone_t *) Hunk_AllocName (zonesize, "zone" ); - Memory_InitZone (mainzone, zonesize); + mainzone = (memzone_t *) Hunk_AllocName(zonesize, "zone"); + Memory_InitZone(mainzone, zonesize); - Cmd_AddCommand ("hunk_print", Hunk_Print_f); //johnfitz + Cmd_AddCommand("hunk_print", Hunk_Print_f); //johnfitz } diff --git a/source/zone.h b/source/zone.h index af2cce0..e2d12da 100644 --- a/source/zone.h +++ b/source/zone.h @@ -89,46 +89,46 @@ Zone block */ -void Memory_Init (void *buf, int32_t size); +void Memory_Init(void *buf, int32_t size); -void Z_Free (void *ptr); -void *Z_Malloc (int32_t size); // returns 0 filled memory -void *Z_Realloc (void *ptr, int32_t size); -char *Z_Strdup (const char *s); +void Z_Free(void *ptr); +void *Z_Malloc(int32_t size); // returns 0 filled memory +void *Z_Realloc(void *ptr, int32_t size); +char *Z_Strdup(const char *s); -void *Hunk_Alloc (int32_t size); // returns 0 filled memory -void *Hunk_AllocName (int32_t size, const char *name); -void *Hunk_HighAllocName (int32_t size, const char *name); -char *Hunk_Strdup (const char *s, const char *name); +void *Hunk_Alloc(int32_t size); // returns 0 filled memory +void *Hunk_AllocName(int32_t size, const char *name); +void *Hunk_HighAllocName(int32_t size, const char *name); +char *Hunk_Strdup(const char *s, const char *name); -int32_t Hunk_LowMark (void); -void Hunk_FreeToLowMark (int32_t mark); +int32_t Hunk_LowMark(void); +void Hunk_FreeToLowMark(int32_t mark); -int32_t Hunk_HighMark (void); -void Hunk_FreeToHighMark (int32_t mark); +int32_t Hunk_HighMark(void); +void Hunk_FreeToHighMark(int32_t mark); -void *Hunk_TempAlloc (int32_t size); +void *Hunk_TempAlloc(int32_t size); -void Hunk_Check (void); +void Hunk_Check(void); typedef struct cache_user_s { - void *data; + void *data; } cache_user_t; -void Cache_Flush (void); +void Cache_Flush(void); -void *Cache_Check (cache_user_t *c); +void *Cache_Check(cache_user_t *c); // returns the cached data, and moves to the head of the LRU list // if present, otherwise returns NULL -void Cache_Free (cache_user_t *c, bool freetextures); //johnfitz -- added second argument +void Cache_Free(cache_user_t *c, bool freetextures); //johnfitz -- added second argument -void *Cache_Alloc (cache_user_t *c, int32_t size, const char *name); +void *Cache_Alloc(cache_user_t *c, int32_t size, const char *name); // Returns NULL if all purgable data was tossed and there still // wasn't enough room. -void Cache_Report (void); +void Cache_Report(void); -#endif /* __ZZONE_H */ +#endif /* __ZZONE_H */